dodot-lib 5.0.0

Core library for dodot dotfiles manager
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
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use crate::datastore::{CommandRunner, DataStore, DidRunStatus};
use crate::fs::Fs;
use crate::paths::Pather;
use crate::{DodotError, Result};

/// Suffix used on the sibling file that snapshots the run-once script
/// content at the time it was last successfully executed.
///
/// Layout: alongside each sentinel `<filename>-<hash>`, the snapshot
/// lives at `<filename>-<hash>.snapshot` in the same handler data dir
/// (`<datastore>/packs/<pack>/<handler>/`). Snapshots are plain
/// regular files — users who want to manage run-once state by hand
/// can delete the sentinel + snapshot pair to roll a file back to
/// `NeverRan`.
///
/// Old sentinels predating PR C of #169 have no sibling — `did_run`
/// surfaces `previous_snapshot: None` in that case so `dodot status`
/// can render the `ran older version` state without diff details
/// (and `dodot status --diff` can omit the entry from its output).
pub(crate) const SNAPSHOT_SUFFIX: &str = ".snapshot";

/// Length of the hex hash suffix used in sentinel names.
///
/// Sentinels are named `<filename>-<hash>` where `<hash>` is the
/// first 8 bytes of a SHA-256 in lowercase hex — exactly 16 chars.
/// [`extract_sentinel_hash`] uses this to split a candidate sentinel
/// name into filename and hash without committing to "split on last
/// `-`" (filenames may contain hyphens).
const HASH_LEN: usize = 16;

/// Parse the unix timestamp recorded in a sentinel file's content.
///
/// `run_and_record` writes `completed|<unix-secs>` to each sentinel.
/// Returns `Some(ts)` when the content has that shape, `None` for
/// any other content (older sentinel formats, manually-edited files,
/// truncated reads). Callers in `did_run` use this to order
/// multiple non-matching sentinels by recency for tie-break.
fn parse_completed_timestamp(content: &str) -> Option<u64> {
    let payload = content.trim_end().strip_prefix("completed|")?;
    payload.parse::<u64>().ok()
}

/// Parse a sentinel filename into its `(filename, hash)` parts.
///
/// Returns `None` for any name that doesn't end in `-<16 lowercase
/// hex chars>` — including the `.snapshot` sibling files, which
/// have a different suffix shape.
fn extract_sentinel_hash(sentinel_name: &str) -> Option<(&str, &str)> {
    if sentinel_name.len() < HASH_LEN + 1 {
        return None;
    }
    let split_at = sentinel_name.len() - HASH_LEN - 1;
    let (head, tail) = sentinel_name.split_at(split_at);
    let mut chars = tail.chars();
    if chars.next() != Some('-') {
        return None;
    }
    let hash = &tail[1..];
    if hash.len() != HASH_LEN
        || !hash
            .chars()
            .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
    {
        return None;
    }
    Some((head, hash))
}

/// Validate that `raw` is a safe relative path to be used under `base`.
///
/// Defense-in-depth against path traversal: rejects absolute paths, `..`
/// components, and anything that would escape `base`. Returns the
/// normalised relative `PathBuf` on success.
fn validate_safe_relative(raw: &str, base: &Path) -> Result<PathBuf> {
    let candidate = Path::new(raw);
    let mut cleaned = PathBuf::new();
    for component in candidate.components() {
        match component {
            Component::Normal(n) => cleaned.push(n),
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(DodotError::Other(format!(
                    "unsafe datastore path: {} (would escape {})",
                    raw,
                    base.display()
                )));
            }
        }
    }
    if cleaned.as_os_str().is_empty() {
        return Err(DodotError::Other(format!(
            "empty datastore path (from {raw:?})"
        )));
    }
    Ok(cleaned)
}

/// Extract the leading documentation comment block from a script.
///
/// Skips an optional `#!` shebang and any blank lines, then collects
/// contiguous `#`-prefixed lines. From each line, every leading `#`
/// character and any following whitespace is stripped, so `## Section`
/// becomes `Section`. Stops at the first non-comment, non-blank line.
/// Used to print "what does this script do" before kicking it off, so
/// the user has context while it runs.
pub(crate) fn extract_header_block(content: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut iter = content.lines().peekable();
    if matches!(iter.peek(), Some(l) if l.starts_with("#!")) {
        iter.next();
    }
    while matches!(iter.peek(), Some(l) if l.trim().is_empty()) {
        iter.next();
    }
    for line in iter {
        let t = line.trim_start();
        if !t.starts_with('#') || t.starts_with("#!") {
            break;
        }
        let stripped = t.trim_start_matches('#').trim_start().to_string();
        out.push(stripped);
    }
    out
}

/// [`DataStore`] implementation backed by the real filesystem.
///
/// State is stored as symlinks and sentinel files under the XDG data
/// directory. The double-link architecture works as follows:
///
/// ```text
/// ~/dotfiles/vim/vimrc                              (source)
///   -> ~/.local/share/dodot/packs/vim/symlink/vimrc (data link)
///     -> ~/.vimrc                                   (user link)
/// ```
pub struct FilesystemDataStore {
    fs: Arc<dyn Fs>,
    paths: Arc<dyn Pather>,
    runner: Arc<dyn CommandRunner>,
}

impl FilesystemDataStore {
    pub fn new(fs: Arc<dyn Fs>, paths: Arc<dyn Pather>, runner: Arc<dyn CommandRunner>) -> Self {
        Self { fs, paths, runner }
    }
}

impl DataStore for FilesystemDataStore {
    fn create_data_link(&self, pack: &str, handler: &str, source_file: &Path) -> Result<PathBuf> {
        let filename = source_file.file_name().ok_or_else(|| {
            crate::DodotError::Other(format!(
                "source file has no filename: {}",
                source_file.display()
            ))
        })?;

        let link_dir = self.paths.handler_data_dir(pack, handler);
        let link_path = link_dir.join(filename);

        self.fs.mkdir_all(&link_dir)?;

        // Idempotent: if the link already points to the correct source, skip.
        if self.fs.is_symlink(&link_path) {
            if let Ok(current_target) = self.fs.readlink(&link_path) {
                if current_target == source_file {
                    return Ok(link_path);
                }
            }
            // Wrong target — remove and re-create.
            self.fs.remove_file(&link_path)?;
        }

        self.fs.symlink(source_file, &link_path)?;
        Ok(link_path)
    }

    fn create_user_link(&self, datastore_path: &Path, user_path: &Path) -> Result<()> {
        // Create parent directory
        if let Some(parent) = user_path.parent() {
            self.fs.mkdir_all(parent)?;
        }

        // If something already exists at user_path, handle it
        if self.fs.is_symlink(user_path) {
            // Existing symlink — check if it's correct
            if let Ok(current_target) = self.fs.readlink(user_path) {
                if current_target == datastore_path {
                    return Ok(()); // Already correct
                }
            }
            // Wrong target — remove and re-create
            self.fs.remove_file(user_path)?;
        } else if self.fs.exists(user_path) {
            // Exists but is not a symlink — conflict
            return Err(crate::DodotError::SymlinkConflict {
                path: user_path.to_path_buf(),
            });
        }

        self.fs.symlink(datastore_path, user_path)
    }

    fn run_and_record(
        &self,
        pack: &str,
        handler: &str,
        executable: &str,
        arguments: &[String],
        sentinel: &str,
        force: bool,
    ) -> Result<()> {
        // Idempotent: skip if sentinel exists
        if !force && self.has_sentinel(pack, handler, sentinel)? {
            return Ok(());
        }

        // Provisioning scripts are consequential and can take a while; surface
        // start/end markers on stderr so the user knows what's running and
        // whether it succeeded. The script's own stdout/stderr still flows
        // through the runner as before.
        //
        // The script path is the last argument by convention: install
        // invokes `bash -- <path>` / `zsh -- <path>` and homebrew invokes
        // `brew bundle --file <path>`. Using the last arg directly (vs a
        // filename-with-dot heuristic) means extensionless install scripts
        // — which the install handler explicitly supports — also get a
        // header block printed.
        let script_path = arguments.last().cloned();
        let display_name = script_path
            .as_deref()
            .and_then(|p| Path::new(p).file_name())
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| executable.to_string());
        let header = format!("==== {pack}{handler}{display_name}");
        let tty = std::io::IsTerminal::is_terminal(&std::io::stderr());
        let dim = if tty { "\x1b[2m" } else { "" };
        let green = if tty { "\x1b[32m" } else { "" };
        let red = if tty { "\x1b[31m" } else { "" };
        let reset = if tty { "\x1b[0m" } else { "" };
        eprintln!("{header}  {dim}running…{reset}");

        // Best-effort: print the script's leading comment block so the
        // user knows what's about to run. Silently skipped on read error
        // (script could be a binary, missing, or unreadable).
        if let Some(path_str) = script_path.as_deref() {
            if let Ok(content) = self.fs.read_to_string(Path::new(path_str)) {
                let lines = extract_header_block(&content);
                if !lines.is_empty() {
                    let stdout = std::io::stdout();
                    let mut h = stdout.lock();
                    use std::io::Write;
                    for line in lines {
                        let _ = writeln!(h, "{dim}    {line}{reset}");
                    }
                }
            }
        }

        let result = self.runner.run(executable, arguments);
        match &result {
            Ok(_) => eprintln!("{header}  {green}OK{reset}"),
            Err(_) => eprintln!("{header}  {red}FAILED{reset}"),
        }
        result?;

        // Record sentinel
        let sentinel_dir = self.paths.handler_data_dir(pack, handler);
        self.fs.mkdir_all(&sentinel_dir)?;

        let sentinel_path = sentinel_dir.join(sentinel);
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        let content = format!("completed|{timestamp}");
        self.fs.write_file(&sentinel_path, content.as_bytes())?;

        // Snapshot the file we just ran so that a future `did_run`
        // can return its previous content for diff display when the
        // current file's hash differs (notify-don't-rerun, #169 PR
        // C). The path of the file ran is the last argument by
        // convention — same as the header-block read above. Snapshot
        // writes are best-effort: if the read or write fails, log
        // and move on. The sentinel itself is already recorded, so
        // the user's run state is correct; only the diff capability
        // is lost.
        if let Some(path_str) = script_path.as_deref() {
            let snapshot_path = sentinel_dir.join(format!("{sentinel}{SNAPSHOT_SUFFIX}"));
            match self.fs.read_file(Path::new(path_str)) {
                Ok(bytes) => {
                    if let Err(e) = self.fs.write_file(&snapshot_path, &bytes) {
                        tracing::warn!(
                            pack,
                            handler,
                            sentinel,
                            error = %e,
                            "snapshot write failed (best-effort; sentinel still recorded)"
                        );
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        pack,
                        handler,
                        sentinel,
                        path = path_str,
                        error = %e,
                        "snapshot source read failed (best-effort; sentinel still recorded)"
                    );
                }
            }
        }

        Ok(())
    }

    fn has_sentinel(&self, pack: &str, handler: &str, sentinel: &str) -> Result<bool> {
        let sentinel_path = self.paths.handler_data_dir(pack, handler).join(sentinel);
        Ok(self.fs.exists(&sentinel_path))
    }

    fn did_run(
        &self,
        pack: &str,
        handler: &str,
        filename: &str,
        current_hash: &str,
    ) -> Result<DidRunStatus> {
        let handler_dir = self.paths.handler_data_dir(pack, handler);
        if !self.fs.exists(&handler_dir) {
            return Ok(DidRunStatus::NeverRan);
        }

        // Collect every sentinel for this filename (each shaped
        // `<filename>-<16 hex chars>`). Snapshot siblings end in
        // `.snapshot` and are filtered out by `extract_sentinel_hash`.
        let matches: Vec<(String, String)> = self
            .fs
            .read_dir(&handler_dir)?
            .into_iter()
            .filter(|e| e.is_file)
            .filter_map(|e| {
                let (fname, hash) = extract_sentinel_hash(&e.name)?;
                (fname == filename).then(|| (e.name.clone(), hash.to_string()))
            })
            .collect();

        if matches.is_empty() {
            return Ok(DidRunStatus::NeverRan);
        }

        // RanCurrent if any sentinel records the current hash.
        if matches.iter().any(|(_, h)| h == current_hash) {
            return Ok(DidRunStatus::RanCurrent);
        }

        // For tie-break between multiple non-matching sentinels, pick
        // the sentinel with the most recent `completed|<unix-ts>`
        // payload (written by `run_and_record`). This is the closest
        // signal we have to "most recent prior run" without needing
        // mtime access through the Fs trait. Sentinels whose payload
        // doesn't parse fall to the bottom of the ranking (timestamp
        // 0); ties on timestamp break by lexical order on the
        // sentinel filename for determinism.
        let prior = matches
            .into_iter()
            .map(|(name, hash)| {
                let path = handler_dir.join(&name);
                let ts = self
                    .fs
                    .read_to_string(&path)
                    .ok()
                    .as_deref()
                    .and_then(parse_completed_timestamp)
                    .unwrap_or(0);
                (name, hash, ts)
            })
            .max_by(|a, b| a.2.cmp(&b.2).then_with(|| a.0.cmp(&b.0)))
            .expect("non-empty checked above");
        let (prior_sentinel_name, prior_hash, _) = prior;

        let snapshot_path = handler_dir.join(format!("{prior_sentinel_name}{SNAPSHOT_SUFFIX}"));
        let previous_snapshot = if self.fs.exists(&snapshot_path) {
            self.fs.read_file(&snapshot_path).ok()
        } else {
            None
        };

        Ok(DidRunStatus::RanDifferent {
            previous_hash: prior_hash,
            previous_snapshot,
        })
    }

    fn remove_state(&self, pack: &str, handler: &str) -> Result<()> {
        let state_dir = self.paths.handler_data_dir(pack, handler);
        if !self.fs.exists(&state_dir) {
            return Ok(());
        }
        self.fs.remove_dir_all(&state_dir)
    }

    fn has_handler_state(&self, pack: &str, handler: &str) -> Result<bool> {
        let state_dir = self.paths.handler_data_dir(pack, handler);
        if !self.fs.exists(&state_dir) {
            return Ok(false);
        }
        let entries = self.fs.read_dir(&state_dir)?;
        Ok(!entries.is_empty())
    }

    fn list_pack_handlers(&self, pack: &str) -> Result<Vec<String>> {
        let pack_dir = self.paths.pack_data_dir(pack);
        if !self.fs.exists(&pack_dir) {
            return Ok(Vec::new());
        }
        let entries = self.fs.read_dir(&pack_dir)?;
        Ok(entries
            .into_iter()
            .filter(|e| e.is_dir)
            .map(|e| e.name)
            .collect())
    }

    fn list_handler_sentinels(&self, pack: &str, handler: &str) -> Result<Vec<String>> {
        let handler_dir = self.paths.handler_data_dir(pack, handler);
        if !self.fs.exists(&handler_dir) {
            return Ok(Vec::new());
        }
        let entries = self.fs.read_dir(&handler_dir)?;
        Ok(entries
            .into_iter()
            .filter(|e| e.is_file)
            .map(|e| e.name)
            .collect())
    }

    fn write_rendered_file(
        &self,
        pack: &str,
        handler: &str,
        filename: &str,
        content: &[u8],
    ) -> Result<PathBuf> {
        let dir = self.paths.handler_data_dir(pack, handler);
        let relative = validate_safe_relative(filename, &dir)?;
        let path = dir.join(&relative);
        // Create the full parent chain (supports nested filenames like "sub/file.txt")
        if let Some(parent) = path.parent() {
            self.fs.mkdir_all(parent)?;
        } else {
            self.fs.mkdir_all(&dir)?;
        }
        self.fs.write_file(&path, content)?;
        Ok(path)
    }

    fn write_rendered_file_with_mode(
        &self,
        pack: &str,
        handler: &str,
        filename: &str,
        content: &[u8],
        mode: u32,
    ) -> Result<PathBuf> {
        let dir = self.paths.handler_data_dir(pack, handler);
        let relative = validate_safe_relative(filename, &dir)?;
        let path = dir.join(&relative);
        if let Some(parent) = path.parent() {
            self.fs.mkdir_all(parent)?;
        } else {
            self.fs.mkdir_all(&dir)?;
        }
        // Atomic create-with-mode + chmod-empty + write — the
        // bytes never sit on disk at a permissive mode.
        self.fs.write_file_with_mode(&path, content, mode)?;
        Ok(path)
    }

    fn write_rendered_dir(&self, pack: &str, handler: &str, relative: &str) -> Result<PathBuf> {
        let dir = self.paths.handler_data_dir(pack, handler);
        let rel = validate_safe_relative(relative, &dir)?;
        let path = dir.join(&rel);
        self.fs.mkdir_all(&path)?;
        Ok(path)
    }

    fn sentinel_path(&self, pack: &str, handler: &str, sentinel: &str) -> PathBuf {
        self.paths.handler_data_dir(pack, handler).join(sentinel)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::datastore::{CommandOutput, CommandRunner};
    use crate::testing::TempEnvironment;
    use std::sync::Mutex;

    #[test]
    fn extract_header_block_skips_shebang() {
        let content = "#!/bin/bash\n# Install nvm\n# Requires curl\necho hi\n";
        assert_eq!(
            extract_header_block(content),
            vec!["Install nvm".to_string(), "Requires curl".to_string()]
        );
    }

    #[test]
    fn extract_header_block_no_shebang() {
        let content = "# header line\necho hi\n";
        assert_eq!(extract_header_block(content), vec!["header line"]);
    }

    #[test]
    fn extract_header_block_blanks_between_shebang_and_comments() {
        let content = "#!/bin/bash\n\n\n# first\n# second\nstuff\n";
        assert_eq!(
            extract_header_block(content),
            vec!["first".to_string(), "second".to_string()]
        );
    }

    #[test]
    fn extract_header_block_stops_at_first_non_comment() {
        let content = "# a\n# b\necho mid\n# late\n";
        assert_eq!(
            extract_header_block(content),
            vec!["a".to_string(), "b".to_string()]
        );
    }

    #[test]
    fn extract_header_block_strips_extra_hashes_and_spaces() {
        // Common style: `## section` or `#  spaced`. Strip all leading
        // `#` then a single optional space.
        let content = "## Section\n#   spaced\n";
        assert_eq!(
            extract_header_block(content),
            vec!["Section".to_string(), "spaced".to_string()]
        );
    }

    #[test]
    fn extract_header_block_empty_input() {
        assert!(extract_header_block("").is_empty());
    }

    #[test]
    fn extract_header_block_no_comments() {
        assert!(extract_header_block("#!/bin/bash\necho hi\n").is_empty());
    }

    /// Mock command runner that records calls and can be configured to
    /// succeed or fail.
    struct MockCommandRunner {
        calls: Mutex<Vec<String>>,
        should_fail: bool,
    }

    impl MockCommandRunner {
        fn new() -> Self {
            Self {
                calls: Mutex::new(Vec::new()),
                should_fail: false,
            }
        }

        fn failing() -> Self {
            Self {
                calls: Mutex::new(Vec::new()),
                should_fail: true,
            }
        }

        fn calls(&self) -> Vec<String> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl CommandRunner for MockCommandRunner {
        fn run(&self, executable: &str, arguments: &[String]) -> Result<CommandOutput> {
            let cmd_str = format!("{} {}", executable, arguments.join(" "));
            self.calls.lock().unwrap().push(cmd_str.trim().to_string());
            if self.should_fail {
                Err(crate::DodotError::CommandFailed {
                    command: cmd_str.trim().to_string(),
                    exit_code: 1,
                    stderr: "mock failure".to_string(),
                })
            } else {
                Ok(CommandOutput {
                    exit_code: 0,
                    stdout: String::new(),
                    stderr: String::new(),
                })
            }
        }
    }

    fn make_datastore(env: &TempEnvironment) -> (FilesystemDataStore, Arc<MockCommandRunner>) {
        let runner = Arc::new(MockCommandRunner::new());
        let ds = FilesystemDataStore::new(env.fs.clone(), env.paths.clone(), runner.clone());
        (ds, runner)
    }

    // ── create_data_link ────────────────────────────────────────

    #[test]
    fn create_data_link_creates_symlink() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "set nocompatible")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        let link_path = ds.create_data_link("vim", "symlink", &source).unwrap();

        // Link should be in the handler data dir
        assert_eq!(
            link_path,
            env.paths.handler_data_dir("vim", "symlink").join("vimrc")
        );

        // Link should point to source
        env.assert_symlink(&link_path, &source);
    }

    #[test]
    fn create_data_link_is_idempotent() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "set nocompatible")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");

        let path1 = ds.create_data_link("vim", "symlink", &source).unwrap();
        let path2 = ds.create_data_link("vim", "symlink", &source).unwrap();

        assert_eq!(path1, path2);
        env.assert_symlink(&path1, &source);
    }

    #[test]
    fn create_data_link_replaces_wrong_target() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "v1")
            .file("vimrc-new", "v2")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source1 = env.dotfiles_root.join("vim/vimrc");
        let source2 = env.dotfiles_root.join("vim/vimrc-new");

        // Create initial link to source1
        let link_dir = env.paths.handler_data_dir("vim", "symlink");
        env.fs.mkdir_all(&link_dir).unwrap();
        // Manually create a link named "vimrc-new" pointing to source1 (wrong target)
        let wrong_link = link_dir.join("vimrc-new");
        env.fs.symlink(&source1, &wrong_link).unwrap();

        // Now create_data_link should fix it to point at source2
        let link_path = ds.create_data_link("vim", "symlink", &source2).unwrap();
        env.assert_symlink(&link_path, &source2);
    }

    // ── create_user_link ────────────────────────────────────────

    #[test]
    fn create_user_link_creates_symlink() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let datastore_path = env.data_dir.join("packs/vim/symlink/vimrc");
        let user_path = env.home.join(".vimrc");

        // Create the datastore file so the symlink target exists
        env.fs.mkdir_all(datastore_path.parent().unwrap()).unwrap();
        env.fs.write_file(&datastore_path, b"link target").unwrap();

        ds.create_user_link(&datastore_path, &user_path).unwrap();

        env.assert_symlink(&user_path, &datastore_path);
    }

    #[test]
    fn create_user_link_is_idempotent() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let datastore_path = env.data_dir.join("packs/vim/symlink/vimrc");
        let user_path = env.home.join(".vimrc");

        env.fs.mkdir_all(datastore_path.parent().unwrap()).unwrap();
        env.fs.write_file(&datastore_path, b"x").unwrap();

        ds.create_user_link(&datastore_path, &user_path).unwrap();
        ds.create_user_link(&datastore_path, &user_path).unwrap();

        env.assert_symlink(&user_path, &datastore_path);
    }

    #[test]
    fn create_user_link_conflict_with_regular_file() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let datastore_path = env.data_dir.join("packs/vim/symlink/vimrc");
        let user_path = env.home.join(".vimrc");

        // Create a regular file at the user path
        env.fs.write_file(&user_path, b"existing content").unwrap();

        let err = ds
            .create_user_link(&datastore_path, &user_path)
            .unwrap_err();
        assert!(
            matches!(err, crate::DodotError::SymlinkConflict { .. }),
            "expected SymlinkConflict, got: {err}"
        );
    }

    #[test]
    fn create_user_link_replaces_wrong_symlink() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let wrong_target = env.data_dir.join("wrong");
        let correct_target = env.data_dir.join("correct");
        let user_path = env.home.join(".vimrc");

        env.fs.mkdir_all(&env.data_dir).unwrap();
        env.fs.write_file(&wrong_target, b"wrong").unwrap();
        env.fs.write_file(&correct_target, b"right").unwrap();

        // Create wrong symlink
        env.fs.symlink(&wrong_target, &user_path).unwrap();

        // Should fix it
        ds.create_user_link(&correct_target, &user_path).unwrap();
        env.assert_symlink(&user_path, &correct_target);
    }

    // ── Double-link chain ───────────────────────────────────────

    #[test]
    fn full_double_link_chain() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "set nocompatible")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        let user_path = env.home.join(".vimrc");

        // Step 1: data link
        let datastore_path = ds.create_data_link("vim", "symlink", &source).unwrap();

        // Step 2: user link
        ds.create_user_link(&datastore_path, &user_path).unwrap();

        // Verify the full chain
        env.assert_double_link("vim", "symlink", "vimrc", &source, &user_path);

        // Reading through the chain should yield the original content
        let content = env.fs.read_to_string(&user_path).unwrap();
        assert_eq!(content, "set nocompatible");
    }

    // ── run_and_record / has_sentinel ───────────────────────────

    #[test]
    fn run_and_record_creates_sentinel() {
        let env = TempEnvironment::builder().build();
        let (ds, runner) = make_datastore(&env);

        assert!(!ds.has_sentinel("vim", "install", "install.sh-abc").unwrap());

        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["hello".into()],
            "install.sh-abc",
            false,
        )
        .unwrap();

        assert!(ds.has_sentinel("vim", "install", "install.sh-abc").unwrap());
        assert_eq!(runner.calls(), vec!["echo hello"]);

        // Sentinel file should contain "completed|..."
        let sentinel_path = env
            .paths
            .handler_data_dir("vim", "install")
            .join("install.sh-abc");
        let content = env.fs.read_to_string(&sentinel_path).unwrap();
        assert!(content.starts_with("completed|"), "got: {content}");
    }

    #[test]
    fn run_and_record_is_idempotent() {
        let env = TempEnvironment::builder().build();
        let (ds, runner) = make_datastore(&env);

        ds.run_and_record("vim", "install", "echo", &["first".into()], "s1", false)
            .unwrap();
        ds.run_and_record("vim", "install", "echo", &["second".into()], "s1", false)
            .unwrap();

        // Command only ran once
        assert_eq!(runner.calls(), vec!["echo first"]);
    }

    #[test]
    fn run_and_record_propagates_command_failure() {
        let env = TempEnvironment::builder().build();
        let runner = Arc::new(MockCommandRunner::failing());
        let ds = FilesystemDataStore::new(env.fs.clone(), env.paths.clone(), runner);

        let err = ds
            .run_and_record("vim", "install", "bad-cmd", &[], "s1", false)
            .unwrap_err();

        assert!(
            matches!(err, crate::DodotError::CommandFailed { .. }),
            "expected CommandFailed, got: {err}"
        );

        // No sentinel should be created on failure
        assert!(!ds.has_sentinel("vim", "install", "s1").unwrap());
    }

    // ── remove_state ────────────────────────────────────────────

    #[test]
    fn remove_state_clears_handler_dir() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "x")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        ds.create_data_link("vim", "symlink", &source).unwrap();
        assert!(ds.has_handler_state("vim", "symlink").unwrap());

        ds.remove_state("vim", "symlink").unwrap();
        env.assert_no_handler_state("vim", "symlink");
    }

    #[test]
    fn remove_state_is_noop_when_no_state() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        // Should not error
        ds.remove_state("nonexistent", "handler").unwrap();
    }

    // ── has_handler_state ───────────────────────────────────────

    #[test]
    fn has_handler_state_false_when_no_dir() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        assert!(!ds.has_handler_state("vim", "symlink").unwrap());
    }

    #[test]
    fn has_handler_state_false_when_empty_dir() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let dir = env.paths.handler_data_dir("vim", "symlink");
        env.fs.mkdir_all(&dir).unwrap();

        assert!(!ds.has_handler_state("vim", "symlink").unwrap());
    }

    #[test]
    fn has_handler_state_true_when_entries_exist() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "x")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source = env.dotfiles_root.join("vim/vimrc");
        ds.create_data_link("vim", "symlink", &source).unwrap();

        assert!(ds.has_handler_state("vim", "symlink").unwrap());
    }

    // ── list_pack_handlers ──────────────────────────────────────

    #[test]
    fn list_pack_handlers_returns_handler_dirs() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("vimrc", "x")
            .file("aliases.sh", "y")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let source1 = env.dotfiles_root.join("vim/vimrc");
        let source2 = env.dotfiles_root.join("vim/aliases.sh");
        ds.create_data_link("vim", "symlink", &source1).unwrap();
        ds.create_data_link("vim", "shell", &source2).unwrap();

        let mut handlers = ds.list_pack_handlers("vim").unwrap();
        handlers.sort();
        assert_eq!(handlers, vec!["shell", "symlink"]);
    }

    #[test]
    fn list_pack_handlers_empty_when_no_pack_state() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let handlers = ds.list_pack_handlers("nonexistent").unwrap();
        assert!(handlers.is_empty());
    }

    // ── list_handler_sentinels ──────────────────────────────────

    #[test]
    fn list_handler_sentinels_returns_file_names() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["a".into()],
            "install.sh-aaa",
            false,
        )
        .unwrap();
        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["b".into()],
            "install.sh-bbb",
            false,
        )
        .unwrap();

        let mut sentinels = ds.list_handler_sentinels("vim", "install").unwrap();
        sentinels.sort();
        assert_eq!(sentinels, vec!["install.sh-aaa", "install.sh-bbb"]);
    }

    #[test]
    fn list_handler_sentinels_empty_when_no_state() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let sentinels = ds.list_handler_sentinels("vim", "install").unwrap();
        assert!(sentinels.is_empty());
    }

    // ── write_rendered_file ───────────────────────────────────────

    #[test]
    fn write_rendered_file_creates_regular_file() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let path = ds
            .write_rendered_file("app", "preprocessed", "config.toml", b"host = localhost")
            .unwrap();

        assert!(env.fs.exists(&path));
        assert!(!env.fs.is_symlink(&path));
        assert_eq!(env.fs.read_to_string(&path).unwrap(), "host = localhost");
    }

    #[test]
    fn write_rendered_file_overwrites_existing() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let path1 = ds
            .write_rendered_file("app", "preprocessed", "config.toml", b"version 1")
            .unwrap();
        let path2 = ds
            .write_rendered_file("app", "preprocessed", "config.toml", b"version 2")
            .unwrap();

        assert_eq!(path1, path2);
        assert_eq!(env.fs.read_to_string(&path1).unwrap(), "version 2");
    }

    #[test]
    fn write_rendered_file_empty_content() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let path = ds
            .write_rendered_file("app", "preprocessed", "empty.conf", b"")
            .unwrap();

        assert!(env.fs.exists(&path));
        assert_eq!(env.fs.read_to_string(&path).unwrap(), "");
    }

    #[test]
    fn write_rendered_file_binary_content() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let binary = vec![0u8, 1, 2, 255, 254, 253];
        let path = ds
            .write_rendered_file("app", "preprocessed", "data.bin", &binary)
            .unwrap();

        assert_eq!(env.fs.read_file(&path).unwrap(), binary);
    }

    #[test]
    fn write_rendered_file_creates_parent_dirs() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        // handler_data_dir doesn't exist yet — write_rendered_file should create it
        let handler_dir = env.paths.handler_data_dir("newpack", "preprocessed");
        assert!(!env.fs.exists(&handler_dir));

        let path = ds
            .write_rendered_file("newpack", "preprocessed", "file.txt", b"hello")
            .unwrap();

        assert!(env.fs.exists(&path));
        assert_eq!(env.fs.read_to_string(&path).unwrap(), "hello");
    }

    #[test]
    fn write_rendered_file_rejects_absolute_path() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let err = ds
            .write_rendered_file("app", "preprocessed", "/etc/passwd", b"x")
            .unwrap_err();
        assert!(
            matches!(err, crate::DodotError::Other(ref m) if m.contains("unsafe")),
            "expected unsafe-path error, got: {err}"
        );
    }

    #[test]
    fn write_rendered_file_rejects_parent_dir() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let err = ds
            .write_rendered_file("app", "preprocessed", "../escape.txt", b"x")
            .unwrap_err();
        assert!(
            matches!(err, crate::DodotError::Other(ref m) if m.contains("unsafe")),
            "expected unsafe-path error, got: {err}"
        );
    }

    #[test]
    fn write_rendered_dir_creates_dir() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let path = ds
            .write_rendered_dir("app", "preprocessed", "sub/nested")
            .unwrap();

        assert!(env.fs.is_dir(&path));
        assert!(!env.fs.is_symlink(&path));
    }

    #[test]
    fn write_rendered_dir_is_idempotent() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let p1 = ds.write_rendered_dir("app", "preprocessed", "d").unwrap();
        let p2 = ds.write_rendered_dir("app", "preprocessed", "d").unwrap();
        assert_eq!(p1, p2);
        assert!(env.fs.is_dir(&p1));
    }

    #[test]
    fn write_rendered_dir_rejects_unsafe_paths() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        assert!(ds
            .write_rendered_dir("app", "preprocessed", "/abs")
            .is_err());
        assert!(ds
            .write_rendered_dir("app", "preprocessed", "../esc")
            .is_err());
    }

    #[test]
    fn write_rendered_file_supports_nested_filename() {
        // A filename containing `/` should be written to the corresponding
        // nested directory under the handler data dir, creating any needed
        // parents. This preserves source structure for preprocessor output.
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let path = ds
            .write_rendered_file("app", "preprocessed", "sub/nested/file.txt", b"deep")
            .unwrap();

        assert!(env.fs.exists(&path));
        assert!(!env.fs.is_symlink(&path));
        assert_eq!(env.fs.read_to_string(&path).unwrap(), "deep");
        assert!(
            path.to_string_lossy().contains("sub/nested/file.txt"),
            "path should contain nested structure: {}",
            path.display()
        );
    }

    // ── did_run + snapshots ─────────────────────────────────────

    #[test]
    fn extract_sentinel_hash_parses_canonical_form() {
        // 16 lowercase hex chars after the last `-`.
        assert_eq!(
            extract_sentinel_hash("install.sh-abcdef0123456789"),
            Some(("install.sh", "abcdef0123456789"))
        );
        // Filenames with hyphens still parse — boundary is fixed-width hash.
        assert_eq!(
            extract_sentinel_hash("my-install-script.sh-0123456789abcdef"),
            Some(("my-install-script.sh", "0123456789abcdef"))
        );
    }

    #[test]
    fn extract_sentinel_hash_rejects_non_sentinels() {
        // No dash.
        assert_eq!(extract_sentinel_hash("install.sh"), None);
        // Hash too short.
        assert_eq!(extract_sentinel_hash("install.sh-abc"), None);
        // Hash has uppercase (we expect lowercase).
        assert_eq!(extract_sentinel_hash("install.sh-ABCDEF0123456789"), None);
        // Snapshot sibling files — the suffix is ".snapshot", not 16 hex chars.
        assert_eq!(
            extract_sentinel_hash("install.sh-abcdef0123456789.snapshot"),
            None
        );
        // Hash contains non-hex.
        assert_eq!(extract_sentinel_hash("install.sh-abcdef012345xyz9"), None);
    }

    #[test]
    fn did_run_never_ran_when_no_state() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);
        let status = ds
            .did_run("vim", "install", "install.sh", "abcdef0123456789")
            .unwrap();
        assert_eq!(status, DidRunStatus::NeverRan);
    }

    #[test]
    fn did_run_returns_current_when_hash_matches() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["hi".into()],
            "install.sh-abcdef0123456789",
            false,
        )
        .unwrap();

        let status = ds
            .did_run("vim", "install", "install.sh", "abcdef0123456789")
            .unwrap();
        assert_eq!(status, DidRunStatus::RanCurrent);
    }

    #[test]
    fn did_run_returns_different_when_only_other_hash_present() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("install.sh", "old content")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        // Run with one hash, then ask about a different one.
        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &[env
                .dotfiles_root
                .join("vim/install.sh")
                .to_string_lossy()
                .into()],
            "install.sh-aaaaaaaaaaaaaaaa",
            false,
        )
        .unwrap();

        let status = ds
            .did_run("vim", "install", "install.sh", "bbbbbbbbbbbbbbbb")
            .unwrap();
        match status {
            DidRunStatus::RanDifferent {
                previous_hash,
                previous_snapshot,
            } => {
                assert_eq!(previous_hash, "aaaaaaaaaaaaaaaa");
                // run_and_record wrote a snapshot sibling; we should
                // get the bytes back.
                assert_eq!(previous_snapshot, Some(b"old content".to_vec()));
            }
            other => panic!("expected RanDifferent, got {other:?}"),
        }
    }

    #[test]
    fn did_run_different_without_snapshot_returns_none() {
        // Pre-PR-C sentinel: no .snapshot sibling. did_run should
        // still classify as RanDifferent but with previous_snapshot=None.
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let sentinel_dir = env.paths.handler_data_dir("vim", "install");
        env.fs.mkdir_all(&sentinel_dir).unwrap();
        env.fs
            .write_file(
                &sentinel_dir.join("install.sh-aaaaaaaaaaaaaaaa"),
                b"completed|12345",
            )
            .unwrap();
        // No .snapshot file written — simulates pre-upgrade state.

        let status = ds
            .did_run("vim", "install", "install.sh", "bbbbbbbbbbbbbbbb")
            .unwrap();
        match status {
            DidRunStatus::RanDifferent {
                previous_hash,
                previous_snapshot,
            } => {
                assert_eq!(previous_hash, "aaaaaaaaaaaaaaaa");
                assert_eq!(previous_snapshot, None);
            }
            other => panic!("expected RanDifferent, got {other:?}"),
        }
    }

    #[test]
    fn did_run_ignores_other_filenames_in_same_handler_dir() {
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let sentinel_dir = env.paths.handler_data_dir("vim", "install");
        env.fs.mkdir_all(&sentinel_dir).unwrap();
        // Sentinel for a *different* filename.
        env.fs
            .write_file(
                &sentinel_dir.join("install.bash-aaaaaaaaaaaaaaaa"),
                b"completed|12345",
            )
            .unwrap();

        // Asking about install.sh should return NeverRan — the bash one
        // doesn't count.
        let status = ds
            .did_run("vim", "install", "install.sh", "bbbbbbbbbbbbbbbb")
            .unwrap();
        assert_eq!(status, DidRunStatus::NeverRan);
    }

    #[test]
    fn did_run_picks_most_recent_timestamp_for_tie_break() {
        // Two non-matching sentinels: the one with the newer
        // `completed|<ts>` payload wins, even when its hash sorts
        // earlier lexically. This is the recent-run-wins property
        // that ties the "ran older version" diff display to the
        // actual most-recent prior run.
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let sentinel_dir = env.paths.handler_data_dir("vim", "install");
        env.fs.mkdir_all(&sentinel_dir).unwrap();

        // Older run, hash sorts LATER lexically.
        env.fs
            .write_file(
                &sentinel_dir.join("install.sh-ffffffffffffffff"),
                b"completed|100",
            )
            .unwrap();
        // Newer run, hash sorts EARLIER lexically.
        env.fs
            .write_file(
                &sentinel_dir.join("install.sh-1111111111111111"),
                b"completed|900",
            )
            .unwrap();

        let status = ds
            .did_run("vim", "install", "install.sh", "0000000000000000")
            .unwrap();
        match status {
            DidRunStatus::RanDifferent { previous_hash, .. } => {
                // Recent (`|900`) should win over lex-last (`ffff…`).
                assert_eq!(previous_hash, "1111111111111111");
            }
            other => panic!("expected RanDifferent, got {other:?}"),
        }
    }

    #[test]
    fn did_run_unparseable_timestamp_falls_to_bottom() {
        // A sentinel with a malformed payload still classifies as a
        // prior run, but loses the tie-break to any parseable one.
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let sentinel_dir = env.paths.handler_data_dir("vim", "install");
        env.fs.mkdir_all(&sentinel_dir).unwrap();
        env.fs
            .write_file(
                &sentinel_dir.join("install.sh-aaaaaaaaaaaaaaaa"),
                b"garbage|not-a-number",
            )
            .unwrap();
        env.fs
            .write_file(
                &sentinel_dir.join("install.sh-bbbbbbbbbbbbbbbb"),
                b"completed|5",
            )
            .unwrap();

        let status = ds
            .did_run("vim", "install", "install.sh", "0000000000000000")
            .unwrap();
        match status {
            DidRunStatus::RanDifferent { previous_hash, .. } => {
                assert_eq!(previous_hash, "bbbbbbbbbbbbbbbb");
            }
            other => panic!("expected RanDifferent, got {other:?}"),
        }
    }

    #[test]
    fn parse_completed_timestamp_extracts_unix_seconds() {
        assert_eq!(
            parse_completed_timestamp("completed|1700000000"),
            Some(1700000000)
        );
        assert_eq!(parse_completed_timestamp("completed|0"), Some(0));
        assert_eq!(
            parse_completed_timestamp("completed|1700000000\n"),
            Some(1700000000)
        );
        assert_eq!(parse_completed_timestamp("completed|"), None);
        assert_eq!(parse_completed_timestamp("completed|not-a-number"), None);
        assert_eq!(parse_completed_timestamp("running|12345"), None);
        assert_eq!(parse_completed_timestamp(""), None);
    }

    #[test]
    fn run_and_record_writes_snapshot_sibling() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("install.sh", "#!/bin/sh\necho hello")
            .done()
            .build();
        let (ds, _) = make_datastore(&env);

        let abs = env.dotfiles_root.join("vim/install.sh");
        ds.run_and_record(
            "vim",
            "install",
            "bash",
            &["--".into(), abs.to_string_lossy().into()],
            "install.sh-abcdef0123456789",
            false,
        )
        .unwrap();

        let snapshot_path = env
            .paths
            .handler_data_dir("vim", "install")
            .join("install.sh-abcdef0123456789.snapshot");
        assert!(env.fs.exists(&snapshot_path), "snapshot sibling missing");
        assert_eq!(
            env.fs.read_to_string(&snapshot_path).unwrap(),
            "#!/bin/sh\necho hello"
        );
    }

    #[test]
    fn run_and_record_snapshot_failure_does_not_fail_run() {
        // If the script path can't be read, the sentinel still records
        // and run_and_record succeeds — snapshot is best-effort.
        let env = TempEnvironment::builder().build();
        let (ds, _) = make_datastore(&env);

        let ghost = env.dotfiles_root.join("vim/missing.sh");
        ds.run_and_record(
            "vim",
            "install",
            "echo",
            &["--".into(), ghost.to_string_lossy().into()],
            "missing.sh-abcdef0123456789",
            false,
        )
        .unwrap();

        // Sentinel exists.
        assert!(ds
            .has_sentinel("vim", "install", "missing.sh-abcdef0123456789")
            .unwrap());
        // Snapshot does not.
        let snapshot_path = env
            .paths
            .handler_data_dir("vim", "install")
            .join("missing.sh-abcdef0123456789.snapshot");
        assert!(!env.fs.exists(&snapshot_path));
    }

    // ── Object safety ───────────────────────────────────────────

    #[allow(dead_code)]
    fn assert_object_safe(_: &dyn DataStore) {}
}