ftui-harness 0.4.0

Test harness and reference fixtures for FrankenTUI.
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
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
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
#![forbid(unsafe_code)]

//! Golden Output Harness for deterministic testing and isomorphism proofs.
//!
//! This module provides infrastructure for:
//! - Generating golden (reference) outputs for resize scenarios
//! - Computing BLAKE3 checksums for isomorphism verification
//! - JSONL logging with stable schema for CI/debugging
//! - Deterministic mode with fixed seeds
//!
//! # JSONL Schema
//!
//! Each test case emits structured logs in JSONL format:
//!
//! ```json
//! {"event":"start","run_id":"...","case":"resize_80x24","env":{...},"seed":0,"timestamp":"..."}
//! {"event":"frame","frame_id":0,"width":80,"height":24,"checksum":"blake3:...","timing_ms":12}
//! {"event":"resize","from":"80x24","to":"120x40","timing_ms":5}
//! {"event":"frame","frame_id":1,"width":120,"height":40,"checksum":"blake3:...","timing_ms":14}
//! {"event":"complete","outcome":"pass","checksums":["blake3:...","blake3:..."],"total_ms":42}
//! ```
//!
//! # Determinism
//!
//! Set `GOLDEN_SEED` environment variable for reproducible runs:
//!
//! ```sh
//! GOLDEN_SEED=42 cargo test golden_
//! ```
//!
//! # Isomorphism Proof Template
//!
//! When a golden checksum changes, record the proof alongside the update:
//!
//! ```text
//! Change:
//!   - What changed?
//!   - Why is the new output equivalent?
//! Old checksums:
//!   - [list]
//! New checksums:
//!   - [list]
//! Preserved invariants:
//!   - Deterministic ordering
//!   - Stable tie-breaking
//!   - Seeded randomness only
//!   - Buffer dimensions/content rules
//! Justification:
//!   - Explain the equivalence and why drift is acceptable.
//! Approved by:
//!   - Name + date
//! ```

use std::fs::{self, File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use ftui_render::buffer::Buffer;

/// BLAKE3 checksum prefix for clarity in logs.
const CHECKSUM_PREFIX: &str = "blake3:";

// ============================================================================
// Checksum Computation
// ============================================================================

/// Compute BLAKE3 checksum of full buffer content (characters, colors, attributes).
///
/// Returns a hex-encoded string prefixed with "blake3:".
pub fn compute_buffer_checksum(buf: &Buffer) -> String {
    let mut hasher = blake3::Hasher::new();

    // Hash dimensions (little-endian for determinism)
    hasher.update(&buf.width().to_le_bytes());
    hasher.update(&buf.height().to_le_bytes());

    // Hash every cell: content + fg + bg + attrs (full visual state)
    for y in 0..buf.height() {
        for x in 0..buf.width() {
            if let Some(cell) = buf.get(x, y) {
                hasher.update(&cell.content.raw().to_le_bytes());
                hasher.update(&cell.fg.0.to_le_bytes());
                hasher.update(&cell.bg.0.to_le_bytes());
                hasher.update(&[cell.attrs.flags().bits()]);
                hasher.update(&cell.attrs.link_id().to_le_bytes());
            }
        }
    }

    let hash = hasher.finalize();
    format!("{CHECKSUM_PREFIX}{hash}")
}

/// Compute BLAKE3 checksum of a text string.
pub fn compute_text_checksum(text: &str) -> String {
    let hash = blake3::hash(text.as_bytes());
    format!("{CHECKSUM_PREFIX}{hash}")
}

// ============================================================================
// Environment Capture
// ============================================================================

/// Capture relevant environment for reproducibility.
#[derive(Debug, Clone)]
pub struct GoldenEnv {
    pub term: String,
    pub colorterm: String,
    pub no_color: bool,
    pub tmux: bool,
    pub screen: bool,
    pub zellij: bool,
    pub wezterm_unix_socket: bool,
    pub wezterm_pane: bool,
    pub seed: u64,
    pub rust_version: String,
    pub git_commit: String,
    pub git_branch: String,
}

impl GoldenEnv {
    /// Capture current environment.
    pub fn capture() -> Self {
        Self {
            term: std::env::var("TERM").unwrap_or_default(),
            colorterm: std::env::var("COLORTERM").unwrap_or_default(),
            no_color: std::env::var("NO_COLOR").is_ok(),
            tmux: std::env::var("TMUX").is_ok(),
            screen: std::env::var("STY").is_ok(),
            zellij: std::env::var("ZELLIJ").is_ok(),
            wezterm_unix_socket: std::env::var("WEZTERM_UNIX_SOCKET").is_ok(),
            wezterm_pane: std::env::var("WEZTERM_PANE").is_ok(),
            seed: std::env::var("GOLDEN_SEED")
                .ok()
                .and_then(|s| s.parse().ok())
                .unwrap_or(0),
            rust_version: rustc_version(),
            git_commit: git_commit(),
            git_branch: git_branch(),
        }
    }

    /// Convert to JSON string.
    pub fn to_json(&self) -> String {
        format!(
            r#"{{"term":"{}","colorterm":"{}","no_color":{},"tmux":{},"screen":{},"zellij":{},"wezterm_unix_socket":{},"wezterm_pane":{},"seed":{},"rust_version":"{}","git_commit":"{}","git_branch":"{}"}}"#,
            escape_json(&self.term),
            escape_json(&self.colorterm),
            self.no_color,
            self.tmux,
            self.screen,
            self.zellij,
            self.wezterm_unix_socket,
            self.wezterm_pane,
            self.seed,
            escape_json(&self.rust_version),
            escape_json(&self.git_commit),
            escape_json(&self.git_branch),
        )
    }
}

fn rustc_version() -> String {
    std::process::Command::new("rustc")
        .arg("--version")
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "unknown".into())
}

fn git_commit() -> String {
    std::process::Command::new("git")
        .args(["rev-parse", "HEAD"])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "unknown".into())
}

fn git_branch() -> String {
    std::process::Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_else(|| "unknown".into())
}

fn escape_json(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
        .replace('\r', "\\r")
        .replace('\t', "\\t")
}

// ============================================================================
// JSONL Logger
// ============================================================================

/// JSONL event logger for golden tests.
pub struct GoldenLogger {
    writer: Option<BufWriter<File>>,
    run_id: String,
    start_time: Instant,
    checksums: Vec<String>,
}

impl GoldenLogger {
    /// Create a new logger writing to the specified path.
    pub fn new(path: &Path) -> std::io::Result<Self> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)?;
        }
        let file = OpenOptions::new().create(true).append(true).open(path)?;
        Ok(Self {
            writer: Some(BufWriter::new(file)),
            run_id: generate_run_id(),
            start_time: Instant::now(),
            checksums: Vec::new(),
        })
    }

    /// Create a no-op logger (for when logging is disabled).
    pub fn noop() -> Self {
        Self {
            writer: None,
            run_id: generate_run_id(),
            start_time: Instant::now(),
            checksums: Vec::new(),
        }
    }

    /// Log test start event.
    pub fn log_start(&mut self, case: &str, env: &GoldenEnv) {
        let timestamp = iso_timestamp();
        self.write_line(&format!(
            r#"{{"event":"start","run_id":"{}","case":"{}","env":{},"seed":{},"timestamp":"{}"}}"#,
            self.run_id,
            escape_json(case),
            env.to_json(),
            env.seed,
            timestamp,
        ));
    }

    /// Log a frame capture with checksum.
    pub fn log_frame(
        &mut self,
        frame_id: u32,
        width: u16,
        height: u16,
        checksum: &str,
        timing_ms: u64,
    ) {
        self.checksums.push(checksum.to_string());
        self.write_line(&format!(
            r#"{{"event":"frame","run_id":"{}","frame_id":{},"width":{},"height":{},"checksum":"{}","timing_ms":{}}}"#,
            self.run_id, frame_id, width, height, escape_json(checksum), timing_ms,
        ));
    }

    /// Log a resize event.
    pub fn log_resize(&mut self, from_w: u16, from_h: u16, to_w: u16, to_h: u16, timing_ms: u64) {
        self.write_line(&format!(
            r#"{{"event":"resize","run_id":"{}","from":"{}x{}","to":"{}x{}","timing_ms":{}}}"#,
            self.run_id, from_w, from_h, to_w, to_h, timing_ms,
        ));
    }

    /// Log test completion.
    pub fn log_complete(&mut self, outcome: GoldenOutcome) {
        let total_ms = self.start_time.elapsed().as_millis() as u64;
        let checksums_json: String = self
            .checksums
            .iter()
            .map(|c| format!(r#""{}""#, escape_json(c)))
            .collect::<Vec<_>>()
            .join(",");
        self.write_line(&format!(
            r#"{{"event":"complete","run_id":"{}","outcome":"{}","checksums":[{}],"total_ms":{}}}"#,
            self.run_id,
            outcome.as_str(),
            checksums_json,
            total_ms,
        ));
    }

    /// Log an error event.
    pub fn log_error(&mut self, message: &str) {
        self.write_line(&format!(
            r#"{{"event":"error","run_id":"{}","message":"{}","timestamp":"{}"}}"#,
            self.run_id,
            escape_json(message),
            iso_timestamp(),
        ));
    }

    /// Get collected checksums.
    pub fn checksums(&self) -> &[String] {
        &self.checksums
    }

    fn write_line(&mut self, line: &str) {
        if let Some(ref mut writer) = self.writer {
            let _ = writeln!(writer, "{line}");
            let _ = writer.flush();
        }
    }
}

/// Test outcome.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GoldenOutcome {
    Pass,
    Fail,
    Skip,
}

impl GoldenOutcome {
    fn as_str(self) -> &'static str {
        match self {
            Self::Pass => "pass",
            Self::Fail => "fail",
            Self::Skip => "skip",
        }
    }
}

fn generate_run_id() -> String {
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos();
    format!("{timestamp:x}")
}

fn iso_timestamp() -> String {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    // Simple ISO-like timestamp
    format!("{now}")
}

// ============================================================================
// Golden Test Case
// ============================================================================

/// A resize scenario for golden testing.
#[derive(Debug, Clone)]
pub struct ResizeScenario {
    /// Scenario name (e.g., "80x24_to_120x40").
    pub name: String,
    /// Initial terminal width.
    pub initial_width: u16,
    /// Initial terminal height.
    pub initial_height: u16,
    /// Resize steps: (width, height, delay_ms).
    pub resize_steps: Vec<(u16, u16, u64)>,
    /// Expected checksums for verification (if known).
    pub expected_checksums: Vec<String>,
}

impl ResizeScenario {
    /// Create a simple single-size scenario (no resize).
    pub fn fixed(name: &str, width: u16, height: u16) -> Self {
        Self {
            name: name.to_string(),
            initial_width: width,
            initial_height: height,
            resize_steps: Vec::new(),
            expected_checksums: Vec::new(),
        }
    }

    /// Create a resize scenario.
    pub fn resize(name: &str, from_w: u16, from_h: u16, to_w: u16, to_h: u16) -> Self {
        Self {
            name: name.to_string(),
            initial_width: from_w,
            initial_height: from_h,
            resize_steps: vec![(to_w, to_h, 0)],
            expected_checksums: Vec::new(),
        }
    }

    /// Add expected checksums for verification.
    #[must_use]
    pub fn with_expected(mut self, checksums: Vec<String>) -> Self {
        self.expected_checksums = checksums;
        self
    }
}

/// Standard resize scenarios for testing.
pub fn standard_resize_scenarios() -> Vec<ResizeScenario> {
    vec![
        // Fixed sizes
        ResizeScenario::fixed("fixed_80x24", 80, 24),
        ResizeScenario::fixed("fixed_120x40", 120, 40),
        ResizeScenario::fixed("fixed_60x15", 60, 15),
        ResizeScenario::fixed("fixed_40x10", 40, 10),
        ResizeScenario::fixed("fixed_200x60", 200, 60),
        // Resize transitions
        ResizeScenario::resize("resize_80x24_to_120x40", 80, 24, 120, 40),
        ResizeScenario::resize("resize_120x40_to_80x24", 120, 40, 80, 24),
        ResizeScenario::resize("resize_80x24_to_40x10", 80, 24, 40, 10),
        ResizeScenario::resize("resize_40x10_to_200x60", 40, 10, 200, 60),
    ]
}

// ============================================================================
// Golden File Management
// ============================================================================

/// Path to golden checksums file for a scenario.
pub fn golden_checksum_path(base_dir: &Path, scenario_name: &str) -> PathBuf {
    base_dir
        .join("tests")
        .join("golden")
        .join(format!("{scenario_name}.checksums"))
}

/// Load expected checksums from a golden file.
pub fn load_golden_checksums(path: &Path) -> std::io::Result<Vec<String>> {
    match fs::read_to_string(path) {
        Ok(content) => Ok(content
            .lines()
            .filter(|l| !l.is_empty() && !l.starts_with('#'))
            .map(|l| l.trim().to_string())
            .collect()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
        Err(e) => Err(e),
    }
}

/// Save checksums to a golden file.
pub fn save_golden_checksums(path: &Path, checksums: &[String]) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent)?;
    }
    let content = format!(
        "# Golden checksums - do not edit manually\n# Generated at: {}\n{}\n",
        iso_timestamp(),
        checksums.join("\n")
    );
    fs::write(path, content)
}

/// Check if we should update golden files (BLESS mode).
pub fn is_bless_mode() -> bool {
    std::env::var("BLESS").is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"))
}

/// Check if golden checksums are enforced (CI or explicit env).
pub fn is_golden_enforced() -> bool {
    let explicit = std::env::var("FTUI_GOLDEN_ENFORCE")
        .is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
    let ci = std::env::var("CI").is_ok_and(|v| v == "1" || v.eq_ignore_ascii_case("true"));
    explicit || ci
}

// ============================================================================
// Golden Test Runner
// ============================================================================

/// Result of a golden test.
#[derive(Debug)]
pub struct GoldenResult {
    pub scenario: String,
    pub outcome: GoldenOutcome,
    pub checksums: Vec<String>,
    pub expected_checksums: Vec<String>,
    pub mismatch_index: Option<usize>,
    pub duration_ms: u64,
}

impl GoldenResult {
    /// Check if the result is a pass.
    pub fn is_pass(&self) -> bool {
        self.outcome == GoldenOutcome::Pass
    }

    /// Format as human-readable string.
    pub fn format(&self) -> String {
        match self.outcome {
            GoldenOutcome::Pass => format!("PASS: {} ({}ms)", self.scenario, self.duration_ms),
            GoldenOutcome::Fail => {
                if self.expected_checksums.is_empty() {
                    format!("FAIL: {} - missing golden checksums", self.scenario)
                } else if let Some(idx) = self.mismatch_index {
                    format!(
                        "FAIL: {} - checksum mismatch at frame {}\n  expected: {}\n  actual: {}",
                        self.scenario,
                        idx,
                        self.expected_checksums
                            .get(idx)
                            .unwrap_or(&"<none>".to_string()),
                        self.checksums.get(idx).unwrap_or(&"<none>".to_string()),
                    )
                } else {
                    format!("FAIL: {} - checksum count mismatch", self.scenario)
                }
            }
            GoldenOutcome::Skip => format!("SKIP: {}", self.scenario),
        }
    }
}

/// Verify checksums against expected values.
///
/// Emits a `golden.compare` tracing span with comparison metadata.
/// On mismatch, emits an ERROR-level event including both expected and actual hashes.
pub fn verify_checksums(actual: &[String], expected: &[String]) -> (GoldenOutcome, Option<usize>) {
    let span = tracing::info_span!(
        "golden.compare",
        actual_count = actual.len(),
        expected_count = expected.len(),
        outcome = tracing::field::Empty,
        mismatch_frame = tracing::field::Empty,
    );
    let _guard = span.enter();

    if expected.is_empty() {
        // No expected checksums - optionally enforce in CI
        if is_golden_enforced() {
            tracing::error!(
                actual_count = actual.len(),
                "golden checksums enforced but no expected checksums found"
            );
            span.record("outcome", "fail");
            return (GoldenOutcome::Fail, None);
        }
        span.record("outcome", "pass");
        return (GoldenOutcome::Pass, None);
    }

    if actual.len() != expected.len() {
        tracing::error!(
            actual_count = actual.len(),
            expected_count = expected.len(),
            "golden checksum count mismatch"
        );
        span.record("outcome", "fail");
        return (GoldenOutcome::Fail, None);
    }

    for (i, (a, e)) in actual.iter().zip(expected.iter()).enumerate() {
        if a != e {
            tracing::error!(
                frame = i,
                expected_hash = %e,
                actual_hash = %a,
                "golden checksum mismatch"
            );
            span.record("outcome", "fail");
            span.record("mismatch_frame", i);
            return (GoldenOutcome::Fail, Some(i));
        }
    }

    span.record("outcome", "pass");
    (GoldenOutcome::Pass, None)
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_compute_buffer_checksum_empty() {
        let buf = Buffer::new(10, 5);
        let checksum = compute_buffer_checksum(&buf);
        assert!(checksum.starts_with(CHECKSUM_PREFIX));
        // BLAKE3 hex digest is 64 chars
        assert_eq!(checksum.len(), CHECKSUM_PREFIX.len() + 64);
    }

    #[test]
    fn test_compute_buffer_checksum_deterministic() {
        let mut buf = Buffer::new(10, 5);
        buf.set(0, 0, Cell::from_char('A'));
        buf.set(1, 0, Cell::from_char('B'));

        let checksum1 = compute_buffer_checksum(&buf);
        let checksum2 = compute_buffer_checksum(&buf);
        assert_eq!(checksum1, checksum2);
    }

    #[test]
    fn test_compute_buffer_checksum_differs_on_content() {
        let mut buf1 = Buffer::new(10, 5);
        buf1.set(0, 0, Cell::from_char('A'));

        let mut buf2 = Buffer::new(10, 5);
        buf2.set(0, 0, Cell::from_char('B'));

        let checksum1 = compute_buffer_checksum(&buf1);
        let checksum2 = compute_buffer_checksum(&buf2);
        assert_ne!(checksum1, checksum2);
    }

    #[test]
    fn test_compute_buffer_checksum_differs_on_size() {
        let buf1 = Buffer::new(10, 5);
        let buf2 = Buffer::new(11, 5);

        let checksum1 = compute_buffer_checksum(&buf1);
        let checksum2 = compute_buffer_checksum(&buf2);
        assert_ne!(checksum1, checksum2);
    }

    #[test]
    fn test_compute_text_checksum() {
        let text = "Hello, World!";
        let checksum = compute_text_checksum(text);
        assert!(checksum.starts_with(CHECKSUM_PREFIX));

        // Should be deterministic
        assert_eq!(checksum, compute_text_checksum(text));
    }

    #[test]
    fn test_golden_env_capture() {
        let env = GoldenEnv::capture();
        let json = env.to_json();
        assert!(json.contains("term"));
        assert!(json.contains("seed"));
    }

    #[test]
    fn test_escape_json() {
        assert_eq!(escape_json("hello"), "hello");
        assert_eq!(escape_json("he\"llo"), "he\\\"llo");
        assert_eq!(escape_json("he\\llo"), "he\\\\llo");
        assert_eq!(escape_json("line1\nline2"), "line1\\nline2");
    }

    #[test]
    fn test_verify_checksums_pass() {
        let actual = vec!["blake3:abc".to_string(), "blake3:def".to_string()];
        let expected = vec!["blake3:abc".to_string(), "blake3:def".to_string()];
        let (outcome, idx) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Pass);
        assert!(idx.is_none());
    }

    #[test]
    fn test_verify_checksums_mismatch() {
        let actual = vec!["blake3:abc".to_string(), "blake3:xyz".to_string()];
        let expected = vec!["blake3:abc".to_string(), "blake3:def".to_string()];
        let (outcome, idx) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Fail);
        assert_eq!(idx, Some(1));
    }

    #[test]
    fn test_verify_checksums_length_mismatch() {
        let actual = vec!["blake3:abc".to_string()];
        let expected = vec!["blake3:abc".to_string(), "blake3:def".to_string()];
        let (outcome, idx) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Fail);
        assert!(idx.is_none());
    }

    #[test]
    fn test_verify_checksums_empty_expected() {
        let actual = vec!["blake3:abc".to_string()];
        let expected: Vec<String> = vec![];
        let (outcome, _) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Pass);
    }

    #[test]
    fn test_resize_scenario_fixed() {
        let scenario = ResizeScenario::fixed("test", 80, 24);
        assert_eq!(scenario.name, "test");
        assert_eq!(scenario.initial_width, 80);
        assert_eq!(scenario.initial_height, 24);
        assert!(scenario.resize_steps.is_empty());
    }

    #[test]
    fn test_resize_scenario_resize() {
        let scenario = ResizeScenario::resize("test", 80, 24, 120, 40);
        assert_eq!(scenario.initial_width, 80);
        assert_eq!(scenario.initial_height, 24);
        assert_eq!(scenario.resize_steps.len(), 1);
        assert_eq!(scenario.resize_steps[0], (120, 40, 0));
    }

    #[test]
    fn test_standard_scenarios() {
        let scenarios = standard_resize_scenarios();
        assert!(!scenarios.is_empty());
        // Should have both fixed and resize scenarios
        assert!(scenarios.iter().any(|s| s.resize_steps.is_empty()));
        assert!(scenarios.iter().any(|s| !s.resize_steps.is_empty()));
    }

    // ── GoldenOutcome ─────────────────────────────────────────────────

    #[test]
    fn outcome_as_str() {
        assert_eq!(GoldenOutcome::Pass.as_str(), "pass");
        assert_eq!(GoldenOutcome::Fail.as_str(), "fail");
        assert_eq!(GoldenOutcome::Skip.as_str(), "skip");
    }

    // ── GoldenResult formatting ───────────────────────────────────────

    #[test]
    fn result_format_pass() {
        let r = GoldenResult {
            scenario: "test".into(),
            outcome: GoldenOutcome::Pass,
            checksums: vec![],
            expected_checksums: vec![],
            mismatch_index: None,
            duration_ms: 42,
        };
        assert!(r.is_pass());
        let s = r.format();
        assert!(s.contains("PASS"), "{s}");
        assert!(s.contains("42ms"), "{s}");
    }

    #[test]
    fn result_format_fail_missing_golden() {
        let r = GoldenResult {
            scenario: "test".into(),
            outcome: GoldenOutcome::Fail,
            checksums: vec!["blake3:abc".into()],
            expected_checksums: vec![],
            mismatch_index: None,
            duration_ms: 0,
        };
        assert!(!r.is_pass());
        let s = r.format();
        assert!(s.contains("missing golden checksums"), "{s}");
    }

    #[test]
    fn result_format_fail_mismatch() {
        let r = GoldenResult {
            scenario: "test".into(),
            outcome: GoldenOutcome::Fail,
            checksums: vec!["blake3:abc".into(), "blake3:wrong".into()],
            expected_checksums: vec!["blake3:abc".into(), "blake3:def".into()],
            mismatch_index: Some(1),
            duration_ms: 0,
        };
        let s = r.format();
        assert!(s.contains("checksum mismatch at frame 1"), "{s}");
        assert!(s.contains("blake3:def"), "expected: {s}");
        assert!(s.contains("blake3:wrong"), "actual: {s}");
    }

    #[test]
    fn result_format_fail_count_mismatch() {
        let r = GoldenResult {
            scenario: "test".into(),
            outcome: GoldenOutcome::Fail,
            checksums: vec!["blake3:abc".into()],
            expected_checksums: vec!["blake3:abc".into(), "blake3:def".into()],
            mismatch_index: None,
            duration_ms: 0,
        };
        let s = r.format();
        assert!(s.contains("checksum count mismatch"), "{s}");
    }

    #[test]
    fn result_format_skip() {
        let r = GoldenResult {
            scenario: "test".into(),
            outcome: GoldenOutcome::Skip,
            checksums: vec![],
            expected_checksums: vec![],
            mismatch_index: None,
            duration_ms: 0,
        };
        assert!(r.format().starts_with("SKIP:"));
    }

    // ── GoldenLogger ──────────────────────────────────────────────────

    #[test]
    fn noop_logger_does_not_crash() {
        let mut logger = GoldenLogger::noop();
        let env = GoldenEnv::capture();
        logger.log_start("test_case", &env);
        logger.log_frame(0, 80, 24, "blake3:abc", 10);
        logger.log_resize(80, 24, 120, 40, 5);
        logger.log_error("some error");
        logger.log_complete(GoldenOutcome::Pass);
        assert_eq!(logger.checksums(), &["blake3:abc".to_string()]);
    }

    #[test]
    fn file_logger_writes_events() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_test_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let log_path = dir.join("test.jsonl");
        {
            let mut logger = GoldenLogger::new(&log_path).expect("create logger");
            let env = GoldenEnv::capture();
            logger.log_start("test", &env);
            logger.log_frame(0, 80, 24, "blake3:aaa", 1);
            logger.log_resize(80, 24, 120, 40, 2);
            logger.log_frame(1, 120, 40, "blake3:bbb", 3);
            logger.log_complete(GoldenOutcome::Pass);
        }
        let content = std::fs::read_to_string(&log_path).expect("read log");
        let lines: Vec<&str> = content.lines().collect();
        assert_eq!(lines.len(), 5, "should have 5 JSONL events");
        assert!(lines[0].contains("\"event\":\"start\""));
        assert!(lines[1].contains("\"event\":\"frame\""));
        assert!(lines[2].contains("\"event\":\"resize\""));
        assert!(lines[3].contains("\"event\":\"frame\""));
        assert!(lines[4].contains("\"event\":\"complete\""));
        assert!(lines[4].contains("\"outcome\":\"pass\""));
        let _ = std::fs::remove_dir_all(&dir);
    }

    // ── Golden file I/O ───────────────────────────────────────────────

    #[test]
    fn save_and_load_golden_checksums() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_io_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let path = dir.join("tests").join("golden").join("test.checksums");
        let checksums = vec!["blake3:abc".to_string(), "blake3:def".to_string()];
        save_golden_checksums(&path, &checksums).expect("save");
        let loaded = load_golden_checksums(&path).expect("load");
        assert_eq!(loaded, checksums);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_golden_checksums_nonexistent_returns_empty() {
        let path = std::path::Path::new("/tmp/nonexistent_golden_12345.checksums");
        let loaded = load_golden_checksums(path).expect("should return empty");
        assert!(loaded.is_empty());
    }

    #[test]
    fn load_golden_checksums_skips_comments_and_blanks() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_comments_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.checksums");
        std::fs::write(
            &path,
            "# comment\nblake3:abc\n\nblake3:def\n# another comment\n",
        )
        .unwrap();
        let loaded = load_golden_checksums(&path).expect("load");
        assert_eq!(loaded, vec!["blake3:abc", "blake3:def"]);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn golden_checksum_path_format() {
        let base = std::path::Path::new("/project");
        let path = golden_checksum_path(base, "resize_80x24");
        assert_eq!(
            path,
            std::path::PathBuf::from("/project/tests/golden/resize_80x24.checksums")
        );
    }

    // ── ResizeScenario builder ────────────────────────────────────────

    #[test]
    fn resize_scenario_with_expected() {
        let scenario =
            ResizeScenario::fixed("test", 80, 24).with_expected(vec!["blake3:abc".into()]);
        assert_eq!(scenario.expected_checksums, vec!["blake3:abc"]);
    }

    // ── GoldenEnv::to_json produces valid JSON ────────────────────────

    #[test]
    fn golden_env_to_json_is_valid() {
        let env = GoldenEnv::capture();
        let json = env.to_json();
        let parsed: serde_json::Value =
            serde_json::from_str(&json).expect("GoldenEnv::to_json should produce valid JSON");
        assert!(parsed.get("term").is_some());
        assert!(parsed.get("seed").is_some());
        assert!(parsed.get("rust_version").is_some());
        assert!(parsed.get("git_commit").is_some());
    }

    // ====================================================================
    // bd-3fc.7: Additional golden frame infrastructure self-tests
    // ====================================================================

    // ── BLAKE3 hash computation correctness ─────────────────────────

    #[test]
    fn blake3_hash_prefix_is_correct() {
        let buf = Buffer::new(1, 1);
        let checksum = compute_buffer_checksum(&buf);
        assert!(
            checksum.starts_with("blake3:"),
            "checksum must start with 'blake3:' prefix"
        );
        // BLAKE3 digest is exactly 64 hex characters
        let hex_part = &checksum["blake3:".len()..];
        assert_eq!(hex_part.len(), 64, "BLAKE3 hex digest must be 64 chars");
        assert!(
            hex_part.chars().all(|c| c.is_ascii_hexdigit()),
            "digest must be valid hex"
        );
    }

    #[test]
    fn blake3_hash_sensitive_to_fg_color() {
        use ftui_render::cell::PackedRgba;

        let mut buf1 = Buffer::new(5, 1);
        let mut cell1 = Cell::from_char('X');
        cell1.fg = PackedRgba::rgb(255, 0, 0); // Red
        buf1.set(0, 0, cell1);

        let mut buf2 = Buffer::new(5, 1);
        let mut cell2 = Cell::from_char('X');
        cell2.fg = PackedRgba::rgb(0, 0, 255); // Blue
        buf2.set(0, 0, cell2);

        assert_ne!(
            compute_buffer_checksum(&buf1),
            compute_buffer_checksum(&buf2),
            "different foreground colors must produce different hashes"
        );
    }

    #[test]
    fn blake3_hash_sensitive_to_bg_color() {
        use ftui_render::cell::PackedRgba;

        let mut buf1 = Buffer::new(5, 1);
        let mut cell1 = Cell::from_char('X');
        cell1.bg = PackedRgba::rgb(0, 255, 0); // Green
        buf1.set(0, 0, cell1);

        let mut buf2 = Buffer::new(5, 1);
        let mut cell2 = Cell::from_char('X');
        cell2.bg = PackedRgba::rgb(255, 255, 0); // Yellow
        buf2.set(0, 0, cell2);

        assert_ne!(
            compute_buffer_checksum(&buf1),
            compute_buffer_checksum(&buf2),
            "different background colors must produce different hashes"
        );
    }

    #[test]
    fn blake3_hash_sensitive_to_cell_position() {
        let mut buf1 = Buffer::new(5, 1);
        buf1.set(0, 0, Cell::from_char('A'));

        let mut buf2 = Buffer::new(5, 1);
        buf2.set(1, 0, Cell::from_char('A'));

        assert_ne!(
            compute_buffer_checksum(&buf1),
            compute_buffer_checksum(&buf2),
            "same char at different positions must produce different hashes"
        );
    }

    #[test]
    fn blake3_text_checksum_differs_for_different_text() {
        let c1 = compute_text_checksum("hello");
        let c2 = compute_text_checksum("world");
        assert_ne!(c1, c2);
    }

    #[test]
    fn blake3_text_checksum_empty_string() {
        let c = compute_text_checksum("");
        assert!(c.starts_with("blake3:"));
        assert_eq!(c.len(), "blake3:".len() + 64);
    }

    #[test]
    fn blake3_hash_dimensions_included() {
        // Two buffers with same content but different dimensions should differ
        let buf1 = Buffer::new(10, 5); // 50 cells
        let buf2 = Buffer::new(5, 10); // 50 cells
        assert_ne!(
            compute_buffer_checksum(&buf1),
            compute_buffer_checksum(&buf2),
            "different dimensions must produce different hashes even with same cell count"
        );
    }

    // ── Golden file read/write ──────────────────────────────────────

    #[test]
    fn save_creates_parent_directories() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_mkdir_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let deeply_nested = dir.join("a").join("b").join("c").join("test.checksums");
        let checksums = vec!["blake3:abc123".to_string()];
        save_golden_checksums(&deeply_nested, &checksums).expect("save should create dirs");
        assert!(deeply_nested.exists());
        let loaded = load_golden_checksums(&deeply_nested).expect("load");
        assert_eq!(loaded, checksums);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn save_golden_includes_header_comment() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_header_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let path = dir.join("test.checksums");
        let checksums = vec!["blake3:aaa".to_string()];
        save_golden_checksums(&path, &checksums).expect("save");
        let raw = std::fs::read_to_string(&path).expect("read");
        assert!(
            raw.starts_with("# Golden checksums"),
            "file should start with header comment"
        );
        assert!(raw.contains("# Generated at:"), "should have timestamp");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn save_and_load_empty_checksums() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_empty_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let path = dir.join("test.checksums");
        save_golden_checksums(&path, &[]).expect("save empty");
        let loaded = load_golden_checksums(&path).expect("load");
        assert!(loaded.is_empty(), "empty save should load as empty");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn save_and_load_many_checksums() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_many_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let path = dir.join("test.checksums");
        let checksums: Vec<String> = (0..100).map(|i| format!("blake3:{i:064x}")).collect();
        save_golden_checksums(&path, &checksums).expect("save");
        let loaded = load_golden_checksums(&path).expect("load");
        assert_eq!(loaded, checksums);
        let _ = std::fs::remove_dir_all(&dir);
    }

    // ── Hash comparison logic ───────────────────────────────────────

    #[test]
    fn verify_checksums_both_empty_is_pass() {
        let (outcome, idx) = verify_checksums(&[], &[]);
        assert_eq!(outcome, GoldenOutcome::Pass);
        assert!(idx.is_none());
    }

    #[test]
    fn verify_checksums_first_frame_mismatch() {
        let actual = vec!["blake3:aaa".to_string()];
        let expected = vec!["blake3:bbb".to_string()];
        let (outcome, idx) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Fail);
        assert_eq!(idx, Some(0), "mismatch should be at frame 0");
    }

    #[test]
    fn verify_checksums_last_frame_mismatch() {
        let actual = vec![
            "blake3:aaa".to_string(),
            "blake3:bbb".to_string(),
            "blake3:xxx".to_string(),
        ];
        let expected = vec![
            "blake3:aaa".to_string(),
            "blake3:bbb".to_string(),
            "blake3:ccc".to_string(),
        ];
        let (outcome, idx) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Fail);
        assert_eq!(idx, Some(2), "mismatch should be at last frame");
    }

    #[test]
    fn verify_checksums_actual_shorter() {
        let actual: Vec<String> = vec![];
        let expected = vec!["blake3:abc".to_string()];
        let (outcome, _) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Fail);
    }

    #[test]
    fn verify_checksums_actual_longer() {
        let actual = vec!["blake3:abc".to_string(), "blake3:def".to_string()];
        let expected = vec!["blake3:abc".to_string()];
        let (outcome, _) = verify_checksums(&actual, &expected);
        assert_eq!(outcome, GoldenOutcome::Fail);
    }

    // ── Update mode / bless mode ────────────────────────────────────

    #[test]
    fn bless_mode_round_trip() {
        // Test that bless mode round-trip (save then load) produces identical checksums
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_bless_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let path = golden_checksum_path(&dir, "bless_test");

        // Simulate bless: compute checksums and save
        let mut buf = Buffer::new(80, 24);
        buf.set(0, 0, Cell::from_char('H'));
        buf.set(1, 0, Cell::from_char('i'));
        let checksum = compute_buffer_checksum(&buf);
        save_golden_checksums(&path, std::slice::from_ref(&checksum)).expect("save");

        // Verify: load and compare
        let loaded = load_golden_checksums(&path).expect("load");
        let (outcome, idx) = verify_checksums(&[checksum], &loaded);
        assert_eq!(outcome, GoldenOutcome::Pass);
        assert!(idx.is_none());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn bless_mode_overwrites_old_golden() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_overwrite_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let path = golden_checksum_path(&dir, "overwrite_test");

        // First bless
        save_golden_checksums(&path, &["blake3:old_hash".to_string()]).expect("save old");
        let loaded_old = load_golden_checksums(&path).expect("load old");
        assert_eq!(loaded_old, vec!["blake3:old_hash"]);

        // Second bless (overwrite)
        save_golden_checksums(&path, &["blake3:new_hash".to_string()]).expect("save new");
        let loaded_new = load_golden_checksums(&path).expect("load new");
        assert_eq!(loaded_new, vec!["blake3:new_hash"]);

        let _ = std::fs::remove_dir_all(&dir);
    }

    // ── Tracing span verification (golden.compare) ─────────────────

    #[test]
    fn verify_checksums_emits_golden_compare_span() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        struct SpanChecker {
            saw_golden_compare: Arc<AtomicBool>,
        }

        impl tracing::Subscriber for SpanChecker {
            fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
                true
            }
            fn new_span(&self, span: &tracing::span::Attributes<'_>) -> tracing::span::Id {
                if span.metadata().name() == "golden.compare" {
                    self.saw_golden_compare.store(true, Ordering::Relaxed);
                }
                tracing::span::Id::from_u64(1)
            }
            fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
            fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
            fn event(&self, _: &tracing::Event<'_>) {}
            fn enter(&self, _: &tracing::span::Id) {}
            fn exit(&self, _: &tracing::span::Id) {}
        }

        let saw_it = Arc::new(AtomicBool::new(false));
        let subscriber = SpanChecker {
            saw_golden_compare: Arc::clone(&saw_it),
        };
        let _guard = tracing::subscriber::set_default(subscriber);

        let actual = vec!["blake3:abc".to_string()];
        let expected = vec!["blake3:abc".to_string()];
        let _ = verify_checksums(&actual, &expected);

        assert!(
            saw_it.load(Ordering::Relaxed),
            "verify_checksums() must emit a 'golden.compare' tracing span"
        );
    }

    #[test]
    fn verify_checksums_emits_error_on_mismatch_with_both_hashes() {
        use std::sync::Arc;
        use std::sync::Mutex;

        struct ErrorCollector {
            errors: Arc<Mutex<Vec<String>>>,
        }

        impl tracing::Subscriber for ErrorCollector {
            fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
                true
            }
            fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
                tracing::span::Id::from_u64(1)
            }
            fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
            fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
            fn event(&self, event: &tracing::Event<'_>) {
                if *event.metadata().level() == tracing::Level::ERROR {
                    let mut collector = ErrorFieldCollector { fields: Vec::new() };
                    event.record(&mut collector);
                    self.errors
                        .lock()
                        .unwrap()
                        .push(collector.fields.join(", "));
                }
            }
            fn enter(&self, _: &tracing::span::Id) {}
            fn exit(&self, _: &tracing::span::Id) {}
        }

        struct ErrorFieldCollector {
            fields: Vec<String>,
        }

        impl tracing::field::Visit for ErrorFieldCollector {
            fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
                self.fields.push(format!("{}={:?}", field.name(), value));
            }
        }

        let errors = Arc::new(Mutex::new(Vec::new()));
        let subscriber = ErrorCollector {
            errors: Arc::clone(&errors),
        };
        let _guard = tracing::subscriber::set_default(subscriber);

        let actual = vec!["blake3:actual_hash".to_string()];
        let expected = vec!["blake3:expected_hash".to_string()];
        let (outcome, idx) = verify_checksums(&actual, &expected);

        assert_eq!(outcome, GoldenOutcome::Fail);
        assert_eq!(idx, Some(0));

        let collected = errors.lock().unwrap();
        assert!(
            !collected.is_empty(),
            "should emit at least one ERROR event on mismatch"
        );
        let error_msg = collected.join(" ");
        assert!(
            error_msg.contains("expected_hash") || error_msg.contains("actual_hash"),
            "ERROR should include hash values, got: {error_msg}"
        );
    }

    #[test]
    fn verify_checksums_emits_error_on_count_mismatch() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicBool, Ordering};

        struct CountMismatchChecker {
            saw_error: Arc<AtomicBool>,
        }

        impl tracing::Subscriber for CountMismatchChecker {
            fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
                true
            }
            fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
                tracing::span::Id::from_u64(1)
            }
            fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {}
            fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
            fn event(&self, event: &tracing::Event<'_>) {
                if *event.metadata().level() == tracing::Level::ERROR {
                    self.saw_error.store(true, Ordering::Relaxed);
                }
            }
            fn enter(&self, _: &tracing::span::Id) {}
            fn exit(&self, _: &tracing::span::Id) {}
        }

        let saw = Arc::new(AtomicBool::new(false));
        let subscriber = CountMismatchChecker {
            saw_error: Arc::clone(&saw),
        };
        let _guard = tracing::subscriber::set_default(subscriber);

        let actual = vec!["blake3:abc".to_string()];
        let expected = vec!["blake3:abc".to_string(), "blake3:def".to_string()];
        let _ = verify_checksums(&actual, &expected);

        assert!(
            saw.load(Ordering::Relaxed),
            "count mismatch should emit ERROR event"
        );
    }

    #[test]
    fn verify_checksums_span_records_outcome_pass() {
        use std::sync::Arc;
        use std::sync::Mutex;

        struct OutcomeRecorder {
            outcome: Arc<Mutex<Option<String>>>,
        }

        struct OutcomeVisitor(Arc<Mutex<Option<String>>>);

        impl tracing::field::Visit for OutcomeVisitor {
            fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
                if field.name() == "outcome" {
                    *self.0.lock().unwrap() = Some(value.to_string());
                }
            }
            fn record_debug(&mut self, _: &tracing::field::Field, _: &dyn std::fmt::Debug) {}
        }

        impl tracing::Subscriber for OutcomeRecorder {
            fn enabled(&self, _: &tracing::Metadata<'_>) -> bool {
                true
            }
            fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id {
                tracing::span::Id::from_u64(1)
            }
            fn record(&self, _: &tracing::span::Id, values: &tracing::span::Record<'_>) {
                let mut v = OutcomeVisitor(Arc::clone(&self.outcome));
                values.record(&mut v);
            }
            fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {}
            fn event(&self, _: &tracing::Event<'_>) {}
            fn enter(&self, _: &tracing::span::Id) {}
            fn exit(&self, _: &tracing::span::Id) {}
        }

        let outcome = Arc::new(Mutex::new(None));
        let subscriber = OutcomeRecorder {
            outcome: Arc::clone(&outcome),
        };
        let _guard = tracing::subscriber::set_default(subscriber);

        let actual = vec!["blake3:abc".to_string()];
        let expected = vec!["blake3:abc".to_string()];
        let _ = verify_checksums(&actual, &expected);

        let recorded = outcome.lock().unwrap();
        assert_eq!(
            recorded.as_deref(),
            Some("pass"),
            "outcome field should be 'pass'"
        );
    }

    // ── GoldenResult format with both hashes ────────────────────────

    #[test]
    fn result_format_mismatch_includes_both_hashes() {
        let expected_hash =
            "blake3:aaaa1111bbbb2222cccc3333dddd4444eeee5555ffff6666aabb7788ccdd9900";
        let actual_hash = "blake3:1111aaaa2222bbbb3333cccc4444dddd5555eeee6666ffff7788aabb9900ccdd";
        let r = GoldenResult {
            scenario: "test".into(),
            outcome: GoldenOutcome::Fail,
            checksums: vec![actual_hash.to_string()],
            expected_checksums: vec![expected_hash.to_string()],
            mismatch_index: Some(0),
            duration_ms: 5,
        };
        let s = r.format();
        assert!(
            s.contains(expected_hash),
            "should contain expected hash in error output"
        );
        assert!(
            s.contains(actual_hash),
            "should contain actual hash in error output"
        );
    }

    // ── Logger frame collection ─────────────────────────────────────

    #[test]
    fn logger_collects_checksums_in_order() {
        let mut logger = GoldenLogger::noop();
        logger.log_frame(0, 80, 24, "blake3:first", 1);
        logger.log_frame(1, 80, 24, "blake3:second", 2);
        logger.log_frame(2, 80, 24, "blake3:third", 3);
        assert_eq!(
            logger.checksums(),
            &["blake3:first", "blake3:second", "blake3:third"]
        );
    }

    #[test]
    fn logger_error_event_format() {
        let dir = std::env::temp_dir().join(format!(
            "ftui_golden_error_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos()
        ));
        let log_path = dir.join("test.jsonl");
        {
            let mut logger = GoldenLogger::new(&log_path).expect("create logger");
            logger.log_error("something went wrong");
        }
        let content = std::fs::read_to_string(&log_path).expect("read log");
        assert!(content.contains("\"event\":\"error\""));
        assert!(content.contains("something went wrong"));
        let _ = std::fs::remove_dir_all(&dir);
    }
}