vfa-tui 0.0.24

Enterprise-grade terminal UI for the Vanguard Frontier Agentic marketplace catalog
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
//! Audit logger with SHA-256 hash chain for tamper detection.
//!
//! Implements Requirement 14 (all 8 criteria):
//! - Append-only SQLite table (14.1, 14.2)
//! - JSON / CSV export (14.4)
//! - Console + schema version in meta (14.6)
//! - SHA-256 hash chain (14.8): each entry hashes the previous entry's hash
//!   with its own fields. Rows record their recipe in `hash_version`: v1
//!   (legacy) concatenates the fields without the operator; v2 length-prefixes
//!   every field and includes the operator.

use std::fmt::Write as FmtWrite;
use std::fs;
use std::path::Path;

use chrono::Utc;
use sha2::{Digest, Sha256};

use crate::error::TuiError;
use crate::models::audit::{AuditEntry, AuditEventType};
use crate::persistence::index::IndexManager;

// ---------------------------------------------------------------------------
// AuditLogger
// ---------------------------------------------------------------------------

/// Append-only audit logger backed by an in-process `IndexManager`.
///
/// Maintains `last_hash` so each call to [`AuditLogger::log`] automatically
/// threads the chain without additional DB round-trips.
/// Hash-recipe marker stored in `audit_log.hash_version`.
///
/// Rows predating schema version 5 carry `1` (operator not hashed); rows this
/// build writes carry `2`, binding the operator into the chain.
pub const HASH_VERSION_WITH_OPERATOR: i64 = 2;

pub struct AuditLogger<'a> {
    mgr: &'a IndexManager,
    /// Hash of the most-recently appended entry, or `""` for the first entry.
    last_hash: String,
}

impl<'a> AuditLogger<'a> {
    // -----------------------------------------------------------------------
    // Constructors
    // -----------------------------------------------------------------------

    /// Create a logger that will append to the database owned by `mgr`.
    ///
    /// `last_hash` should be the `entry_hash` of the last row already in the
    /// table (pass `""` for a fresh database).
    pub fn new(mgr: &'a IndexManager, last_hash: String) -> Self {
        Self { mgr, last_hash }
    }

    /// Initialise from a manager: reads the last `entry_hash` from the table
    /// so the chain is correct even if entries already exist.
    pub fn from_manager(mgr: &'a IndexManager) -> Result<Self, TuiError> {
        let last_hash: String = mgr
            .write_conn()
            .query_row(
                "SELECT entry_hash FROM audit_log ORDER BY id DESC LIMIT 1",
                [],
                |row| row.get(0),
            )
            .unwrap_or_default();
        Ok(Self { mgr, last_hash })
    }

    // -----------------------------------------------------------------------
    // Logging
    // -----------------------------------------------------------------------

    /// Append one entry to the audit log.
    ///
    /// Computes the hash chain link automatically and stores both
    /// `entry_hash` and `prev_hash` in the database row.
    /// Returns the fully-populated [`AuditEntry`] (id assigned by SQLite).
    pub fn log(
        &mut self,
        event_type: AuditEventType,
        subject: &str,
        details: serde_json::Value,
        operator: &str,
    ) -> Result<AuditEntry, TuiError> {
        let timestamp = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();
        let details_json = serde_json::to_string(&details).unwrap_or_else(|_| "{}".to_string());

        let entry_hash = Self::compute_hash_v2(
            &self.last_hash,
            &timestamp,
            &event_type,
            subject,
            &details_json,
            operator,
        );

        let event_type_str = serde_json::to_string(&event_type)
            .unwrap_or_default()
            .trim_matches('"')
            .to_string();

        let conn = self.mgr.write_conn();
        conn.execute(
            "INSERT INTO audit_log \
             (timestamp, event_type, subject, details, operator, entry_hash, prev_hash, \
              hash_version) \
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
            rusqlite::params![
                timestamp,
                event_type_str,
                subject,
                details_json,
                operator,
                entry_hash,
                self.last_hash,
                HASH_VERSION_WITH_OPERATOR,
            ],
        )?;

        let id = conn.last_insert_rowid();
        let prev_hash = self.last_hash.clone();
        self.last_hash = entry_hash.clone();

        Ok(AuditEntry {
            id,
            timestamp,
            event_type,
            subject: subject.to_string(),
            details,
            operator: operator.to_string(),
            entry_hash,
            prev_hash,
        })
    }

    // -----------------------------------------------------------------------
    // Hash chain
    // -----------------------------------------------------------------------

    /// Compute the **v1 (legacy)** entry hash:
    /// `SHA256(prev_hash || timestamp || event_type_str || subject || details_json)`.
    ///
    /// This recipe leaves `operator` unauthenticated.  It is retained only so
    /// rows written before schema version 5 keep verifying; new entries use
    /// [`compute_hash_v2`](Self::compute_hash_v2).
    pub fn compute_hash(
        prev_hash: &str,
        timestamp: &str,
        event_type: &AuditEventType,
        subject: &str,
        details_json: &str,
    ) -> String {
        let event_str = serde_json::to_string(event_type)
            .unwrap_or_default()
            .trim_matches('"')
            .to_string();

        let mut hasher = Sha256::new();
        hasher.update(prev_hash.as_bytes());
        hasher.update(timestamp.as_bytes());
        hasher.update(event_str.as_bytes());
        hasher.update(subject.as_bytes());
        hasher.update(details_json.as_bytes());

        let result = hasher.finalize();
        result.iter().fold(String::new(), |mut s, b| {
            let _ = write!(s, "{b:02x}");
            s
        })
    }

    /// Compute the **v2** entry hash, binding the acting operator into the
    /// chain. Each of `prev`, `timestamp`, `event_type`, `subject`, `details`
    /// and `operator` is fed to SHA-256 as an 8-byte big-endian length followed
    /// by its bytes.
    ///
    /// Without the operator field the stored actor on an entry could be
    /// rewritten without breaking the chain, so the chain could not attest *who*
    /// performed a recorded action. Without the length prefixes, bytes could
    /// move across a field boundary: `details = "1", operator = "23"` and
    /// `details = "12", operator = "3"` would hash identically, so an edit to
    /// the database could change both the details and the actor of a row
    /// without breaking the chain.
    pub fn compute_hash_v2(
        prev_hash: &str,
        timestamp: &str,
        event_type: &AuditEventType,
        subject: &str,
        details_json: &str,
        operator: &str,
    ) -> String {
        let event_str = serde_json::to_string(event_type)
            .unwrap_or_default()
            .trim_matches('"')
            .to_string();

        let mut hasher = Sha256::new();
        for field in [
            prev_hash,
            timestamp,
            event_str.as_str(),
            subject,
            details_json,
            operator,
        ] {
            hasher.update((field.len() as u64).to_be_bytes());
            hasher.update(field.as_bytes());
        }

        let result = hasher.finalize();
        result.iter().fold(String::new(), |mut s, b| {
            let _ = write!(s, "{b:02x}");
            s
        })
    }

    // -----------------------------------------------------------------------
    // Chain verification (Req 14.8)
    // -----------------------------------------------------------------------

    /// Walk every entry in insertion order and recompute each `entry_hash`.
    ///
    /// Returns `Ok(())` if the chain is intact, or
    /// `Err(TuiError::AuditChainBroken { entry_id })` at the first mismatch.
    pub fn verify_chain(&self) -> Result<(), TuiError> {
        let conn = self.mgr.write_conn();
        let mut stmt = conn.prepare(
            "SELECT id, timestamp, event_type, subject, details, operator, \
                    entry_hash, prev_hash, hash_version \
             FROM audit_log ORDER BY id ASC",
        )?;

        let mut expected_prev = String::new();

        let rows = stmt.query_map([], |row| {
            Ok((
                row.get::<_, i64>(0)?,    // id
                row.get::<_, String>(1)?, // timestamp
                row.get::<_, String>(2)?, // event_type
                row.get::<_, String>(3)?, // subject
                row.get::<_, String>(4)?, // details
                row.get::<_, String>(5)?, // operator
                row.get::<_, String>(6)?, // entry_hash
                row.get::<_, String>(7)?, // prev_hash
                row.get::<_, i64>(8)?,    // hash_version
            ))
        })?;

        for row_result in rows {
            let (
                id,
                timestamp,
                event_type_str,
                subject,
                details_json,
                operator,
                stored_hash,
                stored_prev,
                hash_version,
            ) = row_result?;

            // prev_hash in the row must match what we expect.
            if stored_prev != expected_prev {
                return Err(TuiError::AuditChainBroken { entry_id: id });
            }

            // Recompute entry_hash from stored fields.
            let event_type: AuditEventType = serde_json::from_str(&format!("\"{event_type_str}\""))
                .map_err(|_| TuiError::AuditChainBroken { entry_id: id })?;

            // Dispatch on the recipe that produced the row so pre-migration
            // entries keep verifying while new ones authenticate the operator.
            let recomputed = if hash_version >= HASH_VERSION_WITH_OPERATOR {
                Self::compute_hash_v2(
                    &expected_prev,
                    &timestamp,
                    &event_type,
                    &subject,
                    &details_json,
                    &operator,
                )
            } else {
                Self::compute_hash(
                    &expected_prev,
                    &timestamp,
                    &event_type,
                    &subject,
                    &details_json,
                )
            };

            if recomputed != stored_hash {
                return Err(TuiError::AuditChainBroken { entry_id: id });
            }

            expected_prev = stored_hash;
        }

        Ok(())
    }

    // -----------------------------------------------------------------------
    // Export (Req 14.4)
    // -----------------------------------------------------------------------

    /// Export the audit log to `out_path` in `format` (`"json"` or `"csv"`).
    ///
    /// `hash_version` is exported alongside every row. Two hash recipes are in
    /// circulation (v1 leaves `operator` unauthenticated, v2 binds it), so
    /// without the marker an auditor holding only the export cannot know which
    /// recipe to recompute and the artifact is not independently verifiable.
    pub fn export_audit(&self, format: &str, out_path: &Path) -> Result<(), TuiError> {
        let conn = self.mgr.write_conn();
        let mut stmt = conn.prepare(
            "SELECT id, timestamp, event_type, subject, details, operator, \
                    entry_hash, prev_hash, hash_version \
             FROM audit_log ORDER BY id ASC",
        )?;

        match format {
            "json" => {
                let rows: Vec<serde_json::Value> = stmt
                    .query_map([], |row| {
                        let details_str: String = row.get(4)?;
                        Ok(serde_json::json!({
                            "id":         row.get::<_, i64>(0)?,
                            "timestamp":  row.get::<_, String>(1)?,
                            "event_type": row.get::<_, String>(2)?,
                            "subject":    row.get::<_, String>(3)?,
                            "details":    details_str,
                            "operator":   row.get::<_, String>(5)?,
                            "entry_hash": row.get::<_, String>(6)?,
                            "prev_hash":  row.get::<_, String>(7)?,
                            "hash_version": row.get::<_, i64>(8)?,
                        }))
                    })?
                    .filter_map(|r| r.ok())
                    .collect();

                let json = serde_json::to_string_pretty(&rows).map_err(|e| {
                    TuiError::PersistenceQuery {
                        detail: e.to_string(),
                    }
                })?;
                fs::write(out_path, json).map_err(|e| TuiError::LogDestination {
                    path: out_path.display().to_string(),
                    reason: e.to_string(),
                })
            }

            "csv" => {
                let mut csv = String::from(
                    "id,timestamp,event_type,subject,details,operator,entry_hash,prev_hash,\
                     hash_version\n",
                );
                let rows: Vec<_> = stmt
                    .query_map([], |row| {
                        Ok((
                            row.get::<_, i64>(0)?,
                            row.get::<_, String>(1)?,
                            row.get::<_, String>(2)?,
                            row.get::<_, String>(3)?,
                            row.get::<_, String>(4)?,
                            row.get::<_, String>(5)?,
                            row.get::<_, String>(6)?,
                            row.get::<_, String>(7)?,
                            row.get::<_, i64>(8)?,
                        ))
                    })?
                    .filter_map(|r| r.ok())
                    .collect();

                for (id, ts, et, subj, det, op, eh, ph, hv) in rows {
                    let _ = writeln!(
                        csv,
                        "{id},{ts},{et},{},{},{},{eh},{ph},{hv}",
                        escape_csv(&subj),
                        escape_csv(&det),
                        escape_csv(&op),
                    );
                }

                fs::write(out_path, csv).map_err(|e| TuiError::LogDestination {
                    path: out_path.display().to_string(),
                    reason: e.to_string(),
                })
            }

            other => Err(TuiError::ConfigInvalid {
                flag: "--export-audit".to_string(),
                detail: format!("unknown format '{other}'; expected 'json' or 'csv'"),
            }),
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Minimal CSV field escape: wrap in double-quotes if the value contains
/// a comma, double-quote, or newline.
fn escape_csv(s: &str) -> String {
    if s.contains(',') || s.contains('"') || s.contains('\n') {
        format!("\"{}\"", s.replace('"', "\"\""))
    } else {
        s.to_string()
    }
}

// ---------------------------------------------------------------------------
// Record console version in meta (Req 14.6)
// ---------------------------------------------------------------------------

/// Store the Console version and schema version in `schema_meta`.
///
/// Called once during startup so audit exports can include version context.
pub fn record_version_meta(mgr: &IndexManager, console_version: &str) -> Result<(), TuiError> {
    let conn = mgr.write_conn();
    conn.execute(
        "INSERT OR REPLACE INTO schema_meta (key, value) VALUES ('console_version', ?1)",
        rusqlite::params![console_version],
    )?;
    conn.execute(
        "INSERT OR REPLACE INTO schema_meta (key, value) \
         VALUES ('schema_version', ?1)",
        rusqlite::params![mgr.schema_version.to_string()],
    )?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::audit::AuditEventType;
    use crate::persistence::index::IndexManager;

    fn fresh_logger() -> (IndexManager,) {
        let mgr = IndexManager::open_in_memory().expect("open_in_memory");
        (mgr,)
    }

    // -----------------------------------------------------------------------
    // Basic logging
    // -----------------------------------------------------------------------

    #[test]
    fn log_first_entry_has_empty_prev_hash() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        let entry = logger
            .log(
                AuditEventType::PolicyEvaluation,
                "ws-a",
                serde_json::json!({"passed": true}),
                "system",
            )
            .expect("log");
        assert_eq!(entry.prev_hash, "");
        assert!(!entry.entry_hash.is_empty());
        assert_eq!(entry.id, 1);
    }

    #[test]
    fn log_second_entry_chains_to_first() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());

        let e1 = logger
            .log(
                AuditEventType::Promotion,
                "asset-1",
                serde_json::json!({}),
                "system",
            )
            .expect("log e1");
        let e2 = logger
            .log(
                AuditEventType::GateExecution,
                "gate-lint",
                serde_json::json!({}),
                "system",
            )
            .expect("log e2");

        assert_eq!(e2.prev_hash, e1.entry_hash, "chain must link");
    }

    // -----------------------------------------------------------------------
    // Append-only enforcement (Req 14.2)
    // -----------------------------------------------------------------------

    #[test]
    fn update_on_audit_log_rejected() {
        let mgr = IndexManager::open_in_memory().expect("open_in_memory");
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::DriftDetected,
                "ws",
                serde_json::json!({}),
                "system",
            )
            .expect("log");

        let result = mgr
            .write_conn()
            .execute("UPDATE audit_log SET subject = 'tampered' WHERE id = 1", []);
        assert!(result.is_err(), "UPDATE should be rejected by trigger");
    }

    #[test]
    fn delete_on_audit_log_rejected() {
        let mgr = IndexManager::open_in_memory().expect("open_in_memory");
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::OperatorAction,
                "ws",
                serde_json::json!({}),
                "operator",
            )
            .expect("log");

        let result = mgr
            .write_conn()
            .execute("DELETE FROM audit_log WHERE id = 1", []);
        assert!(result.is_err(), "DELETE should be rejected by trigger");
    }

    // -----------------------------------------------------------------------
    // Hash chain verification
    // -----------------------------------------------------------------------

    #[test]
    fn verify_chain_empty_db_ok() {
        let (mgr,) = fresh_logger();
        let logger = AuditLogger::new(&mgr, String::new());
        logger.verify_chain().expect("empty chain should be valid");
    }

    #[test]
    fn verify_chain_single_entry_ok() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::ConfigChange,
                "cfg",
                serde_json::json!({}),
                "system",
            )
            .expect("log");
        logger.verify_chain().expect("single-entry chain valid");
    }

    #[test]
    fn verify_chain_multiple_entries_ok() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        for i in 0..5 {
            logger
                .log(
                    AuditEventType::GateExecution,
                    &format!("gate-{i}"),
                    serde_json::json!({"i": i}),
                    "system",
                )
                .expect("log");
        }
        logger.verify_chain().expect("multi-entry chain valid");
    }

    #[test]
    fn verify_chain_detects_tamper() {
        // Build a two-entry chain correctly via the logger so both entries
        // have real, consistent hashes.
        let mgr = IndexManager::open_in_memory().expect("open_in_memory");
        let mut logger = AuditLogger::new(&mgr, String::new());
        let _e1 = logger
            .log(
                AuditEventType::PolicyEvaluation,
                "ws-0",
                serde_json::json!({}),
                "system",
            )
            .expect("log e1");
        let _e2 = logger
            .log(
                AuditEventType::PolicyEvaluation,
                "ws-1",
                serde_json::json!({}),
                "system",
            )
            .expect("log e2");

        // Append a third entry whose prev_hash is intentionally wrong.
        // Since UPDATE/DELETE are blocked by the trigger, we INSERT the broken
        // row directly — INSERT is not restricted.
        mgr.write_conn()
            .execute(
                "INSERT INTO audit_log \
                 (timestamp, event_type, subject, details, operator, entry_hash, prev_hash) \
                 VALUES ('2025-01-01T00:00:02.000Z', 'policy_evaluation', 'ws-2', '{}', \
                         'system', 'any_hash', 'WRONG_PREV_HASH_INTENTIONALLY')",
                [],
            )
            .expect("insert broken entry");

        // verify_chain must detect the break at entry id 3.
        let err = logger
            .verify_chain()
            .expect_err("should detect chain break");
        match err {
            TuiError::AuditChainBroken { entry_id } => {
                assert_eq!(entry_id, 3, "should flag entry 3 (the tampered row)");
            }
            other => panic!("expected AuditChainBroken, got {other:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // compute_hash determinism
    // -----------------------------------------------------------------------

    #[test]
    fn compute_hash_is_deterministic() {
        let h1 = AuditLogger::compute_hash(
            "",
            "2025-01-01T00:00:00.000Z",
            &AuditEventType::PolicyEvaluation,
            "ws",
            "{}",
        );
        let h2 = AuditLogger::compute_hash(
            "",
            "2025-01-01T00:00:00.000Z",
            &AuditEventType::PolicyEvaluation,
            "ws",
            "{}",
        );
        assert_eq!(h1, h2, "same inputs must yield same hash");
    }

    #[test]
    fn compute_hash_v2_frames_each_field() {
        // Unframed concatenation fed both of these the same bytes.
        let a = AuditLogger::compute_hash_v2("p", "ts", &AuditEventType::Promotion, "s", "1", "23");
        let b = AuditLogger::compute_hash_v2("p", "ts", &AuditEventType::Promotion, "s", "12", "3");
        assert_ne!(
            a, b,
            "a byte moved from operator to details must change the hash"
        );
    }

    #[test]
    fn verify_chain_rejects_bytes_moved_between_details_and_operator() {
        let mgr = IndexManager::open_in_memory().expect("open_in_memory");
        let mut logger = AuditLogger::new(&mgr, String::new());
        let first = logger
            .log(
                AuditEventType::Promotion,
                "ws-0",
                serde_json::json!({}),
                "system",
            )
            .expect("log first entry");

        // The hash an honest row with details "1" and operator "23" would carry,
        // attached to a forged row whose details and operator have traded a byte.
        let ts = "2025-01-01T00:00:01.000Z";
        let honest_hash = AuditLogger::compute_hash_v2(
            &first.entry_hash,
            ts,
            &AuditEventType::Promotion,
            "ws-1",
            "1",
            "23",
        );
        mgr.write_conn()
            .execute(
                "INSERT INTO audit_log \
                 (timestamp, event_type, subject, details, operator, entry_hash, prev_hash, \
                  hash_version) \
                 VALUES (?1, 'promotion', 'ws-1', '12', '3', ?2, ?3, ?4)",
                rusqlite::params![
                    ts,
                    honest_hash,
                    first.entry_hash,
                    HASH_VERSION_WITH_OPERATOR
                ],
            )
            .expect("insert forged row");

        match logger
            .verify_chain()
            .expect_err("a byte moved across the field boundary must break the chain")
        {
            TuiError::AuditChainBroken { entry_id } => assert_eq!(entry_id, 2),
            other => panic!("expected AuditChainBroken, got {other:?}"),
        }
    }

    #[test]
    fn compute_hash_changes_with_prev_hash() {
        let h1 = AuditLogger::compute_hash("prev1", "ts", &AuditEventType::Promotion, "s", "{}");
        let h2 = AuditLogger::compute_hash("prev2", "ts", &AuditEventType::Promotion, "s", "{}");
        assert_ne!(h1, h2);
    }

    // -----------------------------------------------------------------------
    // Export
    // -----------------------------------------------------------------------

    #[test]
    fn export_json_creates_file() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::Promotion,
                "asset-x",
                serde_json::json!({}),
                "headless",
            )
            .expect("log");

        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("audit.json");
        logger.export_audit("json", &out).expect("export json");

        let content = fs::read_to_string(&out).expect("read file");
        assert!(
            content.contains("promotion"),
            "JSON should contain event type"
        );
        assert!(content.contains("asset-x"), "JSON should contain subject");
    }

    #[test]
    fn export_csv_creates_file() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::DriftDetected,
                "ws-csv",
                serde_json::json!({}),
                "system",
            )
            .expect("log");

        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("audit.csv");
        logger.export_audit("csv", &out).expect("export csv");

        let content = fs::read_to_string(&out).expect("read file");
        assert!(content.starts_with("id,timestamp"), "CSV header missing");
        assert!(content.contains("drift_detected"), "CSV missing event_type");
        assert!(content.contains("ws-csv"), "CSV missing subject");
    }

    #[test]
    fn export_json_carries_hash_version() {
        // Positive probe: a row this build writes exports the v2 marker, so an
        // auditor holding only the export knows which recipe to recompute.
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::Promotion,
                "asset-hv",
                serde_json::json!({}),
                "headless",
            )
            .expect("log");

        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("audit.json");
        logger.export_audit("json", &out).expect("export json");

        let parsed: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&out).expect("read")).expect("parse");
        assert_eq!(
            parsed[0]["hash_version"],
            serde_json::json!(HASH_VERSION_WITH_OPERATOR),
            "export must publish the hash recipe marker"
        );
    }

    #[test]
    fn export_distinguishes_legacy_and_current_hash_versions() {
        // Negative probe: a legacy (v1) row must NOT be exported as v2.  If the
        // exporter hard-coded the current version the artifact would claim the
        // operator was authenticated on a row where it was not.
        let mgr = IndexManager::open_in_memory().expect("open_in_memory");
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::PolicyEvaluation,
                "ws-v2",
                serde_json::json!({}),
                "system",
            )
            .expect("log v2 row");

        // Insert a row the way a pre-migration build would: hash_version 1.
        mgr.write_conn()
            .execute(
                "INSERT INTO audit_log \
                 (timestamp, event_type, subject, details, operator, entry_hash, prev_hash, \
                  hash_version) \
                 VALUES ('2025-01-01T00:00:00.000Z', 'policy_evaluation', 'ws-v1', '{}', \
                         'legacy', 'legacy_hash', '', 1)",
                [],
            )
            .expect("insert legacy row");

        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("audit.json");
        logger.export_audit("json", &out).expect("export json");
        let parsed: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&out).expect("read")).expect("parse");

        let by_subject = |subj: &str| -> i64 {
            parsed
                .as_array()
                .expect("array")
                .iter()
                .find(|r| r["subject"] == subj)
                .unwrap_or_else(|| panic!("row {subj} missing"))["hash_version"]
                .as_i64()
                .expect("hash_version is an integer")
        };

        assert_eq!(by_subject("ws-v2"), HASH_VERSION_WITH_OPERATOR);
        assert_eq!(by_subject("ws-v1"), 1, "legacy row must not be relabelled");
    }

    #[test]
    fn export_csv_carries_hash_version() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        logger
            .log(
                AuditEventType::DriftDetected,
                "ws-csv-hv",
                serde_json::json!({}),
                "system",
            )
            .expect("log");

        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("audit.csv");
        logger.export_audit("csv", &out).expect("export csv");

        let content = fs::read_to_string(&out).expect("read file");
        let mut lines = content.lines();
        assert_eq!(
            lines.next().expect("header"),
            "id,timestamp,event_type,subject,details,operator,entry_hash,prev_hash,hash_version"
        );
        let row = lines.next().expect("one data row");
        assert!(
            row.ends_with(&format!(",{HASH_VERSION_WITH_OPERATOR}")),
            "CSV row must end with the hash version, got: {row}"
        );
    }

    #[test]
    fn export_unknown_format_returns_error() {
        let (mgr,) = fresh_logger();
        let logger = AuditLogger::new(&mgr, String::new());
        let dir = tempfile::tempdir().expect("tempdir");
        let out = dir.path().join("audit.xml");
        let err = logger.export_audit("xml", &out).expect_err("should fail");
        match err {
            TuiError::ConfigInvalid { .. } => {}
            other => panic!("expected ConfigInvalid, got {other:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // from_manager reads existing last_hash
    // -----------------------------------------------------------------------

    #[test]
    fn from_manager_reads_last_hash() {
        let (mgr,) = fresh_logger();
        let mut logger = AuditLogger::new(&mgr, String::new());
        let e1 = logger
            .log(
                AuditEventType::PolicyEvaluation,
                "ws",
                serde_json::json!({}),
                "system",
            )
            .expect("log");

        // Re-create logger from manager — should pick up e1's hash.
        let mut logger2 = AuditLogger::from_manager(&mgr).expect("from_manager");
        let e2 = logger2
            .log(
                AuditEventType::GateExecution,
                "gate",
                serde_json::json!({}),
                "system",
            )
            .expect("log e2");
        assert_eq!(e2.prev_hash, e1.entry_hash);
    }

    // -----------------------------------------------------------------------
    // record_version_meta
    // -----------------------------------------------------------------------

    #[test]
    fn record_version_meta_stores_versions() {
        let (mgr,) = fresh_logger();
        record_version_meta(&mgr, "0.2.0").expect("record_version_meta");

        let v: String = mgr
            .write_conn()
            .query_row(
                "SELECT value FROM schema_meta WHERE key = 'console_version'",
                [],
                |row| row.get(0),
            )
            .expect("query console_version");
        assert_eq!(v, "0.2.0");
    }
}