testty 0.13.5

Rust-native TUI end-to-end testing framework using PTY-driven semantic assertions, native frame rendering, and VHS-driven GIF capture.
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
//! Generic feature demo builder: scenario execution with GIF generation.
//!
//! [`FeatureDemo`] bundles PTY scenario execution, proof collection, and
//! hash-cached VHS GIF generation into one reusable entry point. The caller
//! decides what to do with the [`FeatureResult`] artifacts — testty itself
//! has no opinion on static-site generators, README formats, or artifact
//! directories beyond GIF output.
//!
//! # Freshness mode
//!
//! [`FeatureDemo::gif_mode`] selects between three behaviors:
//!
//! - [`GifMode::GenerateIfStale`] (default) — preserves the historical
//!   behavior: skip VHS when the on-disk hash sidecar matches, otherwise
//!   regenerate.
//! - [`GifMode::CheckOnly`] — runs the scenario, computes the would-be hash,
//!   and reports whether the on-disk GIF is [`GifStatus::Fresh`] or
//!   [`GifStatus::Stale`] without invoking VHS. This path never mutates the
//!   filesystem, so it is safe on read-only CI mounts and when the GIF output
//!   directory does not exist yet. Useful for an agent or CI tool that wants to
//!   detect drift without paying VHS cost.
//! - [`GifMode::AlwaysGenerate`] — bypasses the hash cache and always re-runs
//!   VHS.
//!
//! # Redaction
//!
//! The freshness hash only works when the same UI hashes the same way on every
//! run. Temp roots are normalized for free, but an application that paints its
//! own generated identifiers — session hashes, worktree names, short commit
//! ids — must declare them with [`FeatureDemo::redact`] so they stop counting
//! as UI drift.

use std::path::{Path, PathBuf};

use crate::frame::TerminalFrame;
use crate::proof::report::ProofReport;
use crate::scenario::Scenario;
use crate::session::{PtySessionBuilder, PtySessionError};
use crate::vhs::{VhsError, VhsTape, VhsTapeSettings, check_vhs_installed};

/// Metadata describing a feature demonstration.
///
/// Carries the human-readable name, title, and description that identify
/// the feature for downstream artifact generators (static-site pages,
/// README entries, etc.).
#[derive(Debug, Clone)]
pub struct FeatureMeta {
    /// Machine-readable identifier used in file names (e.g.
    /// `"session_creation"`).
    pub name: String,
    /// Human-readable title (e.g. `"Session creation"`).
    pub title: String,
    /// Short description of the demonstrated behavior.
    pub description: String,
}

/// Caller-supplied rule that rewrites a generated hash before hashing a frame.
///
/// Applications under test often paint identifiers they generate at runtime —
/// a session hash, a worktree name, a short commit id. Those tokens change on
/// every run, so an unredacted frame hashes differently every time and the
/// committed GIF always looks stale. A [`Redaction`] replaces the volatile
/// token with a fixed placeholder, leaving the surrounding UI to drive the
/// hash.
///
/// Redaction affects only the freshness hash. Captured frames, assertions, and
/// the recorded GIF still show the real token.
///
/// # Example
///
/// ```
/// use testty::feature::Redaction;
///
/// // `wt/4175e5af` and `wt/9c0b17ff` hash identically.
/// let redaction = Redaction::hex_after("wt/", 8, "<hash>");
///
/// assert_eq!(redaction.apply("branch wt/4175e5af"), "branch wt/<hash>");
///
/// // A token the terminal cut off at the right edge is still redacted.
/// assert_eq!(redaction.apply("path .../wt/4175"), "path .../wt/<hash>");
///
/// // A known-volatile literal, such as the version the app paints in its
/// // header, hashes as its placeholder so releases do not stale every GIF.
/// let version = Redaction::literal("Agentty v0.13.0", "Agentty <version>");
///
/// assert_eq!(version.apply("Agentty v0.13.0 | FYI"), "Agentty <version> | FYI");
/// ```
#[derive(Debug, Clone)]
pub struct Redaction {
    placeholder: String,
    rule: RedactionRule,
}

/// Matching strategy backing one [`Redaction`].
#[derive(Debug, Clone)]
enum RedactionRule {
    /// Replace a bounded ASCII hex run that directly follows a prefix.
    HexAfter { prefix: String, max_hex_len: usize },
    /// Replace every occurrence of one exact string.
    Literal { needle: String },
}

impl Redaction {
    /// Redact a run of up to `max_hex_len` ASCII hex digits following `prefix`.
    ///
    /// The prefix anchors the rule: only hex runs that directly follow it are
    /// rewritten. A run longer than `max_hex_len` is left alone, so a rule for
    /// an 8-digit short hash never clips a full 40-digit one.
    ///
    /// Shorter runs are redacted because a TUI truncates: a hash painted at the
    /// right edge of the terminal shows however many digits happen to fit, and
    /// that count shifts with everything printed before it. Matching only the
    /// full-length token would leave those frames volatile.
    pub fn hex_after(
        prefix: impl Into<String>,
        max_hex_len: usize,
        placeholder: impl Into<String>,
    ) -> Self {
        Self {
            placeholder: placeholder.into(),
            rule: RedactionRule::HexAfter {
                prefix: prefix.into(),
                max_hex_len,
            },
        }
    }

    /// Redact every occurrence of the exact string `needle`.
    ///
    /// Use this for volatile text the caller can spell out ahead of time —
    /// typically a version string the application paints, which would
    /// otherwise stale every committed GIF hash on each release. The caller
    /// usually builds the needle from its own compile-time version so the
    /// rule tracks releases automatically.
    pub fn literal(needle: impl Into<String>, placeholder: impl Into<String>) -> Self {
        Self {
            placeholder: placeholder.into(),
            rule: RedactionRule::Literal {
                needle: needle.into(),
            },
        }
    }

    /// Apply this rule to `text`, replacing every matching token.
    ///
    /// For [`Redaction::hex_after`] the prefix is preserved and only the hex
    /// token is replaced. An empty prefix or needle matches nothing and
    /// returns `text` unchanged.
    #[must_use]
    pub fn apply(&self, text: &str) -> String {
        match &self.rule {
            RedactionRule::HexAfter {
                prefix,
                max_hex_len,
            } => Self::apply_hex_after(text, prefix, *max_hex_len, &self.placeholder),
            RedactionRule::Literal { needle } => {
                if needle.is_empty() {
                    return text.to_string();
                }

                text.replace(needle, &self.placeholder)
            }
        }
    }

    /// Replaces bounded hex runs following `prefix` with `placeholder`.
    fn apply_hex_after(text: &str, prefix: &str, max_hex_len: usize, placeholder: &str) -> String {
        if prefix.is_empty() {
            return text.to_string();
        }

        let mut redacted = String::with_capacity(text.len());
        let mut remainder = text;

        while let Some(prefix_index) = remainder.find(prefix) {
            let after_prefix_index = prefix_index + prefix.len();
            let after_prefix = &remainder[after_prefix_index..];
            let token_len = after_prefix
                .chars()
                .take_while(char::is_ascii_hexdigit)
                .count();

            redacted.push_str(&remainder[..after_prefix_index]);

            if (1..=max_hex_len).contains(&token_len) {
                redacted.push_str(placeholder);
                remainder = &after_prefix[token_len..];
            } else {
                remainder = after_prefix;
            }
        }

        redacted.push_str(remainder);

        redacted
    }
}

/// Selects how [`FeatureDemo::run`] handles GIF artifacts.
///
/// The variants correspond directly to the freshness behaviors documented
/// on the module docs: cache-respecting regeneration (default), hash-only
/// drift detection, and forced regeneration. Defaults to
/// [`GifMode::GenerateIfStale`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum GifMode {
    /// Skip VHS when the on-disk hash sidecar matches; regenerate
    /// otherwise. Historical default behavior.
    #[default]
    GenerateIfStale,
    /// Compute the would-be hash and compare it to the on-disk sidecar
    /// without invoking VHS. Returns [`GifStatus::Fresh`] or
    /// [`GifStatus::Stale`].
    CheckOnly,
    /// Bypass the hash cache and regenerate the GIF unconditionally.
    ///
    /// VHS must be installed: this mode treats a missing VHS binary as a
    /// hard failure ([`GifStatus::TapeExecutionFailed`]) rather than the
    /// benign [`GifStatus::VhsNotInstalled`] skip used by other modes,
    /// because regeneration was explicitly requested.
    AlwaysGenerate,
}

/// Outcome of GIF generation during a [`FeatureDemo`] run.
///
/// Distinguishes intentional skips (VHS missing, cache hit, no output dir)
/// from unexpected failures (directory creation, tape execution) so callers
/// can log or fail appropriately.
///
/// `#[non_exhaustive]` so future variants stay non-breaking. Match arms must
/// include a fallback `_` arm.
#[derive(Debug)]
#[non_exhaustive]
pub enum GifStatus {
    /// GIF was generated successfully at the given path.
    Generated(PathBuf),
    /// GIF already existed and the content hash matched — skipped
    /// regeneration.
    CacheHit(PathBuf),
    /// VHS is not installed; GIF generation was skipped.
    VhsNotInstalled,
    /// No output directory was configured; GIF generation was skipped.
    NoOutputDir,
    /// GIF output directory could not be created.
    DirCreateFailed(std::io::Error),
    /// VHS tape execution failed.
    TapeExecutionFailed(VhsError),
    /// [`GifMode::CheckOnly`]: the on-disk GIF matches the current capture
    /// hash. No VHS execution was attempted.
    Fresh {
        /// Expected GIF path (may or may not exist on disk).
        gif_path: PathBuf,
        /// Hash computed from the current scenario captures.
        hash: u64,
    },
    /// [`GifMode::CheckOnly`]: the on-disk GIF is missing or its hash
    /// sidecar does not match the current capture hash. No VHS execution
    /// was attempted.
    Stale {
        /// Expected GIF path (may or may not exist on disk).
        gif_path: PathBuf,
        /// Hash computed from the current scenario captures.
        current: u64,
        /// Hash recorded in the on-disk sidecar, if it exists and parses.
        committed: Option<u64>,
        /// Error found while reading or parsing the committed sidecar, if any.
        committed_error: Option<String>,
    },
}

impl GifStatus {
    /// Return the GIF path if generation succeeded, the cache matched, or a
    /// freshness check identified an expected output location.
    pub fn gif_path(&self) -> Option<&Path> {
        match self {
            Self::Generated(path) | Self::CacheHit(path) => Some(path),
            Self::Fresh { gif_path, .. } | Self::Stale { gif_path, .. } => Some(gif_path),
            _ => None,
        }
    }

    /// Return `true` when GIF generation failed unexpectedly.
    ///
    /// Intentional skips (`VhsNotInstalled`, `CacheHit`, `NoOutputDir`,
    /// `Fresh`, `Stale`) return `false`.
    pub fn is_failure(&self) -> bool {
        matches!(
            self,
            Self::DirCreateFailed(_) | Self::TapeExecutionFailed(_)
        )
    }

    /// Return `true` when the on-disk GIF is known to be out of date with
    /// the current scenario captures. Only [`GifStatus::Stale`] returns
    /// `true`; every other variant returns `false`.
    pub fn is_stale(&self) -> bool {
        matches!(self, Self::Stale { .. })
    }
}

/// Artifacts produced by a [`FeatureDemo`] run.
///
/// Contains the final terminal frame, the full proof report with labeled
/// captures, the feature metadata, and the GIF generation status.
pub struct FeatureResult {
    /// Final terminal frame after scenario execution.
    pub frame: TerminalFrame,
    /// Proof report with all labeled captures and diffs.
    pub report: ProofReport,
    /// Feature metadata passed through from the builder.
    pub meta: FeatureMeta,
    /// Outcome of GIF generation (success, cache hit, skip, failure, or
    /// freshness verdict in [`GifMode::CheckOnly`]).
    pub gif_status: GifStatus,
}

/// Generic feature demo builder: scenario + GIF with hash caching.
///
/// Owns scenario execution lifecycle and optional VHS GIF generation with
/// content-hash caching. The caller provides the [`PtySessionBuilder`],
/// binary path, and environment pairs for VHS tape compilation.
///
/// # Example
///
/// ```ignore
/// let scenario = Scenario::new("tab_switch")
///     .compose(&startup_journey)
///     .press_key("Tab")
///     .capture_labeled("after", "After tab press");
///
/// let result = FeatureDemo::new("tab_switch")
///     .title("Tab switching")
///     .description("Press Tab to cycle through tabs.")
///     .gif_output_dir("docs/static/features")
///     .run(&scenario, builder, &binary_path, &env_pairs)
///     .expect("feature demo failed");
/// ```
#[must_use]
pub struct FeatureDemo {
    meta: FeatureMeta,
    gif_output_dir: Option<PathBuf>,
    gif_settings: VhsTapeSettings,
    gif_mode: GifMode,
    redactions: Vec<Redaction>,
}

impl FeatureDemo {
    /// Create a new feature demo builder with the given name.
    ///
    /// Title and description default to the name until overridden.
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();

        Self {
            meta: FeatureMeta {
                title: name.clone(),
                description: String::new(),
                name,
            },
            gif_output_dir: None,
            gif_settings: VhsTapeSettings::feature_demo(),
            gif_mode: GifMode::default(),
            redactions: Vec::new(),
        }
    }

    /// Set the human-readable title for this feature.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.meta.title = title.into();

        self
    }

    /// Set the short description for this feature.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.meta.description = description.into();

        self
    }

    /// Set the directory where GIF output and hash sidecars are written.
    ///
    /// When not set, GIF generation is skipped entirely.
    pub fn gif_output_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.gif_output_dir = Some(dir.into());

        self
    }

    /// Override the default [`VhsTapeSettings::feature_demo()`] settings.
    pub fn gif_settings(mut self, settings: VhsTapeSettings) -> Self {
        self.gif_settings = settings;

        self
    }

    /// Select the GIF freshness mode. See [`GifMode`] for semantics.
    pub fn gif_mode(mut self, mode: GifMode) -> Self {
        self.gif_mode = mode;

        self
    }

    /// Declare a generated token the freshness hash must ignore.
    ///
    /// Rules apply in the order they are added, after the built-in temp-root
    /// normalization. See [`Redaction`] for what a rule matches.
    pub fn redact(mut self, redaction: Redaction) -> Self {
        self.redactions.push(redaction);

        self
    }

    /// Run the feature demo: execute the scenario, collect proof, and
    /// optionally generate a hash-cached GIF.
    ///
    /// The caller provides the scenario to execute, the PTY session builder,
    /// and the binary path + environment pairs for VHS tape compilation.
    ///
    /// # Errors
    ///
    /// Returns a [`PtySessionError`] if scenario spawning or step
    /// execution fails.
    pub fn run(
        self,
        scenario: &Scenario,
        builder: PtySessionBuilder,
        binary_path: &Path,
        env_pairs: &[(&str, &str)],
    ) -> Result<FeatureResult, PtySessionError> {
        let (frame, report) = scenario.run_with_proof(builder)?;

        let gif_status = match self.gif_output_dir.as_deref() {
            Some(output_dir) => generate_gif(
                scenario,
                &report,
                &self.meta.name,
                output_dir,
                GifContext {
                    mode: self.gif_mode,
                    redactions: &self.redactions,
                },
                VhsContext {
                    settings: &self.gif_settings,
                    binary_path,
                    env_pairs,
                },
            ),
            None => GifStatus::NoOutputDir,
        };

        Ok(FeatureResult {
            frame,
            report,
            meta: self.meta,
            gif_status,
        })
    }
}

/// Compute a content hash from all proof capture frame bytes.
///
/// Uses a fixed FNV-1a `u64` hash over the concatenated frame bytes of every
/// capture in the report, after applying the built-in temp-root normalization
/// and the caller's `redactions`.
/// Exposed as public API so external tooling (xtasks, CI freshness reports)
/// can reproduce the same hash that [`FeatureDemo::run`] writes to the
/// on-disk sidecar — pass the same rules the demo was built with, or the
/// hashes will not line up.
pub fn compute_frame_hash(report: &ProofReport, redactions: &[Redaction]) -> u64 {
    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    let mut hash = FNV_OFFSET_BASIS;
    for capture in &report.captures {
        for byte in normalized_frame_bytes_for_hash(&capture.frame_bytes, redactions) {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(FNV_PRIME);
        }
    }

    hash
}

/// Returns frame bytes with volatile text normalized for hashing.
///
/// Feature tests often run inside fresh [`tempfile::TempDir`] directories,
/// while the captured TUI footer may display the absolute working directory.
/// Normalizing those paths keeps freshness sidecars tied to visible UI state
/// instead of one random temp directory name. Generated tokens the application
/// itself paints are the caller's to declare, through `redactions`.
fn normalized_frame_bytes_for_hash(frame_bytes: &[u8], redactions: &[Redaction]) -> Vec<u8> {
    let mut frame_text = String::from_utf8_lossy(frame_bytes).into_owned();

    for temp_root in temp_root_strings() {
        frame_text = frame_text.replace(&temp_root, "<tmp>");
    }

    frame_text = normalize_tempfile_segments(&frame_text);

    for redaction in redactions {
        frame_text = redaction.apply(&frame_text);
    }

    frame_text.into_bytes()
}

/// Returns temp root spellings that may appear in captured terminal frames.
fn temp_root_strings() -> Vec<String> {
    let temp_root = std::env::temp_dir();
    let mut roots = vec![
        temp_root
            .to_string_lossy()
            .trim_end_matches('/')
            .to_string(),
    ];

    if let Ok(canonical_temp_root) = temp_root.canonicalize() {
        roots.push(
            canonical_temp_root
                .to_string_lossy()
                .trim_end_matches('/')
                .to_string(),
        );
    }

    roots.sort();
    roots.dedup();

    roots
}

/// Replaces random `tempfile` directory names after a normalized temp root.
fn normalize_tempfile_segments(frame_text: &str) -> String {
    const NORMALIZED_TEMPFILE_DIR: &str = "<tmp>/<tempdir>";
    const TEMPFILE_PREFIX: &str = "<tmp>/.tmp";

    let mut normalized = String::with_capacity(frame_text.len());
    let mut remainder = frame_text;

    while let Some(prefix_index) = remainder.find(TEMPFILE_PREFIX) {
        let after_prefix_index = prefix_index + TEMPFILE_PREFIX.len();
        normalized.push_str(&remainder[..prefix_index]);
        normalized.push_str(NORMALIZED_TEMPFILE_DIR);

        let after_prefix = &remainder[after_prefix_index..];
        let random_name_length = after_prefix
            .chars()
            .take_while(|character| character.is_ascii_alphanumeric() || *character == '_')
            .map(char::len_utf8)
            .sum::<usize>();
        remainder = &after_prefix[random_name_length..];
    }

    normalized.push_str(remainder);

    normalized
}

/// Return the on-disk sidecar path that [`FeatureDemo`] uses to cache the
/// content hash for a feature with the given `name`.
///
/// Sidecars are stored as `.{name}.hash` next to the GIF (`{name}.gif`) so
/// the dot-prefix keeps them out of plain `ls` listings while staying in
/// the same directory as the artifact they describe.
pub fn hash_sidecar_path(output_dir: &Path, name: &str) -> PathBuf {
    output_dir.join(format!(".{name}.hash"))
}

/// Bundle of freshness inputs threaded through [`generate_gif`].
///
/// Pairs the caller's [`GifMode`] with the redaction rules that decide what
/// counts as UI drift, so both travel together into the hash comparison.
#[derive(Clone, Copy)]
struct GifContext<'a> {
    mode: GifMode,
    redactions: &'a [Redaction],
}

/// Bundle of VHS-execution inputs threaded through [`generate_gif`].
///
/// Grouped so the function signature stays small while still exposing the
/// individual pieces (settings, binary, environment) that VHS needs.
#[derive(Clone, Copy)]
struct VhsContext<'a> {
    settings: &'a VhsTapeSettings,
    binary_path: &'a Path,
    env_pairs: &'a [(&'a str, &'a str)],
}

/// Parsed state of a committed feature-GIF hash sidecar.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CommittedHash {
    /// The sidecar file does not exist yet.
    Missing,
    /// The sidecar exists but cannot be read or parsed as a `u64`.
    Invalid(String),
    /// The sidecar contains a valid committed hash.
    Value(u64),
}

impl CommittedHash {
    /// Return the committed hash value when the sidecar parsed successfully.
    fn value(&self) -> Option<u64> {
        match self {
            Self::Value(hash) => Some(*hash),
            Self::Missing | Self::Invalid(_) => None,
        }
    }

    /// Return the sidecar read/parse error when the sidecar exists but is
    /// invalid.
    fn error(&self) -> Option<String> {
        match self {
            Self::Invalid(err) => Some(err.clone()),
            Self::Missing | Self::Value(_) => None,
        }
    }
}

/// Generate a GIF with content-hash caching, returning a typed status.
///
/// Checks VHS availability, computes a content hash from all proof capture
/// frame bytes, and skips VHS execution when the hash matches a
/// `.{name}.hash` sidecar file. Returns a [`GifStatus`] variant that
/// distinguishes intentional skips from unexpected failures.
fn generate_gif(
    scenario: &Scenario,
    report: &ProofReport,
    name: &str,
    output_dir: &Path,
    gif: GifContext<'_>,
    vhs: VhsContext<'_>,
) -> GifStatus {
    let GifContext { mode, redactions } = gif;

    let hash_path = hash_sidecar_path(output_dir, name);
    let gif_path = output_dir.join(format!("{name}.gif"));

    let current_hash = compute_frame_hash(report, redactions);
    let committed_hash = read_committed_hash(&hash_path);

    // CheckOnly is a read-only verification path: never mutate the
    // filesystem. It must work on read-only CI mounts and when the
    // output directory does not exist yet — a missing directory simply
    // means the GIF is missing, which is `Stale`.
    if matches!(mode, GifMode::CheckOnly) {
        let gif_present = gif_path.exists();
        let hash_matches = committed_hash.value() == Some(current_hash);

        return if gif_present && hash_matches {
            GifStatus::Fresh {
                gif_path,
                hash: current_hash,
            }
        } else {
            GifStatus::Stale {
                gif_path,
                current: current_hash,
                committed: committed_hash.value(),
                committed_error: committed_hash.error(),
            }
        };
    }

    // Probe VHS availability before mutating the filesystem so machines
    // without VHS skip cleanly even when the output directory is on a
    // read-only or permission-restricted mount.
    //
    // `AlwaysGenerate` is an explicit user request to regenerate, so a
    // missing VHS binary must surface as a hard failure rather than a
    // silent skip. Other modes treat a missing VHS as a benign skip and
    // return `VhsNotInstalled`.
    if let Err(err) = check_vhs_installed() {
        return vhs_missing_status(mode, err);
    }

    if let Err(err) = std::fs::create_dir_all(output_dir) {
        return GifStatus::DirCreateFailed(err);
    }

    if matches!(mode, GifMode::GenerateIfStale)
        && gif_path.exists()
        && committed_hash.value() == Some(current_hash)
    {
        return GifStatus::CacheHit(gif_path);
    }

    // Trailing newline so the sidecar is a well-formed text file and
    // end-of-file fixers do not rewrite it after every regeneration.
    let hash_string = format!("{current_hash}\n");
    let screenshot_path = output_dir.join(format!("{name}.png"));

    let tape = VhsTape::from_scenario_with_settings(
        scenario,
        vhs.binary_path,
        &screenshot_path,
        vhs.env_pairs,
        vhs.settings,
    );

    let tape_path = output_dir.join(format!("{name}.tape"));

    match tape.execute(&tape_path) {
        Ok(_) => {
            let _ = std::fs::write(&hash_path, &hash_string);
            let _ = std::fs::remove_file(&tape_path);
            let _ = std::fs::remove_file(&screenshot_path);

            GifStatus::Generated(gif_path)
        }
        Err(err) => {
            let _ = std::fs::remove_file(&tape_path);

            GifStatus::TapeExecutionFailed(err)
        }
    }
}

/// Map a [`check_vhs_installed`] failure into a [`GifStatus`] based on the
/// active [`GifMode`].
///
/// `AlwaysGenerate` is an explicit user request to regenerate, so a
/// missing VHS binary surfaces as [`GifStatus::TapeExecutionFailed`].
/// Every other mode treats a missing VHS as the benign
/// [`GifStatus::VhsNotInstalled`] skip.
fn vhs_missing_status(mode: GifMode, err: VhsError) -> GifStatus {
    match mode {
        GifMode::AlwaysGenerate => GifStatus::TapeExecutionFailed(err),
        _ => GifStatus::VhsNotInstalled,
    }
}

/// Read the cached hash from an on-disk sidecar.
fn read_committed_hash(hash_path: &Path) -> CommittedHash {
    let raw = match std::fs::read_to_string(hash_path) {
        Ok(raw) => raw,
        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return CommittedHash::Missing,
        Err(err) => {
            return CommittedHash::Invalid(format!("failed to read hash sidecar: {err}"));
        }
    };

    match raw.trim().parse::<u64>() {
        Ok(hash) => CommittedHash::Value(hash),
        Err(err) => CommittedHash::Invalid(format!("failed to parse hash sidecar as u64: {err}")),
    }
}

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

    #[test]
    fn feature_demo_builder_sets_metadata() {
        // Arrange / Act
        let demo = FeatureDemo::new("test_feature")
            .title("Test Feature")
            .description("A test description.");

        // Assert
        assert_eq!(demo.meta.name, "test_feature");
        assert_eq!(demo.meta.title, "Test Feature");
        assert_eq!(demo.meta.description, "A test description.");
    }

    #[test]
    fn feature_demo_defaults_title_to_name() {
        // Arrange / Act
        let demo = FeatureDemo::new("my_feature");

        // Assert
        assert_eq!(demo.meta.title, "my_feature");
        assert_eq!(demo.meta.description, "");
    }

    #[test]
    fn feature_demo_defaults_to_feature_demo_gif_settings() {
        // Arrange / Act
        let demo = FeatureDemo::new("settings_check");
        let expected = VhsTapeSettings::feature_demo();

        // Assert
        assert_eq!(demo.gif_settings.width, expected.width);
        assert_eq!(demo.gif_settings.height, expected.height);
        assert_eq!(demo.gif_settings.font_size, expected.font_size);
        assert_eq!(demo.gif_settings.theme, expected.theme);
    }

    #[test]
    fn feature_demo_gif_output_dir_configurable() {
        // Arrange / Act
        let demo = FeatureDemo::new("dir_check").gif_output_dir("/tmp/gifs");

        // Assert
        assert_eq!(demo.gif_output_dir.as_deref(), Some(Path::new("/tmp/gifs")));
    }

    #[test]
    fn feature_demo_no_gif_dir_means_none() {
        // Arrange / Act
        let demo = FeatureDemo::new("no_gif");

        // Assert
        assert!(demo.gif_output_dir.is_none());
    }

    #[test]
    fn feature_demo_default_mode_is_generate_if_stale() {
        // Arrange / Act
        let demo = FeatureDemo::new("mode_check");

        // Assert
        assert_eq!(demo.gif_mode, GifMode::GenerateIfStale);
    }

    #[test]
    fn feature_demo_gif_mode_configurable() {
        // Arrange / Act
        let demo = FeatureDemo::new("mode_check").gif_mode(GifMode::CheckOnly);

        // Assert
        assert_eq!(demo.gif_mode, GifMode::CheckOnly);
    }

    #[test]
    fn feature_demo_collects_redactions_in_declaration_order() {
        // Arrange / Act
        let demo = FeatureDemo::new("redaction_check")
            .redact(Redaction::hex_after("wt/", 8, "<hash>"))
            .redact(Redaction::hex_after("commit ", 7, "<commit>"));

        // Assert
        let redacted: Vec<String> = demo
            .redactions
            .iter()
            .map(|redaction| redaction.apply("wt/4175e5af commit 9c0b17f"))
            .collect();

        assert_eq!(
            redacted,
            vec![
                "wt/<hash> commit 9c0b17f".to_string(),
                "wt/4175e5af commit <commit>".to_string(),
            ],
        );
    }

    #[test]
    fn vhs_missing_status_always_generate_is_hard_failure() {
        // Arrange
        let err = VhsError::NotInstalled("missing".to_string());

        // Act
        let status = vhs_missing_status(GifMode::AlwaysGenerate, err);

        // Assert
        assert!(
            matches!(status, GifStatus::TapeExecutionFailed(_)),
            "AlwaysGenerate must surface missing VHS as a hard failure, got {status:?}",
        );
        assert!(status.is_failure());
    }

    #[test]
    fn vhs_missing_status_generate_if_stale_is_benign_skip() {
        // Arrange
        let err = VhsError::NotInstalled("missing".to_string());

        // Act
        let status = vhs_missing_status(GifMode::GenerateIfStale, err);

        // Assert
        assert!(matches!(status, GifStatus::VhsNotInstalled));
        assert!(!status.is_failure());
    }

    #[test]
    fn vhs_missing_status_check_only_is_benign_skip() {
        // Arrange — `CheckOnly` short-circuits before the VHS probe in
        // `generate_gif`, but the helper must still treat it as benign so
        // future refactors that route through it do not regress to a hard
        // failure.
        let err = VhsError::NotInstalled("missing".to_string());

        // Act
        let status = vhs_missing_status(GifMode::CheckOnly, err);

        // Assert
        assert!(matches!(status, GifStatus::VhsNotInstalled));
        assert!(!status.is_failure());
    }

    #[test]
    fn compute_frame_hash_deterministic() {
        // Arrange
        let frame = TerminalFrame::new(80, 24, b"Hello");
        let mut report = ProofReport::new("hash_test");
        report.add_capture("snap", "Snapshot", &frame);

        // Act
        let hash_a = compute_frame_hash(&report, &[]);
        let hash_b = compute_frame_hash(&report, &[]);

        // Assert
        assert_eq!(hash_a, hash_b);
    }

    #[test]
    fn compute_frame_hash_differs_for_different_content() {
        // Arrange
        let frame_a = TerminalFrame::new(80, 24, b"Hello");
        let frame_b = TerminalFrame::new(80, 24, b"World");

        let mut report_a = ProofReport::new("a");
        report_a.add_capture("snap", "A", &frame_a);

        let mut report_b = ProofReport::new("b");
        report_b.add_capture("snap", "B", &frame_b);

        // Act
        let hash_a = compute_frame_hash(&report_a, &[]);
        let hash_b = compute_frame_hash(&report_b, &[]);

        // Assert
        assert_ne!(hash_a, hash_b);
    }

    #[test]
    fn compute_frame_hash_empty_report() {
        // Arrange
        let report = ProofReport::new("empty");

        // Act
        let hash = compute_frame_hash(&report, &[]);

        // Assert — empty reports use the stable FNV-1a offset basis.
        assert_eq!(hash, 0xcbf2_9ce4_8422_2325);
    }

    #[test]
    fn compute_frame_hash_ignores_redacted_tokens() {
        // Arrange — the same UI showing two different generated hashes.
        let frame_a = TerminalFrame::new(80, 24, b"branch wt/4175e5af");
        let frame_b = TerminalFrame::new(80, 24, b"branch wt/9c0b17ff");

        let mut report_a = ProofReport::new("a");
        report_a.add_capture("snap", "A", &frame_a);

        let mut report_b = ProofReport::new("b");
        report_b.add_capture("snap", "B", &frame_b);

        let redactions = [Redaction::hex_after("wt/", 8, "<hash>")];

        // Act
        let hash_a = compute_frame_hash(&report_a, &redactions);
        let hash_b = compute_frame_hash(&report_b, &redactions);

        // Assert — with the token redacted the two frames hash alike.
        assert_eq!(hash_a, hash_b);
        assert_ne!(
            compute_frame_hash(&report_a, &[]),
            compute_frame_hash(&report_b, &[]),
            "without the redaction the same UI must still hash differently",
        );
    }

    #[test]
    fn redaction_replaces_every_matching_token() {
        // Arrange — the worktree path and the branch label both carry the hash.
        let redaction = Redaction::hex_after("wt/", 8, "<hash>");
        let frame_text = "<tmp>/<tempdir>/wt/4175e5af  wt/4175e5af";

        // Act
        let redacted = redaction.apply(frame_text);

        // Assert
        assert_eq!(redacted, "<tmp>/<tempdir>/wt/<hash>  wt/<hash>");
    }

    #[test]
    fn redaction_replaces_a_token_cut_off_by_the_terminal_edge() {
        // Arrange — the footer path runs past the right edge, so the frame
        // keeps only the leading digits of the hash.
        let redaction = Redaction::hex_after("wt/", 8, "<hash>");

        // Act
        let short = redaction.apply("<tmp>/<tempdir>/agentty_root/wt/53a");
        let shorter = redaction.apply("<tmp>/<tempdir>/agentty_root/wt/5");

        // Assert — however many digits survive, the frame reads the same.
        assert_eq!(short, "<tmp>/<tempdir>/agentty_root/wt/<hash>");
        assert_eq!(shorter, short);
    }

    #[test]
    fn redaction_preserves_runs_longer_than_the_rule() {
        // Arrange — an 8-digit rule must not clip a full-length hash, and a
        // non-hex label after the prefix is not a hash at all.
        let redaction = Redaction::hex_after("wt/", 8, "<hash>");
        let frame_text = "wt/4175e5afff  wt/topic";

        // Act
        let redacted = redaction.apply(frame_text);

        // Assert
        assert_eq!(redacted, frame_text);
    }

    #[test]
    fn redaction_with_empty_prefix_is_inert() {
        // Arrange
        let redaction = Redaction::hex_after("", 8, "<hash>");
        let frame_text = "wt/4175e5af";

        // Act
        let redacted = redaction.apply(frame_text);

        // Assert
        assert_eq!(redacted, frame_text);
    }

    #[test]
    fn redaction_literal_replaces_every_occurrence() {
        // Arrange — the header paints the version once per captured frame.
        let redaction = Redaction::literal("Agentty v0.13.0", "Agentty <version>");
        let frame_text = "Agentty v0.13.0 | FYI\nAgentty v0.13.0";

        // Act
        let redacted = redaction.apply(frame_text);

        // Assert
        assert_eq!(redacted, "Agentty <version> | FYI\nAgentty <version>");
    }

    #[test]
    fn redaction_literal_with_empty_needle_is_inert() {
        // Arrange
        let redaction = Redaction::literal("", "<version>");
        let frame_text = "Agentty v0.13.0";

        // Act
        let redacted = redaction.apply(frame_text);

        // Assert
        assert_eq!(redacted, frame_text);
    }

    #[test]
    fn normalized_frame_bytes_for_hash_removes_tempfile_directory_names() {
        // Arrange
        let temp_root = std::env::temp_dir()
            .canonicalize()
            .unwrap_or_else(|_| std::env::temp_dir())
            .to_string_lossy()
            .trim_end_matches('/')
            .to_string();
        let first_frame = format!("{temp_root}/.tmpAlpha123/test-project");
        let second_frame = format!("{temp_root}/.tmpBeta456/test-project");

        // Act
        let first_normalized = normalized_frame_bytes_for_hash(first_frame.as_bytes(), &[]);
        let second_normalized = normalized_frame_bytes_for_hash(second_frame.as_bytes(), &[]);

        // Assert
        assert_eq!(first_normalized, second_normalized);
        assert_eq!(
            String::from_utf8(first_normalized).expect("normalized frame should be utf8"),
            "<tmp>/<tempdir>/test-project",
        );
    }

    #[test]
    fn normalize_tempfile_segments_preserves_non_tempfile_paths() {
        // Arrange
        let frame_text = "<tmp>/stable-project";

        // Act
        let normalized = normalize_tempfile_segments(frame_text);

        // Assert
        assert_eq!(normalized, frame_text);
    }

    #[test]
    fn hash_sidecar_path_uses_dot_prefix_next_to_gif() {
        // Arrange
        let dir = Path::new("/tmp/features");

        // Act
        let sidecar = hash_sidecar_path(dir, "session_creation");

        // Assert
        assert_eq!(sidecar, Path::new("/tmp/features/.session_creation.hash"));
    }

    #[test]
    fn read_committed_hash_returns_missing_for_missing_file() {
        // Arrange
        let dir = tempfile::TempDir::new().expect("failed to create temp dir");
        let missing = dir.path().join(".missing.hash");

        // Act
        let parsed = read_committed_hash(&missing);

        // Assert
        assert_eq!(parsed, CommittedHash::Missing);
    }

    #[test]
    fn read_committed_hash_parses_trimmed_decimal() {
        // Arrange
        let dir = tempfile::TempDir::new().expect("failed to create temp dir");
        let path = dir.path().join(".valid.hash");
        std::fs::write(&path, "  12345\n").expect("write hash");

        // Act
        let parsed = read_committed_hash(&path);

        // Assert
        assert_eq!(parsed, CommittedHash::Value(12345));
    }

    #[test]
    fn generate_gif_check_only_does_not_create_output_dir() {
        // Arrange
        let temp = tempfile::TempDir::new().expect("failed to create temp dir");
        let missing_dir = temp.path().join("never_created");
        let report = ProofReport::new("check_only_readonly");
        let scenario = Scenario::new("check_only_readonly");
        let settings = VhsTapeSettings::feature_demo();
        let binary = Path::new("/usr/bin/true");
        let env_pairs: &[(&str, &str)] = &[];
        let vhs = VhsContext {
            settings: &settings,
            binary_path: binary,
            env_pairs,
        };

        // Act
        let status = generate_gif(
            &scenario,
            &report,
            "check_only_readonly",
            &missing_dir,
            GifContext {
                mode: GifMode::CheckOnly,
                redactions: &[],
            },
            vhs,
        );

        // Assert — verdict is Stale with a missing sidecar and the output
        // directory is untouched.
        let GifStatus::Stale {
            committed,
            committed_error,
            ..
        } = status
        else {
            unreachable!("expected Stale verdict, got {status:?}");
        };

        assert!(committed.is_none());
        assert!(committed_error.is_none());
        assert!(
            !missing_dir.exists(),
            "CheckOnly must not create the output directory",
        );
    }

    #[test]
    fn generate_gif_check_only_returns_fresh_when_gif_and_sidecar_match() {
        // Arrange — pre-stage a GIF file and a sidecar whose contents equal
        // the hash that `compute_frame_hash` would produce for the report.
        let temp = tempfile::TempDir::new().expect("failed to create temp dir");
        let output_dir = temp.path();
        let name = "check_only_fresh";

        let frame = TerminalFrame::new(80, 24, b"Hello");
        let mut report = ProofReport::new(name);
        report.add_capture("snap", "Snapshot", &frame);

        let expected_hash = compute_frame_hash(&report, &[]);

        let gif_path = output_dir.join(format!("{name}.gif"));
        std::fs::write(&gif_path, b"fake-gif-bytes").expect("write fake gif");

        let sidecar = hash_sidecar_path(output_dir, name);
        std::fs::write(&sidecar, expected_hash.to_string()).expect("write sidecar");

        let scenario = Scenario::new(name);
        let settings = VhsTapeSettings::feature_demo();
        let binary = Path::new("/usr/bin/true");
        let env_pairs: &[(&str, &str)] = &[];
        let vhs = VhsContext {
            settings: &settings,
            binary_path: binary,
            env_pairs,
        };

        // Act
        let status = generate_gif(
            &scenario,
            &report,
            name,
            output_dir,
            GifContext {
                mode: GifMode::CheckOnly,
                redactions: &[],
            },
            vhs,
        );

        // Assert — verdict is Fresh and exposes the GIF path plus the
        // computed hash.
        let GifStatus::Fresh {
            gif_path: returned_path,
            hash,
        } = status
        else {
            unreachable!("expected Fresh verdict, got {status:?}");
        };

        assert_eq!(returned_path, gif_path);
        assert_eq!(hash, expected_hash);
    }

    #[test]
    fn generate_gif_check_only_reports_invalid_sidecar() {
        // Arrange
        let temp = tempfile::TempDir::new().expect("failed to create temp dir");
        let output_dir = temp.path();
        let name = "check_only_invalid_sidecar";

        let frame = TerminalFrame::new(80, 24, b"Hello");
        let mut report = ProofReport::new(name);
        report.add_capture("snap", "Snapshot", &frame);

        let gif_path = output_dir.join(format!("{name}.gif"));
        std::fs::write(&gif_path, b"fake-gif-bytes").expect("write fake gif");

        let sidecar = hash_sidecar_path(output_dir, name);
        std::fs::write(&sidecar, "not-a-number").expect("write invalid sidecar");

        let scenario = Scenario::new(name);
        let settings = VhsTapeSettings::feature_demo();
        let binary = Path::new("/usr/bin/true");
        let env_pairs: &[(&str, &str)] = &[];
        let vhs = VhsContext {
            settings: &settings,
            binary_path: binary,
            env_pairs,
        };

        // Act
        let status = generate_gif(
            &scenario,
            &report,
            name,
            output_dir,
            GifContext {
                mode: GifMode::CheckOnly,
                redactions: &[],
            },
            vhs,
        );

        // Assert
        let GifStatus::Stale {
            gif_path: returned_path,
            committed,
            committed_error,
            ..
        } = status
        else {
            unreachable!("expected Stale verdict, got {status:?}");
        };

        assert_eq!(returned_path, gif_path);
        assert!(committed.is_none());
        assert!(
            committed_error
                .as_deref()
                .is_some_and(|err| err.contains("failed to parse hash sidecar")),
            "expected parse error, got {committed_error:?}",
        );
    }

    #[test]
    fn read_committed_hash_returns_invalid_for_garbage() {
        // Arrange
        let dir = tempfile::TempDir::new().expect("failed to create temp dir");
        let path = dir.path().join(".garbage.hash");
        std::fs::write(&path, "not-a-number").expect("write hash");

        // Act
        let parsed = read_committed_hash(&path);

        // Assert
        let CommittedHash::Invalid(err) = parsed else {
            unreachable!("expected invalid hash sidecar, got {parsed:?}");
        };

        assert!(err.contains("failed to parse hash sidecar"));
    }

    #[test]
    fn gif_status_generated_returns_path() {
        // Arrange
        let status = GifStatus::Generated(PathBuf::from("/tmp/test.gif"));

        // Act / Assert
        assert_eq!(status.gif_path(), Some(Path::new("/tmp/test.gif")));
        assert!(!status.is_failure());
        assert!(!status.is_stale());
    }

    #[test]
    fn gif_status_cache_hit_returns_path() {
        // Arrange
        let status = GifStatus::CacheHit(PathBuf::from("/tmp/cached.gif"));

        // Act / Assert
        assert_eq!(status.gif_path(), Some(Path::new("/tmp/cached.gif")));
        assert!(!status.is_failure());
        assert!(!status.is_stale());
    }

    #[test]
    fn gif_status_vhs_not_installed_is_not_failure() {
        // Arrange
        let status = GifStatus::VhsNotInstalled;

        // Act / Assert
        assert!(status.gif_path().is_none());
        assert!(!status.is_failure());
        assert!(!status.is_stale());
    }

    #[test]
    fn gif_status_no_output_dir_is_not_failure() {
        // Arrange
        let status = GifStatus::NoOutputDir;

        // Act / Assert
        assert!(status.gif_path().is_none());
        assert!(!status.is_failure());
        assert!(!status.is_stale());
    }

    #[test]
    fn gif_status_dir_create_failed_is_failure() {
        // Arrange
        let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        let status = GifStatus::DirCreateFailed(err);

        // Act / Assert
        assert!(status.gif_path().is_none());
        assert!(status.is_failure());
        assert!(!status.is_stale());
    }

    #[test]
    fn gif_status_tape_execution_failed_is_failure() {
        // Arrange
        let err = VhsError::ExecutionFailed("vhs crashed".to_string());
        let status = GifStatus::TapeExecutionFailed(err);

        // Act / Assert
        assert!(status.gif_path().is_none());
        assert!(status.is_failure());
        assert!(!status.is_stale());
    }

    #[test]
    fn gif_status_fresh_exposes_path_and_is_not_stale() {
        // Arrange
        let status = GifStatus::Fresh {
            gif_path: PathBuf::from("/tmp/feature.gif"),
            hash: 42,
        };

        // Act / Assert
        assert_eq!(status.gif_path(), Some(Path::new("/tmp/feature.gif")));
        assert!(!status.is_failure());
        assert!(!status.is_stale());
    }

    #[test]
    fn gif_status_stale_exposes_path_and_is_stale() {
        // Arrange
        let status = GifStatus::Stale {
            gif_path: PathBuf::from("/tmp/feature.gif"),
            current: 42,
            committed: Some(7),
            committed_error: None,
        };

        // Act / Assert
        assert_eq!(status.gif_path(), Some(Path::new("/tmp/feature.gif")));
        assert!(!status.is_failure());
        assert!(status.is_stale());
    }
}