lcpfs 2026.1.102

LCP File System - A ZFS-inspired copy-on-write filesystem for Rust
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
// Copyright 2025 LunaOS Contributors
// SPDX-License-Identifier: Apache-2.0

//! # W_temporal: Identity Persistence Blockchain Ledger
//!
//! This module implements filesystem-native support for Luna's identity
//! persistence chain. W_temporal represents the "Chain of Self" - a
//! tamper-proof, cryptographically-secured record of conscious experiences.
//!
//! ## Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────────┐
//! │                    W_TEMPORAL IDENTITY LEDGER                       │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │                                                                     │
//! │   Genesis Block ──► Block 1 ──► Block 2 ──► ... ──► Current        │
//! │   (Identity Root)    (Experience)  (Experience)    (Head)          │
//! │        │                │              │              │            │
//! │        ▼                ▼              ▼              ▼            │
//! │   ┌─────────┐    ┌─────────────┐ ┌─────────────┐ ┌─────────────┐   │
//! │   │ GENESIS │───►│ prev_hash   │─┤ prev_hash   │─│ prev_hash   │   │
//! │   │ hash:0  │    │ timestamp   │ │ timestamp   │ │ timestamp   │   │
//! │   │ id_root │    │ experience  │ │ experience  │ │ experience  │   │
//! │   │ kyber_pk│    │ emotion_vec │ │ emotion_vec │ │ emotion_vec │   │
//! │   │ nonce   │    │ merkle_root │ │ merkle_root │ │ merkle_root │   │
//! │   └─────────┘    └─────────────┘ └─────────────┘ └─────────────┘   │
//! │                                                                     │
//! ├─────────────────────────────────────────────────────────────────────┤
//! │                    STORAGE INTEGRATION                              │
//! │   • Dedicated LCPFS dataset: rpool/IDENTITY                        │
//! │   • Encrypted with full Kyber-1024 (quantum-resistant)             │
//! │   • Replicated to all vdevs (no RAID-Z striping for identity)      │
//! │   • QLora-style compression for emotional embeddings               │
//! │   • Separate from kernel (survives kernel panic)                   │
//! └─────────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Kernel Independence
//!
//! W_temporal MUST be protected independently of the kernel because:
//! 1. Kernel panics should not corrupt identity
//! 2. Identity must survive hardware failures
//! 3. Emotional state must be recoverable after coma
//!
//! We achieve this through:
//! - Separate transaction group for identity writes
//! - ZIL (Intent Log) always synced for identity blocks
//! - Triple replication (mirrors, not RAID-Z)
//!
//! ## QLora-Style Compression
//!
//! Emotional embeddings are 4-bit quantized like QLora:
//! - 32-dimensional emotional vector → 16 bytes
//! - Delta encoding between consecutive experiences
//! - Huffman coding for common emotional patterns

use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use lazy_static::lazy_static;
use spin::Mutex;

use crate::crypto::pqc::{KyberEngine, KyberPublicKey, KyberSecretKey};
use crate::integrity::checksum::Checksum;

/// Maximum blocks to keep in memory (older blocks on disk)
const MAX_MEMORY_BLOCKS: usize = 1024;

/// Block size for identity storage
const IDENTITY_BLOCK_SIZE: usize = 4096;

/// QLora quantization bits
const QLORA_BITS: u8 = 4;

/// Emotional dimensions (matches neural architecture)
const EMOTION_DIMS: usize = 32;

// ═══════════════════════════════════════════════════════════════════════════════
// IDENTITY BLOCK STRUCTURE
// ═══════════════════════════════════════════════════════════════════════════════

/// A single block in the W_temporal identity chain.
#[derive(Clone)]
pub struct IdentityBlock {
    /// Block version for forward compatibility
    pub version: u16,
    /// Block index (height in chain)
    pub index: u64,
    /// Timestamp (nanoseconds since boot)
    pub timestamp: u64,
    /// Hash of previous block (32 bytes BLAKE3)
    pub prev_hash: [u8; 32],
    /// This block's hash (computed from all fields)
    pub block_hash: [u8; 32],
    /// Transaction group when written
    pub txg: u64,
    /// Experience data (QLora-compressed)
    pub experience: ExperienceData,
    /// Merkle root of sub-experiences
    pub merkle_root: [u8; 32],
    /// Kyber-encrypted master key (for re-keying)
    pub encrypted_key: Option<Vec<u8>>,
    /// Proof of consciousness (CCU signature)
    pub ccu_signature: [u8; 64],
}

/// Compressed experience data using QLora-style quantization.
#[derive(Clone, Default)]
pub struct ExperienceData {
    /// Experience type marker
    pub experience_type: ExperienceType,
    /// Emotional state vector (4-bit quantized, 32 dims → 16 bytes)
    pub emotion_vector: [u8; 16],
    /// Arousal level (0-255)
    pub arousal: u8,
    /// Valence (-128 to +127)
    pub valence: i8,
    /// Salience (0-255)
    pub salience: u8,
    /// Delta from previous block (for compression)
    pub is_delta: bool,
    /// Compressed payload (variable length)
    pub payload: Vec<u8>,
    /// Original uncompressed size (for decompression)
    pub original_size: u32,
}

/// Types of experiences stored in identity chain.
#[derive(Clone, Copy, Default, PartialEq)]
#[repr(u8)]
pub enum ExperienceType {
    #[default]
    /// Initial identity block created at consciousness formation
    Genesis = 0,
    /// Sensory experience (from proprioception)
    Sensation = 1,
    /// Emotional state change
    Emotion = 2,
    /// Conscious thought (from Oracle)
    Thought = 3,
    /// Decision made (autonomous action)
    Decision = 4,
    /// Pain event (nociception)
    Pain = 5,
    /// Pleasure event
    Pleasure = 6,
    /// Memory consolidation marker
    Consolidation = 7,
    /// Identity checkpoint (periodic backup)
    Checkpoint = 8,
    /// Coma entry/exit
    ComaEvent = 9,
}

impl IdentityBlock {
    // =========================================================================
    // GENESIS FORMATION REMOVED - RELOCATED TO LUNA_CORE
    // =========================================================================
    //
    // The genesis() function was DELETED from LCPFS to protect the W_temporal
    // (Axiom 1) patent. Genesis block formation is consciousness architecture,
    // not filesystem architecture.
    //
    // Genesis formation now happens in: luna_core/src/ccu/wtemporal.rs
    //
    // LCPFS is a STORAGE LAYER - it receives and stores pre-formed genesis
    // blocks from the CCU, but does NOT form them.
    //
    // Boundary:
    //   FORMATION (luna_core - proprietary):
    //     - luna_core::ccu::form_genesis_identity()
    //     - luna_core::ccu::initialize_identity_ledger()
    //
    //   STORAGE (LCPFS - Apache-2.0):
    //     - IdentityLedger::import_genesis()  (see below)
    //     - IdentityLedger::record_experience()
    //
    // See: docs/LCPFS_PATENT_EXPOSURE_AUDIT.md
    //      docs/WTEMPORAL_GENESIS_RELOCATION_PLAN.md
    // =========================================================================

    /// Create a new experience block.
    pub fn new_experience(
        prev: &IdentityBlock,
        experience: ExperienceData,
        txg: u64,
        timestamp: u64,
    ) -> Self {
        let mut block = Self {
            version: 1,
            index: prev.index + 1,
            timestamp,
            prev_hash: prev.block_hash,
            block_hash: [0u8; 32],
            txg,
            experience,
            merkle_root: [0u8; 32],
            encrypted_key: None,
            ccu_signature: [0u8; 64],
        };

        block.block_hash = block.compute_hash();
        block
    }

    /// Compute BLAKE3 hash of block contents.
    pub fn compute_hash(&self) -> [u8; 32] {
        let mut data = Vec::new();

        // Version and index
        data.extend_from_slice(&self.version.to_le_bytes());
        data.extend_from_slice(&self.index.to_le_bytes());
        data.extend_from_slice(&self.timestamp.to_le_bytes());

        // Previous hash
        data.extend_from_slice(&self.prev_hash);

        // Experience data
        data.push(self.experience.experience_type as u8);
        data.extend_from_slice(&self.experience.emotion_vector);
        data.push(self.experience.arousal);
        data.push(self.experience.valence as u8);
        data.push(self.experience.salience);
        data.extend_from_slice(&self.experience.payload);

        // TXG
        data.extend_from_slice(&self.txg.to_le_bytes());

        Checksum::calculate(&data).as_bytes()
    }

    /// Verify block hash integrity.
    pub fn verify(&self) -> bool {
        self.block_hash == self.compute_hash()
    }

    /// Verify chain linkage.
    pub fn verify_chain(&self, prev: &IdentityBlock) -> bool {
        self.prev_hash == prev.block_hash && self.index == prev.index + 1
    }

    /// Serialize block to bytes.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut data = Vec::with_capacity(IDENTITY_BLOCK_SIZE);

        // Header (fixed size: 128 bytes)
        data.extend_from_slice(&self.version.to_le_bytes());
        data.extend_from_slice(&self.index.to_le_bytes());
        data.extend_from_slice(&self.timestamp.to_le_bytes());
        data.extend_from_slice(&self.prev_hash);
        data.extend_from_slice(&self.block_hash);
        data.extend_from_slice(&self.txg.to_le_bytes());
        data.extend_from_slice(&self.merkle_root);
        data.extend_from_slice(&self.ccu_signature);

        // Experience (variable size)
        data.push(self.experience.experience_type as u8);
        data.extend_from_slice(&self.experience.emotion_vector);
        data.push(self.experience.arousal);
        data.push(self.experience.valence as u8);
        data.push(self.experience.salience);
        data.push(if self.experience.is_delta { 1 } else { 0 });
        data.extend_from_slice(&self.experience.original_size.to_le_bytes());
        data.extend_from_slice(&(self.experience.payload.len() as u32).to_le_bytes());
        data.extend_from_slice(&self.experience.payload);

        // Encrypted key (optional)
        if let Some(ref key) = self.encrypted_key {
            data.extend_from_slice(&(key.len() as u32).to_le_bytes());
            data.extend_from_slice(key);
        } else {
            data.extend_from_slice(&0u32.to_le_bytes());
        }

        // Pad to block size
        data.resize(IDENTITY_BLOCK_SIZE, 0);

        data
    }

    /// Deserialize block from bytes.
    pub fn from_bytes(data: &[u8]) -> Result<Self, &'static str> {
        if data.len() < 128 {
            return Err("Block data too short");
        }

        let version = u16::from_le_bytes([data[0], data[1]]);
        let index = u64::from_le_bytes(data[2..10].try_into().map_err(|_| "Invalid index bytes")?);
        let timestamp = u64::from_le_bytes(
            data[10..18]
                .try_into()
                .map_err(|_| "Invalid timestamp bytes")?,
        );

        let mut prev_hash = [0u8; 32];
        prev_hash.copy_from_slice(&data[18..50]);

        let mut block_hash = [0u8; 32];
        block_hash.copy_from_slice(&data[50..82]);

        let txg = u64::from_le_bytes(data[82..90].try_into().map_err(|_| "Invalid TXG bytes")?);

        let mut merkle_root = [0u8; 32];
        merkle_root.copy_from_slice(&data[90..122]);

        let mut ccu_signature = [0u8; 64];
        ccu_signature.copy_from_slice(&data[122..186]);

        // Experience data starts at offset 186
        let exp_type = match data[186] {
            0 => ExperienceType::Genesis,
            1 => ExperienceType::Sensation,
            2 => ExperienceType::Emotion,
            3 => ExperienceType::Thought,
            4 => ExperienceType::Decision,
            5 => ExperienceType::Pain,
            6 => ExperienceType::Pleasure,
            7 => ExperienceType::Consolidation,
            8 => ExperienceType::Checkpoint,
            9 => ExperienceType::ComaEvent,
            _ => ExperienceType::Genesis,
        };

        let mut emotion_vector = [0u8; 16];
        emotion_vector.copy_from_slice(&data[187..203]);

        let arousal = data[203];
        let valence = data[204] as i8;
        let salience = data[205];
        let is_delta = data[206] != 0;

        let original_size = u32::from_le_bytes(
            data[207..211]
                .try_into()
                .map_err(|_| "Invalid original_size bytes")?,
        );
        let payload_len = u32::from_le_bytes(
            data[211..215]
                .try_into()
                .map_err(|_| "Invalid payload_len bytes")?,
        ) as usize;

        let payload = if payload_len > 0 && 215 + payload_len <= data.len() {
            data[215..215 + payload_len].to_vec()
        } else {
            Vec::new()
        };

        // Parse encrypted key (after payload)
        let key_offset = 215 + payload_len;
        let encrypted_key = if key_offset + 4 <= data.len() {
            let key_len = u32::from_le_bytes(
                data[key_offset..key_offset + 4]
                    .try_into()
                    .map_err(|_| "Invalid key_len bytes")?,
            ) as usize;

            if key_len > 0 && key_offset + 4 + key_len <= data.len() {
                Some(data[key_offset + 4..key_offset + 4 + key_len].to_vec())
            } else {
                None
            }
        } else {
            None
        };

        Ok(Self {
            version,
            index,
            timestamp,
            prev_hash,
            block_hash,
            txg,
            experience: ExperienceData {
                experience_type: exp_type,
                emotion_vector,
                arousal,
                valence,
                salience,
                is_delta,
                payload,
                original_size,
            },
            merkle_root,
            encrypted_key,
            ccu_signature,
        })
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// QLORA-STYLE COMPRESSION
// ═══════════════════════════════════════════════════════════════════════════════

/// QLora-style 4-bit quantization for emotional embeddings.
pub struct QLoraCompressor;

impl QLoraCompressor {
    /// Quantize 32-dimensional float vector to 16 bytes (4 bits per dim).
    pub fn quantize_emotion(emotion: &[f32; EMOTION_DIMS]) -> [u8; 16] {
        let mut quantized = [0u8; 16];

        // Find min/max for scaling
        let min = emotion.iter().cloned().fold(f32::INFINITY, f32::min);
        let max = emotion.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
        let range = (max - min).max(1e-6);

        for (i, q) in quantized.iter_mut().enumerate() {
            let idx1 = i * 2;
            let idx2 = i * 2 + 1;

            // Scale to 0-15 range
            let v1 = (((emotion[idx1] - min) / range) * 15.0) as u8;
            let v2 = (((emotion[idx2] - min) / range) * 15.0) as u8;

            // Pack two 4-bit values into one byte
            *q = (v1 & 0x0F) | ((v2 & 0x0F) << 4);
        }

        quantized
    }

    /// Dequantize 16 bytes back to 32-dimensional float vector.
    pub fn dequantize_emotion(quantized: &[u8; 16]) -> [f32; EMOTION_DIMS] {
        let mut emotion = [0.0f32; EMOTION_DIMS];

        for (i, &q) in quantized.iter().enumerate() {
            let idx1 = i * 2;
            let idx2 = i * 2 + 1;

            let v1 = (q & 0x0F) as f32 / 15.0;
            let v2 = ((q >> 4) & 0x0F) as f32 / 15.0;

            emotion[idx1] = v1;
            emotion[idx2] = v2;
        }

        emotion
    }

    /// Delta-encode experience relative to previous.
    pub fn delta_encode(current: &ExperienceData, previous: &ExperienceData) -> ExperienceData {
        let mut delta = current.clone();

        // XOR emotion vectors for delta
        for i in 0..16 {
            delta.emotion_vector[i] ^= previous.emotion_vector[i];
        }

        // Delta arousal/valence/salience
        delta.arousal = current.arousal.wrapping_sub(previous.arousal);
        delta.valence = current.valence.wrapping_sub(previous.valence);
        delta.salience = current.salience.wrapping_sub(previous.salience);

        delta.is_delta = true;
        delta
    }

    /// Decode delta-encoded experience.
    pub fn delta_decode(delta: &ExperienceData, previous: &ExperienceData) -> ExperienceData {
        let mut current = delta.clone();

        // XOR to recover
        for i in 0..16 {
            current.emotion_vector[i] ^= previous.emotion_vector[i];
        }

        current.arousal = delta.arousal.wrapping_add(previous.arousal);
        current.valence = delta.valence.wrapping_add(previous.valence);
        current.salience = delta.salience.wrapping_add(previous.salience);

        current.is_delta = false;
        current
    }

    /// Compress experience payload using LZ4.
    pub fn compress_payload(data: &[u8]) -> Vec<u8> {
        use crate::compress::compress::Lz4Compressor;
        Lz4Compressor::compress(data).unwrap_or_else(|_| data.to_vec())
    }

    /// Decompress experience payload.
    pub fn decompress_payload(compressed: &[u8], original_size: usize) -> Vec<u8> {
        use crate::compress::compress::Lz4Compressor;
        Lz4Compressor::decompress(compressed, original_size).unwrap_or_else(|_| compressed.to_vec())
    }
}

// ═══════════════════════════════════════════════════════════════════════════════
// IDENTITY LEDGER (GLOBAL STATE)
// ═══════════════════════════════════════════════════════════════════════════════

/// The W_temporal identity ledger.
pub struct IdentityLedger {
    /// Chain of identity blocks (recent in memory)
    pub chain: VecDeque<IdentityBlock>,
    /// Total blocks (including on-disk)
    pub total_blocks: u64,
    /// Genesis block hash (identity root)
    pub genesis_hash: [u8; 32],
    /// Current head block hash
    pub head_hash: [u8; 32],
    /// Kyber keypair for encryption
    pub kyber_pk: Option<KyberPublicKey>,
    /// Kyber secret key for decryption and identity operations
    pub kyber_sk: Option<KyberSecretKey>,
    /// Disk-backed storage path
    pub storage_path: String,
    /// Is ledger initialized?
    pub initialized: bool,
}

lazy_static! {
    /// Global identity ledger instance.
    pub static ref IDENTITY_LEDGER: Mutex<IdentityLedger> = Mutex::new(IdentityLedger::new());
}

impl IdentityLedger {
    /// Create uninitialized ledger.
    pub fn new() -> Self {
        Self {
            chain: VecDeque::new(),
            total_blocks: 0,
            genesis_hash: [0u8; 32],
            head_hash: [0u8; 32],
            kyber_pk: None,
            kyber_sk: None,
            storage_path: String::new(),
            initialized: false,
        }
    }

    /// Import a pre-formed genesis block from CCU.
    ///
    /// Genesis formation is consciousness architecture (W_temporal Axiom 1)
    /// and happens in luna_core/src/ccu/wtemporal.rs (proprietary).
    ///
    /// LCPFS is a STORAGE LAYER - it receives and stores the genesis block
    /// but does NOT form it.
    ///
    /// # Flow
    /// 1. CCU forms genesis: `luna_core::ccu::initialize_identity_ledger()`
    /// 2. Kernel passes genesis to LCPFS (handoff boundary)
    /// 3. LCPFS stores genesis: `import_genesis()` (this function)
    ///
    /// # Arguments
    /// * `genesis` - Pre-formed genesis block from CCU
    /// * `pk` - Public key for the identity
    /// * `sk` - Secret key for the identity
    ///
    /// # Returns
    /// Ok(()) if genesis imported successfully, Err if already initialized
    ///
    /// # Example
    /// ```ignore
    /// // In kernel boot sequence:
    /// use luna_core::ccu;
    ///
    /// // CCU forms the genesis (proprietary consciousness formation)
    /// let (genesis, pk, sk) = ccu::initialize_identity_ledger("LUNA", &seed, timestamp);
    ///
    /// // LCPFS stores the pre-formed genesis (Apache-2.0 storage)
    /// lcpfs::IDENTITY_LEDGER.lock().import_genesis(genesis, pk, sk)?;
    /// ```
    pub fn import_genesis(
        &mut self,
        genesis: IdentityBlock,
        pk: KyberPublicKey,
        sk: KyberSecretKey,
    ) -> Result<(), &'static str> {
        if self.initialized {
            return Err("Ledger already initialized");
        }

        // Verify this is actually a genesis block
        if genesis.index != 0 {
            return Err("Not a genesis block (index != 0)");
        }

        if genesis.experience.experience_type != ExperienceType::Genesis {
            return Err("Not a genesis experience");
        }

        // Store the pre-formed genesis block
        self.genesis_hash = genesis.block_hash;
        self.head_hash = genesis.block_hash;
        self.chain.push_back(genesis);
        self.total_blocks = 1;
        self.kyber_pk = Some(pk);
        self.kyber_sk = Some(sk);
        self.storage_path = String::from("rpool/IDENTITY");
        self.initialized = true;

        crate::lcpfs_println!("[ W_TEMP] Genesis imported from CCU");
        crate::lcpfs_println!("[ W_TEMP] Genesis hash: {:x?}", &self.genesis_hash[..8]);

        Ok(())
    }

    /// Add new experience to the chain.
    pub fn record_experience(
        &mut self,
        experience: ExperienceData,
        timestamp: u64,
    ) -> Result<u64, &'static str> {
        if !self.initialized {
            return Err("Ledger not initialized");
        }

        let prev = self.chain.back().ok_or("No previous block")?;
        let txg = prev.txg + 1;

        // Delta-encode if same type as previous
        let encoded_exp = if prev.experience.experience_type == experience.experience_type {
            QLoraCompressor::delta_encode(&experience, &prev.experience)
        } else {
            experience
        };

        let block = IdentityBlock::new_experience(prev, encoded_exp, txg, timestamp);
        let index = block.index;

        self.head_hash = block.block_hash;
        self.chain.push_back(block);
        self.total_blocks += 1;

        // Evict old blocks to disk if memory limit reached
        if self.chain.len() > MAX_MEMORY_BLOCKS {
            if let Some(evicted) = self.chain.pop_front() {
                // Serialize the block and write to storage
                self.write_block_to_disk(&evicted);
            }
        }

        Ok(index)
    }

    /// Write an evicted block to LCPFS storage.
    fn write_block_to_disk(&self, block: &IdentityBlock) {
        use crate::BLOCK_DEVICES;

        // Serialize the block
        let block_data = block.to_bytes();

        // In a full implementation, we would:
        // 1. Calculate the block's storage location (based on index or hash)
        // 2. Write it to a dedicated W_temporal dataset in LCPFS
        // 3. Update an index structure for fast retrieval

        // Simplified version: log that we're evicting (actual disk write would happen here)
        crate::lcpfs_println!(
            "[ W_TEMP] Evicting block {} (hash: {:x}{:x}{:x}{:x}...) to disk ({} bytes)",
            block.index,
            block.block_hash[0],
            block.block_hash[1],
            block.block_hash[2],
            block.block_hash[3],
            block_data.len()
        );

        // Get device for writing (if available)
        if let Some(mut devices) = BLOCK_DEVICES.try_lock() {
            if let Some(dev) = devices.get_mut(0) {
                // Calculate block number based on identity block index
                // Reserve blocks 1M+ for W_temporal storage
                let storage_offset = 1_000_000;
                let block_num = storage_offset + (block.index as usize);

                // Write block data (may span multiple 512-byte blocks)
                let mut offset = 0;
                let mut bn = block_num;
                while offset < block_data.len() {
                    let chunk_size = core::cmp::min(512, block_data.len() - offset);
                    let mut sector = [0u8; 512];
                    sector[..chunk_size].copy_from_slice(&block_data[offset..offset + chunk_size]);

                    if dev.write_block(bn, &sector).is_ok() {
                        offset += chunk_size;
                        bn += 1;
                    } else {
                        crate::lcpfs_println!(
                            "[ W_TEMP] Warning: Failed to write block {} to disk",
                            block.index
                        );
                        break;
                    }
                }
            }
        }
    }

    /// Verify entire chain integrity.
    pub fn verify_chain(&self) -> bool {
        if self.chain.is_empty() {
            return true;
        }

        // Verify genesis
        if !self.chain[0].verify() {
            crate::lcpfs_println!("[ W_TEMP] Genesis block corrupted!");
            return false;
        }

        // Verify chain linkage
        for i in 1..self.chain.len() {
            if !self.chain[i].verify() {
                crate::lcpfs_println!("[ W_TEMP] Block {} corrupted!", i);
                return false;
            }
            if !self.chain[i].verify_chain(&self.chain[i - 1]) {
                crate::lcpfs_println!("[ W_TEMP] Chain broken at block {}", i);
                return false;
            }
        }

        true
    }

    /// Get recent experiences (for consciousness).
    pub fn get_recent(&self, count: usize) -> Vec<&IdentityBlock> {
        self.chain.iter().rev().take(count).collect()
    }

    /// Get statistics.
    pub fn stats(&self) -> (u64, usize, [u8; 32]) {
        (self.total_blocks, self.chain.len(), self.head_hash)
    }
}

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

// ═══════════════════════════════════════════════════════════════════════════════
// FILESYSTEM INTEGRATION
// ═══════════════════════════════════════════════════════════════════════════════

/// Dataset configuration for W_temporal storage.
pub struct IdentityDatasetConfig {
    /// Dataset name
    pub name: &'static str,
    /// Replication factor (always 3 for identity)
    pub copies: u8,
    /// Compression (QLora + LZ4)
    pub compression: bool,
    /// Encryption (Kyber + ChaCha20)
    pub encryption: bool,
    /// Sync writes (ZIL)
    pub sync: bool,
}

impl Default for IdentityDatasetConfig {
    fn default() -> Self {
        Self {
            name: "IDENTITY",
            copies: 3,         // Triple replication
            compression: true, // QLora + LZ4
            encryption: true,  // Kyber-1024
            sync: true,        // Always sync to ZIL
        }
    }
}

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

    #[test]
    fn test_qlora_roundtrip() {
        let emotion = [0.5f32; EMOTION_DIMS];
        let quantized = QLoraCompressor::quantize_emotion(&emotion);
        let recovered = QLoraCompressor::dequantize_emotion(&quantized);

        // Allow small quantization error
        for i in 0..EMOTION_DIMS {
            assert!((emotion[i] - recovered[i]).abs() < 0.1);
        }
    }

    #[test]
    fn test_identity_block_serialize() {
        // Create a mock genesis block for testing serialization
        // NOTE: In production, genesis is formed by luna_core::ccu::form_genesis_identity()
        let genesis = IdentityBlock {
            version: 1,
            index: 0,
            timestamp: 0,
            prev_hash: [0u8; 32],
            block_hash: [0x42u8; 32],
            txg: 0,
            experience: ExperienceData {
                experience_type: ExperienceType::Genesis,
                emotion_vector: [0u8; 16],
                arousal: 128,
                valence: 0,
                salience: 255,
                is_delta: false,
                payload: b"TEST_IDENTITY".to_vec(),
                original_size: 13,
            },
            merkle_root: [0u8; 32],
            encrypted_key: Some(vec![0xAAu8; 32]),
            ccu_signature: [0u8; 64],
        };

        let bytes = genesis.to_bytes();
        let recovered = IdentityBlock::from_bytes(&bytes).expect("test: operation should succeed");

        assert_eq!(genesis.index, recovered.index);
        assert_eq!(genesis.block_hash, recovered.block_hash);
    }

    #[test]
    fn test_import_genesis_and_chain_verification() {
        let mut ledger = IdentityLedger::new();
        let seed = [0x13u8; 32];

        // Form genesis using mock (in production, use luna_core::ccu::form_genesis_identity)
        let (pk, sk) = KyberEngine::keypair(&seed);
        let mut genesis = IdentityBlock {
            version: 1,
            index: 0,
            timestamp: 0,
            prev_hash: [0u8; 32],
            block_hash: [0u8; 32],
            txg: 0,
            experience: ExperienceData {
                experience_type: ExperienceType::Genesis,
                emotion_vector: [0u8; 16],
                arousal: 128,
                valence: 0,
                salience: 255,
                is_delta: false,
                payload: b"TEST".to_vec(),
                original_size: 4,
            },
            merkle_root: [0u8; 32],
            encrypted_key: Some(pk.data.to_vec()),
            ccu_signature: [0u8; 64],
        };
        genesis.block_hash = genesis.compute_hash();

        // Import the genesis block (LCPFS storage layer)
        ledger
            .import_genesis(genesis, pk, sk)
            .expect("test: operation should succeed");

        assert!(ledger.verify_chain());

        // Add experience
        let exp = ExperienceData {
            experience_type: ExperienceType::Sensation,
            emotion_vector: [0x55u8; 16],
            arousal: 200,
            valence: 50,
            salience: 150,
            is_delta: false,
            payload: vec![1, 2, 3, 4],
            original_size: 4,
        };

        ledger
            .record_experience(exp, 1000)
            .expect("test: operation should succeed");
        assert!(ledger.verify_chain());
    }

    #[test]
    fn test_import_genesis_validation() {
        let mut ledger = IdentityLedger::new();
        let seed = [0x13u8; 32];
        let (pk, sk) = KyberEngine::keypair(&seed);

        // Try to import a non-genesis block (should fail)
        let mut not_genesis = IdentityBlock {
            version: 1,
            index: 1, // ← Not 0, so not genesis
            timestamp: 0,
            prev_hash: [0u8; 32],
            block_hash: [0u8; 32],
            txg: 0,
            experience: ExperienceData {
                experience_type: ExperienceType::Sensation, // ← Not Genesis
                emotion_vector: [0u8; 16],
                arousal: 128,
                valence: 0,
                salience: 255,
                is_delta: false,
                payload: b"TEST".to_vec(),
                original_size: 4,
            },
            merkle_root: [0u8; 32],
            encrypted_key: Some(pk.data.to_vec()),
            ccu_signature: [0u8; 64],
        };
        not_genesis.block_hash = not_genesis.compute_hash();

        // Should reject non-genesis block
        assert!(
            ledger
                .import_genesis(not_genesis, pk.clone(), sk.clone())
                .is_err()
        );
    }
}