oxios-kernel 1.0.1

Oxios kernel: supervisor, event bus, state store
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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
//! Tamper-evident audit trail with cryptographic hash chain.
//!
//! Provides a Merkle-chain style audit log for all kernel events.
//! Each entry is cryptographically linked to the previous entry,
//! making tampering detectable.

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU64, Ordering};

use crate::state_store::StateStore;

/// Type alias for hash digest (blake3 hex output).
pub type HashDigest = String;

/// Unique identifier for an agent (String for flexibility).
pub type AgentId = String;

// ─── Error Types ─────────────────────────────────────────────────────────────

/// Errors that can occur during audit trail operations.
#[derive(Debug, Clone)]
pub enum AuditError {
    /// Chain link broken at given sequence number.
    ChainBroken {
        /// Sequence number where the chain broke.
        seq: u64,
        /// Expected hash value.
        expected: String,
        /// Actual hash value found.
        found: String,
    },
    /// Invalid timestamp detected.
    InvalidTimestamp {
        /// Sequence number with the bad timestamp.
        seq: u64,
    },
    /// Failed to export audit log.
    ExportFailed(String),
}

impl std::fmt::Display for AuditError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            AuditError::ChainBroken {
                seq,
                expected,
                found,
            } => {
                write!(
                    f,
                    "chain broken at seq {seq}: expected hash '{expected}', found '{found}'"
                )
            }
            AuditError::InvalidTimestamp { seq } => {
                write!(f, "invalid timestamp at seq {seq}")
            }
            AuditError::ExportFailed(msg) => {
                write!(f, "export failed: {msg}")
            }
        }
    }
}

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

// ─── Audit Action ─────────────────────────────────────────────────────────────

/// Types of actions that can be audited.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "type", content = "data")]
pub enum AuditAction {
    /// Agent spawned with task type.
    AgentSpawn {
        /// Type of task the agent was spawned for.
        task_type: String,
    },
    /// Agent exited with reason.
    AgentExit {
        /// Reason for agent exit.
        reason: String,
    },
    /// Tool was called.
    ToolCall {
        /// Name of the tool invoked.
        tool: String,
        /// JSON-encoded arguments passed to the tool.
        args_json: String,
    },
    /// Tool returned a result.
    ToolResult {
        /// Name of the tool that produced the result.
        tool: String,
        /// Whether the tool call succeeded.
        success: bool,
    },
    /// Memory entry written.
    MemoryWrite {
        /// ID of the written memory entry.
        entry_id: String,
    },
    /// Memory entry read.
    MemoryRead {
        /// ID of the read memory entry.
        entry_id: String,
    },
    /// Configuration changed.
    ConfigChange {
        /// Configuration key that changed.
        key: String,
    },
    /// Program installed.
    ProgramInstall {
        /// Name of the installed program.
        program: String,
        /// Version of the installed program.
        version: String,
    },
    /// Cron job triggered.
    CronTrigger {
        /// ID of the triggered cron job.
        job_id: String,
    },
    /// Git commit created.
    GitCommit {
        /// Commit message.
        message: String,
    },
    /// Access was denied.
    AccessDenied {
        /// Permission that was denied.
        permission: String,
    },
    /// Other/unclassified action.
    Other {
        /// Free-form detail string.
        detail: String,
    },
}

// ─── Audit Entry ─────────────────────────────────────────────────────────────

/// A single entry in the audit trail.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    /// Sequential entry number.
    pub seq: u64,
    /// Timestamp of the entry.
    pub timestamp: DateTime<Utc>,
    /// Agent ID that performed the action.
    pub actor: AgentId,
    /// The action that was performed.
    pub action: AuditAction,
    /// Resource affected by the action.
    pub resource: String,
    /// Hash of the previous entry (empty string for genesis).
    pub prev_hash: HashDigest,
    /// Hash of this entry.
    pub hash: HashDigest,
    /// Optional arbitrary metadata.
    pub metadata: Option<serde_json::Value>,
}

// ─── Hash Computation ──────────────────────────────────────────────────────────

/// Compute the hash for an audit entry.
/// Uses blake3 to hash all entry fields in a deterministic way.
fn compute_entry_hash(
    seq: u64,
    ts: &DateTime<Utc>,
    actor: &str,
    action: &AuditAction,
    resource: &str,
    prev: &str,
) -> HashDigest {
    use blake3::Hasher;

    let mut h = Hasher::new();
    h.update(b"oxios-audit-v1");
    h.update(&seq.to_be_bytes());
    h.update(ts.to_rfc3339().as_bytes());
    h.update(actor.as_bytes());

    // Serialize action to bytes for hashing
    let action_bytes = serde_json::to_vec(action).unwrap_or_default();
    h.update(&action_bytes);
    h.update(prev.as_bytes());
    h.update(resource.as_bytes());

    h.finalize().to_hex().to_string()
}

// ─── Audit Trail ─────────────────────────────────────────────────────────────

/// A tamper-evident audit trail with cryptographic hash chain.
///
/// Each entry is cryptographically linked to the previous entry using
/// blake3 hashing. This makes it possible to detect any tampering with
/// historical entries.
pub struct AuditTrail {
    /// All audit entries in order.
    entries: parking_lot::RwLock<Vec<AuditEntry>>,
    /// Sequence number counter for next entry.
    seq_counter: AtomicU64,
    /// Chain hasher for computing hashes (mutex for interior mutability).
    #[allow(dead_code)]
    chain_hasher: parking_lot::Mutex<blake3::Hasher>,
    /// Maximum number of entries before auto-pruning.
    max_entries: usize,
}

impl AuditTrail {
    /// Create a new audit trail.
    pub fn new(max_entries: usize) -> Self {
        Self {
            entries: parking_lot::RwLock::new(Vec::new()),
            seq_counter: AtomicU64::new(1), // Start at 1, 0 is genesis marker
            chain_hasher: parking_lot::Mutex::new(blake3::Hasher::new()),
            max_entries,
        }
    }

    /// Get the current number of entries.
    pub fn len(&self) -> usize {
        self.entries.read().len()
    }

    /// Check if the trail is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Get the last hash in the chain.
    fn last_hash(&self) -> HashDigest {
        let entries = self.entries.read();
        entries
            .last()
            .map(|e| e.hash.clone())
            .unwrap_or_else(|| "genesis".to_string())
    }

    /// Append an audit entry. Computes hash chain automatically.
    pub fn append(&self, actor: AgentId, action: AuditAction, resource: String) -> HashDigest {
        self.append_with_meta(actor, action, resource, None)
    }

    /// Append an audit entry with optional metadata.
    pub fn append_with_meta(
        &self,
        actor: AgentId,
        action: AuditAction,
        resource: String,
        metadata: Option<serde_json::Value>,
    ) -> HashDigest {
        let seq = self.seq_counter.fetch_add(1, Ordering::SeqCst);
        let timestamp = Utc::now();
        let prev_hash = self.last_hash();
        let hash = compute_entry_hash(seq, &timestamp, &actor, &action, &resource, &prev_hash);

        let entry = AuditEntry {
            seq,
            timestamp,
            actor,
            action,
            resource,
            prev_hash,
            hash,
            metadata,
        };

        let entry_hash = entry.hash.clone();

        {
            let mut entries = self.entries.write();
            entries.push(entry);

            // Auto-prune if over limit
            if entries.len() > self.max_entries {
                let excess = entries.len() - self.max_entries;
                entries.drain(0..excess);
                // Fix the chain: mark the first remaining entry as a new chain root.
                // We only update prev_hash to "pruned" — we do NOT recompute the hash.
                // Remaining entries still link to each other correctly since their
                // hashes are unchanged, so no cascade is needed. O(1) instead of O(N).
                if let Some(first) = entries.first_mut() {
                    first.prev_hash = "pruned".to_string();
                }
            }
        }

        entry_hash
    }

    /// Verify the integrity of the hash chain.
    ///
    /// The chain is valid if:
    /// - The first entry has prev_hash "genesis" or "pruned" (after auto-pruning)
    /// - Every subsequent entry's prev_hash matches the previous entry's hash
    /// - Every entry's hash can be independently recomputed
    pub fn verify(&self) -> Result<bool, AuditError> {
        let entries = self.entries.read();
        let mut prev_hash = "genesis".to_string();

        for (i, entry) in entries.iter().enumerate() {
            // Check sequence is correct
            if entry.seq == 0 {
                return Err(AuditError::ChainBroken {
                    seq: 0,
                    expected: "non-zero sequence".to_string(),
                    found: "0".to_string(),
                });
            }

            // First entry after pruning gets a free pass on prev_hash matching.
            // We also skip hash recomputation since the stored hash was computed
            // with the original prev_hash, not "pruned". We trust the stored hash.
            if i == 0 && entry.prev_hash == "pruned" {
                // Accept "pruned" as a valid starting point
                prev_hash = entry.hash.clone();
                continue;
            } else if entry.prev_hash != prev_hash {
                return Err(AuditError::ChainBroken {
                    seq: entry.seq,
                    expected: prev_hash,
                    found: entry.prev_hash.clone(),
                });
            }

            // Verify timestamp is not in the future
            let now = Utc::now();
            if entry.timestamp > now {
                return Err(AuditError::InvalidTimestamp { seq: entry.seq });
            }

            // Recompute hash and verify
            let computed = compute_entry_hash(
                entry.seq,
                &entry.timestamp,
                &entry.actor,
                &entry.action,
                &entry.resource,
                &entry.prev_hash,
            );

            if computed != entry.hash {
                return Err(AuditError::ChainBroken {
                    seq: entry.seq,
                    expected: computed,
                    found: entry.hash.clone(),
                });
            }

            prev_hash = entry.hash.clone();
        }

        Ok(true)
    }

    /// Get entries within a sequence range (inclusive).
    pub fn entries(&self, from_seq: u64, to_seq: u64) -> Vec<AuditEntry> {
        let entries = self.entries.read();
        entries
            .iter()
            .filter(|e| e.seq >= from_seq && e.seq <= to_seq)
            .cloned()
            .collect()
    }

    /// Get all entries.
    pub fn all_entries(&self) -> Vec<AuditEntry> {
        self.entries.read().clone()
    }

    /// Query entries by agent ID.
    pub fn by_agent(&self, agent_id: &str) -> Vec<AuditEntry> {
        let entries = self.entries.read();
        entries
            .iter()
            .filter(|e| e.actor == agent_id)
            .cloned()
            .collect()
    }

    /// Query entries by action type.
    pub fn by_action(&self, action: &AuditAction) -> Vec<AuditEntry> {
        let entries = self.entries.read();
        entries
            .iter()
            .filter(|e| &e.action == action)
            .cloned()
            .collect()
    }

    /// Query entries by action discriminant (for faster lookup).
    pub fn by_action_type(&self, type_name: &str) -> Vec<AuditEntry> {
        let entries = self.entries.read();
        entries
            .iter()
            .filter(|e| {
                let action_name = match &e.action {
                    AuditAction::AgentSpawn { .. } => "AgentSpawn",
                    AuditAction::AgentExit { .. } => "AgentExit",
                    AuditAction::ToolCall { .. } => "ToolCall",
                    AuditAction::ToolResult { .. } => "ToolResult",
                    AuditAction::MemoryWrite { .. } => "MemoryWrite",
                    AuditAction::MemoryRead { .. } => "MemoryRead",
                    AuditAction::ConfigChange { .. } => "ConfigChange",
                    AuditAction::ProgramInstall { .. } => "ProgramInstall",
                    AuditAction::CronTrigger { .. } => "CronTrigger",
                    AuditAction::GitCommit { .. } => "GitCommit",
                    AuditAction::AccessDenied { .. } => "AccessDenied",
                    AuditAction::Other { .. } => "Other",
                };
                action_name == type_name
            })
            .cloned()
            .collect()
    }

    /// Export entries from a sequence number as JSON.
    pub fn export_json(&self, from_seq: u64) -> Result<String, AuditError> {
        let entries = self.entries.read();
        let filtered: Vec<&AuditEntry> = entries.iter().filter(|e| e.seq >= from_seq).collect();

        serde_json::to_string_pretty(&filtered).map_err(|e| AuditError::ExportFailed(e.to_string()))
    }

    /// Export all entries as JSON.
    pub fn export_all_json(&self) -> Result<String, AuditError> {
        let entries = self.entries.read();
        serde_json::to_string_pretty(&*entries).map_err(|e| AuditError::ExportFailed(e.to_string()))
    }

    /// Flush entries to the state store for persistence.
    pub fn flush(&self, state_store: &StateStore) -> Result<(), AuditError> {
        let entries = self.entries.read();
        state_store
            .save_audit_entries(&entries)
            .map_err(|e| AuditError::ExportFailed(e.to_string()))
    }

    /// Restore previously persisted entries.
    ///
    /// Sets `seq_counter` to `max(entries.seq) + 1` so new entries
    /// don't collide with restored ones. Trims to `max_entries` if
    /// the restored set is larger, re-linking the hash chain.
    pub fn restore_from(&self, entries: Vec<AuditEntry>) {
        if entries.is_empty() {
            return;
        }

        // Advance seq_counter past the highest restored seq.
        let max_seq = entries.iter().map(|e| e.seq).max().unwrap_or(0);
        self.seq_counter.store(max_seq + 1, Ordering::SeqCst);

        let mut current = self.entries.write();
        *current = entries;

        // Trim if restored set exceeds max_entries.
        if current.len() > self.max_entries {
            let excess = current.len() - self.max_entries;
            current.drain(0..excess);

            // Mark the first remaining entry as pruned root.
            // Do NOT recompute hashes — remaining entries still link
            // to each other correctly. O(1) instead of O(N).
            if let Some(first) = current.first_mut() {
                first.prev_hash = "pruned".to_string();
            }
        }

        tracing::info!(
            restored = current.len(),
            next_seq = max_seq + 1,
            "Audit trail restored from persistence"
        );
    }
}

impl Default for AuditTrail {
    fn default() -> Self {
        Self::new(100_000)
    }
}

impl std::fmt::Debug for AuditTrail {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuditTrail")
            .field("entries", &self.len())
            .field("seq_counter", &self.seq_counter)
            .field("max_entries", &self.max_entries)
            .finish()
    }
}

// ─── StateStore Extension ─────────────────────────────────────────────────────

use anyhow::Result;

impl StateStore {
    /// Save audit entries to the state store.
    pub fn save_audit_entries(&self, entries: &[AuditEntry]) -> Result<()> {
        let path = self.audit_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let json = serde_json::to_string_pretty(entries)?;
        std::fs::write(&path, json)?;
        Ok(())
    }

    /// Load audit entries from the state store.
    pub fn load_audit_entries(&self) -> Result<Vec<AuditEntry>> {
        let path = self.audit_path();
        if !path.exists() {
            return Ok(Vec::new());
        }
        let json = std::fs::read_to_string(&path)?;
        let entries: Vec<AuditEntry> = serde_json::from_str(&json)?;
        Ok(entries)
    }

    /// Get the path to the audit trail file.
    fn audit_path(&self) -> std::path::PathBuf {
        self.base_path.join("audit").join("trail.json")
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    fn create_test_trail() -> AuditTrail {
        AuditTrail::new(1000)
    }

    #[test]
    fn test_append_generates_hash() {
        let trail = create_test_trail();
        let hash = trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        assert!(!hash.is_empty());
        assert_eq!(hash.len(), 64); // blake3 hex is 64 chars
    }

    #[test]
    fn test_append_increments_seq() {
        let trail = create_test_trail();

        let h1 = trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        let h2 = trail.append(
            "agent-002".to_string(),
            AuditAction::ToolCall {
                tool: "bash".to_string(),
                args_json: "{}".to_string(),
            },
            "/test/resource2".to_string(),
        );

        assert_ne!(h1, h2);

        let entries = trail.all_entries();
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].seq, 1);
        assert_eq!(entries[1].seq, 2);
    }

    #[test]
    fn test_hash_chain_linked() {
        let trail = create_test_trail();

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentExit {
                reason: "done".to_string(),
            },
            "/test/resource".to_string(),
        );

        let entries = trail.all_entries();
        assert_eq!(entries[0].prev_hash, "genesis");
        assert_eq!(entries[1].prev_hash, entries[0].hash);
    }

    #[test]
    fn test_verify_passes_clean_chain() {
        let trail = create_test_trail();

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::ToolCall {
                tool: "bash".to_string(),
                args_json: "{}".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::ToolResult {
                tool: "bash".to_string(),
                success: true,
            },
            "/test/resource".to_string(),
        );

        assert!(trail.verify().is_ok());
    }

    #[test]
    fn test_verify_detects_tampering() {
        let trail = create_test_trail();

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::ToolCall {
                tool: "bash".to_string(),
                args_json: "{}".to_string(),
            },
            "/test/resource".to_string(),
        );

        // Tamper with an entry (change actor, which changes its hash)
        {
            let mut entries = trail.entries.write();
            entries[0].actor = "hacker-001".to_string();
        }

        // Verification should fail - entry 1's stored hash no longer matches recomputed hash
        let result = trail.verify();
        assert!(result.is_err());
        match result {
            Err(AuditError::ChainBroken { seq, .. }) => {
                // First entry's stored hash doesn't match its recomputed hash after tampering
                assert_eq!(seq, 1);
            }
            _ => panic!("expected ChainBroken error"),
        }
    }

    #[test]
    fn test_verify_detects_prev_hash_tampering() {
        let trail = create_test_trail();

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::ToolCall {
                tool: "bash".to_string(),
                args_json: "{}".to_string(),
            },
            "/test/resource".to_string(),
        );

        // Tamper with prev_hash
        {
            let mut entries = trail.entries.write();
            entries[1].prev_hash = "fake-hash".to_string();
        }

        let result = trail.verify();
        assert!(result.is_err());
    }

    #[test]
    fn test_export_json_format() {
        let trail = create_test_trail();

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        let json = trail.export_json(0).unwrap();

        // Should be valid JSON
        let parsed: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.len(), 1);

        // Should have expected fields
        let entry = &parsed[0];
        assert!(entry.get("seq").is_some());
        assert!(entry.get("timestamp").is_some());
        assert!(entry.get("actor").is_some());
        assert!(entry.get("action").is_some());
        assert!(entry.get("resource").is_some());
        assert!(entry.get("prev_hash").is_some());
        assert!(entry.get("hash").is_some());
    }

    #[test]
    fn test_by_agent_query() {
        let trail = create_test_trail();

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-002".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentExit {
                reason: "done".to_string(),
            },
            "/test/resource".to_string(),
        );

        let agent_001_entries = trail.by_agent("agent-001");
        assert_eq!(agent_001_entries.len(), 2);

        let agent_002_entries = trail.by_agent("agent-002");
        assert_eq!(agent_002_entries.len(), 1);
    }

    #[test]
    fn test_by_action_query() {
        let trail = create_test_trail();

        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::ToolCall {
                tool: "bash".to_string(),
                args_json: "{}".to_string(),
            },
            "/test/resource".to_string(),
        );

        trail.append(
            "agent-001".to_string(),
            AuditAction::ToolCall {
                tool: "grep".to_string(),
                args_json: "{}".to_string(),
            },
            "/test/resource".to_string(),
        );

        let spawn_entries = trail.by_action(&AuditAction::AgentSpawn {
            task_type: "test".to_string(),
        });
        assert_eq!(spawn_entries.len(), 1);

        let tool_calls = trail.by_action_type("ToolCall");
        assert_eq!(tool_calls.len(), 2);
    }

    #[test]
    fn test_entries_range() {
        let trail = create_test_trail();

        for i in 0..10 {
            trail.append(
                "agent-001".to_string(),
                AuditAction::Other {
                    detail: format!("action-{}", i),
                },
                "/test/resource".to_string(),
            );
        }

        let range = trail.entries(3, 7);
        assert_eq!(range.len(), 5);
        assert_eq!(range[0].seq, 3);
        assert_eq!(range[4].seq, 7);
    }

    #[test]
    fn test_auto_prune() {
        let trail = AuditTrail::new(5);

        for i in 0..10 {
            trail.append(
                "agent-001".to_string(),
                AuditAction::Other {
                    detail: format!("action-{}", i),
                },
                "/test/resource".to_string(),
            );
        }

        // Should only have 5 entries (oldest pruned)
        assert_eq!(trail.len(), 5);

        let entries = trail.all_entries();
        // First entry should be seq 6 (after pruning 1-5)
        assert_eq!(entries[0].seq, 6);
        assert_eq!(entries[4].seq, 10);

        // After pruning, the chain should still be verifiable.
        assert!(trail.verify().is_ok(), "Pruned trail should still verify");
    }

    #[test]
    fn test_append_with_metadata() {
        let trail = create_test_trail();
        let metadata = serde_json::json!({
            "duration_ms": 150,
            "memory_mb": 32
        });

        let hash = trail.append_with_meta(
            "agent-001".to_string(),
            AuditAction::MemoryWrite {
                entry_id: "mem-001".to_string(),
            },
            "/memory/entries".to_string(),
            Some(metadata.clone()),
        );

        assert!(!hash.is_empty());

        let entries = trail.all_entries();
        assert!(entries[0].metadata.is_some());
        assert_eq!(entries[0].metadata.as_ref().unwrap(), &metadata);
    }

    #[test]
    fn test_genesis_hash() {
        let trail = create_test_trail();

        // First entry should have prev_hash = "genesis"
        trail.append(
            "agent-001".to_string(),
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/test/resource".to_string(),
        );

        let entries = trail.all_entries();
        assert_eq!(entries[0].prev_hash, "genesis");
    }

    #[test]
    fn test_deterministic_hash() {
        let trail1 = create_test_trail();
        let _trail2 = create_test_trail();

        let action = AuditAction::AgentSpawn {
            task_type: "test".to_string(),
        };

        trail1.append(
            "agent-001".to_string(),
            action.clone(),
            "/test/resource".to_string(),
        );

        // Same input should produce same hash
        let hash = compute_entry_hash(
            1,
            &trail1.all_entries()[0].timestamp,
            "agent-001",
            &action,
            "/test/resource",
            "genesis",
        );

        assert_eq!(hash, trail1.all_entries()[0].hash);
    }

    #[test]
    fn test_empty_trail_verify() {
        let trail = create_test_trail();
        assert!(trail.verify().is_ok());
    }

    #[test]
    fn test_all_action_types() {
        let trail = create_test_trail();

        let actions = vec![
            AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            AuditAction::AgentExit {
                reason: "done".to_string(),
            },
            AuditAction::ToolCall {
                tool: "bash".to_string(),
                args_json: "{}".to_string(),
            },
            AuditAction::ToolResult {
                tool: "bash".to_string(),
                success: true,
            },
            AuditAction::MemoryWrite {
                entry_id: "mem-001".to_string(),
            },
            AuditAction::MemoryRead {
                entry_id: "mem-001".to_string(),
            },
            AuditAction::ConfigChange {
                key: "max_agents".to_string(),
            },
            AuditAction::ProgramInstall {
                program: "test-program".to_string(),
                version: "1.0.0".to_string(),
            },
            AuditAction::CronTrigger {
                job_id: "job-001".to_string(),
            },
            AuditAction::GitCommit {
                message: "test commit".to_string(),
            },
            AuditAction::AccessDenied {
                permission: "write".to_string(),
            },
            AuditAction::Other {
                detail: "misc".to_string(),
            },
        ];

        for (i, action) in actions.into_iter().enumerate() {
            trail.append("agent-001".to_string(), action, format!("/resource/{}", i));
        }

        assert_eq!(trail.len(), 12);
        assert!(trail.verify().is_ok());
    }

    #[test]
    fn test_hash_different_for_different_inputs() {
        let ts = Utc::now();

        let hash1 = compute_entry_hash(
            1,
            &ts,
            "agent-001",
            &AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/resource",
            "genesis",
        );

        let hash2 = compute_entry_hash(
            2,
            &ts,
            "agent-001",
            &AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/resource",
            "genesis",
        );

        assert_ne!(hash1, hash2);

        let hash3 = compute_entry_hash(
            1,
            &ts,
            "agent-002",
            &AuditAction::AgentSpawn {
                task_type: "test".to_string(),
            },
            "/resource",
            "genesis",
        );

        assert_ne!(hash1, hash3);
    }

    #[test]
    fn test_restore_from_empty() {
        let trail = create_test_trail();
        trail.restore_from(Vec::new());
        assert!(trail.is_empty());
        // seq_counter should remain at 1 (default)
        assert_eq!(trail.all_entries().len(), 0);
    }

    #[test]
    fn test_restore_from_advances_seq_counter() {
        let trail = create_test_trail();

        // Simulate persisted entries with seq 1..5
        let ts = Utc::now();
        let mut entries = Vec::new();
        let mut prev = "genesis".to_string();
        for i in 1..=5 {
            let hash = compute_entry_hash(
                i,
                &ts,
                "agent-001",
                &AuditAction::Other {
                    detail: format!("action-{}", i),
                },
                "/resource",
                &prev,
            );
            entries.push(AuditEntry {
                seq: i,
                timestamp: ts,
                actor: "agent-001".to_string(),
                action: AuditAction::Other {
                    detail: format!("action-{}", i),
                },
                resource: "/resource".to_string(),
                prev_hash: prev.clone(),
                hash: hash.clone(),
                metadata: None,
            });
            prev = hash;
        }

        trail.restore_from(entries);
        assert_eq!(trail.len(), 5);

        // Next append should get seq 6
        let new_hash = trail.append(
            "agent-001".to_string(),
            AuditAction::Other {
                detail: "new".to_string(),
            },
            "/resource".to_string(),
        );
        assert!(!new_hash.is_empty());
        assert_eq!(trail.len(), 6);

        let all = trail.all_entries();
        assert_eq!(all[5].seq, 6);
    }

    #[test]
    fn test_restore_from_trims_to_max() {
        let trail = AuditTrail::new(3);

        let ts = Utc::now();
        let mut entries = Vec::new();
        let mut prev = "genesis".to_string();
        for i in 1..=5 {
            let hash = compute_entry_hash(
                i,
                &ts,
                "agent-001",
                &AuditAction::Other {
                    detail: format!("action-{}", i),
                },
                "/resource",
                &prev,
            );
            entries.push(AuditEntry {
                seq: i,
                timestamp: ts,
                actor: "agent-001".to_string(),
                action: AuditAction::Other {
                    detail: format!("action-{}", i),
                },
                resource: "/resource".to_string(),
                prev_hash: prev.clone(),
                hash: hash.clone(),
                metadata: None,
            });
            prev = hash;
        }

        trail.restore_from(entries);
        assert_eq!(trail.len(), 3);
        // Should have trimmed to last 3 (seq 3, 4, 5)
        let all = trail.all_entries();
        assert_eq!(all[0].seq, 3);
        assert_eq!(all[2].seq, 5);
        // Pruned chain should verify
        assert!(trail.verify().is_ok());
    }
}