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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
// SPDX-License-Identifier: LGPL-3.0-only
#![allow(missing_docs)]

//! Perspectival ledger: per-unit hash chains and cross-verification.
//!
//! ## Spec traceability
//! - Perspectival Ledger Extension Specification §2.2: Perspectival hash chain definition
//! - Perspectival Ledger Extension Specification §3.2: Commit/verify pattern
//! - Perspectival Ledger Extension Specification §4.1: Cross-verification digest
//! - Perspectival Ledger Extension Specification §5: SOM Tree trait (data trait)
//! - Perspectival Ledger Extension Specification §6: Genesis bootstrapping
//! - Perspectival Ledger Extension Specification §7: Formal properties (Propositions 1–4)
//! - M4 Project Specification §6: Perspectival ledger implementation
//!
//! ## Design
//!
//! Each of the six units maintains its own perspectival hash chain across cycles.
//! The chain is anchored to the genesis seed and extends with each cycle closure.
//! At cycle closure, all six perspectival hashes are combined into a cross-verification
//! digest that provides collective attestation of cycle integrity.
//!
//! The perspectival state `S_u^(t)` is defined as the hash of unit u's complete
//! Quad state: 4 SOM Quads (Data, Server, Client, Interface) + 1 SOMA Quad.
//! This captures the full perspectival view without coupling to boundary records
//! (Perspectival Ledger §10, Open Question 1: implementation decision).

use serde::{Deserialize, Serialize};

use crate::error::SomaError;
use crate::quad::Quad;
use crate::ring::UnitState;
use crate::types::{Layer, UnitId};

// ═══════════════════════════════════════════════════════════════════════════
// PerspectivalState trait — Perspectival Ledger §5 (SOM Tree data trait)
// ═══════════════════════════════════════════════════════════════════════════

/// The SOM Tree trait: a uniform interface for perspectival operations.
///
/// ## Perspectival Ledger §5
///
/// > The SOM Tree trait is a structural interface requiring three operations:
/// > `perspectival_hash`, `verify_predecessor`, and `commit`. Every unit's
/// > SOMA Tree implements this trait.
///
/// The trait is defined on `UnitState` rather than on a separate SOMA Tree
/// type, since the unit's complete state (4 SOM + 1 SOMA Quads)
/// constitutes its perspectival view.
pub trait PerspectivalState {
    /// Compute the perspectival state hash S_u^(t).
    ///
    /// This is the serialized content of the unit's complete Quad state,
    /// hashed into a single 32-byte digest. The hash includes all 5 Quads
    /// (4 SOM layers + 1 SOMA) in canonical order.
    fn perspectival_state_hash(&self) -> [u8; 32];
}

impl PerspectivalState for UnitState {
    fn perspectival_state_hash(&self) -> [u8; 32] {
        unit_state_hash(self)
    }
}

/// Compute the perspectival state hash for a unit.
///
/// ## M4 §6: Perspectival Hash
///
/// S_u^(t) is the serialized SOMA Tree state of unit u at cycle t.
/// We define this as the BLAKE3 hash of the unit's 5 Quads in canonical
/// order: Data, Server, Client, Interface, SOMA.
///
/// Each Quad contributes root, pointer, and tree entries (in deterministic
/// key order via BTreeMap) — the same serialization used by the fingerprint
/// module, ensuring consistency.
pub fn unit_state_hash(unit: &UnitState) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();

    // 4 SOM Quads in layer order (Data, Server, Client, Interface)
    for &layer in &Layer::ALL {
        hash_quad_into(&mut hasher, unit.som_quad(layer));
    }

    // 1 SOMA Quad
    hash_quad_into(&mut hasher, &unit.soma_quad);

    *hasher.finalize().as_bytes()
}

/// Feed a Quad's content into a hasher (same serialization as fingerprint.rs).
fn hash_quad_into(hasher: &mut blake3::Hasher, quad: &Quad) {
    hasher.update(&quad.root);
    hasher.update(&quad.pointer);
    for (key, value) in &quad.tree {
        hasher.update(key.as_bytes());
        hasher.update(&(value.len() as u64).to_le_bytes());
        hasher.update(value);
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// PerspectivalChain — Perspectival Ledger §2.2
// ═══════════════════════════════════════════════════════════════════════════

/// A single unit's perspectival hash chain.
///
/// ## Perspectival Ledger §2.2
///
/// > L_u = (ℓ_u^(0), ℓ_u^(1), ...) where:
/// > - Genesis: ℓ_u^(0) = H(S_u^(0) ‖ s₀)
/// > - Standard: ℓ_u^(t) = H(S_u^(t) ‖ ℓ_u^(t-1))
///
/// The chain is append-only. Each link's hash includes the previous link,
/// creating a backward-verifiable sequence anchored to the genesis seed.
#[derive(Debug, Clone)]
pub struct PerspectivalChain {
    /// The unit this chain belongs to.
    unit_id: UnitId,

    /// The ordered sequence of perspectival hashes.
    /// Index 0 is the genesis hash (t = 0).
    entries: Vec<PerspectivalEntry>,
}

/// A single entry in a perspectival chain.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PerspectivalEntry {
    /// Cycle index (t).
    pub cycle_index: u64,

    /// The perspectival state hash S_u^(t) — what was hashed.
    pub state_hash: [u8; 32],

    /// The perspectival hash ℓ_u^(t) — the chain link.
    pub perspectival_hash: [u8; 32],
}

impl PerspectivalChain {
    /// Create a new empty chain for the given unit.
    pub fn new(unit_id: UnitId) -> Self {
        Self {
            unit_id,
            entries: Vec::new(),
        }
    }

    /// The unit this chain belongs to.
    pub fn unit_id(&self) -> UnitId {
        self.unit_id
    }

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

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

    /// The latest perspectival hash (chain head).
    pub fn head(&self) -> Option<[u8; 32]> {
        self.entries.last().map(|e| e.perspectival_hash)
    }

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

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

    /// The latest entry.
    pub fn latest(&self) -> Option<&PerspectivalEntry> {
        self.entries.last()
    }

    // ── Commit operations ───────────────────────────────────────────────

    /// Record the genesis perspectival hash (t = 0).
    ///
    /// ## Perspectival Ledger §6.1
    ///
    /// > ℓ_u^(0) = H(S_u^(0) ‖ s₀) for all u ∈ U
    ///
    /// The genesis seed anchors the chain. Two instances with the same seed
    /// but different per-unit processing will produce different perspectival
    /// genesis identities.
    pub fn commit_genesis(
        &mut self,
        state_hash: [u8; 32],
        genesis_seed: &[u8],
    ) -> Result<PerspectivalEntry, SomaError> {
        if !self.entries.is_empty() {
            return Err(SomaError::GenesisAlreadyRecorded);
        }

        // ℓ_u^(0) = H(S_u^(0) ‖ s₀)
        let perspectival_hash = compute_perspectival_hash(&state_hash, genesis_seed);

        let entry = PerspectivalEntry {
            cycle_index: 0,
            state_hash,
            perspectival_hash,
        };

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

    /// Record a standard-cycle perspectival hash (t > 0).
    ///
    /// ## Perspectival Ledger §2.2
    ///
    /// > ℓ_u^(t) = H(S_u^(t) ‖ ℓ_u^(t-1))
    ///
    /// The hash chains to the previous perspectival hash, creating
    /// a backward-verifiable link.
    pub fn commit(&mut self, state_hash: [u8; 32]) -> Result<PerspectivalEntry, SomaError> {
        let prev = self.entries.last().ok_or(SomaError::LedgerEmpty)?;
        let prev_hash = prev.perspectival_hash;
        let cycle_index = prev.cycle_index + 1;

        // ℓ_u^(t) = H(S_u^(t) ‖ ℓ_u^(t-1))
        let perspectival_hash = compute_perspectival_hash(&state_hash, &prev_hash);

        let entry = PerspectivalEntry {
            cycle_index,
            state_hash,
            perspectival_hash,
        };

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

    // ── Verification ────────────────────────────────────────────────────

    /// Verify the entire chain's integrity from genesis to head.
    ///
    /// ## Perspectival Ledger Proposition 1 (Chain integrity)
    ///
    /// > If all perspectival hashes are computed honestly, then alteration
    /// > of any prior perspectival state S_u^(t') (t' < t) is detectable
    /// > by recomputing the chain from ℓ_u^(t') to ℓ_u^(t).
    ///
    /// The genesis entry (t = 0) requires the genesis seed for verification.
    /// Subsequent entries are verified against their predecessor's hash.
    pub fn verify_chain(&self, genesis_seed: &[u8]) -> Result<(), SomaError> {
        if self.entries.is_empty() {
            return Ok(());
        }

        // Verify genesis entry
        #[allow(clippy::indexing_slicing)] // non-empty guarded above
        let genesis = &self.entries[0];
        let expected_genesis = compute_perspectival_hash(&genesis.state_hash, genesis_seed);
        if genesis.perspectival_hash != expected_genesis {
            return Err(SomaError::ChainIntegrityViolation { cycle_index: 0 });
        }

        // Verify subsequent entries
        for i in 1..self.entries.len() {
            #[allow(clippy::indexing_slicing)] // i and i-1 within bounds (loop range)
            let prev = &self.entries[i - 1];
            #[allow(clippy::indexing_slicing)]
            let curr = &self.entries[i];

            let expected = compute_perspectival_hash(&curr.state_hash, &prev.perspectival_hash);
            if curr.perspectival_hash != expected {
                return Err(SomaError::ChainIntegrityViolation {
                    cycle_index: curr.cycle_index,
                });
            }
        }

        Ok(())
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Cross-verification digest — Perspectival Ledger §4.1
// ═══════════════════════════════════════════════════════════════════════════

/// Compute the cross-verification digest from six perspectival hashes.
///
/// ## Perspectival Ledger §4.1 (Definition)
///
/// > X^(t) = H(ℓ_FU^(t) ‖ ℓ_MU^(t) ‖ ℓ_CU^(t) ‖ ℓ_OU^(t) ‖ ℓ_SU^(t) ‖ ℓ_HU^(t))
///
/// The digest has three properties:
/// 1. **Completeness**: every unit's contribution is included.
/// 2. **Ring-order sensitivity**: concatenation follows the ring's directed order.
/// 3. **Collective attestation**: no single unit can produce the digest alone.
///
/// ## Parameters
///
/// `perspectival_hashes` must contain exactly 6 hashes in ring order
/// (FU, MU, CU, OU, SU, HU). This is enforced by the function signature
/// taking `[u8; 32]` per unit indexed by `UnitId::ALL`.
pub fn cross_verification_digest(perspectival_hashes: &[[u8; 32]; 6]) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();

    // Concatenate in ring order: FU, MU, CU, OU, SU, HU
    // UnitId::ALL is already in ring order, and the array is indexed 0..5.
    for hash in perspectival_hashes {
        hasher.update(hash);
    }

    *hasher.finalize().as_bytes()
}

// ═══════════════════════════════════════════════════════════════════════════
// Internal helpers
// ═══════════════════════════════════════════════════════════════════════════

/// Compute a perspectival hash: H(state_hash ‖ chain_input).
///
/// For genesis: chain_input = genesis_seed (raw bytes).
/// For standard cycles: chain_input = previous perspectival hash (32 bytes).
fn compute_perspectival_hash(state_hash: &[u8; 32], chain_input: &[u8]) -> [u8; 32] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(state_hash);
    hasher.update(chain_input);
    *hasher.finalize().as_bytes()
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

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

    const TEST_SEED: &[u8] = b"soma-perspectival-test-seed-v1";

    /// Create a UnitState with deterministic but distinct content.
    fn make_unit_state(unit: UnitId, cycle: u64) -> UnitState {
        let mut us = UnitState::new(unit);
        us.soma_quad = Quad::from_strings(
            &format!("{unit}.soma.root.c{cycle}"),
            &format!("{unit}.soma.ptr.c{cycle}"),
            {
                let mut t = Tree::new();
                t.insert("unit".into(), format!("{unit}").into_bytes());
                t.insert("cycle".into(), cycle.to_le_bytes().to_vec());
                t
            },
        );
        for &layer in &Layer::ALL {
            let mut tree = Tree::new();
            tree.insert(
                "origin".into(),
                format!("{unit}.{layer}.c{cycle}").into_bytes(),
            );
            *us.som_quad_mut(layer) = Quad::from_strings(
                &format!("{unit}.{layer}.root.c{cycle}"),
                &format!("{unit}.{layer}.ptr.c{cycle}"),
                tree,
            );
        }
        us
    }

    // ── PerspectivalState trait tests ────────────────────────────────────

    #[test]
    fn perspectival_state_hash_is_deterministic() {
        let us = make_unit_state(UnitId::FU, 0);
        let h1 = us.perspectival_state_hash();
        let h2 = us.perspectival_state_hash();
        assert_eq!(h1, h2);
    }

    #[test]
    fn perspectival_state_hash_differs_across_units() {
        let states: Vec<_> = UnitId::ALL
            .iter()
            .map(|&u| make_unit_state(u, 0).perspectival_state_hash())
            .collect();

        // All 6 must be distinct
        let mut sorted = states.clone();
        sorted.sort();
        sorted.dedup();
        assert_eq!(
            sorted.len(),
            6,
            "All units must produce distinct state hashes"
        );
    }

    #[test]
    fn perspectival_state_hash_differs_across_cycles() {
        let h0 = make_unit_state(UnitId::FU, 0).perspectival_state_hash();
        let h1 = make_unit_state(UnitId::FU, 1).perspectival_state_hash();
        assert_ne!(
            h0, h1,
            "Same unit at different cycles must produce different state hashes"
        );
    }

    #[test]
    fn perspectival_state_hash_sensitive_to_any_quad_change() {
        let base = make_unit_state(UnitId::CU, 3);
        let base_hash = base.perspectival_state_hash();

        // Mutate each SOM layer's root
        for &layer in &Layer::ALL {
            let mut modified = base.clone();
            modified.som_quad_mut(layer).root[0] ^= 0xFF;
            assert_ne!(
                modified.perspectival_state_hash(),
                base_hash,
                "Changing {}.{:?} root must change perspectival state hash",
                UnitId::CU,
                layer
            );
        }

        // Mutate SOMA Quad
        let mut modified = base.clone();
        modified.soma_quad.root[0] ^= 0xFF;
        assert_ne!(
            modified.perspectival_state_hash(),
            base_hash,
            "Changing SOMA Quad must change perspectival state hash"
        );
    }

    // ── PerspectivalChain: genesis ──────────────────────────────────────

    #[test]
    fn genesis_commit_creates_chain() {
        let mut chain = PerspectivalChain::new(UnitId::FU);
        let state_hash = make_unit_state(UnitId::FU, 0).perspectival_state_hash();

        let entry = chain.commit_genesis(state_hash, TEST_SEED).unwrap();
        assert_eq!(entry.cycle_index, 0);
        assert_eq!(chain.len(), 1);
        assert_eq!(chain.head(), Some(entry.perspectival_hash));
    }

    #[test]
    fn genesis_hash_formula_is_correct() {
        // Verify: ℓ_u^(0) = H(S_u^(0) ‖ s₀)
        let mut chain = PerspectivalChain::new(UnitId::FU);
        let state_hash = make_unit_state(UnitId::FU, 0).perspectival_state_hash();

        let entry = chain.commit_genesis(state_hash, TEST_SEED).unwrap();

        let mut hasher = blake3::Hasher::new();
        hasher.update(&state_hash);
        hasher.update(TEST_SEED);
        let expected: [u8; 32] = *hasher.finalize().as_bytes();

        assert_eq!(entry.perspectival_hash, expected);
    }

    #[test]
    fn cannot_commit_genesis_twice() {
        let mut chain = PerspectivalChain::new(UnitId::FU);
        let state_hash = [0xAA; 32];

        chain.commit_genesis(state_hash, TEST_SEED).unwrap();
        assert!(chain.commit_genesis(state_hash, TEST_SEED).is_err());
    }

    #[test]
    fn different_seeds_produce_different_genesis_hashes() {
        let state_hash = make_unit_state(UnitId::FU, 0).perspectival_state_hash();

        let mut chain_a = PerspectivalChain::new(UnitId::FU);
        let entry_a = chain_a.commit_genesis(state_hash, b"seed-alpha").unwrap();

        let mut chain_b = PerspectivalChain::new(UnitId::FU);
        let entry_b = chain_b.commit_genesis(state_hash, b"seed-beta").unwrap();

        assert_ne!(entry_a.perspectival_hash, entry_b.perspectival_hash);
    }

    // ── PerspectivalChain: standard commits ─────────────────────────────

    #[test]
    fn standard_commit_extends_chain() {
        let mut chain = PerspectivalChain::new(UnitId::MU);
        let s0 = make_unit_state(UnitId::MU, 0).perspectival_state_hash();
        chain.commit_genesis(s0, TEST_SEED).unwrap();

        let s1 = make_unit_state(UnitId::MU, 1).perspectival_state_hash();
        let entry = chain.commit(s1).unwrap();

        assert_eq!(entry.cycle_index, 1);
        assert_eq!(chain.len(), 2);
    }

    #[test]
    fn standard_hash_formula_is_correct() {
        // Verify: ℓ_u^(t) = H(S_u^(t) ‖ ℓ_u^(t-1))
        let mut chain = PerspectivalChain::new(UnitId::MU);
        let s0 = make_unit_state(UnitId::MU, 0).perspectival_state_hash();
        let genesis_entry = chain.commit_genesis(s0, TEST_SEED).unwrap();

        let s1 = make_unit_state(UnitId::MU, 1).perspectival_state_hash();
        let entry = chain.commit(s1).unwrap();

        let mut hasher = blake3::Hasher::new();
        hasher.update(&s1);
        hasher.update(&genesis_entry.perspectival_hash);
        let expected: [u8; 32] = *hasher.finalize().as_bytes();

        assert_eq!(entry.perspectival_hash, expected);
    }

    #[test]
    fn cannot_commit_standard_without_genesis() {
        let mut chain = PerspectivalChain::new(UnitId::FU);
        assert!(chain.commit([0xBB; 32]).is_err());
    }

    #[test]
    fn multi_cycle_chain() {
        let mut chain = PerspectivalChain::new(UnitId::HU);
        let s0 = make_unit_state(UnitId::HU, 0).perspectival_state_hash();
        chain.commit_genesis(s0, TEST_SEED).unwrap();

        for cycle in 1..=10 {
            let sh = make_unit_state(UnitId::HU, cycle).perspectival_state_hash();
            let entry = chain.commit(sh).unwrap();
            assert_eq!(entry.cycle_index, cycle);
        }

        assert_eq!(chain.len(), 11);
    }

    // ── Chain verification (Proposition 1) ──────────────────────────────

    #[test]
    fn chain_verification_succeeds_for_honest_chain() {
        let mut chain = PerspectivalChain::new(UnitId::CU);
        let s0 = make_unit_state(UnitId::CU, 0).perspectival_state_hash();
        chain.commit_genesis(s0, TEST_SEED).unwrap();

        for cycle in 1..=5 {
            let sh = make_unit_state(UnitId::CU, cycle).perspectival_state_hash();
            chain.commit(sh).unwrap();
        }

        assert!(chain.verify_chain(TEST_SEED).is_ok());
    }

    #[test]
    fn chain_verification_detects_tampered_state_hash() {
        let mut chain = PerspectivalChain::new(UnitId::OU);
        let s0 = make_unit_state(UnitId::OU, 0).perspectival_state_hash();
        chain.commit_genesis(s0, TEST_SEED).unwrap();

        for cycle in 1..=5 {
            let sh = make_unit_state(UnitId::OU, cycle).perspectival_state_hash();
            chain.commit(sh).unwrap();
        }

        // Tamper with entry at cycle 3: modify state_hash
        chain.entries[3].state_hash[0] ^= 0xFF;

        let result = chain.verify_chain(TEST_SEED);
        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 chain_verification_detects_tampered_genesis() {
        let mut chain = PerspectivalChain::new(UnitId::SU);
        let s0 = make_unit_state(UnitId::SU, 0).perspectival_state_hash();
        chain.commit_genesis(s0, TEST_SEED).unwrap();

        // Tamper with genesis state_hash
        chain.entries[0].state_hash[0] ^= 0xFF;

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

    #[test]
    fn chain_verification_detects_wrong_seed() {
        let mut chain = PerspectivalChain::new(UnitId::FU);
        let s0 = make_unit_state(UnitId::FU, 0).perspectival_state_hash();
        chain.commit_genesis(s0, TEST_SEED).unwrap();

        // Verify with a different seed
        let result = chain.verify_chain(b"wrong-seed");
        assert!(result.is_err());
    }

    #[test]
    fn empty_chain_verification_succeeds() {
        let chain = PerspectivalChain::new(UnitId::FU);
        assert!(chain.verify_chain(TEST_SEED).is_ok());
    }

    // ── Perspectival isolation (Proposition 3) ──────────────────────────

    #[test]
    fn perspectival_chains_are_independent() {
        // Proposition 3: ℓ_u^(t) depends only on unit u's state and its
        // own prior chain. Modifying unit v's chain does not affect unit u's chain.

        let mut chains: Vec<PerspectivalChain> = UnitId::ALL
            .iter()
            .map(|&u| {
                let mut chain = PerspectivalChain::new(u);
                let s0 = make_unit_state(u, 0).perspectival_state_hash();
                chain.commit_genesis(s0, TEST_SEED).unwrap();
                for cycle in 1..=3 {
                    let sh = make_unit_state(u, cycle).perspectival_state_hash();
                    chain.commit(sh).unwrap();
                }
                chain
            })
            .collect();

        // Record all heads
        let original_heads: Vec<[u8; 32]> = chains.iter().map(|c| c.head().unwrap()).collect();

        // Extend only FU's chain with one more cycle
        let extra = make_unit_state(UnitId::FU, 4).perspectival_state_hash();
        chains[0].commit(extra).unwrap();

        // FU's head changed
        assert_ne!(chains[0].head().unwrap(), original_heads[0]);

        // All other chains are unchanged
        for i in 1..6 {
            assert_eq!(
                chains[i].head().unwrap(),
                original_heads[i],
                "Chain for {:?} should not change when FU's chain is extended",
                UnitId::ALL[i]
            );
        }
    }

    // ── Cross-verification digest (Proposition 2) ───────────────────────

    #[test]
    fn cross_verification_digest_is_deterministic() {
        let hashes: [[u8; 32]; 6] =
            core::array::from_fn(|i| *blake3::hash(format!("unit-{i}").as_bytes()).as_bytes());

        let d1 = cross_verification_digest(&hashes);
        let d2 = cross_verification_digest(&hashes);
        assert_eq!(d1, d2);
    }

    #[test]
    fn cross_verification_digest_formula_is_correct() {
        // Verify: X^(t) = H(ℓ_FU ‖ ℓ_MU ‖ ℓ_CU ‖ ℓ_OU ‖ ℓ_SU ‖ ℓ_HU)
        let hashes: [[u8; 32]; 6] =
            core::array::from_fn(|i| *blake3::hash(format!("unit-{i}").as_bytes()).as_bytes());

        let digest = cross_verification_digest(&hashes);

        let mut hasher = blake3::Hasher::new();
        for h in &hashes {
            hasher.update(h);
        }
        let expected: [u8; 32] = *hasher.finalize().as_bytes();

        assert_eq!(digest, expected);
    }

    #[test]
    fn cross_verification_sensitivity_to_single_unit_change() {
        // Proposition 2: altering any single unit's perspectival hash
        // changes the cross-verification digest.
        let base_hashes: [[u8; 32]; 6] =
            core::array::from_fn(|i| *blake3::hash(format!("unit-{i}").as_bytes()).as_bytes());
        let base_digest = cross_verification_digest(&base_hashes);

        for i in 0..6 {
            let mut modified = base_hashes;
            modified[i][0] ^= 0xFF; // Flip one byte in unit i's hash
            let modified_digest = cross_verification_digest(&modified);
            assert_ne!(
                base_digest,
                modified_digest,
                "Changing unit {}'s hash must change the cross-verification digest",
                UnitId::ALL[i]
            );
        }
    }

    #[test]
    fn cross_verification_is_ring_order_sensitive() {
        // The same six hashes in a different order produce a different digest.
        let hashes: [[u8; 32]; 6] = core::array::from_fn(|i| {
            *blake3::hash(format!("distinct-unit-{i}").as_bytes()).as_bytes()
        });

        let original_digest = cross_verification_digest(&hashes);

        // Swap FU and MU hashes
        let mut swapped = hashes;
        swapped.swap(0, 1);
        let swapped_digest = cross_verification_digest(&swapped);

        assert_ne!(
            original_digest, swapped_digest,
            "Swapping unit order must change the digest (ring-order sensitivity)"
        );
    }

    #[test]
    fn cross_verification_all_single_changes_produce_distinct_digests() {
        let base_hashes: [[u8; 32]; 6] = core::array::from_fn(|i| {
            *blake3::hash(format!("base-unit-{i}").as_bytes()).as_bytes()
        });

        let mut digests = Vec::with_capacity(6);
        for i in 0..6 {
            let mut modified = base_hashes;
            modified[i][0] ^= 0xFF;
            digests.push(cross_verification_digest(&modified));
        }

        // All 6 modified digests must be distinct from each other
        let count = digests.len();
        digests.sort();
        digests.dedup();
        assert_eq!(
            digests.len(),
            count,
            "Each single-unit change must produce a distinct digest"
        );
    }

    // ── Integration: chain + cross-verification ─────────────────────────

    #[test]
    fn full_perspectival_ledger_workflow() {
        // Simulate genesis + 3 cycles for all 6 units.
        let mut chains: Vec<PerspectivalChain> = UnitId::ALL
            .iter()
            .map(|&u| PerspectivalChain::new(u))
            .collect();

        // Genesis (t = 0)
        let mut genesis_hashes = [[0u8; 32]; 6];
        for (i, &unit) in UnitId::ALL.iter().enumerate() {
            let state_hash = make_unit_state(unit, 0).perspectival_state_hash();
            let entry = chains[i].commit_genesis(state_hash, TEST_SEED).unwrap();
            genesis_hashes[i] = entry.perspectival_hash;
        }
        let genesis_xv = cross_verification_digest(&genesis_hashes);
        assert_ne!(genesis_xv, [0u8; 32]);

        // 3 standard cycles
        let mut prev_xv = genesis_xv;
        for cycle in 1..=3u64 {
            let mut cycle_hashes = [[0u8; 32]; 6];
            for (i, &unit) in UnitId::ALL.iter().enumerate() {
                let state_hash = make_unit_state(unit, cycle).perspectival_state_hash();
                let entry = chains[i].commit(state_hash).unwrap();
                cycle_hashes[i] = entry.perspectival_hash;
            }
            let xv = cross_verification_digest(&cycle_hashes);

            // Cross-verification digest changes each cycle
            assert_ne!(xv, prev_xv, "Digest must change between cycles");
            prev_xv = xv;
        }

        // All chains verify
        for chain in &chains {
            assert!(chain.verify_chain(TEST_SEED).is_ok());
        }
    }
}