cargo-cleanme 0.2.3

Safely clean inactive Cargo build artifacts through Cargo
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
use crate::error::AppError;
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
use std::{
    borrow::Cow,
    fs,
    io::Write,
    path::{Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
};

pub const CONFIG_TEMPLATE: &str = include_str!("../config.toml");
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default)]
    pub scan: ScanConfig,
    #[serde(default)]
    pub cleanup: CleanupConfig,
}
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CleanupConfig {
    #[serde(default)]
    pub allowed_output_roots: Vec<PathBuf>,
    #[serde(default)]
    pub policy: CleanupPolicyConfig,
}
#[derive(Clone, Debug, Deserialize, Serialize, Default)]
#[serde(deny_unknown_fields)]
pub struct CleanupPolicyConfig {
    #[serde(default)]
    pub min_reclaimable_bytes: u64,
    pub min_inactive_seconds: Option<u64>,
    #[serde(default)]
    pub include: Vec<String>,
    #[serde(default)]
    pub exclude: Vec<String>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ScanConfig {
    #[serde(default = "default_recency")]
    pub recency_seconds: u64,
    pub root: Option<PathBuf>,
    #[serde(default)]
    pub ignore: Vec<String>,
    #[serde(default)]
    pub unignore: Vec<PathBuf>,
    #[serde(default = "default_retention")]
    pub learned_root_retention_days: u32,
}
impl Default for ScanConfig {
    fn default() -> Self {
        Self {
            recency_seconds: 300,
            root: None,
            ignore: vec![],
            unignore: vec![],
            learned_root_retention_days: 30,
        }
    }
}
fn default_recency() -> u64 {
    300
}
fn default_retention() -> u32 {
    30
}
#[derive(Clone, Debug)]
pub struct ConfigPathResolver {
    override_path: Option<PathBuf>,
}
impl ConfigPathResolver {
    pub fn new(path: Option<PathBuf>) -> Self {
        Self {
            override_path: path,
        }
    }
    pub fn path(&self) -> Result<PathBuf, AppError> {
        if let Some(p) = &self.override_path {
            return Ok(p.clone());
        }
        let d = ProjectDirs::from("", "", "cargo-cleanme").ok_or_else(|| {
            AppError::Config("platform config directory is unavailable; use --config".into())
        })?;
        Ok(d.config_dir().join("config.toml"))
    }
}
pub fn load(path: &Path) -> Result<Config, AppError> {
    let mut c = if path.exists() {
        let s = fs::read_to_string(path)
            .map_err(|e| AppError::Config(format!("cannot read {}: {e}", path.display())))?;
        toml::from_str(&s)
            .map_err(|e| AppError::Config(format!("cannot parse {}: {e}", path.display())))?
    } else {
        Config::default()
    };
    if c.scan.recency_seconds == 0 {
        return Err(AppError::Config(
            "scan.recency_seconds must be greater than 0; 0 would disable the inactivity guard that keeps recently used artifacts out of cleanup".into(),
        ));
    }
    if c.scan.recency_seconds > u64::MAX / 1_000_000_000 {
        return Err(AppError::Config("scan.recency_seconds is too large".into()));
    }
    if c.scan.learned_root_retention_days > 3650 {
        return Err(AppError::Config(
            "scan.learned_root_retention_days must be between 0 and 3650".into(),
        ));
    }
    if let Some(p) = &c.scan.root {
        require_absolute(p, "scan.root")?;
    }
    for p in &c.scan.ignore {
        if !Path::new(p).is_absolute() {
            return Err(AppError::Config(format!(
                "ignore pattern must be absolute: {p}"
            )));
        }
    }
    for p in &c.scan.unignore {
        require_absolute(p, "unignore")?;
    }
    for p in &c.cleanup.allowed_output_roots {
        require_absolute(p, "cleanup.allowed_output_roots")?;
    }
    if let Some(seconds) = c.cleanup.policy.min_inactive_seconds
        && seconds > u64::MAX / 1_000_000_000
    {
        return Err(AppError::Config(
            "cleanup.policy.min_inactive_seconds is too large".into(),
        ));
    }
    // Every pattern the scanner and the cleaner compile is validated here, so
    // `config edit` fails exactly as loudly as the next scan/clean would.
    for pattern in c
        .cleanup
        .policy
        .include
        .iter()
        .chain(&c.cleanup.policy.exclude)
    {
        globset::Glob::new(pattern).map_err(|e| {
            AppError::Config(format!("invalid cleanup policy glob {pattern:?}: {e}"))
        })?;
    }
    for pattern in &c.scan.ignore {
        globset::Glob::new(pattern)
            .map_err(|e| AppError::Config(format!("invalid scan.ignore glob {pattern:?}: {e}")))?;
    }
    // Patterns are matched against canonicalized paths, so a pattern spelled the
    // way the user's own shell shows it (`/tmp/...` where `/tmp` is a symlink)
    // would silently match nothing. Canonicalize each pattern's literal prefix.
    c.scan.ignore = c
        .scan
        .ignore
        .iter()
        .map(|p| canonical_pattern_prefix(p, PatternKind::Glob))
        .collect();
    // `unignore` is a literal relative path, not a glob, so its canonical
    // spelling is spliced unescaped: escaping it would corrupt the path.
    c.scan.unignore = c
        .scan
        .unignore
        .iter()
        .map(|p| {
            PathBuf::from(canonical_pattern_prefix(
                &p.to_string_lossy(),
                PatternKind::Literal,
            ))
        })
        .collect();
    c.cleanup.policy.include = c
        .cleanup
        .policy
        .include
        .iter()
        .map(|p| canonical_pattern_prefix(p, PatternKind::Glob))
        .collect();
    c.cleanup.policy.exclude = c
        .cleanup
        .policy
        .exclude
        .iter()
        .map(|p| canonical_pattern_prefix(p, PatternKind::Glob))
        .collect();
    // The rewrite above manufactures pattern text that no longer exists in the
    // file, so what was validated on the way in is not what is compiled on the
    // way out. Validating the results is what stops a canonical spelling from
    // turning a good pattern into an uncompilable one (or, worse, a different
    // one). No authorization depends on this list: `ignore`/`include`/`exclude`
    // filter discovery and policy, never ownership.
    for pattern in c
        .scan
        .ignore
        .iter()
        .chain(&c.cleanup.policy.include)
        .chain(&c.cleanup.policy.exclude)
    {
        globset::Glob::new(pattern)
            .map_err(|e| AppError::Config(format!("invalid scan.ignore glob {pattern:?}: {e}")))?;
    }
    Ok(c)
}

/// How a pattern-shaped config value is matched, which decides whether its
/// canonical spelling may be bracket-escaped on the way in.
#[derive(Clone, Copy, PartialEq, Eq)]
enum PatternKind {
    /// Compiled by `globset`. A canonical directory name carrying a glob
    /// character would be read as a pattern, not as itself.
    Glob,
    /// Compared as a literal path (`scan.unignore` is a literal relative path by
    /// design, predating glob support).
    Literal,
}

/// A canonical path spelled the way `globset` matches it.
///
/// Both sides of the comparison are `/`-spelled. Candidates are normalized by
/// `globset`'s `Candidate::new` (`normalize_path`), and on Windows patterns get
/// the same treatment at compile time: `backslash_escape` defaults to
/// `!is_separator('\\')`, and with it off `parse_backslash` pushes a `/` for
/// every `\` — "normalize all patterns to use / as a separator".
///
/// That is also why the splice used to be a no-op here. It was gated on a
/// spelling that could not be escaped, and `\` — which every canonical Windows
/// path contains, and which `escape_glob_literal` used to reject outright — was
/// one of the rejected characters. The separator was never the problem; it was
/// only the reason the rewrite could not run.
fn glob_spelling(path: &Path) -> String {
    glob_spelling_with(&path.to_string_lossy(), std::path::MAIN_SEPARATOR)
}

/// [`glob_spelling`] for a spelling whose separators are known.
///
/// The separator is a parameter rather than a `cfg!` so the Windows answer can
/// be asserted on a Unix lane: `\` is the one character whose treatment differs
/// by platform, and it is the character this whole defect turned on.
/// `separator == '\\'` is the same test `globset` uses to tell that it is on
/// Windows (`backslash_escape: !is_separator('\\')`).
fn glob_spelling_with(canonical: &str, separator: char) -> String {
    let canonical = if separator == '\\' {
        dereference(canonical)
    } else {
        Cow::Borrowed(canonical)
    };
    canonical.replace(separator, "/")
}

/// Drop a Win32 verbatim prefix (`\\?\`), restoring the spelling a user writes.
///
/// `fs::canonicalize` hands back `\\?\C:\…` whenever the path it was given was
/// already verbatim, and can hand it back for paths that were not. The prefix is
/// a Win32 API artefact, not part of the path: a walked candidate is compared as
/// `Path::display` spells it, and — decisively — the `?` in `\\?\` is a glob
/// metacharacter, so a prefix left in place both reopens the split-at-`?`
/// problem and produces a pattern that matches nothing. Leaving it out would
/// repeat the original defect's failure direction on exactly the inputs that
/// exhibit it.
///
/// A verbatim UNC path is the other form: `\\?\UNC\server\share` names the same
/// thing as `\\server\share`, so it loses `?` and keeps its two separators.
fn dereference(canonical: &str) -> Cow<'_, str> {
    if let Some(unc) = canonical.strip_prefix(r"\\?\UNC\") {
        return Cow::Owned(format!(r"\\{unc}"));
    }
    match canonical.strip_prefix(r"\\?\") {
        Some(rest) => Cow::Borrowed(rest),
        None => Cow::Borrowed(canonical),
    }
}

/// Escape globset metacharacters in a literal path so it splices in as itself.
///
/// The input is expected to be `/`-spelled already ([`glob_spelling`]), which
/// is what makes the `\` arm reachable at all: after that normalization a `\` is
/// a character of a *file name*, never a separator. No Windows file name may
/// contain one, so on that platform the arm is unreachable; where it is
/// reachable (Unix) `\` is the escape character, so a literal one is doubled.
///
/// Returns `None` for a spelling that cannot be escaped, so the caller can leave
/// the user's pattern alone rather than guess. `{` opens an alternation that no
/// bracket form closes. `\` was in this set for exactly the reason
/// `glob_spelling` now handles, which is why that arm moved rather than
/// narrowing the reachable inputs.
fn escape_glob_literal(path: &str) -> Option<String> {
    let mut out = String::with_capacity(path.len());
    for c in path.chars() {
        match c {
            // `[]]` and `[[]` are single-character classes holding `]` and `[`;
            // globset's class parser accepts a leading `]` as a literal member.
            // `[` and `]` are legal Windows file-name characters, so this is not
            // a Unix-only precaution.
            '*' | '?' | '[' | ']' => {
                out.push('[');
                out.push(c);
                out.push(']');
            }
            '{' | '}' => return None,
            '\\' => out.push_str(r"\\"),
            _ => out.push(c),
        }
    }
    Some(out)
}

/// Rewrite a pattern's glob-free prefix to its canonical spelling.
///
/// Only the leading literal run can be canonicalized, so the suffix is copied
/// verbatim. The pattern is left untouched when the prefix is relative (it could
/// not be resolved against anything meaningful), when it ends in an escape
/// (the split would land inside an escape sequence), when it does not
/// resolve — a pattern naming a path that does not exist still means exactly
/// what it says: it matches nothing — or when the canonical spelling cannot be
/// escaped and therefore cannot be spliced without changing the match.
///
/// A `Glob` prefix is spliced in [`glob_spelling`]-normalized and escaped, so
/// the rewrite is no longer a no-op on any platform. A `Literal` one is spliced
/// in the filesystem's own spelling, because it is compared as a path rather
/// than compiled.
/// Whether a prefix ending in `\` is a dangling escape rather than a separator.
///
/// `\` is the escape character only where it is not a path separator —
/// `backslash_escape` defaults to `!is_separator('\\')`, the same rule
/// [`glob_spelling`] is built on. Where it *is* a separator, a prefix ending in
/// one is the ordinary structural trailing separator of `…/x/*`, and refusing it
/// would refuse every Windows pattern: `C:\dev\proj\*` has a prefix that ends in
/// `\`, so the check used to decline the whole rewrite on that platform. That was
/// the third Unix assumption to surface, and the hosted Windows lane found it the
/// same way it found the other two.
fn dangling_trailing_escape(prefix: &str, backslash_escapes: bool) -> bool {
    backslash_escapes && prefix.ends_with('\\')
}

fn canonical_pattern_prefix(pattern: &str, kind: PatternKind) -> String {
    let cut = pattern.find(['*', '?', '[', '{']).unwrap_or(pattern.len());
    let (prefix, tail) = pattern.split_at(cut);
    // Splitting after a dangling escape would land inside the escape sequence,
    // so the split is refused. A trailing *separator* is not that case.
    if dangling_trailing_escape(prefix, !std::path::is_separator('\\')) {
        return pattern.to_owned();
    }
    // Trailing separators are structural (`…/x/*` means "children of x"), so
    // they are preserved around the canonicalized directory name.
    let bare = prefix.trim_end_matches(['/', '\\']);
    if bare.is_empty() || !Path::new(bare).is_absolute() {
        return pattern.to_owned();
    }
    let separators = &prefix[bare.len()..];
    match fs::canonicalize(bare) {
        Ok(canonical) => {
            let native = canonical.to_string_lossy();
            if native == bare {
                pattern.to_owned()
            } else {
                // The canonical spelling is a real directory name, not a
                // pattern. Splicing it raw lets *its* glob characters rewrite
                // what the user's own pattern matches: a directory named
                // `real[abc]` becomes a character class that stops matching the
                // tree the user named and matches two they never wrote down.
                match kind {
                    // A literal path is compared as a `PathBuf`, not compiled,
                    // so escaping it would corrupt the path it names — and its
                    // separators are whatever the filesystem calls them.
                    PatternKind::Literal => format!("{native}{separators}{tail}"),
                    // `/`-spelled first, then escaped. Both halves are
                    // load-bearing: the spelling is what a candidate on any
                    // platform is compared against, and the escaping is what
                    // stops the directory's own `real[abc]` from being read as
                    // a character class.
                    PatternKind::Glob => match escape_glob_literal(&glob_spelling(&canonical)) {
                        Some(literal) => format!("{literal}{separators}{tail}"),
                        None => pattern.to_owned(),
                    },
                }
            }
        }
        Err(_) => pattern.to_owned(),
    }
}

pub fn load_or_create(path: &Path) -> Result<Config, AppError> {
    if !path.exists() {
        create_initial(path)?;
    }
    load(path)
}

/// Ensure a config editor target exists without requiring its current contents to parse.
pub fn ensure_exists(path: &Path) -> Result<(), AppError> {
    if !path.exists() {
        create_initial(path)?;
    }
    Ok(())
}
fn require_absolute(p: &Path, field: &str) -> Result<(), AppError> {
    if !p.is_absolute() {
        Err(AppError::Config(format!(
            "{field} must be absolute: {}",
            p.display()
        )))
    } else {
        Ok(())
    }
}
/// Name the step that failed without changing the error's kind.
///
/// Every branch in `create_initial` decides what to do next by inspecting
/// `e.kind()` — `AlreadyExists` means a concurrent writer won and is success,
/// everything else is a failure. Wrapping an error to add context must
/// therefore preserve its kind exactly, or the race handling below silently
/// stops recognising its own benign outcome.
///
/// It is also the only way a diagnostic can say *which* call failed. A bare
/// `AppError::Io` reports the kind and the OS message but not the step, and on
/// Windows two different calls can report the same kind.
/// Monotonic counter making each staging name unique within this process.
static STAGING_NONCE: AtomicU64 = AtomicU64::new(0);

fn step_error(step: &str, e: std::io::Error) -> std::io::Error {
    std::io::Error::new(e.kind(), format!("{step} failed: {e}"))
}

fn create_initial(path: &Path) -> Result<(), AppError> {
    if let Some(parent) = path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent).map_err(|e| step_error("creating the config directory", e))?;
    }
    let parent = path
        .parent()
        .filter(|p| !p.as_os_str().is_empty())
        .map(Path::to_path_buf)
        .unwrap_or_else(|| PathBuf::from("."));
    if !parent.exists() {
        return Err(AppError::Config(format!(
            "config directory is unavailable: {}",
            parent.display()
        )));
    }
    let file_name = path
        .file_name()
        .map(|s| s.to_os_string())
        .unwrap_or_else(|| std::ffi::OsString::from("config.toml"));
    // The staging name must be unique among everything that can be creating a
    // config at the same time, or "lost the race" becomes a routine event
    // dressed up as an error. The pid separates *processes*, so threads within
    // one process were the only remaining collision -- and they collided on
    // every concurrent first use, because they all started at the same
    // `attempt`. A process-wide nonce removes that collision instead of
    // teaching the code to recognise a lost one.
    //
    // The `attempt` suffix stays as a second line for the case the nonce cannot
    // cover: a stale `.tmp.` file left by a crashed process whose pid the OS
    // later reuses. That one really is a name collision, and `AlreadyExists` is
    // the authoritative answer to it.
    for attempt in 0..100 {
        let nonce = STAGING_NONCE.fetch_add(1, Ordering::Relaxed);
        let mut temp_name = file_name.clone();
        temp_name.push(format!(".tmp.{}.{}.{}", std::process::id(), nonce, attempt));
        let temp = parent.join(temp_name);
        let created = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&temp);
        let mut f = match created {
            Ok(f) => f,
            // Only a stale name from a previous process can land here now, and
            // `AlreadyExists` is the authoritative answer to that.
            //
            // It is deliberately NOT decided by probing `temp.exists()`. That
            // probe was tried and is wrong on both platforms: the winner of the
            // publication can unlink its staging file before a loser inspects
            // the path, so the name reads free and the real `AlreadyExists`
            // escapes as an error -- observed failing Linux, macOS, and the 1.89
            // lane -- and a Windows `PermissionDenied` leaks through the same
            // gap. A syscall answers whether the name was taken *then*; a probe
            // answers whether it is taken *now*. Where they disagree, the kind.
            //
            // A genuine permissions problem still hard-fails: with the nonce,
            // nothing else is competing for this name, so `PermissionDenied`
            // means exactly what it says.
            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
            Err(e) => return Err(AppError::Io(step_error("creating a staging file", e))),
        };
        let write_result: std::io::Result<()> = (|| {
            f.write_all(CONFIG_TEMPLATE.as_bytes())
                .map_err(|e| step_error("writing the staging file", e))?;
            f.sync_all()
                .map_err(|e| step_error("flushing the staging file", e))?;
            drop(f);
            // Creating the final link is atomic and never overwrites a
            // concurrent winner. Both names are siblings on the same volume.
            match fs::hard_link(&temp, path) {
                Ok(()) => {}
                // Some filesystems have no hard links at all: FAT32 and exFAT,
                // several CIFS mounts, and WSL's `/mnt/c` drvfs. There
                // `link(2)` reports "unsupported" *after* the staging file is
                // written, which used to make every single command fail at
                // startup, because `config::load_or_create` is on every path.
                //
                // The fallback keeps the property the design cannot give up —
                // never overwriting a concurrent winner — by creating the
                // destination with `create_new`, which is equally exclusive.
                // What it gives up is crash-atomicity of the *contents*: a
                // crash mid-write leaves a truncated file, which `load` refuses
                // rather than silently reading as defaults. That is the right
                // trade against not running at all.
                Err(e) if e.kind() == std::io::ErrorKind::Unsupported => {
                    // A successful `create_new` means this process owns the
                    // destination and no racer can have created it, so a later
                    // failure removes its own partial file — otherwise the
                    // lost-race check below would read our truncated write as a
                    // winner's complete config and call it success.
                    let mut published = fs::OpenOptions::new()
                        .write(true)
                        .create_new(true)
                        .open(path)
                        .map_err(|e| step_error("publishing the config", e))?;
                    let written = published
                        .write_all(CONFIG_TEMPLATE.as_bytes())
                        .and_then(|()| published.sync_all());
                    if let Err(e) = written {
                        drop(published);
                        let _ = fs::remove_file(path);
                        return Err(step_error("writing the config", e));
                    }
                }
                Err(e) => return Err(step_error("publishing the config", e)),
            }
            fs::remove_file(&temp).map_err(|e| step_error("removing the staging file", e))?;
            Ok(())
        })();
        if let Err(e) = write_result {
            let _ = fs::remove_file(&temp);
            // "A racer already published a complete config" is success, not
            // failure, and every caller reaching this point wants to carry on
            // with that file.
            //
            // Here the *filesystem* is the discriminator, because unlike the
            // staging name the destination is never unlinked: once published it
            // stays, so `path.is_file()` is a stable answer rather than a race
            // against a winner cleaning up. It is also the only file that can
            // exist at this path, because this is the code that publishes it,
            // and it is only ever published by hard-linking a fully written and
            // synced staging file -- so a regular file here is a complete
            // template, never a partial one. That makes the check independent
            // of which error the platform chose for the lost race: POSIX
            // reports `AlreadyExists`, and Windows can report
            // `PermissionDenied` for the same contention.
            if path.is_file() {
                return Ok(());
            }
            // A destination that exists but is not a regular file is still
            // refused: "exists" must not become "acceptable".
            if path.exists() {
                return Err(AppError::Config(format!(
                    "refusing to replace non-file config {}: {e}",
                    path.display()
                )));
            }
            return Err(AppError::Io(e));
        }
        return Ok(());
    }
    Err(AppError::Config(format!(
        "could not create a temporary config beside {}",
        path.display()
    )))
}
pub fn show(config: &Config) -> Result<String, AppError> {
    toml::to_string_pretty(config).map_err(|e| AppError::Config(e.to_string()))
}

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

    /// A TOML array element holding exactly one string value.
    ///
    /// The fixtures below are built from `Path::display()`, which on Windows
    /// contains backslashes — and inside a basic TOML string a backslash is an
    /// escape introducer, so `C:\Users\RUNNER~1\...\real[abc]` does not parse:
    /// `\U` is a valid escape for a 8-digit unicode escape and the rest is
    /// not, so the *fixture* failed before the subject could be consulted.
    /// Handing the value to the `toml` crate lets it choose the representation
    /// that encodes it legally, which is the approach `tests/cli_contract.rs`
    /// already uses for the same reason. The path text itself, brackets
    /// included, is unchanged — the bracket must survive into the parsed
    /// string, because it is what the canonical rewrite has to escape.
    ///
    /// Ungated since C024: the Windows lane writes a `\`-spelled pattern into
    /// TOML for exactly this reason, so this is no longer a Unix-only helper.
    /// C021's lesson stands for helpers that are *still* single-platform — this
    /// one has a caller on each side of the fence.
    fn toml_string(value: &str) -> String {
        toml::Value::String(value.to_owned()).to_string()
    }

    #[cfg(unix)]
    #[test]
    fn patterns_are_canonicalized_so_exclusions_actually_apply() {
        // H1/M2/L22: patterns are matched against canonicalized paths, so a
        // pattern spelled the way the shell shows the path matched nothing - an
        // exclusion that silently excluded nothing.
        use std::os::unix::fs::symlink;
        let d = tempfile::tempdir().unwrap();
        let real = d.path().join("real");
        fs::create_dir_all(real.join("workspace")).unwrap();
        let link_parent = d.path().join("link");
        fs::create_dir_all(&link_parent).unwrap();
        let link = link_parent.join("real");
        symlink(&real, &link).unwrap();
        assert_ne!(
            link.display().to_string(),
            real.display().to_string(),
            "the fixture needs a non-canonical spelling"
        );

        let config = d.path().join("config.toml");
        let shell_spelled = format!("{}/*", link.display());
        fs::write(
            &config,
            format!(
                "[scan]\nignore = [{}]\n[cleanup.policy]\nexclude = [{}]\n",
                toml_string(&shell_spelled),
                toml_string(&shell_spelled)
            ),
        )
        .unwrap();
        let loaded = load(&config).unwrap();
        let canonical_prefix = fs::canonicalize(&real).unwrap();
        assert_eq!(
            loaded.scan.ignore,
            vec![format!("{}/*", canonical_prefix.display())]
        );
        assert_eq!(
            loaded.cleanup.policy.exclude,
            vec![format!("{}/*", canonical_prefix.display())]
        );

        // A pattern with no glob metacharacter, and one that does not resolve,
        // keep their spelling (the latter still matches nothing, by definition).
        fs::write(
            &config,
            format!(
                "[cleanup.policy]\nexclude = [{}]\n",
                toml_string(&link.display().to_string())
            ),
        )
        .unwrap();
        assert_eq!(
            load(&config).unwrap().cleanup.policy.exclude,
            vec![canonical_prefix.display().to_string()]
        );
        fs::write(
            &config,
            format!(
                "[cleanup.policy]\nexclude = [{}]\n",
                toml_string(&format!("{}/does/not/exist/*", link.display()))
            ),
        )
        .unwrap();
        assert_eq!(
            load(&config).unwrap().cleanup.policy.exclude,
            vec![format!("{}/does/not/exist/*", link.display())]
        );
        // A relative pattern is never resolved against the process CWD.
        assert_eq!(
            canonical_pattern_prefix("relative/*", PatternKind::Glob),
            "relative/*",
            "relative patterns keep their spelling"
        );
    }

    // Unix-only, and the gate is the subject rather than the fixture. The
    // premise is a canonical spelling that (a) differs from what the user
    // wrote, which needs a second name for one directory, and (b) can be
    // spliced, which `escape_glob_literal` defines as "carries no `\`". Every
    // canonical path on Windows carries backslashes, so the glob rewrite is a
    // no-op on that platform and there is nothing here for it to get wrong.
    // The earlier `#[cfg(not(unix))]` branch sidestepped this by naming the
    // bracketed directory directly, which voided the premise: the bracket was
    // then in the *user's* pattern, the rewrite never ran, and the test could
    // only ever have failed. Reporting that honestly is the point.
    #[cfg(unix)]
    #[test]
    fn a_canonical_spelling_cannot_inject_glob_characters() {
        use std::os::unix::fs::symlink;
        // The rewrite validated the *user's* pattern and then spliced in text
        // that had never been validated. A directory named `real[abc]`, reached
        // through a symlink, turned `link/*` into a character class: the tree
        // the user named stopped matching, and two trees they never named
        // started being pruned.
        let d = tempfile::tempdir().unwrap();
        // Production canonicalizes a pattern's prefix before splicing it, so
        // the candidate it is matched against is always the *canonical*
        // spelling. On macOS the temporary directory sits under a symlinked
        // prefix (`/var` -> `/private/var`), so `tempdir()` and
        // `fs::canonicalize` disagree about the first path segment and the
        // fixture tested two different directories. Deriving every path from
        // the canonical root is what makes this case test the same thing on
        // every lane.
        let base = fs::canonicalize(d.path()).unwrap();
        let real = base.join("real[abc]");
        fs::create_dir_all(&real).unwrap();
        for sibling in ["reala", "realb"] {
            fs::create_dir_all(base.join(sibling)).unwrap();
        }
        let link = base.join("link");
        symlink(&real, &link).unwrap();
        assert_ne!(
            link.display().to_string(),
            real.display().to_string(),
            "premise: the fixture needs a spelling that is not the canonical one, \
             or the rewrite never has a bracketed name to splice"
        );

        let config = base.join("config.toml");
        fs::write(
            &config,
            format!(
                "[scan]\nignore = [{}]\n",
                toml_string(&format!("{}/*", link.display()))
            ),
        )
        .unwrap();
        let ignore = load(&config).unwrap().scan.ignore;
        assert_eq!(ignore.len(), 1);
        // The compiled pattern must match the tree the user named...
        let matcher = globset::Glob::new(&ignore[0]).unwrap().compile_matcher();
        assert!(
            matcher.is_match(format!("{}/proj", real.display())),
            "the named tree must still match: {}",
            ignore[0]
        );
        // ...and nothing else.
        for sibling in ["reala", "realb"] {
            assert!(
                !matcher.is_match(format!("{}/{}/proj", base.display(), sibling)),
                "{} must not be pruned by {}",
                sibling,
                ignore[0]
            );
        }
        // `unignore` is a literal path, so its canonical spelling is spliced
        // unescaped: escaping it would corrupt the path it names.
        let literal =
            canonical_pattern_prefix(&format!("{}/*", link.display()), PatternKind::Literal);
        assert_eq!(literal, format!("{}/*", real.display()));
        // A spelling with no portable escape is left exactly as written.
        let braces = base.join("a{b}c");
        fs::create_dir_all(&braces).unwrap();
        let brace_link = base.join("bracelink");
        symlink(&braces, &brace_link).unwrap();
        let written = format!("{}/*", brace_link.display());
        assert_eq!(
            canonical_pattern_prefix(&written, PatternKind::Glob),
            written,
            "a `{{` in the canonical spelling cannot be escaped, so the pattern is untouched"
        );
    }

    // Every lane. The escaped spelling and the matching consequences of it are
    // pure string work, so they are asserted where they can be asserted rather
    // than only on the one platform whose canonical spelling motivated C024.
    // What this cannot cover is `fs::canonicalize`'s own answer on Windows,
    // which is what the lane test below exists for.
    #[test]
    fn a_spliced_canonical_spelling_matches_the_directory_it_names() {
        let d = tempfile::tempdir().unwrap();
        // Derived from the canonical root for the same macOS reason the Unix
        // test above gives: `tempdir()` and `canonicalize` disagree about the
        // first segment under `/var`. Through `glob_spelling` because on
        // Windows `canonicalize` answers `\\?\C:\…`, and a fixture rooted there
        // would be testing the Win32 prefix rather than the directory name —
        // its `?` is a glob metacharacter, so the pattern split would land
        // inside it. The hosted Windows lane found exactly that.
        let base = PathBuf::from(glob_spelling(&fs::canonicalize(d.path()).unwrap()));
        let real = base.join("real[abc]");
        fs::create_dir_all(&real).unwrap();
        for sibling in ["reala", "realb"] {
            fs::create_dir_all(base.join(sibling)).unwrap();
        }

        // Both halves of the fix, asserted directly. The spelling is what a
        // candidate is compared against on *every* platform, so a `\` left in
        // it is a Windows-only defect: there it cannot match a candidate whose
        // separators have been normalized away, and the escape would have to be
        // the other escape as well.
        let spelling = glob_spelling(&real);
        assert!(
            !spelling.contains('\\'),
            "the spliced spelling must be /-spelled on every platform: {spelling}"
        );
        assert_eq!(
            spelling,
            format!("{}/real[abc]", glob_spelling(&base)),
            "a canonical path spells its own brackets, which is what has to be escaped"
        );
        let spliced = escape_glob_literal(&spelling)
            .expect("a bracketed name is escapable; only `{{` and `}}` are not");
        assert_eq!(spliced, format!("{}/real[[]abc[]]", glob_spelling(&base)));

        let matcher = globset::Glob::new(&format!("{spliced}/*"))
            .unwrap()
            .compile_matcher();
        assert!(
            matcher.is_match(format!("{}/proj", glob_spelling(&real))),
            "the named tree must match the spliced spelling {spliced}"
        );
        for sibling in ["reala", "realb"] {
            assert!(
                !matcher.is_match(format!("{}/{sibling}/proj", glob_spelling(&base))),
                "{sibling} must not match the spliced spelling {spliced}"
            );
        }

        // The premise of everything above, asserted rather than assumed: the
        // spelling that C024 shipped — the canonical name spliced in with its
        // brackets live — misses the tree the user named and prunes two they
        // never wrote down. If this ever stopped being true the assertions
        // above would be decoration.
        let unescaped = format!("{}/real[abc]/*", glob_spelling(&base));
        let unescaped = globset::Glob::new(&unescaped).unwrap().compile_matcher();
        assert!(
            !unescaped.is_match(format!("{}/proj", glob_spelling(&real))),
            "premise: the unescaped reading must NOT match the directory it names"
        );
        assert!(
            unescaped.is_match(format!("{}/reala/proj", glob_spelling(&base))),
            "premise: the unescaped reading must match a sibling, which is the defect"
        );

        // The same splice with the Windows answer to the platform-dependent
        // questions, asserted on this lane too. A `/`-spelled candidate is what
        // `globset` builds on every platform, so these two matches are the ones
        // a Windows run would make — which is why the rule can be pinned here
        // rather than only on a platform that has a Windows filesystem.
        //
        // The second case is what the hosted lane found: a verbatim
        // `\\?\C:\…` spelling has a `?` in it, which is both a metacharacter
        // and not part of the path. Splicing it as-is yields a pattern that
        // cannot match any candidate a walk produces.
        let windows_spliced =
            escape_glob_literal(&glob_spelling_with(r"C:\Users\runneradmin\real[abc]", '\\'))
                .unwrap();
        assert_eq!(
            windows_spliced, "C:/Users/runneradmin/real[[]abc[]]",
            "a Windows canonical spelling is `/`-spelled and its brackets escaped"
        );
        let windows = globset::Glob::new(&format!("{windows_spliced}/*"))
            .unwrap()
            .compile_matcher();
        assert!(
            windows.is_match("C:/Users/runneradmin/real[abc]/proj"),
            "the spliced Windows spelling must match the tree it names"
        );
        assert!(
            !windows.is_match("C:/Users/runneradmin/reala/proj"),
            "the spliced Windows spelling must not match a sibling"
        );

        // The same input verbatim, which is what `fs::canonicalize` answers on
        // a Windows lane. Stripping the prefix is what keeps the pattern
        // expressible at all: `?` is a metacharacter, so the prefix would
        // otherwise end up escaped into the middle of the pattern and require a
        // candidate no walk produces.
        for (verbatim, expected) in [
            (
                r"\\?\C:\Users\runneradmin\real[abc]",
                "C:/Users/runneradmin/real[abc]",
            ),
            (
                r"\\?\UNC\server\share\real[abc]",
                "//server/share/real[abc]",
            ),
        ] {
            let spelling = glob_spelling_with(verbatim, '\\');
            assert_eq!(
                spelling, expected,
                "a verbatim prefix is a Win32 artefact, not part of the path"
            );
            let spliced = escape_glob_literal(&spelling).unwrap();
            let matcher = globset::Glob::new(&format!("{spliced}/*"))
                .unwrap()
                .compile_matcher();
            assert!(
                matcher.is_match(format!("{expected}/proj")),
                "the de-verbatim spelling must still match the tree it names: {spliced}"
            );
        }

        // The third Windows refusal, asserted on every lane: a prefix ending in
        // `\` is a dangling escape only where `\` escapes. On Windows it is the
        // ordinary trailing separator of `C:\dev\proj\*`, and refusing it refused
        // the whole rewrite for every `\`-spelled pattern on the platform.
        assert!(
            !dangling_trailing_escape(r"C:\Users\runneradmin\proj\", false),
            "a trailing separator is not a dangling escape where `\\` is a separator"
        );
        assert!(
            dangling_trailing_escape("/home/you/proj\\", true),
            "a trailing `\\` is a dangling escape where it escapes"
        );
        assert!(!dangling_trailing_escape("/home/you/proj/", true));
    }

    // Unix, and the mirror of the defect above: a `\` is legal in a Unix file
    // name and is the escape character in a Unix pattern, so it has to be
    // doubled to splice. `escape_glob_literal` used to refuse it outright, which
    // left this prefix un-rewritten — the same no-op, on the other platform.
    #[cfg(unix)]
    #[test]
    fn a_backslash_in_a_canonical_directory_name_is_spliced_as_a_escape() {
        use std::os::unix::fs::symlink;
        let d = tempfile::tempdir().unwrap();
        let base = fs::canonicalize(d.path()).unwrap();
        let real = base.join("back\\slash");
        fs::create_dir_all(&real).unwrap();
        let link = base.join("bslink");
        symlink(&real, &link).unwrap();

        let written = format!("{}/*", link.display());
        let rewritten = canonical_pattern_prefix(&written, PatternKind::Glob);
        assert_eq!(
            rewritten,
            format!("{}/back\\\\slash/*", base.display()),
            "a literal backslash in the canonical name is spliced as an escaped backslash"
        );
        // A splice that compiled to the wrong text would pass the equality
        // above and still match nothing, so the compiled behaviour is asserted
        // too: `\\` is a literal `\`, not an escape of `s`.
        let matcher = globset::Glob::new(&rewritten).unwrap().compile_matcher();
        assert!(
            matcher.is_match(format!("{}/proj", real.display())),
            "the named tree must match {rewritten}"
        );
        assert!(
            !matcher.is_match(format!("{}/backslash/proj", base.display())),
            "an unescaped reading would have matched `backslash`: {rewritten}"
        );
    }

    // Windows. The end-to-end lane C024 asked for: a real canonical spelling
    // from `fs::canonicalize`, a real bracket in a real file name, and the
    // production path from a `config.toml` to a compiled matcher.
    //
    // fixture-scope: `#[cfg(windows)]` is the explicit scope. The alias a
    // canonical rewrite needs — two names for one directory — is a symlink on
    // Unix and a junction here; a Windows symlink needs Developer Mode or
    // elevation, which a hosted runner does not grant, so `mklink /J` is the
    // alias that can actually be made there. The junction fails loudly if it
    // cannot be made, because a fixture that quietly did not run is the exact
    // shape C009/C011/C012 were about.
    #[cfg(windows)]
    #[test]
    fn a_bracketed_canonical_spelling_is_matched_literally_on_windows() {
        let d = tempfile::tempdir().unwrap();
        // Rooted at the drive-letter spelling, not `canonicalize`'s own answer.
        // On this platform `canonicalize` answers `\\?\C:\…`, and a pattern
        // written from that text splits at the prefix's `?` — which is how the
        // first run of this test on the hosted lane failed, with the rewrite
        // correctly declining a prefix it could not express.
        let base = PathBuf::from(glob_spelling(&fs::canonicalize(d.path()).unwrap()));
        assert!(
            !base.display().to_string().contains('?'),
            "premise: the fixture root must be spelled the way a user spells it"
        );
        let real = base.join("real[abc]");
        fs::create_dir_all(&real).unwrap();
        for sibling in ["reala", "realb"] {
            fs::create_dir_all(base.join(sibling)).unwrap();
        }
        let link = base.join("link");
        // Backslashes, not the `/` this fixture's paths are built from: `cmd`
        // reads a `/` as a switch introducer, so `C:/Users/…` reaches `mklink`
        // as `Invalid switch - "Users"`. The hosted lane said so first.
        let link_arg = link.display().to_string().replace('/', "\\");
        let real_arg = real.display().to_string().replace('/', "\\");
        let made = std::process::Command::new("cmd")
            .args(["/c", "mklink", "/J"])
            .arg(&link_arg)
            .arg(&real_arg)
            .output()
            .unwrap();
        assert!(
            made.status.success(),
            "fixture-scope: a directory junction is the Windows alias a canonical \
             rewrite needs, and it needs no elevation: {}",
            String::from_utf8_lossy(&made.stderr)
        );
        assert_ne!(
            link.display().to_string(),
            real.display().to_string(),
            "premise: the fixture needs a spelling that is not the canonical one"
        );

        // The pattern is written the way a Windows user writes one, in `\` and
        // all. globset compiles a `\` in a pattern to `/` on this platform, so
        // the user's own spelling is not part of the defect.
        let written = format!("{link_arg}\\*");
        let config = base.join("config.toml");
        fs::write(
            &config,
            format!("[cleanup.policy]\nexclude = [{}]\n", toml_string(&written)),
        )
        .unwrap();
        let exclude = load(&config).unwrap().cleanup.policy.exclude;
        assert_eq!(exclude.len(), 1);
        // The canonical spelling, escaped and `/`-spelled, with the user's own
        // separator run and glob tail spliced back on verbatim.
        assert_eq!(
            exclude[0],
            format!("{}/real[[]abc[]]\\*", glob_spelling(&base)),
            "the rewritten pattern is the canonical name, escaped, with the \
             user's own separators and tail untouched"
        );

        let matcher = globset::Glob::new(&exclude[0]).unwrap().compile_matcher();
        assert!(
            matcher.is_match(format!("{}/proj", glob_spelling(&real))),
            "the named tree must match the spliced spelling {}",
            exclude[0]
        );
        for sibling in ["reala", "realb"] {
            assert!(
                !matcher.is_match(format!("{}/{sibling}/proj", glob_spelling(&base))),
                "{sibling} must not match the spliced spelling {}",
                exclude[0]
            );
        }

        // The premise again, on this platform: the spelling C024 shipped misses
        // the tree the user named and matches a sibling they never wrote down.
        let unescaped = format!("{}/real[abc]/*", glob_spelling(&base));
        let unescaped = globset::Glob::new(&unescaped).unwrap().compile_matcher();
        assert!(!unescaped.is_match(format!("{}/proj", glob_spelling(&real))));
        assert!(unescaped.is_match(format!("{}/reala/proj", glob_spelling(&base))));
    }

    #[test]
    fn recency_seconds_of_zero_is_rejected() {
        // H5: 0 silently disabled the inactivity guard. The default is 300, so an
        // explicit 0 is always a mistake and must be reported as one.
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("config.toml");
        fs::write(&p, "[scan]\nrecency_seconds = 0\n").unwrap();
        let err = load(&p).unwrap_err().to_string();
        assert!(err.contains("recency_seconds"), "{err}");
        assert!(err.contains("inactivity guard"), "{err}");
        fs::write(&p, "[scan]\nrecency_seconds = 1\n").unwrap();
        assert_eq!(load(&p).unwrap().scan.recency_seconds, 1);
    }

    #[test]
    fn out_of_range_retention_reports_a_range_not_a_parse_error() {
        // L23: a value beyond the field's integer width used to surface as a TOML
        // parse error ("invalid type: integer, expected u16").
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("config.toml");
        fs::write(&p, "[scan]\nlearned_root_retention_days = 99999\n").unwrap();
        let err = load(&p).unwrap_err().to_string();
        assert!(
            err.contains("learned_root_retention_days must be between 0 and 3650"),
            "{err}"
        );
        fs::write(&p, "[scan]\nlearned_root_retention_days = 7\n").unwrap();
        assert_eq!(load(&p).unwrap().scan.learned_root_retention_days, 7);
    }

    #[test]
    fn invalid_scan_ignore_glob_is_reported_at_load() {
        // M6: an invalid `scan.ignore` glob used to be silently ignored and only
        // fail later (or never).
        //
        // The pattern must be absolute on *this* platform, otherwise the
        // absolute-path check fires first and the test would pass/fail for a
        // reason unrelated to glob compilation. Derive it from the platform
        // temporary directory instead of hardcoding a POSIX literal.
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("config.toml");
        let absolute_invalid = d.path().join("[unclosed");
        let pattern = absolute_invalid.to_string_lossy().replace('\\', "/");
        fs::write(&p, format!("[scan]\nignore = [\"{pattern}\"]\n")).unwrap();
        let err = load(&p).unwrap_err().to_string();
        assert!(err.contains("invalid scan.ignore glob"), "{err}");
    }

    #[test]
    fn default_recency_and_absent_config() {
        let d = tempfile::tempdir().unwrap();
        let c = load(&d.path().join("missing.toml")).unwrap();
        assert_eq!(c.scan.recency_seconds, 300);
    }
    #[test]
    fn malformed_and_relative_paths_fail() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("bad.toml");
        fs::write(&p, "[scan]\nrecency_seconds = nope\n").unwrap();
        assert!(load(&p).is_err());
        fs::write(&p, "[scan]\nroot = \"relative\"\n").unwrap();
        assert!(load(&p).is_err());
        fs::write(
            &p,
            "[cleanup]\nallowed_output_roots = [\"relative/root\"]\n",
        )
        .unwrap();
        assert!(load(&p).is_err());
    }
    #[test]
    fn checked_in_template_parses_and_matches_defaults() {
        let config: Config =
            toml::from_str(CONFIG_TEMPLATE).expect("checked-in template must parse");
        assert_eq!(config.scan.recency_seconds, 300);
        assert!(config.scan.root.is_none());
        assert!(config.scan.ignore.is_empty());
        assert!(config.scan.unignore.is_empty());
        assert!(config.cleanup.allowed_output_roots.is_empty());
        let defaults = Config::default();
        assert_eq!(config.scan.recency_seconds, defaults.scan.recency_seconds);
        assert_eq!(config.scan.root, defaults.scan.root);
        assert_eq!(config.scan.ignore, defaults.scan.ignore);
        assert_eq!(config.scan.unignore, defaults.scan.unignore);
        assert_eq!(
            config.cleanup.allowed_output_roots,
            defaults.cleanup.allowed_output_roots
        );
    }
    #[test]
    fn config_template_matches_repository_file() {
        let on_disk = fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/config.toml"))
            .expect("repository config.toml must exist");
        assert_eq!(
            CONFIG_TEMPLATE, on_disk,
            "bootstrap source must equal the checked-in template"
        );
    }
    #[test]
    fn legacy_cleanup_config_loads_with_neutral_policy() {
        let config: Config = toml::from_str("[cleanup]\nallowed_output_roots = []\n").unwrap();
        assert_eq!(config.cleanup.policy.min_reclaimable_bytes, 0);
        assert_eq!(config.cleanup.policy.min_inactive_seconds, None);
        assert!(config.cleanup.policy.include.is_empty());
        assert!(config.cleanup.policy.exclude.is_empty());
    }
    #[test]
    fn cleanup_policy_globs_and_durations_are_validated() {
        let d = tempfile::tempdir().unwrap();
        let path = d.path().join("config.toml");
        fs::write(&path, "[cleanup.policy]\ninclude = [\"[\"]\n").unwrap();
        assert!(load(&path).is_err());
        fs::write(
            &path,
            "[cleanup.policy]\nmin_inactive_seconds = 18446744073709551615\n",
        )
        .unwrap();
        assert!(load(&path).is_err());
    }
    #[test]
    fn operational_bootstrap_refuses_overwrite() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("config.toml");
        let initial = load_or_create(&p).unwrap();
        assert_eq!(initial.scan.recency_seconds, 300);
        fs::write(&p, "[scan]\nrecency_seconds = 61\n").unwrap();
        assert_eq!(load_or_create(&p).unwrap().scan.recency_seconds, 61);
    }
    #[test]
    fn bootstrap_bytes_equal_checked_in_template() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("config.toml");
        load_or_create(&p).unwrap();
        let written = fs::read_to_string(&p).unwrap();
        assert_eq!(written, CONFIG_TEMPLATE);
        // The written file must load and match defaults.
        let loaded = load(&p).unwrap();
        assert_eq!(loaded.scan.recency_seconds, 300);
    }
    #[test]
    fn malformed_config_is_not_replaced_automatically() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path().join("config.toml");
        fs::write(&p, "[scan]\nrecency_seconds = nope\n").unwrap();
        assert!(load(&p).is_err());
        assert!(load_or_create(&p).is_err());
        assert_eq!(
            fs::read_to_string(&p).unwrap(),
            "[scan]\nrecency_seconds = nope\n"
        );
    }
    #[test]
    fn concurrent_first_use_creates_one_complete_template() {
        // The premise has to be *likely*, not merely possible. A single
        // 8-thread round against one directory hit the race roughly one run in
        // three on Windows, which is not a premise a guard can rest on: the
        // defect it guards is invisible on the runs that pass. Repeated rounds
        // against a fresh nested directory each time give every losing thread
        // many more chances to observe the destination while it is being
        // created, on every platform.
        const WORKERS: usize = 16;
        const ROUNDS: usize = 24;
        let d = tempfile::tempdir().unwrap();
        for round in 0..ROUNDS {
            let p = d.path().join(format!("round{round}/config.toml"));
            let workers: Vec<_> = (0..WORKERS)
                .map(|_| {
                    let path = p.clone();
                    std::thread::spawn(move || load_or_create(&path).unwrap())
                })
                .collect();
            for worker in workers {
                assert_eq!(
                    worker.join().unwrap().scan.recency_seconds,
                    300,
                    "round {round}: every racer must succeed"
                );
            }
            assert_eq!(
                fs::read(&p).unwrap(),
                CONFIG_TEMPLATE.as_bytes(),
                "round {round}: one complete template, never a partial one"
            );
        }
    }

    /// Make `link`/`linkat` report `ENOSYS` on the calling thread.
    ///
    /// `create_initial` publishes by hard-linking a fully written staging file,
    /// and falls back to `create_new` when `link(2)` says the filesystem has no
    /// hard links. Nothing else in the process can produce that condition, and
    /// no filesystem a test can reach does either — see
    /// `the_config_is_published_on_a_filesystem_without_hard_links`.
    ///
    /// A seccomp filter is the one thing that can: it changes what the real
    /// syscall returns, on the real thread, with no seam in production code.
    ///
    /// The filter is per-thread and cannot be removed once installed, so this
    /// must be called on a thread that is about to exit. Installed on a
    /// long-lived libtest worker it would silently change every test that
    /// follows it on that thread.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    mod hard_link_trap {
        // Declared here rather than taken from a crate: `cargo-cleanme` has no
        // `libc` dependency and a test-only FFI shim is not a reason to add
        // one. `sock_filter`/`sock_fprog` are the kernel's own layouts.
        #[repr(C)]
        struct SockFilter {
            code: u16,
            jt: u8,
            jf: u8,
            k: u32,
        }
        #[repr(C)]
        struct SockFprog {
            len: u16,
            filter: *const SockFilter,
        }

        const LD_W_ABS: u16 = 0x20;
        const JEQ_K: u16 = 0x15;
        const RET_K: u16 = 0x06;
        const AUDIT_ARCH_X86_64: u32 = 0xc000_003e;
        const RET_ALLOW: u32 = 0x7fff_0000;
        const RET_ERRNO: u32 = 0x0005_0000;
        const ENOSYS: u32 = 38;
        const SYS_LINK: u32 = 86;
        const SYS_LINKAT: u32 = 265;
        const PR_SET_NO_NEW_PRIVS: i32 = 38;
        const PR_SET_SECCOMP: i32 = 22;
        const SECCOMP_MODE_FILTER: i32 = 2;

        unsafe extern "C" {
            fn prctl(option: i32, ...) -> i32;
        }

        pub fn install() {
            // `seccomp_data` is {nr, arch, instruction_pointer, args[6]}, so the
            // syscall number is the first word and the architecture the second.
            // Both `link(2)` and the `linkat(2)` glibc actually calls are
            // trapped: the number differs per architecture, so this test is
            // x86_64-only rather than wrong on the others.
            let program = [
                SockFilter {
                    code: LD_W_ABS,
                    jt: 0,
                    jf: 0,
                    k: 4,
                },
                SockFilter {
                    code: JEQ_K,
                    jt: 1,
                    jf: 0,
                    k: AUDIT_ARCH_X86_64,
                },
                // A match continues below; a foreign architecture is allowed
                // through, because a filter that wedged the process would be
                // worse than no filter at all.
                SockFilter {
                    code: RET_K,
                    jt: 0,
                    jf: 0,
                    k: RET_ALLOW,
                },
                SockFilter {
                    code: LD_W_ABS,
                    jt: 0,
                    jf: 0,
                    k: 0,
                },
                SockFilter {
                    code: JEQ_K,
                    jt: 2,
                    jf: 0,
                    k: SYS_LINKAT,
                },
                SockFilter {
                    code: JEQ_K,
                    jt: 1,
                    jf: 0,
                    k: SYS_LINK,
                },
                SockFilter {
                    code: RET_K,
                    jt: 0,
                    jf: 0,
                    k: RET_ALLOW,
                },
                SockFilter {
                    code: RET_K,
                    jt: 0,
                    jf: 0,
                    k: RET_ERRNO | ENOSYS,
                },
            ];
            let prog = SockFprog {
                len: program.len() as u16,
                filter: program.as_ptr(),
            };
            // SAFETY: both calls pass an integer and, for the second, a pointer
            // to `prog`, which outlives the call. The kernel copies the program
            // before returning.
            unsafe {
                // Without `NO_NEW_PRIVS` a filter needs CAP_SYS_ADMIN, and this
                // must not require privilege to run.
                assert_eq!(
                    prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0),
                    0,
                    "could not set NO_NEW_PRIVS: errno {}",
                    std::io::Error::last_os_error()
                );
                assert_eq!(
                    prctl(
                        PR_SET_SECCOMP,
                        SECCOMP_MODE_FILTER,
                        &prog as *const SockFprog
                    ),
                    0,
                    "could not install the link trap: errno {}",
                    std::io::Error::last_os_error()
                );
            }
        }
    }

    /// The no-hard-links filesystem the `create_new` fallback exists for.
    ///
    /// `create_initial` publishes with `hard_link`, and takes a `create_new`
    /// fallback when the filesystem reports hard links are unsupported — FAT32
    /// and exFAT, several CIFS mounts, WSL's `/mnt/c` drvfs. Before the
    /// fallback every command on such a filesystem failed at startup, because
    /// `load_or_create` is on every path.
    ///
    /// The condition cannot be staged with a fixture. No writable filesystem in
    /// a test runner lacks hard links, and the Linux kernel does not report
    /// that capability as "unsupported" in the first place: a filesystem with
    /// no `link` method gives `EPERM`, a read-only one `EROFS`, and a
    /// cross-device link `EXDEV` — `PermissionDenied`, `Other` and
    /// `CrossesDevices`, never `ErrorKind::Unsupported`. The only errno the
    /// branch tests for is the one a seccomp filter can produce, so the fixture
    /// traps `link(2)` on a thread of its own (see `hard_link_trap`).
    ///
    /// Two claims, and the first is what the fallback *is*: on such a
    /// filesystem the config must still be published, completely.
    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    #[test]
    fn the_config_is_published_on_a_filesystem_without_hard_links() {
        let d = tempfile::tempdir().unwrap();
        let fresh = d.path().join("fresh/config.toml");
        let raced = d.path().join("raced/config.toml");
        // A racer's complete config, published a moment earlier.
        let winner = b"# a concurrent winner\nrecency_seconds = 300\n";
        fs::create_dir_all(raced.parent().unwrap()).unwrap();
        fs::write(&raced, winner).unwrap();
        let probe_src = d.path().join("probe");
        let probe_dst = d.path().join("probe.link");
        fs::write(&probe_src, b"probe").unwrap();

        let (published, raced_result) = std::thread::spawn({
            let probe_src = probe_src.clone();
            let probe_dst = probe_dst.clone();
            let raced = raced.clone();
            let fresh = fresh.clone();
            move || {
                hard_link_trap::install();
                // The premise, checked on this thread and not assumed: if the
                // trap missed the syscall `std` used, `hard_link` would succeed
                // and everything below would be testing the primary path.
                let trapped = std::fs::hard_link(&probe_src, &probe_dst).unwrap_err();
                assert_eq!(
                    trapped.kind(),
                    std::io::ErrorKind::Unsupported,
                    "premise: link(2) must report the capability as unsupported, got {trapped}"
                );
                (create_initial(&fresh), create_initial(&raced))
            }
        })
        .join()
        .expect("the trapped thread panicked");

        // Without the fallback this is an `AppError::Io` and no config at all,
        // which is the startup failure the fallback removed.
        published.unwrap_or_else(|e| panic!("publication must survive the fallback: {e}"));
        assert_eq!(
            fs::read(&fresh).unwrap(),
            CONFIG_TEMPLATE.as_bytes(),
            "the fallback must write the whole template, not a prefix of it"
        );

        // The exclusivity the design cannot give up: a loser must not touch a
        // winner's config. `create_new` is what guarantees it — `create(true)`
        // would truncate these bytes and report success.
        raced_result.unwrap_or_else(|e| panic!("a lost race is success, not failure: {e}"));
        assert_eq!(
            fs::read(&raced).unwrap(),
            winner,
            "the fallback must not overwrite a config another process published"
        );
        let _ = fs::remove_file(&probe_src);
    }
}