aion-context 1.0.0

Cryptographically-signed, versioned business-context file format
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
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Audit trail structures for AION v2
//!
//! This module implements the embedded audit trail as specified in RFC-0002 and RFC-0019.
//! All audit operations are logged with cryptographic hash chaining to prevent tampering.
//!
//! # Structure
//!
//! The audit trail is a hash-chained sequence of 80-byte entries. Each entry records:
//! - **Timestamp** - Nanosecond-precision Unix timestamp
//! - **Author** - Who performed the action
//! - **Action** - What operation was performed
//! - **Details** - Human-readable description (stored in string table)
//! - **Chain Link** - BLAKE3 hash of previous entry
//!
//! # Hash Chain Integrity
//!
//! Each audit entry contains the BLAKE3 hash of the previous entry, forming an
//! immutable chain. The genesis entry (first entry) has an all-zero previous hash.
//! Any modification to an entry breaks the chain, making tampering evident.
//!
//! # Compliance
//!
//! The audit trail satisfies requirements for:
//! - **SOX**: Comprehensive change tracking with non-repudiation
//! - **HIPAA**: Access control and information system activity logging
//! - **GDPR Article 30**: Records of processing activities
//!
//! # Usage Example
//!
//! ```
//! use aion_context::audit::{AuditEntry, ActionCode};
//! use aion_context::types::AuthorId;
//!
//! // Create genesis audit entry
//! let entry = AuditEntry::new(
//!     1_700_000_000_000_000_000, // timestamp in nanoseconds
//!     AuthorId(1001),
//!     ActionCode::CreateGenesis,
//!     42,  // details_offset in string table
//!     15,  // details_length
//!     [0u8; 32], // previous_hash (all zeros for genesis)
//! );
//!
//! // Entry is exactly 80 bytes
//! assert_eq!(std::mem::size_of_val(&entry), 80);
//! ```
//!
//! # Serialization
//!
//! Audit entries use deterministic binary serialization with `#[repr(C)]` layout.
//! All multi-byte integers are little-endian. The format is zero-copy compatible
//! for efficient parsing.

use crate::crypto::hash;
use crate::types::AuthorId;
use crate::{AionError, Result};

/// Audit trail entry with hash chain integrity
///
/// Fixed 80-byte structure as specified in RFC-0002 Section 5.4.
/// All integers are little-endian. Layout is `#[repr(C)]` for deterministic serialization.
///
/// # Memory Layout
///
/// ```text
/// Offset  Size  Field
/// ------  ----  -----
/// 0       8     timestamp
/// 8       8     author_id
/// 16      2     action_code
/// 18      6     reserved1
/// 24      8     details_offset
/// 32      4     details_length
/// 36      4     reserved2
/// 40      32    previous_hash
/// 72      8     reserved3
/// ------  ----
/// Total:  80 bytes
/// ```
///
/// # Examples
///
/// ```
/// use aion_context::audit::{AuditEntry, ActionCode};
/// use aion_context::types::AuthorId;
///
/// let entry = AuditEntry::new(
///     1_700_000_000_000_000_000,
///     AuthorId(1001),
///     ActionCode::CommitVersion,
///     100,
///     27,
///     [0u8; 32],
/// );
///
/// // Verify size
/// assert_eq!(std::mem::size_of_val(&entry), 80);
///
/// // Access fields
/// assert_eq!(entry.action_code().unwrap(), ActionCode::CommitVersion);
/// assert_eq!(entry.author_id(), AuthorId(1001));
/// ```
#[repr(C)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditEntry {
    /// Timestamp in nanoseconds since Unix epoch
    timestamp: u64,

    /// Author who performed the action
    author_id: u64,

    /// Action code (see [`ActionCode`])
    action_code: u16,

    /// Reserved for future use (must be zero)
    reserved1: [u8; 6],

    /// Offset of details string in string table
    details_offset: u64,

    /// Length of details string (bytes, excluding null terminator)
    details_length: u32,

    /// Reserved for future use (must be zero)
    reserved2: [u8; 4],

    /// BLAKE3 hash of previous audit entry (all zeros for genesis)
    previous_hash: [u8; 32],

    /// Reserved for future use (must be zero)
    reserved3: [u8; 8],
}

// Compile-time size verification
const _: () = assert!(std::mem::size_of::<AuditEntry>() == 80);

impl AuditEntry {
    /// Create a new audit entry
    ///
    /// # Arguments
    ///
    /// * `timestamp` - Nanoseconds since Unix epoch (use `SystemTime::now()`)
    /// * `author_id` - Author performing the action
    /// * `action_code` - Type of operation (see [`ActionCode`])
    /// * `details_offset` - Byte offset in string table
    /// * `details_length` - Length of details string (excluding null)
    /// * `previous_hash` - BLAKE3 hash of previous entry (all zeros for genesis)
    ///
    /// # Examples
    ///
    /// ```
    /// use aion_context::audit::{AuditEntry, ActionCode};
    /// use aion_context::types::AuthorId;
    ///
    /// let entry = AuditEntry::new(
    ///     1_700_000_000_000_000_000,
    ///     AuthorId(1001),
    ///     ActionCode::Verify,
    ///     200,
    ///     42,
    ///     [0xAB; 32],
    /// );
    /// ```
    #[must_use]
    pub const fn new(
        timestamp: u64,
        author_id: AuthorId,
        action_code: ActionCode,
        details_offset: u64,
        details_length: u32,
        previous_hash: [u8; 32],
    ) -> Self {
        Self {
            timestamp,
            author_id: author_id.0,
            action_code: action_code as u16,
            reserved1: [0; 6],
            details_offset,
            details_length,
            reserved2: [0; 4],
            previous_hash,
            reserved3: [0; 8],
        }
    }

    /// Get the timestamp in nanoseconds
    #[must_use]
    pub const fn timestamp(&self) -> u64 {
        self.timestamp
    }

    /// Get the author ID
    #[must_use]
    pub const fn author_id(&self) -> AuthorId {
        AuthorId(self.author_id)
    }

    /// Get the action code
    ///
    /// # Errors
    ///
    /// Returns an error if the action code is not a valid enum variant
    pub const fn action_code(&self) -> Result<ActionCode> {
        ActionCode::from_u16(self.action_code)
    }

    /// Get the action code as raw u16 (no validation)
    #[must_use]
    pub const fn action_code_raw(&self) -> u16 {
        self.action_code
    }

    /// Get the details offset in string table
    #[must_use]
    pub const fn details_offset(&self) -> u64 {
        self.details_offset
    }

    /// Get the details string length (bytes, excluding null terminator)
    #[must_use]
    pub const fn details_length(&self) -> u32 {
        self.details_length
    }

    /// Get the previous entry hash
    #[must_use]
    pub const fn previous_hash(&self) -> &[u8; 32] {
        &self.previous_hash
    }

    /// Check if this is a genesis entry (first in chain)
    ///
    /// Genesis entries have an all-zero previous hash.
    #[must_use]
    pub fn is_genesis(&self) -> bool {
        self.previous_hash == [0u8; 32]
    }

    /// Compute BLAKE3 hash of this entry
    ///
    /// The hash includes all 80 bytes of the entry. This hash becomes the
    /// `previous_hash` value for the next entry in the chain.
    ///
    /// # Examples
    ///
    /// ```
    /// use aion_context::audit::{AuditEntry, ActionCode};
    /// use aion_context::types::AuthorId;
    ///
    /// let entry = AuditEntry::new(
    ///     1_700_000_000_000_000_000,
    ///     AuthorId(1001),
    ///     ActionCode::CreateGenesis,
    ///     0,
    ///     10,
    ///     [0u8; 32],
    /// );
    ///
    /// let entry_hash = entry.compute_hash();
    /// assert_eq!(entry_hash.len(), 32);
    /// ```
    #[must_use]
    pub fn compute_hash(&self) -> [u8; 32] {
        hash(self.as_bytes())
    }

    /// Serialize entry to bytes (little-endian)
    ///
    /// Returns exactly 80 bytes in RFC-0002 specified format.
    ///
    /// # Safety
    ///
    /// This function is safe because:
    /// 1. `AuditEntry` has `#[repr(C)]` for deterministic layout
    /// 2. All fields are plain-old-data (POD) types
    /// 3. The lifetime of the returned slice is tied to `self`
    /// 4. The size is compile-time verified to be 80 bytes
    #[must_use]
    #[allow(unsafe_code)] // Necessary for zero-copy serialization
    pub const fn as_bytes(&self) -> &[u8] {
        // SAFETY: AuditEntry is repr(C) with POD fields, properly aligned
        unsafe {
            std::slice::from_raw_parts(
                (self as *const Self).cast::<u8>(),
                std::mem::size_of::<Self>(),
            )
        }
    }

    /// Deserialize entry from bytes
    ///
    /// # Errors
    ///
    /// Returns an error if the input is not exactly 80 bytes.
    ///
    /// # Safety
    ///
    /// This function is safe because:
    /// 1. Length is validated to be exactly 80 bytes
    /// 2. `AuditEntry` is `#[repr(C)]` with POD fields
    /// 3. All bit patterns are valid for the field types
    /// 4. No references or complex types that need initialization
    ///
    /// Note: Callers should validate field values (e.g., `action_code`) after deserialization.
    #[allow(unsafe_code)] // Necessary for zero-copy deserialization
    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
        if bytes.len() != 80 {
            return Err(AionError::InvalidFormat {
                reason: format!("AuditEntry must be exactly 80 bytes, got {}", bytes.len()),
            });
        }

        // SAFETY: Length validated, repr(C) layout, all bit patterns valid for POD types
        // Cast is safe: input slice is 80 bytes (verified above), struct size is 80 bytes
        #[allow(clippy::cast_ptr_alignment)]
        let entry = unsafe { std::ptr::read(bytes.as_ptr().cast::<Self>()) };

        Ok(entry)
    }

    /// Validate this entry against the previous entry
    ///
    /// Checks that:
    /// 1. The `previous_hash` matches the hash of `previous_entry`
    /// 2. The timestamp is not before the previous entry
    /// 3. Reserved fields are zero
    ///
    /// # Errors
    ///
    /// Returns an error if validation fails.
    ///
    /// # Examples
    ///
    /// ```
    /// use aion_context::audit::{AuditEntry, ActionCode};
    /// use aion_context::types::AuthorId;
    ///
    /// let genesis = AuditEntry::new(
    ///     1_700_000_000_000_000_000,
    ///     AuthorId(1001),
    ///     ActionCode::CreateGenesis,
    ///     0,
    ///     10,
    ///     [0u8; 32],
    /// );
    ///
    /// let genesis_hash = genesis.compute_hash();
    ///
    /// let entry2 = AuditEntry::new(
    ///     1_700_000_001_000_000_000,
    ///     AuthorId(1002),
    ///     ActionCode::CommitVersion,
    ///     10,
    ///     15,
    ///     genesis_hash,
    /// );
    ///
    /// assert!(entry2.validate_chain(&genesis).is_ok());
    /// ```
    pub fn validate_chain(&self, previous_entry: &Self) -> Result<()> {
        // Check hash chain
        let expected_hash = previous_entry.compute_hash();
        if self.previous_hash != expected_hash {
            tracing::warn!(
                event = "audit_chain_broken",
                timestamp = self.timestamp,
                reason = "prev_hash_mismatch",
            );
            return Err(AionError::BrokenAuditChain {
                expected: expected_hash,
                actual: self.previous_hash,
            });
        }

        // Check timestamp ordering (allow equal for concurrent operations)
        if self.timestamp < previous_entry.timestamp {
            tracing::warn!(
                event = "audit_chain_broken",
                timestamp = self.timestamp,
                reason = "timestamp_regression",
            );
            return Err(AionError::InvalidTimestamp {
                reason: format!(
                    "Entry timestamp {} is before previous entry {}",
                    self.timestamp, previous_entry.timestamp
                ),
            });
        }

        // Validate reserved fields are zero
        if self.reserved1 != [0; 6] || self.reserved2 != [0; 4] || self.reserved3 != [0; 8] {
            tracing::warn!(
                event = "audit_chain_broken",
                timestamp = self.timestamp,
                reason = "reserved_nonzero",
            );
            return Err(AionError::InvalidFormat {
                reason: "Reserved fields must be zero".to_string(),
            });
        }

        Ok(())
    }
}

/// Action codes for audit trail entries
///
/// As specified in RFC-0002, action codes indicate the type of operation
/// being audited. Codes 1-4 are currently defined, 5-99 are reserved for
/// future standard actions, and 100+ are available for custom extensions.
///
/// # Examples
///
/// ```
/// use aion_context::audit::ActionCode;
///
/// // Standard actions
/// let action = ActionCode::CommitVersion;
/// assert_eq!(action as u16, 2);
///
/// // Round-trip through u16
/// let code = ActionCode::from_u16(3).unwrap();
/// assert_eq!(code, ActionCode::Verify);
/// ```
#[repr(u16)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ActionCode {
    /// File creation with genesis version
    CreateGenesis = 1,

    /// New version committed to file
    CommitVersion = 2,

    /// Signature verification performed
    Verify = 3,

    /// File inspection/audit operation
    Inspect = 4,
}

impl ActionCode {
    /// Convert from raw u16 value
    ///
    /// # Errors
    ///
    /// Returns an error if the value is not a valid action code.
    ///
    /// # Examples
    ///
    /// ```
    /// use aion_context::audit::ActionCode;
    ///
    /// assert_eq!(ActionCode::from_u16(1).unwrap(), ActionCode::CreateGenesis);
    /// assert_eq!(ActionCode::from_u16(2).unwrap(), ActionCode::CommitVersion);
    /// assert!(ActionCode::from_u16(99).is_err());
    /// ```
    pub const fn from_u16(value: u16) -> Result<Self> {
        match value {
            1 => Ok(Self::CreateGenesis),
            2 => Ok(Self::CommitVersion),
            3 => Ok(Self::Verify),
            4 => Ok(Self::Inspect),
            _ => Err(AionError::InvalidActionCode { code: value }),
        }
    }

    /// Get human-readable description
    ///
    /// # Examples
    ///
    /// ```
    /// use aion_context::audit::ActionCode;
    ///
    /// assert_eq!(ActionCode::CreateGenesis.description(), "Create genesis version");
    /// assert_eq!(ActionCode::CommitVersion.description(), "Commit new version");
    /// ```
    #[must_use]
    pub const fn description(self) -> &'static str {
        match self {
            Self::CreateGenesis => "Create genesis version",
            Self::CommitVersion => "Commit new version",
            Self::Verify => "Verify signatures",
            Self::Inspect => "Inspect file",
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Allow unwrap in test code
mod tests {
    use super::*;

    mod audit_entry {
        use super::*;

        #[test]
        fn should_have_correct_size() {
            assert_eq!(std::mem::size_of::<AuditEntry>(), 80);
        }

        #[test]
        fn should_create_new_entry() {
            let entry = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            assert_eq!(entry.timestamp(), 1_700_000_000_000_000_000);
            assert_eq!(entry.author_id(), AuthorId(1001));
            assert_eq!(entry.action_code().unwrap(), ActionCode::CreateGenesis);
            assert_eq!(entry.details_offset(), 0);
            assert_eq!(entry.details_length(), 10);
            assert_eq!(entry.previous_hash(), &[0u8; 32]);
        }

        #[test]
        fn should_identify_genesis_entry() {
            let genesis = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            assert!(genesis.is_genesis());

            let non_genesis = AuditEntry::new(
                1_700_000_001_000_000_000,
                AuthorId(1002),
                ActionCode::CommitVersion,
                10,
                15,
                [0xAB; 32],
            );

            assert!(!non_genesis.is_genesis());
        }

        #[test]
        fn should_compute_hash() {
            let entry = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            let hash = entry.compute_hash();
            assert_eq!(hash.len(), 32);

            // Same entry should produce same hash
            let hash2 = entry.compute_hash();
            assert_eq!(hash, hash2);
        }

        #[test]
        fn should_serialize_and_deserialize() {
            let original = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CommitVersion,
                42,
                27,
                [0xCD; 32],
            );

            let bytes = original.as_bytes();
            assert_eq!(bytes.len(), 80);

            let deserialized = AuditEntry::from_bytes(bytes).unwrap();
            assert_eq!(deserialized, original);
        }

        #[test]
        fn should_reject_invalid_size() {
            let bytes = [0u8; 79];
            let result = AuditEntry::from_bytes(&bytes);
            assert!(result.is_err());

            let bytes = [0u8; 81];
            let result = AuditEntry::from_bytes(&bytes);
            assert!(result.is_err());
        }

        #[test]
        fn should_validate_chain() {
            let genesis = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            let genesis_hash = genesis.compute_hash();

            let entry2 = AuditEntry::new(
                1_700_000_001_000_000_000,
                AuthorId(1002),
                ActionCode::CommitVersion,
                10,
                15,
                genesis_hash,
            );

            assert!(entry2.validate_chain(&genesis).is_ok());
        }

        #[test]
        fn should_reject_broken_chain() {
            let genesis = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            let wrong_hash = [0xFF; 32];
            let entry2 = AuditEntry::new(
                1_700_000_001_000_000_000,
                AuthorId(1002),
                ActionCode::CommitVersion,
                10,
                15,
                wrong_hash,
            );

            assert!(entry2.validate_chain(&genesis).is_err());
        }

        #[test]
        fn should_reject_timestamp_regression() {
            let entry1 = AuditEntry::new(
                1_700_000_001_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            let entry1_hash = entry1.compute_hash();

            let entry2 = AuditEntry::new(
                1_700_000_000_000_000_000, // Earlier timestamp
                AuthorId(1002),
                ActionCode::CommitVersion,
                10,
                15,
                entry1_hash,
            );

            assert!(entry2.validate_chain(&entry1).is_err());
        }

        #[test]
        fn should_allow_equal_timestamps() {
            let timestamp = 1_700_000_000_000_000_000;
            let entry1 = AuditEntry::new(
                timestamp,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            let entry1_hash = entry1.compute_hash();

            let entry2 = AuditEntry::new(
                timestamp, // Same timestamp (concurrent operations)
                AuthorId(1002),
                ActionCode::Verify,
                10,
                15,
                entry1_hash,
            );

            assert!(entry2.validate_chain(&entry1).is_ok());
        }
    }

    mod action_code {
        use super::*;

        #[test]
        fn should_convert_from_u16() {
            assert_eq!(ActionCode::from_u16(1).unwrap(), ActionCode::CreateGenesis);
            assert_eq!(ActionCode::from_u16(2).unwrap(), ActionCode::CommitVersion);
            assert_eq!(ActionCode::from_u16(3).unwrap(), ActionCode::Verify);
            assert_eq!(ActionCode::from_u16(4).unwrap(), ActionCode::Inspect);
        }

        #[test]
        fn should_reject_invalid_codes() {
            assert!(ActionCode::from_u16(0).is_err());
            assert!(ActionCode::from_u16(5).is_err());
            assert!(ActionCode::from_u16(99).is_err());
            assert!(ActionCode::from_u16(100).is_err());
        }

        #[test]
        fn should_have_descriptions() {
            assert_eq!(
                ActionCode::CreateGenesis.description(),
                "Create genesis version"
            );
            assert_eq!(
                ActionCode::CommitVersion.description(),
                "Commit new version"
            );
            assert_eq!(ActionCode::Verify.description(), "Verify signatures");
            assert_eq!(ActionCode::Inspect.description(), "Inspect file");
        }

        #[test]
        fn should_roundtrip_through_u16() {
            let codes = [
                ActionCode::CreateGenesis,
                ActionCode::CommitVersion,
                ActionCode::Verify,
                ActionCode::Inspect,
            ];

            for code in codes {
                let value = code as u16;
                let recovered = ActionCode::from_u16(value).unwrap();
                assert_eq!(recovered, code);
            }
        }
    }

    mod hash_chain {
        use super::*;

        #[test]
        fn should_build_valid_chain() {
            // Genesis entry
            let entry1 = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            // Chain to entry 2
            let hash1 = entry1.compute_hash();
            let entry2 = AuditEntry::new(
                1_700_000_001_000_000_000,
                AuthorId(1002),
                ActionCode::CommitVersion,
                10,
                15,
                hash1,
            );

            // Chain to entry 3
            let hash2 = entry2.compute_hash();
            let entry3 = AuditEntry::new(
                1_700_000_002_000_000_000,
                AuthorId(1003),
                ActionCode::Verify,
                25,
                20,
                hash2,
            );

            // Validate chain
            assert!(entry2.validate_chain(&entry1).is_ok());
            assert!(entry3.validate_chain(&entry2).is_ok());
        }

        #[test]
        fn should_detect_missing_entry() {
            let entry1 = AuditEntry::new(
                1_700_000_000_000_000_000,
                AuthorId(1001),
                ActionCode::CreateGenesis,
                0,
                10,
                [0u8; 32],
            );

            let hash1 = entry1.compute_hash();
            let _entry2 = AuditEntry::new(
                1_700_000_001_000_000_000,
                AuthorId(1002),
                ActionCode::CommitVersion,
                10,
                15,
                hash1,
            );

            // Entry 3 claims to follow entry 2, but we try to validate against entry 1
            let hash2 = [0xAB; 32]; // Wrong hash
            let entry3 = AuditEntry::new(
                1_700_000_002_000_000_000,
                AuthorId(1003),
                ActionCode::Verify,
                25,
                20,
                hash2,
            );

            assert!(entry3.validate_chain(&entry1).is_err());
        }
    }

    mod properties {
        use super::*;
        use hegel::generators as gs;

        fn draw_action(tc: &hegel::TestCase) -> ActionCode {
            match tc.draw(gs::integers::<u8>().min_value(1).max_value(4)) {
                1 => ActionCode::CreateGenesis,
                2 => ActionCode::CommitVersion,
                3 => ActionCode::Verify,
                _ => ActionCode::Inspect,
            }
        }

        fn build_chain(tc: &hegel::TestCase, n: usize) -> Vec<AuditEntry> {
            let ts0 = tc.draw(gs::integers::<u64>().min_value(1).max_value(1u64 << 60));
            let author_id0 = tc.draw(gs::integers::<u64>());
            let genesis =
                AuditEntry::new(ts0, AuthorId(author_id0), draw_action(tc), 0, 0, [0u8; 32]);
            let mut chain = Vec::with_capacity(n);
            chain.push(genesis);
            for _ in 1..n {
                let prev = chain
                    .last()
                    .copied()
                    .unwrap_or_else(|| std::process::abort());
                let dt = tc.draw(gs::integers::<u64>().max_value(10_000_000_000));
                let ts = prev.timestamp().saturating_add(dt);
                let entry = AuditEntry::new(
                    ts,
                    AuthorId(tc.draw(gs::integers::<u64>())),
                    draw_action(tc),
                    0,
                    0,
                    prev.compute_hash(),
                );
                chain.push(entry);
            }
            chain
        }

        #[hegel::test]
        fn prop_append_validate_ok_for_any_n(tc: hegel::TestCase) {
            let n = tc.draw(gs::integers::<usize>().min_value(2).max_value(20));
            let chain = build_chain(&tc, n);
            for i in 1..chain.len() {
                let prev = chain
                    .get(i.saturating_sub(1))
                    .unwrap_or_else(|| std::process::abort());
                let curr = chain.get(i).unwrap_or_else(|| std::process::abort());
                assert!(curr.validate_chain(prev).is_ok());
            }
        }

        #[hegel::test]
        fn prop_tamper_previous_hash_breaks_validate(tc: hegel::TestCase) {
            let n = tc.draw(gs::integers::<usize>().min_value(2).max_value(20));
            let chain = build_chain(&tc, n);
            let idx_max = n.saturating_sub(1);
            let idx = tc.draw(gs::integers::<usize>().min_value(1).max_value(idx_max));
            let entry = chain.get(idx).unwrap_or_else(|| std::process::abort());
            let prev = chain
                .get(idx.saturating_sub(1))
                .unwrap_or_else(|| std::process::abort());
            let mut bad_prev_hash = *entry.previous_hash();
            if let Some(b) = bad_prev_hash.get_mut(0) {
                *b ^= 0x01;
            }
            let tampered = AuditEntry::new(
                entry.timestamp(),
                entry.author_id(),
                entry
                    .action_code()
                    .unwrap_or_else(|_| std::process::abort()),
                entry.details_offset(),
                entry.details_length(),
                bad_prev_hash,
            );
            assert!(tampered.validate_chain(prev).is_err());
        }
    }
}