soma-som-core 0.1.0

Universal soma(som) structural primitives — Quad / Tree / Ring / Genesis / Fingerprint / TemporalLedger / CrossingRecord
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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
// SPDX-License-Identifier: LGPL-3.0-only
#![allow(missing_docs)]

//! Temporal ledger: the hash chain across ring cycles.
//!
//! ## Spec traceability
//! - Spec §9.5: Temporal Ledger — SOM snapshots as hash chain
//! - Spec §10.3: Genesis hash — SOM_0.hash = H(SOM_0.state ‖ s₀)
//! - Spec §10.3: Standard operation — SOM_t.hash = H(SOM_t.state ‖ SOM_{t-1}.hash)
//!
//! ## Semantic chain enrichment
//!
//! Each `LedgerEntry` carries a `semantic_hash` derived from the cycle's
//! `CycleContext`. The chain hash formula becomes:
//!
//! ```text
//! SOM_t.hash = H(SOM_t.state ‖ semantic_hash ‖ SOM_{t-1}.hash)
//! ```
//!
//! This makes semantic identity (who did what, what was decided) tamper-evident.
//! Legacy entries have `semantic_hash = [0u8; 32]` and verify with
//! the old formula `H(state ‖ prev_hash)` for backward compatibility.

use serde::{Deserialize, Serialize};

use crate::error::SomaError;
use crate::traceability::{CycleContext, LEGACY_SEMANTIC_HASH};

/// A single entry in the temporal ledger.
///
/// Each entry records the SOM snapshot of one complete ring cycle.
///
/// ## Semantic enrichment
///
/// `semantic_hash` is the BLAKE3 hash of the cycle's `CycleContext`,
/// included in `chain_hash` computation. `context` carries the full
/// typed envelope for queryability. Legacy entries have
/// `semantic_hash = [0u8; 32]` and `context = None`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LedgerEntry {
    /// Cycle index (t). 0 for genesis, incremented after each cycle.
    pub cycle_index: u64,

    /// The awareness fingerprint for this cycle (72 SOM positions).
    pub awareness_fingerprint: [u8; 32],

    /// The system fingerprint for this cycle (90 positions).
    pub system_fingerprint: [u8; 32],

    /// The chain hash: H(SOM_t.state ‖ semantic_hash ‖ SOM_{t-1}.hash)
    /// or H(SOM_0.state ‖ s₀) for genesis.
    ///
    /// This is the backward-verifiable link in the temporal chain.
    pub chain_hash: [u8; 32],

    /// BLAKE3 hash of the cycle's semantic context.
    ///
    /// Computed from `CycleContext::semantic_hash()`. Included in the
    /// chain_hash computation to make semantic identity tamper-evident.
    ///
    /// `[0u8; 32]` for legacy entries that predate M1D. `verify_chain()`
    /// recognizes this sentinel and falls back to the legacy hash formula.
    #[serde(default)]
    pub semantic_hash: [u8; 32],

    /// The full semantic envelope for this cycle.
    ///
    /// `None` for legacy entries. Enables queryability: "show me all
    /// cycles where actor=admin and command_type=user.create".
    #[serde(default)]
    pub context: Option<CycleContext>,
}

/// The temporal ledger: an append-only hash chain of SOM snapshots.
///
/// ## Spec §9.5
///
/// > SOM snapshots form a hash chain. Each snapshot's hash includes the
/// > previous snapshot's hash, creating a temporal chain that is backward-
/// > verifiable to the genesis cycle.
///
/// The ledger is append-only. Entries cannot be modified or removed.
/// Altering any entry's hash would break the chain, which is detectable
/// by backward verification to SOM_0.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalLedger {
    entries: Vec<LedgerEntry>,
}

impl TemporalLedger {
    /// Create a new empty ledger.
    pub fn new() -> Self {
        Self {
            entries: Vec::new(),
        }
    }

    /// Record the genesis cycle (t = 0).
    ///
    /// ## Spec §10.3
    ///
    /// Genesis hash: SOM_0.hash = H(SOM_0.state ‖ s₀)
    ///
    /// The genesis hash is computed externally (from seed + initial state)
    /// and passed in. The semantic context is recorded but does not affect
    /// the genesis hash — the genesis entry is trusted by stipulation.
    pub fn record_genesis(
        &mut self,
        awareness_fingerprint: [u8; 32],
        system_fingerprint: [u8; 32],
        genesis_hash: [u8; 32],
        context: CycleContext,
    ) -> Result<(), SomaError> {
        if !self.entries.is_empty() {
            return Err(SomaError::GenesisAlreadyRecorded);
        }

        let semantic_hash = context.semantic_hash();

        self.entries.push(LedgerEntry {
            cycle_index: 0,
            awareness_fingerprint,
            system_fingerprint,
            chain_hash: genesis_hash,
            semantic_hash,
            context: Some(context),
        });

        Ok(())
    }

    /// Record a standard cycle (t > 0).
    ///
    /// ## Spec §10.3
    ///
    /// Enriched operation: SOM_t.hash = H(SOM_t.state ‖ semantic_hash ‖ SOM_{t-1}.hash)
    ///
    /// The chain hash now includes the semantic_hash derived from the
    /// cycle's `CycleContext`. This makes the semantic identity of every
    /// cycle tamper-evident: altering who did what breaks `verify_chain()`.
    pub fn record_cycle(
        &mut self,
        awareness_fingerprint: [u8; 32],
        system_fingerprint: [u8; 32],
        context: CycleContext,
    ) -> Result<LedgerEntry, SomaError> {
        let prev = self.entries.last().ok_or(SomaError::LedgerEmpty)?;
        let prev_hash = prev.chain_hash;
        let cycle_index = prev.cycle_index + 1;
        let semantic_hash = context.semantic_hash();

        let chain_hash = Self::compute_chain_hash(&system_fingerprint, &semantic_hash, &prev_hash);

        let entry = LedgerEntry {
            cycle_index,
            awareness_fingerprint,
            system_fingerprint,
            chain_hash,
            semantic_hash,
            context: Some(context),
        };

        self.entries.push(entry.clone());
        Ok(entry)
    }

    /// Get the latest entry.
    pub fn latest(&self) -> Option<&LedgerEntry> {
        self.entries.last()
    }

    /// Get the genesis entry (t = 0).
    pub fn genesis(&self) -> Option<&LedgerEntry> {
        self.entries.first()
    }

    /// Get an entry by cycle index.
    pub fn entry(&self, cycle_index: u64) -> Option<&LedgerEntry> {
        self.entries.get(cycle_index as usize)
    }

    /// Number of entries in the ledger.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Is the ledger empty?
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// The current chain head hash (latest entry's chain_hash).
    pub fn chain_head(&self) -> Option<[u8; 32]> {
        self.entries.last().map(|e| e.chain_hash)
    }

    /// Compute the enriched chain hash.
    ///
    /// ```text
    /// H(system_fingerprint ‖ semantic_hash ‖ prev_hash)
    /// ```
    pub fn compute_chain_hash(
        system_fingerprint: &[u8; 32],
        semantic_hash: &[u8; 32],
        prev_hash: &[u8; 32],
    ) -> [u8; 32] {
        let mut hasher = blake3::Hasher::new();
        hasher.update(system_fingerprint);
        hasher.update(semantic_hash);
        hasher.update(prev_hash);
        *hasher.finalize().as_bytes()
    }

    /// Compute the legacy chain hash (pre-M1D formula).
    ///
    /// ```text
    /// H(system_fingerprint ‖ prev_hash)
    /// ```
    fn compute_legacy_chain_hash(system_fingerprint: &[u8; 32], prev_hash: &[u8; 32]) -> [u8; 32] {
        let mut hasher = blake3::Hasher::new();
        hasher.update(system_fingerprint);
        hasher.update(prev_hash);
        *hasher.finalize().as_bytes()
    }

    /// Verify the entire chain from genesis to the latest entry.
    ///
    /// Returns `Ok(())` if the chain is intact, or an error indicating
    /// which entry breaks the chain.
    ///
    /// ## Dual-formula verification
    ///
    /// Entries with `semantic_hash == LEGACY_SEMANTIC_HASH` ([0u8; 32])
    /// are verified using the legacy formula: `H(state ‖ prev_hash)`.
    /// Enriched entries use the standard formula: `H(state ‖ semantic_hash ‖ prev_hash)`.
    ///
    /// This allows mixed chains (legacy → enriched) to verify correctly,
    /// supporting rolling upgrades of existing databases.
    pub fn verify_chain(&self) -> Result<(), SomaError> {
        if self.entries.is_empty() {
            return Ok(());
        }

        // Genesis entry (t = 0) is trusted — no predecessor to verify against.
        // Verify all subsequent entries.
        for i in 1..self.entries.len() {
            #[allow(clippy::indexing_slicing)] // i and i-1 are within bounds (loop range)
            let prev = &self.entries[i - 1];
            #[allow(clippy::indexing_slicing)]
            let curr = &self.entries[i];

            let expected = if curr.semantic_hash == LEGACY_SEMANTIC_HASH {
                // Legacy entry: H(state ‖ prev_hash)
                Self::compute_legacy_chain_hash(&curr.system_fingerprint, &prev.chain_hash)
            } else {
                // Enriched entry: H(state ‖ semantic_hash ‖ prev_hash)
                Self::compute_chain_hash(
                    &curr.system_fingerprint,
                    &curr.semantic_hash,
                    &prev.chain_hash,
                )
            };

            if curr.chain_hash != expected {
                return Err(SomaError::ChainIntegrityViolation {
                    cycle_index: curr.cycle_index,
                });
            }
        }

        Ok(())
    }
}

impl Default for TemporalLedger {
    fn default() -> Self {
        Self::new()
    }
}

// inline: exercises module-private items via super::*
#[cfg(test)]
mod tests {
    use super::*;
    use crate::traceability::CycleContext;

    fn make_fingerprints(cycle: u64) -> ([u8; 32], [u8; 32]) {
        let awareness = *blake3::hash(format!("awareness-{cycle}").as_bytes()).as_bytes();
        let system = *blake3::hash(format!("system-{cycle}").as_bytes()).as_bytes();
        (awareness, system)
    }

    #[test]
    fn empty_ledger() {
        let ledger = TemporalLedger::new();
        assert!(ledger.is_empty());
        assert_eq!(ledger.len(), 0);
        assert!(ledger.verify_chain().is_ok());
    }

    #[test]
    fn genesis_recording() {
        let mut ledger = TemporalLedger::new();
        let (a, s) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();

        ledger
            .record_genesis(a, s, genesis_hash, CycleContext::genesis())
            .unwrap();
        assert_eq!(ledger.len(), 1);
        assert_eq!(ledger.genesis().unwrap().cycle_index, 0);
        assert_eq!(ledger.chain_head(), Some(genesis_hash));
    }

    #[test]
    fn genesis_carries_semantic_hash() {
        let mut ledger = TemporalLedger::new();
        let (a, s) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();
        let ctx = CycleContext::genesis();
        let expected_semantic = ctx.semantic_hash();

        ledger.record_genesis(a, s, genesis_hash, ctx).unwrap();

        let entry = ledger.genesis().unwrap();
        assert_eq!(entry.semantic_hash, expected_semantic);
        assert!(entry.context.is_some());
    }

    #[test]
    fn cannot_record_genesis_twice() {
        let mut ledger = TemporalLedger::new();
        let (a, s) = make_fingerprints(0);
        let h = *blake3::hash(b"genesis").as_bytes();

        ledger
            .record_genesis(a, s, h, CycleContext::genesis())
            .unwrap();
        assert!(
            ledger
                .record_genesis(a, s, h, CycleContext::genesis())
                .is_err()
        );
    }

    #[test]
    fn multi_cycle_chain() {
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis-seed").as_bytes();

        ledger
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();

        for cycle in 1..=10 {
            let (a, s) = make_fingerprints(cycle);
            let entry = ledger
                .record_cycle(a, s, CycleContext::heartbeat())
                .unwrap();
            assert_eq!(entry.cycle_index, cycle);
        }

        assert_eq!(ledger.len(), 11);
        assert!(ledger.verify_chain().is_ok());
    }

    #[test]
    fn chain_tamper_detection() {
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();
        ledger
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();

        for cycle in 1..=5 {
            let (a, s) = make_fingerprints(cycle);
            ledger
                .record_cycle(a, s, CycleContext::heartbeat())
                .unwrap();
        }

        // Tamper with entry at cycle 3
        ledger.entries[3].system_fingerprint[0] ^= 0xFF;

        // Chain verification must detect the tampering
        let result = ledger.verify_chain();
        assert!(result.is_err());
        match result.unwrap_err() {
            SomaError::ChainIntegrityViolation { cycle_index } => {
                assert_eq!(cycle_index, 3);
            }
            other => panic!("Expected ChainIntegrityViolation, got {other:?}"),
        }
    }

    #[test]
    fn each_cycle_hash_depends_on_predecessor() {
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();
        ledger
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();

        let (a1, s1) = make_fingerprints(1);
        let ctx = CycleContext::heartbeat();
        let semantic_hash = ctx.semantic_hash();
        let entry1 = ledger.record_cycle(a1, s1, ctx).unwrap();

        // Manually verify: entry1.chain_hash = H(s1 ‖ semantic_hash ‖ genesis_hash)
        let expected = TemporalLedger::compute_chain_hash(&s1, &semantic_hash, &genesis_hash);

        assert_eq!(entry1.chain_hash, expected);
    }

    // ── WP-M1D: Semantic identity tests ─────────────────────────────

    #[test]
    fn semantic_hash_included_in_chain_hash() {
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();
        ledger
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();

        let (a1, s1) = make_fingerprints(1);
        let ctx_a = CycleContext::command("user.create", "alice", "req-1", "authorized");
        let entry_a = ledger.record_cycle(a1, s1, ctx_a).unwrap();

        // Build a separate ledger with a different semantic context but same fingerprints
        let mut ledger2 = TemporalLedger::new();
        ledger2
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();
        let ctx_b = CycleContext::command("user.delete", "bob", "req-2", "denied");
        let entry_b = ledger2.record_cycle(a1, s1, ctx_b).unwrap();

        // Same structural fingerprints, different semantic context → different chain hash
        assert_ne!(entry_a.chain_hash, entry_b.chain_hash);

        // Both chains still verify
        assert!(ledger.verify_chain().is_ok());
        assert!(ledger2.verify_chain().is_ok());
    }

    #[test]
    fn semantic_tamper_detection() {
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();
        ledger
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();

        let (a1, s1) = make_fingerprints(1);
        let ctx = CycleContext::command("user.create", "admin", "req-1", "authorized");
        ledger.record_cycle(a1, s1, ctx).unwrap();

        assert!(ledger.verify_chain().is_ok());

        // Tamper with the semantic hash (as if someone changed who did what)
        ledger.entries[1].semantic_hash[0] ^= 0xFF;

        let result = ledger.verify_chain();
        assert!(result.is_err());
        match result.unwrap_err() {
            SomaError::ChainIntegrityViolation { cycle_index } => {
                assert_eq!(cycle_index, 1);
            }
            other => panic!("Expected ChainIntegrityViolation, got {other:?}"),
        }
    }

    #[test]
    fn mixed_legacy_and_enriched_chain() {
        // Simulate: genesis + 2 legacy entries + 2 enriched entries
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();

        // Genesis (trusted)
        ledger.entries.push(LedgerEntry {
            cycle_index: 0,
            awareness_fingerprint: a0,
            system_fingerprint: s0,
            chain_hash: genesis_hash,
            semantic_hash: LEGACY_SEMANTIC_HASH,
            context: None,
        });

        // Legacy entry 1 (old formula: H(state ‖ prev_hash))
        let (a1, s1) = make_fingerprints(1);
        let legacy_hash_1 = TemporalLedger::compute_legacy_chain_hash(&s1, &genesis_hash);
        ledger.entries.push(LedgerEntry {
            cycle_index: 1,
            awareness_fingerprint: a1,
            system_fingerprint: s1,
            chain_hash: legacy_hash_1,
            semantic_hash: LEGACY_SEMANTIC_HASH,
            context: None,
        });

        // Legacy entry 2
        let (a2, s2) = make_fingerprints(2);
        let legacy_hash_2 = TemporalLedger::compute_legacy_chain_hash(&s2, &legacy_hash_1);
        ledger.entries.push(LedgerEntry {
            cycle_index: 2,
            awareness_fingerprint: a2,
            system_fingerprint: s2,
            chain_hash: legacy_hash_2,
            semantic_hash: LEGACY_SEMANTIC_HASH,
            context: None,
        });

        // Now add enriched entries via the normal API
        let (a3, s3) = make_fingerprints(3);
        ledger
            .record_cycle(a3, s3, CycleContext::heartbeat())
            .unwrap();

        let (a4, s4) = make_fingerprints(4);
        ledger
            .record_cycle(
                a4,
                s4,
                CycleContext::command("user.create", "admin", "req-1", "ok"),
            )
            .unwrap();

        assert_eq!(ledger.len(), 5);
        // Mixed chain must verify — legacy entries use old formula, enriched use new
        assert!(ledger.verify_chain().is_ok());
    }

    #[test]
    fn cycle_context_carried_in_entry() {
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();
        ledger
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();

        let (a1, s1) = make_fingerprints(1);
        let ctx = CycleContext::command("user.create", "admin", "req-1", "authorized")
            .with_detail("username=bob");
        ledger.record_cycle(a1, s1, ctx.clone()).unwrap();

        let entry = ledger.entry(1).unwrap();
        assert_eq!(entry.context.as_ref(), Some(&ctx));
        assert_eq!(entry.semantic_hash, ctx.semantic_hash());
    }

    #[test]
    fn all_cycle_classes_in_chain() {
        let mut ledger = TemporalLedger::new();
        let (a0, s0) = make_fingerprints(0);
        let genesis_hash = *blake3::hash(b"genesis").as_bytes();
        ledger
            .record_genesis(a0, s0, genesis_hash, CycleContext::genesis())
            .unwrap();

        let contexts = vec![
            CycleContext::heartbeat(),
            CycleContext::login("alice", "success"),
            CycleContext::command("user.create", "admin", "req-1", "authorized"),
            CycleContext::gate_transition("operator", "req-2", "authorized", "gate=G1 evidence=3"),
            CycleContext::heartbeat(),
        ];

        for (i, ctx) in contexts.into_iter().enumerate() {
            let (a, s) = make_fingerprints((i + 1) as u64);
            ledger.record_cycle(a, s, ctx).unwrap();
        }

        assert_eq!(ledger.len(), 6);
        assert!(ledger.verify_chain().is_ok());
    }
}