mise 2026.9.4

Dev tools, env vars, and tasks in one CLI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
use crate::config::{Config, Settings};
use crate::dirs;
use crate::file::{self, display_path};
use crate::hash;
use crate::rand::random_string;
use crate::task::Task;
use eyre::{Result, bail};
use flate2::Compression;
use flate2::read::ZlibDecoder;
use flate2::write::ZlibEncoder;
use globwalk::{GlobWalker, GlobWalkerBuilder};
use ignore::overrides::{Override, OverrideBuilder};
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use walkdir::{DirEntry, Error as WalkError, WalkDir};

/// Remove mise's automatic output before rerunning a task so an earlier
/// success cannot make a failed attempt look fresh.
pub(crate) async fn remove_auto_output(task: &Task, config: &Arc<Config>) -> Result<()> {
    if !task.outputs.is_auto() {
        return Ok(());
    }
    let root = task_cwd(task, config).await?;
    for output in task.outputs.paths(task, &root) {
        match fs::remove_file(&output) {
            Ok(()) => debug!("removed auto output file: {output}"),
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
            Err(err) => return Err(err.into()),
        }
    }
    Ok(())
}

/// Check if a path is a glob pattern
pub(crate) fn is_glob_pattern(path: &str) -> bool {
    // This is the character set used for glob detection by glob
    let glob_chars = ['*', '{', '}'];
    path.chars().any(|c| glob_chars.contains(&c))
}

const MAX_BRACE_EXPANSIONS: usize = 1024;

/// Expand globset-style brace alternates before passing a pattern to `glob`.
///
/// `Override`/globset understands patterns such as `{a,b}.txt`, but the `glob`
/// crate used to enumerate task sources and outputs treats braces literally.
/// Expanding only groups with comma-separated choices lets both stages share
/// the same syntax without returning to a recursive filesystem walker. Balanced
/// braces without a comma are encoded as character classes so they keep their
/// literal meaning in both `glob` and globset.
pub(crate) fn expand_glob_braces(pattern: &str) -> Result<Vec<String>> {
    struct BraceGroup {
        start: usize,
        end: usize,
        branches: Vec<(usize, usize)>,
    }

    fn find_group(pattern: &str) -> Result<Option<BraceGroup>> {
        let mut escaped = false;
        let mut class_depth = 0;
        let mut group_start = None;
        let mut group_depth = 0;
        let mut branch_start = 0;
        let mut branches = Vec::new();

        for (idx, ch) in pattern.char_indices() {
            if escaped {
                escaped = false;
                continue;
            }
            // On Windows, backslashes are path separators rather than glob
            // escapes. Literal braces can still be expressed with a character
            // class, e.g. `[{]` and `[}]`.
            if ch == '\\' && !cfg!(windows) {
                escaped = true;
                continue;
            }
            match ch {
                '[' if class_depth == 0 => class_depth = 1,
                ']' if class_depth == 1 => class_depth = 0,
                '{' if class_depth == 0 => {
                    if group_depth == 0 {
                        group_start = Some(idx);
                        branch_start = idx + ch.len_utf8();
                    }
                    group_depth += 1;
                }
                ',' if class_depth == 0 && group_depth == 1 => {
                    branches.push((branch_start, idx));
                    branch_start = idx + ch.len_utf8();
                }
                '}' if class_depth == 0 => {
                    if group_depth == 0 {
                        bail!("unopened brace alternate in glob pattern {pattern:?}");
                    }
                    group_depth -= 1;
                    if group_depth == 0 {
                        let start = group_start.unwrap();
                        if !branches.is_empty() {
                            branches.push((branch_start, idx));
                            return Ok(Some(BraceGroup {
                                start,
                                end: idx,
                                branches,
                            }));
                        }

                        // A balanced group without a top-level comma is a
                        // literal brace pair. It may still contain a nested
                        // alternate, so look inside it before continuing with
                        // the remainder of the pattern.
                        if let Some(mut nested) = find_group(&pattern[start + 1..idx])? {
                            let offset = start + 1;
                            nested.start += offset;
                            nested.end += offset;
                            for (branch_start, branch_end) in &mut nested.branches {
                                *branch_start += offset;
                                *branch_end += offset;
                            }
                            return Ok(Some(nested));
                        }
                        group_start = None;
                        branches.clear();
                    }
                }
                _ => {}
            }
        }
        if group_depth != 0 {
            bail!("unclosed brace alternate in glob pattern {pattern:?}");
        }
        Ok(None)
    }

    fn expand(pattern: &str, expanded: &mut Vec<String>) -> Result<()> {
        let Some(group) = find_group(pattern)? else {
            if expanded.len() >= MAX_BRACE_EXPANSIONS {
                bail!(
                    "glob pattern expands to more than {MAX_BRACE_EXPANSIONS} alternatives: {pattern:?}"
                );
            }
            let mut literal = String::with_capacity(pattern.len());
            let mut escaped = false;
            let mut class_depth = 0;
            for ch in pattern.chars() {
                if escaped {
                    escaped = false;
                    literal.push(ch);
                    continue;
                }
                if ch == '\\' && !cfg!(windows) {
                    escaped = true;
                    literal.push(ch);
                    continue;
                }
                match ch {
                    '[' if class_depth == 0 => {
                        class_depth = 1;
                        literal.push(ch);
                    }
                    ']' if class_depth == 1 => {
                        class_depth = 0;
                        literal.push(ch);
                    }
                    '{' if class_depth == 0 => literal.push_str("[{]"),
                    '}' if class_depth == 0 => literal.push_str("[}]"),
                    _ => literal.push(ch),
                }
            }
            expanded.push(literal);
            return Ok(());
        };

        let prefix = &pattern[..group.start];
        let suffix = &pattern[group.end + 1..];
        for (branch_start, branch_end) in group.branches {
            let branch = &pattern[branch_start..branch_end];
            // Match globset's default: empty alternatives are discarded.
            if branch.is_empty() {
                continue;
            }
            expand(&format!("{prefix}{branch}{suffix}"), expanded)?;
        }
        Ok(())
    }

    let mut expanded = Vec::new();
    expand(pattern, &mut expanded)?;
    Ok(expanded)
}

/// Build an [`Override`] matcher for a task's `sources` patterns.
///
/// `match_root` is the directory the [`Override`] is anchored at (the workspace
/// root in workspace setups, otherwise the task CWD). `task_cwd` is the
/// directory the task actually runs from. Relative patterns are resolved
/// against `task_cwd` and absolute ones taken as-is; either way the result is
/// re-expressed relative to `match_root` so every pattern lives in the same
/// namespace as the paths the matcher is asked about.
///
/// Patterns use gitignore syntax with `!` inverted (the [`Override`] convention):
/// a non-negated entry marks a file as a *source*, `!`-prefixed excludes it,
/// `\!` escapes a literal `!`, and order matters.
pub(crate) fn build_source_matcher(
    match_root: &Path,
    task_cwd: &Path,
    sources: &[String],
) -> Override {
    let mut builder = OverrideBuilder::new(match_root);
    for s in sources {
        let normalized = normalize_pattern(match_root, task_cwd, s);
        let expanded = match expand_glob_braces(&normalized) {
            Ok(expanded) => expanded,
            Err(e) => {
                // Source matcher construction is infallible to callers. An
                // invalid pattern is skipped so freshness falls back to stale
                // when no sources can be enumerated.
                warn!("invalid source pattern {s:?}: {e}");
                continue;
            }
        };
        for normalized in expanded {
            if let Err(e) = builder.add(&normalized) {
                warn!("invalid source pattern {s:?}: {e}");
            }
        }
    }
    builder.build().unwrap_or_else(|e| {
        warn!("failed to build source matcher: {e}");
        Override::empty()
    })
}

/// Resolve `.` and `..` in `path` without consulting the filesystem.
///
/// Being lexical, this disagrees with `canonicalize` whenever a symlink is
/// involved: `dir/link/..` becomes `dir`, not the parent of the link's target.
/// Source matching is lexical too — gitignore globs never resolve symlinks —
/// so both sides of a comparison must be normalized the same way to stay
/// consistent with each other.
///
/// A `..` with nothing to collapse is kept in a relative path (`../x` has no
/// representation without it) and dropped in an absolute one, where `/..` is
/// `/`.
///
/// Only for paths and patterns that are *matched*. A directory the task will
/// actually run in must keep its `..` for the OS to resolve at `chdir` time, so
/// [`normalize_task_cwd`] collapses `.` alone.
pub(crate) fn lexical_normalize(path: &Path) -> PathBuf {
    let absolute = path.is_absolute();
    let mut normalized = PathBuf::new();
    let mut depth = 0usize;
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if depth > 0 {
                    normalized.pop();
                    depth -= 1;
                } else if !absolute {
                    normalized.push("..");
                }
            }
            Component::Normal(part) => {
                normalized.push(part);
                depth += 1;
            }
            component => normalized.push(component.as_os_str()),
        }
    }
    normalized
}

/// Returns true when resolving `..` in `pattern` would collapse a component
/// holding a glob metacharacter.
///
/// `**/../x` has no well-defined expansion — the `..` would have to apply to
/// whatever each match of `**` resolved to — so callers leave such a pattern
/// exactly as written rather than inventing a meaning for it.
fn parent_dir_pops_glob(pattern: &Path) -> bool {
    let mut stack: Vec<bool> = Vec::new();
    for component in pattern.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir if stack.pop() == Some(true) => {
                return true;
            }
            Component::Normal(part) => {
                stack.push(part.to_string_lossy().contains(['*', '?', '[', '{']));
            }
            _ => {}
        }
    }
    false
}

/// Render a relative path as a gitignore pattern body.
///
/// Gitignore patterns are always `/`-separated, but `Path` renders the platform
/// separator, so on Windows a pattern rebuilt from a `PathBuf` arrives as
/// `dist\**\*.map`. `globset` reads `\` as an escape rather than a separator,
/// which silently turns the pattern into one that matches something else
/// entirely — a negated entry then stops excluding and the matcher widens.
/// Joining the components explicitly keeps the separator independent of the
/// platform the path was built on.
fn pattern_from_path(path: &Path) -> Option<String> {
    let mut pattern = String::new();
    for component in path.components() {
        let part = component.as_os_str().to_str()?;
        if !pattern.is_empty() {
            pattern.push('/');
        }
        pattern.push_str(part);
    }
    Some(pattern)
}

/// Normalise `pattern` so it is always expressed relative to `match_root`.
///
/// A relative body is resolved against `task_cwd` and an absolute one taken as
/// written; the result is then lexically normalized and stripped back to a
/// `match_root`-relative path. Relative entries therefore stay anchored at the
/// task directory while `..` climbs out of it: `match_root=/ws`,
/// `task_cwd=/ws/lib/worker`, `src/**/*.go` → `lib/worker/src/**/*.go` and
/// `../shared/*.go` → `lib/shared/*.go`.
///
/// A pattern resolving outside `match_root` is returned unchanged, as is one
/// whose `..` would collapse a glob component. Gitignore syntax cannot express
/// a path above the matcher's root; [`is_source`] passes such absolute paths
/// through without consulting the matcher instead.
fn normalize_pattern(match_root: &Path, task_cwd: &Path, pattern: &str) -> String {
    let (prefix, body) = if pattern.starts_with("\\!") {
        return pattern.to_string();
    } else if let Some(rest) = pattern.strip_prefix('!') {
        ("!", rest)
    } else {
        ("", pattern)
    };
    let body_path = Path::new(body);
    // Inspect the pattern as written: `task_cwd` may legitimately contain a
    // glob metacharacter as a literal directory name, and folding it in would
    // make an ordinary `../` entry look like a `..` popping a glob.
    if parent_dir_pops_glob(body_path) {
        return pattern.to_string();
    }
    let body_abs = if body_path.is_absolute() {
        body_path.to_path_buf()
    } else {
        task_cwd.join(body_path)
    };
    let body_abs = lexical_normalize(&body_abs);
    let Ok(rel) = body_abs.strip_prefix(match_root) else {
        return pattern.to_string();
    };
    let Some(rel_str) = pattern_from_path(rel) else {
        return pattern.to_string();
    };
    if rel_str.is_empty() {
        return pattern.to_string();
    }
    let rel_str = if rel_str.starts_with('!') {
        format!("\\{rel_str}")
    } else {
        rel_str.to_string()
    };
    format!("{prefix}{rel_str}")
}

/// Returns true iff `path` is selected as a source by `matcher`. With
/// [`Override`]'s inverted semantics, a non-negated user pattern produces
/// `Match::Whitelist` for matching paths.
///
/// `path` is lexically normalized first: `glob` builds the paths it returns
/// from the raw pattern, so an enumerated file still carries the `..` that
/// [`normalize_pattern`] has already resolved out of the matcher's copy.
///
/// Absolute paths that don't fall under the matcher's root are out of
/// gitignore's domain — `Override::matched` would return `Match::None` and,
/// when positive patterns are present, promote that to `Match::Ignore`,
/// silently dropping a file the glob legitimately included. Trust the glob
/// in that case.
pub(crate) fn is_source(matcher: &Override, path: &Path) -> bool {
    let path = lexical_normalize(path);
    if path.is_absolute() && !path.starts_with(matcher.path()) {
        return true;
    }
    matcher.matched(&path, false).is_whitelist()
}

/// Expands a trailing `**` to `**/*` so enumeration reaches files.
///
/// The `glob` crate matches a trailing `**` against directories only, while the
/// `ignore`/`globset` matcher built from the same entry matches the files
/// underneath it per gitignore semantics. Enumeration therefore never offers
/// the files the matcher would have accepted, and because everything it does
/// offer matches, nothing looks rejected and no diagnostic fires.
///
/// A `**` in the interior of a pattern (`src/**/foo.rs`) already spans
/// directories correctly and is left alone.
///
/// Separators are tested with [`std::path::is_separator`], matching how `glob`
/// itself decides whether a `**` forms its own path component. `\` is a
/// separator on Windows, so `src\**` carries the same defect there, while on
/// unix that string is an escape and `glob` rejects it outright.
fn expand_trailing_globstar(pattern: &str) -> String {
    let trailing_globstar = pattern == "**"
        || pattern.strip_suffix("**").is_some_and(|head| {
            head.chars()
                .next_back()
                .is_some_and(std::path::is_separator)
        });
    if trailing_globstar {
        format!("{pattern}/*")
    } else {
        pattern.to_string()
    }
}

/// Brace-expands `pattern` for file enumeration, expanding a trailing `**` in
/// each alternative so enumeration reaches files.
///
/// Enumeration callers use this rather than [`expand_glob_braces`] directly,
/// because the expansion has to happen per alternative: `{src/**,dist}` carries
/// its `**` inside the braces, where a check on the whole pattern cannot see
/// it. Matcher construction deliberately keeps calling [`expand_glob_braces`],
/// since `globset` already matches the files under a trailing `**` and
/// rewriting there would change what the matcher selects rather than what
/// enumeration offers.
pub(crate) fn expand_enumeration_patterns(pattern: &str) -> Result<Vec<String>> {
    Ok(expand_glob_braces(pattern)?
        .into_iter()
        .map(|alternative| expand_trailing_globstar(&alternative))
        .collect())
}

/// Returns the include-side glob patterns from `sources`, suitable for file
/// enumeration via [`expand_enumeration_patterns`]. `!`-prefixed entries are
/// dropped (they only constrain matching, not enumeration); `\!`-prefixed
/// entries have the escape removed so they can be globbed as literal
/// `!`-prefixed paths.
pub(crate) fn source_glob_patterns(sources: &[String]) -> Vec<String> {
    sources
        .iter()
        .filter_map(|s| {
            if s.starts_with('!') {
                None
            } else if let Some(rest) = s.strip_prefix("\\!") {
                Some(format!("!{rest}"))
            } else {
                Some(s.clone())
            }
        })
        .collect()
}

/// Build a glob iterator that follows valid directory symlinks but detects
/// ancestor loops instead of recursively expanding them forever.
///
/// `globwalk` recursively searches its base directory, so non-globstar
/// patterns are capped at their component depth to preserve `glob`'s
/// component-by-component expansion semantics. Literal prefixes that do not
/// exist yet are moved into the pattern so they produce zero matches instead
/// of a traversal error.
pub(crate) fn glob_walk(pattern: &Path, case_insensitive: bool) -> Result<GlobWalker> {
    fn has_metacharacters(component: &str) -> bool {
        let mut escaped = false;
        for ch in component.chars() {
            if escaped {
                escaped = false;
            } else if ch == '\\' && !cfg!(windows) {
                escaped = true;
            } else if matches!(ch, '*' | '?' | '[') {
                return true;
            }
        }
        false
    }

    let mut base = PathBuf::new();
    let mut glob_pattern = PathBuf::new();
    let mut globbing = false;
    let mut recursive = false;
    let mut pattern_depth = 0;

    for component in pattern.components() {
        let text = component.as_os_str().to_string_lossy();
        if !globbing && has_metacharacters(&text) {
            globbing = true;
        }
        if globbing {
            recursive |= text == "**";
            pattern_depth += 1;
            glob_pattern.push(component);
        } else {
            base.push(component);
        }
    }

    // `task_source_files` also resolves statically named sources through this
    // helper. Walk the parent in that case because globwalk intentionally does
    // not yield its traversal root.
    if !globbing && let Some(file_name) = base.file_name().map(|name| name.to_os_string()) {
        base.pop();
        glob_pattern.push(file_name);
        pattern_depth = 1;
    }

    while !base.as_os_str().is_empty() && !base.exists() {
        let Some(file_name) = base.file_name().map(|name| name.to_os_string()) else {
            break;
        };
        base.pop();
        let mut prefixed_pattern = PathBuf::from(file_name);
        prefixed_pattern.push(glob_pattern);
        glob_pattern = prefixed_pattern;
        pattern_depth += 1;
    }

    let Some(mut glob_pattern) = pattern_from_path(&glob_pattern) else {
        bail!("glob pattern is not valid UTF-8: {}", pattern.display());
    };
    if glob_pattern.starts_with('!') {
        glob_pattern.insert(0, '\\');
    }

    let mut builder = GlobWalkerBuilder::new(&base, glob_pattern)
        .follow_links(true)
        .sort_by(|a, b| a.file_name().cmp(b.file_name()))
        .case_insensitive(case_insensitive);
    if !recursive {
        builder = builder.max_depth(pattern_depth);
    }
    Ok(builder.build()?)
}

/// Return a successful walk entry, pruning expected errors from following
/// symlinks that loop or point to a missing target.
pub(crate) fn prune_symlink_walk_error(
    entry: std::result::Result<DirEntry, WalkError>,
) -> Result<Option<DirEntry>> {
    match entry {
        Ok(entry) => Ok(Some(entry)),
        Err(err) if symlink_walk_error_path(&err).is_some() => Ok(None),
        Err(err) => Err(err.into()),
    }
}

/// Return the symlink path attached to an expected loop or missing-target
/// traversal error. Callers that only enumerate reachable files prune it;
/// artifact caching retains the symlink itself as an output root.
pub(crate) fn symlink_walk_error_path(err: &WalkError) -> Option<&Path> {
    let path = err.path()?;
    let is_symlink =
        || fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink());
    if err.loop_ancestor().is_some() && is_symlink() {
        return Some(path);
    }
    err.io_error()
        .is_some_and(|error| {
            error.kind() == std::io::ErrorKind::NotFound || is_filesystem_loop_error(error)
        })
        .then_some(path)
        .filter(|_| is_symlink())
}

#[cfg(unix)]
fn is_filesystem_loop_error(error: &std::io::Error) -> bool {
    error.raw_os_error() == Some(nix::errno::Errno::ELOOP as i32)
}

#[cfg(windows)]
fn is_filesystem_loop_error(error: &std::io::Error) -> bool {
    use windows_sys::Win32::Foundation::{ERROR_CANT_RESOLVE_FILENAME, ERROR_CIRCULAR_DEPENDENCY};

    error.raw_os_error().is_some_and(|code| {
        code == ERROR_CANT_RESOLVE_FILENAME as i32 || code == ERROR_CIRCULAR_DEPENDENCY as i32
    })
}

/// Build an ordered matcher for task output patterns.
///
/// Output entries use the same syntax as sources: `!` excludes, `\!` escapes
/// a literal leading bang, and the last matching pattern wins. Each pattern
/// also applies to descendants because a matched output directory is handled
/// recursively by freshness checks and artifact caching.
pub(crate) fn build_output_matcher(root: &Path, outputs: &[String]) -> Result<Override> {
    let mut builder = OverrideBuilder::new(root);
    for output in outputs {
        let output = normalize_pattern(root, root, output);
        // Output callers already propagate matcher errors and conservatively
        // treat the task as stale, so keep malformed patterns visible here.
        for output in expand_glob_braces(&output)? {
            builder.add(&output)?;
            let descendant = if let Some(body) = output.strip_prefix('!') {
                format!("!{body}/**")
            } else if let Some(body) = output.strip_prefix("\\!") {
                format!("\\!{body}/**")
            } else {
                format!("{output}/**")
            };
            if !output.ends_with("/**") {
                builder.add(&descendant)?;
            }
        }
    }
    Ok(builder.build()?)
}

/// Return the include-side output patterns used to enumerate output roots.
pub(crate) fn output_glob_patterns(outputs: &[String]) -> Vec<String> {
    source_glob_patterns(outputs)
}

/// Returns true when an output path is selected by the ordered matcher.
///
/// `path` is lexically normalized to stay in step with [`normalize_pattern`],
/// which resolves `..` out of the matcher's patterns. Output enumeration
/// resolves candidates from the raw pattern, so `outputs = ["dist/../x"]`
/// reaches here still carrying the `..` the matcher no longer holds.
pub(crate) fn is_output(matcher: &Override, path: &Path, is_dir: bool) -> bool {
    let path = lexical_normalize(path);
    if path.is_absolute() && !path.starts_with(matcher.path()) {
        return true;
    }
    matcher.matched(&path, is_dir).is_whitelist()
}

fn resolve_task_path(root: &Path, path: impl AsRef<Path>) -> PathBuf {
    let path = path.as_ref();
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        root.join(path)
    }
}

fn normalize_task_cwd(path: PathBuf) -> PathBuf {
    let mut normalized: PathBuf = path
        .components()
        .filter(|component| !matches!(component, Component::CurDir))
        .collect();
    if normalized.as_os_str().is_empty() && !path.as_os_str().is_empty() {
        normalized.push(".");
    }
    normalized
}

/// Get the working directory for a task
pub(crate) async fn task_cwd(task: &Task, config: &Arc<Config>) -> Result<PathBuf> {
    if let Some(d) = task.dir(config).await? {
        Ok(normalize_task_cwd(d))
    } else {
        Ok(config
            .project_root
            .clone()
            .or_else(|| dirs::CWD.clone())
            .unwrap_or_default())
    }
}

/// Return the outermost config root that contains the task working directory.
///
/// Source patterns are anchored here so workspace-rooted patterns and task-CWD
/// relative patterns use the same namespace.
pub(crate) fn task_source_match_root(root: &Path, config: &Config) -> PathBuf {
    config
        .config_files
        .values()
        .filter_map(|cf| cf.project_root())
        .filter(|pr| root.starts_with(pr) || *pr == root)
        .min_by_key(|p| p.components().count())
        .unwrap_or_else(|| root.to_path_buf())
}

/// Collect source file metadatas for a task, anchored at the correct workspace root.
async fn collect_source_metadatas(
    task: &Task,
    config: &Arc<Config>,
) -> Result<(PathBuf, PathBuf, Vec<(PathBuf, fs::Metadata)>)> {
    let root = task_cwd(task, config).await?;
    // Anchor the Override matcher at the outermost config root that is an
    // ancestor of the task CWD (i.e. the workspace root). This allows
    // workspace-rooted patterns like `{{ config_root }}/lib/**/*` to be
    // correctly relativized so that files inside a subproject directory are
    // not silently dropped.
    //
    // config.project_root cannot be used directly: BTreeMap iterates by
    // lexicographic path order, so a subproject config may be returned
    // before the workspace root config (mise.toml) even though
    // the workspace root has a shorter path.
    let match_root_owned = task_source_match_root(&root, config);
    let match_root = match_root_owned.as_path();
    let matcher = build_source_matcher(match_root, &root, &task.sources);
    let glob_patterns = source_glob_patterns(&task.sources);
    let mut source_metadatas = get_file_metadatas(&root, &glob_patterns, &matcher)?;
    // Always include every file that contributed to the task definition,
    // regardless of excludes — a stray `!mise.toml` must not silently
    // disable invalidation.
    for config_source in task.config_sources() {
        let config_path = if config_source.is_absolute() {
            config_source.to_path_buf()
        } else {
            root.join(config_source)
        };
        if let Ok(meta) = config_path.metadata()
            && meta.is_file()
            && !source_metadatas.iter().any(|(p, _)| p == &config_path)
        {
            source_metadatas.push((config_path, meta));
        }
    }
    Ok((root, match_root_owned, source_metadatas))
}

/// Compute the current source hash for a task. Returns `(hash, hash_file_path)`
/// or `None` if the task has no sources or no matching files were found.
async fn compute_source_hash(
    task: &Task,
    config: &Arc<Config>,
) -> Result<Option<(String, PathBuf)>> {
    if task.sources.is_empty() {
        return Ok(None);
    }
    let use_content_hash = Settings::get().task.source_freshness_hash_contents;
    let (root, _, source_metadatas) = collect_source_metadatas(task, config).await?;
    if source_metadatas.is_empty() {
        return Ok(None);
    }
    let source_hash = if use_content_hash {
        let cache_path = content_hash_cache_path(task, &root);
        let mut cache = load_content_hash_cache(&cache_path);
        let h = file_contents_to_hash(&source_metadatas, &mut cache)?;
        if let Err(e) = save_content_hash_cache(&cache_path, &cache) {
            trace!("failed to save content hash cache: {e}");
        }
        h
    } else {
        file_metadatas_to_hash(&source_metadatas)
    };
    let source_hash_path = sources_hash_path(task, &root, use_content_hash);
    Ok(Some((source_hash, source_hash_path)))
}

pub(crate) struct TaskCacheInputs {
    pub source_hash: String,
    pub source_paths: Vec<PathBuf>,
    pub root_identity: PathBuf,
}

/// Compute stable paths and content hashes for artifact-cache inputs in one source scan.
pub(crate) async fn task_cache_inputs(
    task: &Task,
    config: &Arc<Config>,
    persist_content_hash_cache: bool,
) -> Result<Option<TaskCacheInputs>> {
    if task.sources.is_empty() {
        return Ok(None);
    }
    let (root, match_root, mut source_metadatas) = collect_source_metadatas(task, config).await?;
    if source_metadatas.is_empty() {
        return Ok(None);
    }
    source_metadatas.sort_by(|(a, _), (b, _)| a.cmp(b));
    let cache_path = content_hash_cache_path(task, &root);
    let mut cache = load_content_hash_cache(&cache_path);
    let mut next = ContentHashCache::new();
    let mut hasher = blake3::Hasher::new();
    let mut source_paths = Vec::with_capacity(source_metadatas.len());
    for (path, metadata) in source_metadatas {
        let identity = match path.strip_prefix(&match_root) {
            Ok(relative) => format!("workspace\0{}", relative.to_string_lossy()),
            // Retaining the absolute path deliberately disables cross-checkout reuse for
            // sources outside the workspace instead of allowing ambiguous identities.
            Err(_) => format!("external\0{}", path.to_string_lossy()),
        };
        hasher.update(&(identity.len() as u64).to_le_bytes());
        hasher.update(identity.as_bytes());
        let contents = match cache.get(&path) {
            Some(entry) if cached_entry_matches(entry, &metadata) => entry.hash.clone(),
            _ => hash::file_hash_blake3(&path, None)?,
        };
        hasher.update(contents.as_bytes());
        next.insert(path.clone(), make_cache_entry(&metadata, contents));
        source_paths.push(path.strip_prefix(&root).unwrap_or(&path).to_path_buf());
    }
    cache = next;
    if persist_content_hash_cache && let Err(e) = save_content_hash_cache(&cache_path, &cache) {
        trace!("failed to save content hash cache: {e}");
    }
    let root_identity = root
        .strip_prefix(&match_root)
        .unwrap_or(&root)
        .to_path_buf();
    Ok(Some(TaskCacheInputs {
        source_hash: hasher.finalize().to_hex().to_string(),
        source_paths,
        root_identity,
    }))
}

/// Check if task sources are up to date (fresher than outputs)
pub(crate) async fn sources_are_fresh(task: &Task, config: &Arc<Config>) -> Result<bool> {
    if task.sources.is_empty() {
        return Ok(false);
    }
    let settings = Settings::get();
    let use_content_hash = settings.task.source_freshness_hash_contents;
    let equal_mtime_is_fresh = settings.task.source_freshness_equal_mtime_is_fresh;

    let run = async || -> Result<bool> {
        let (root, _, source_metadatas) = collect_source_metadatas(task, config).await?;

        // Check if sources resolved to no files (likely a config mistake)
        if source_metadatas.is_empty() {
            warn!(
                "task {} has sources defined but no matching files found",
                task.name
            );
            return Ok(false);
        }

        // Check for epoch timestamps (files extracted from tarballs without preserved timestamps)
        // These are considered stale since we can't trust the mtime.
        // Skipped in hash mode — content is the authority there, not timestamps.
        if !use_content_hash {
            for (path, metadata) in &source_metadatas {
                if let Ok(mtime) = metadata.modified()
                    && mtime == UNIX_EPOCH
                {
                    debug!(
                        "source file {} has epoch timestamp, treating as stale",
                        display_path(path)
                    );
                    return Ok(false);
                }
            }
        }

        let source_hash = if use_content_hash {
            let cache_path = content_hash_cache_path(task, &root);
            let mut cache = load_content_hash_cache(&cache_path);
            let h = file_contents_to_hash(&source_metadatas, &mut cache)?;
            if let Err(e) = save_content_hash_cache(&cache_path, &cache) {
                trace!("failed to save content hash cache: {e}");
            }
            h
        } else {
            file_metadatas_to_hash(&source_metadatas)
        };
        let source_hash_path = sources_hash_path(task, &root, use_content_hash);
        if let Some(dir) = source_hash_path.parent() {
            file::create_dir_all(dir)?;
        }
        let existing_hash = source_existing_hash(task, &root, use_content_hash);
        if existing_hash.as_deref().is_some_and(|h| h != source_hash) {
            debug!(
                "source {} hash mismatch in {}",
                if use_content_hash {
                    "content"
                } else {
                    "metadata"
                },
                source_hash_path.display()
            );
            // Do not write the hash here — the task is about to run. If it
            // fails, the baseline must stay at the previous value so the next
            // invocation still detects the mismatch. save_checksum writes the
            // hash after a successful run.
            return Ok(false);
        }
        if use_content_hash {
            // In hash mode, content alone determines freshness — no mtime check.
            // With no stored baseline there is nothing to compare the content
            // against, so the task is stale. Falling through to the mtime
            // comparison here would let an edit whose mtime is older than the
            // output masquerade as fresh — exactly what hash mode exists to
            // prevent — on the first run after the setting is enabled.
            if existing_hash.is_none() {
                debug!("no stored content hash in {}", source_hash_path.display());
                return Ok(false);
            }
            // Compare against the stored output hash to catch partial/missing outputs.
            let current_output_hash = compute_output_hash(task, &root)?;
            let stored_output_hash = output_existing_hash(task, &root);
            let fresh = current_output_hash.is_some()
                && current_output_hash.as_deref() == stored_output_hash.as_deref();
            // Only when there is nothing to do. The hash mismatch above has
            // already returned, so `source_hash` equals what is stored and the
            // write moves nothing but the file's mtime — which is the baseline
            // `task_source_files(only_changed=true)` measures against. Advancing
            // it on the way into a run that has to repair a missing or modified
            // output told that run nothing was outstanding, and it rendered an
            // empty file list. Same reason the mismatch branch does not write:
            // the task is about to run, and `save_checksum` records the baseline
            // once it succeeds.
            if fresh {
                file::write(&source_hash_path, &source_hash)?;
            }
            return Ok(fresh);
        }
        let sources = get_last_modified_from_metadatas(&source_metadatas);
        let outputs = get_last_modified(&root, &task.outputs.paths(task, &root))?;
        trace!("sources: {sources:?}, outputs: {outputs:?}");
        let fresh = match (sources, outputs) {
            (Some(sources), Some(outputs)) => {
                if equal_mtime_is_fresh {
                    sources <= outputs
                } else {
                    sources < outputs
                }
            }
            _ => false,
        };
        if fresh {
            // Write a snapshot of the current hash so future checks can detect
            // source changes even when mtime would appear fresh (e.g. after a
            // touch or a cache restore).
            file::write(&source_hash_path, &source_hash)?;
        }
        Ok(fresh)
    };
    Ok(run().await.unwrap_or_else(|err| {
        warn!("sources_are_fresh: {err:?}");
        false
    }))
}

/// Save a checksum file after a task completes successfully
pub(crate) async fn save_checksum(task: &Task, config: &Arc<Config>) -> Result<()> {
    if task.sources.is_empty() {
        return Ok(());
    }
    let root = task_cwd(task, config).await?;
    if task.outputs.is_auto() {
        for p in task.outputs.paths(task, &root) {
            debug!("touching auto output file: {p}");
            file::touch_file(&PathBuf::from(&p))?;
        }
    } else {
        // Warn if any explicitly declared output was not generated.
        for output in output_glob_patterns(&task.outputs.paths(task, &root)) {
            let output_exists = if is_glob_pattern(&output) {
                expand_enumeration_patterns(&output)
                    .map(|patterns| {
                        patterns.into_iter().any(|pattern| {
                            let pattern = resolve_task_path(&root, pattern);
                            glob_walk(&pattern, false)
                                .map(|mut paths| {
                                    paths.any(|entry| match entry {
                                        Ok(_) => true,
                                        Err(err) => symlink_walk_error_path(&err).is_some(),
                                    })
                                })
                                .unwrap_or(false)
                        })
                    })
                    .unwrap_or(false)
            } else {
                let path = Path::new(&output);
                let full_path = if path.is_relative() {
                    root.join(path)
                } else {
                    path.to_path_buf()
                };
                fs::symlink_metadata(full_path).is_ok()
            };
            if !output_exists {
                warn!(
                    "task {} did not generate expected output: {}",
                    task.name, output
                );
            }
        }
    }
    // Persist the source hash now that the task has succeeded. Doing this here
    // rather than in sources_are_fresh ensures a failed run never advances the
    // baseline — the next invocation will detect a mismatch and re-run.
    if let Some((hash, path)) = compute_source_hash(task, config).await? {
        if let Some(dir) = path.parent() {
            file::create_dir_all(dir)?;
        }
        file::write(&path, &hash)?;
    }
    // Persist the output hash so the next freshness check can detect missing
    // or incomplete outputs even when the source hash still matches.
    // Traversal errors (broken symlinks, unreadable files) are warned but not
    // propagated — the task itself succeeded; failing here would be misleading.
    // Without a stored output hash the next freshness check will conservatively
    // treat the task as stale.
    if Settings::get().task.source_freshness_hash_contents {
        let out_path = outputs_hash_path(task, &root);
        match compute_output_hash(task, &root) {
            Ok(Some(h)) => {
                if let Some(dir) = out_path.parent() {
                    file::create_dir_all(dir)?;
                }
                file::write(&out_path, &h)?;
            }
            Ok(None) => {} // no outputs defined — nothing to save
            Err(e) => {
                // Remove the stale baseline so the next run is not skipped
                // against an obsolete output snapshot.
                let _ = std::fs::remove_file(&out_path);
                warn!(
                    "task {} output hashing failed; next run will not be skipped: {e}",
                    task.name
                );
            }
        }
    }
    Ok(())
}

/// Identity hash for a task in a given working directory. Used as the
/// filename stem for any per-task state we write under `STATE/task-sources/`,
/// so that changes to the task definition (sources, cmd, etc.), the config
/// file it came from, or the working directory all invalidate state in
/// lock-step.
fn task_state_key(task: &Task, root: &Path) -> String {
    let mut hasher = DefaultHasher::new();
    task.hash(&mut hasher);
    task.config_sources().hash(&mut hasher);
    root.hash(&mut hasher);
    task.run.hash(&mut hasher);
    task.sources.hash(&mut hasher);
    task.outputs.patterns().hash(&mut hasher);
    format!("{:x}", hasher.finish())
}

/// Get the path to store source hashes for a task
fn sources_hash_path(task: &Task, root: &Path, content_hash: bool) -> PathBuf {
    let suffix = if content_hash { "-content" } else { "" };
    dirs::STATE
        .join("task-sources")
        .join(format!("{}{suffix}", task_state_key(task, root)))
}

/// Path of the marker recording that this task's work is done. Its mtime is
/// the baseline for "changed since mise last considered this task up to date":
/// `save_checksum` writes it after a successful run, and `sources_are_fresh`
/// writes it when a freshness check finds there is nothing to do. A *failed*
/// run advances neither, so its sources stay outstanding until it passes.
///
/// Callers outside this module cannot build the path themselves, because
/// `task_state_key` hashes the working directory — it is only correct when
/// the root comes from `task_cwd`.
pub(crate) async fn source_baseline_path(task: &Task, config: &Arc<Config>) -> Result<PathBuf> {
    let root = task_cwd(task, config).await?;
    Ok(sources_hash_path(
        task,
        &root,
        Settings::get().task.source_freshness_hash_contents,
    ))
}

/// Get the existing source hash for a task, if it exists
fn source_existing_hash(task: &Task, root: &Path, content_hash: bool) -> Option<String> {
    let path = sources_hash_path(task, root, content_hash);
    if path.exists() {
        Some(file::read_to_string(&path).unwrap_or_default())
    } else {
        None
    }
}

/// Path to the stored output hash for a task.
fn outputs_hash_path(task: &Task, root: &Path) -> PathBuf {
    dirs::STATE
        .join("task-sources")
        .join(format!("{}-outputs", task_state_key(task, root)))
}

/// Read the previously stored output hash, if any.
fn output_existing_hash(task: &Task, root: &Path) -> Option<String> {
    let path = outputs_hash_path(task, root);
    if path.exists() {
        Some(file::read_to_string(&path).unwrap_or_default())
    } else {
        None
    }
}

/// Compute a content-integrity hash for all current output files.
///
/// Returns `None` when any statically-named output is missing (incomplete
/// outputs), when a glob pattern expands to zero matching filesystem objects,
/// or when the task declares no outputs. A `Some` value encodes the sorted
/// `(path, blake3_content_hash)` of every resolved output file — two identical
/// sets of fully-present, content-identical outputs produce the same hash.
///
/// Content hashing (blake3) catches same-size modifications inside directory
/// outputs that `(path, size)` or `(path, size, mtime)` would miss.
/// Directory outputs (static or glob-matched) are walked recursively.
fn compute_output_hash(task: &Task, root: &Path) -> Result<Option<String>> {
    let raw_patterns = task.outputs.paths(task, root);
    let matcher = build_output_matcher(root, &raw_patterns)?;
    let patterns_or_paths = output_glob_patterns(&raw_patterns);
    if patterns_or_paths.is_empty() {
        return Ok(None);
    }

    let (glob_pats, static_paths): (Vec<&String>, Vec<&String>) =
        patterns_or_paths.iter().partition(|p| is_glob_pattern(p));

    // (path, blake3_hex) — full content hash for correctness.
    let mut entries: Vec<(PathBuf, String)> = Vec::new();

    fn hash_file(path: &Path) -> Result<(PathBuf, String)> {
        Ok((path.to_path_buf(), hash::file_hash_blake3(path, None)?))
    }

    /// Walk a directory and push entries for all descendants.
    /// Files get their blake3 content hash; subdirectories get a "dir" sentinel
    /// so that additions/deletions of empty nested directories are detected.
    /// Symlinked directories are followed so content changes inside them are
    /// caught. Returns `true` when at least one entry was found.
    fn push_dir_entries(
        dir: &Path,
        entries: &mut Vec<(PathBuf, String)>,
        matcher: &Override,
    ) -> Result<bool> {
        let mut found_any = false;
        for entry in WalkDir::new(dir).follow_links(true).into_iter() {
            let Some(entry) = prune_symlink_walk_error(entry)? else {
                continue;
            };
            let path = entry.path();
            if path == dir {
                continue; // skip the root directory itself
            }
            if !is_output(matcher, path, entry.file_type().is_dir()) {
                continue;
            }
            if entry.file_type().is_file() {
                entries.push(hash_file(path)?);
                found_any = true;
            } else if entry.file_type().is_dir() {
                entries.push((path.to_path_buf(), "dir".to_string()));
                found_any = true;
            }
        }
        Ok(found_any)
    }

    for path_str in static_paths {
        let path = {
            let p = Path::new(path_str.as_str());
            if p.is_relative() {
                root.join(p)
            } else {
                p.to_path_buf()
            }
        };
        match path.metadata() {
            Ok(m) if m.is_file() => {
                if is_output(&matcher, &path, false) {
                    entries.push(hash_file(&path)?);
                } else {
                    continue;
                }
            }
            Ok(m) if m.is_dir() => {
                if !push_dir_entries(&path, &mut entries, &matcher)?
                    && is_output(&matcher, &path, true)
                {
                    // Empty directory — sentinel so its deletion is detected.
                    entries.push((path, "empty-dir".to_string()));
                }
            }
            Ok(_) => {
                if is_output(&matcher, &path, false) {
                    entries.push((path, "other".to_string()));
                }
            }
            Err(_) => {
                if is_output(&matcher, &path, false) || is_output(&matcher, &path, true) {
                    return Ok(None); // selected and missing → outputs incomplete
                }
            }
        }
    }

    for pattern_str in glob_pats {
        let mut glob_matched = false;
        for expanded in expand_enumeration_patterns(pattern_str)? {
            let full = resolve_task_path(root, expanded);
            for entry in glob_walk(&full, false)? {
                // Propagate glob resolution errors (OS errors during directory
                // reads) rather than silently skipping them — a partial result
                // could produce the same hash as a complete one.
                let Some(entry) = prune_symlink_walk_error(entry)? else {
                    continue;
                };
                let path = entry.into_path();
                glob_matched = true;
                let metadata = match path.metadata() {
                    Ok(metadata) => metadata,
                    Err(_) => {
                        if !is_output(&matcher, &path, false) && !is_output(&matcher, &path, true) {
                            continue;
                        }
                        return Ok(None); // selected and unreadable → outputs incomplete
                    }
                };
                if !is_output(&matcher, &path, metadata.is_dir()) {
                    continue;
                }
                match metadata {
                    m if m.is_file() => {
                        entries.push(hash_file(&path)?);
                    }
                    m if m.is_dir() => {
                        let found = push_dir_entries(&path, &mut entries, &matcher)?;
                        if !found {
                            entries.push((path, "empty-dir".to_string()));
                        }
                    }
                    _ => {
                        entries.push((path, "other".to_string()));
                    }
                }
            }
        }
        // A glob that matches nothing means expected outputs are missing.
        if !glob_matched {
            return Ok(None);
        }
    }

    entries.sort_by(|(a, _), (b, _)| a.cmp(b));
    Ok(Some(hash::hash_to_str(&entries)))
}

/// Get file metadata for a list of include-side patterns or paths, retaining
/// only files that `matcher` selects as a source.
fn get_file_metadatas(
    root: &Path,
    patterns_or_paths: &[String],
    matcher: &Override,
) -> Result<Vec<(PathBuf, fs::Metadata)>> {
    if patterns_or_paths.is_empty() {
        return Ok(vec![]);
    }
    let (patterns, paths): (Vec<&String>, Vec<&String>) =
        patterns_or_paths.iter().partition(|p| is_glob_pattern(p));

    let mut metadatas = BTreeMap::new();
    for pattern in patterns {
        for expanded in expand_enumeration_patterns(pattern)? {
            let pattern = resolve_task_path(root, expanded);
            let files = glob_walk(&pattern, false)?;
            for file in files.flatten().map(|entry| entry.into_path()) {
                if let Ok(metadata) = file.metadata() {
                    metadatas.insert(file, metadata);
                }
            }
        }
    }

    for path in paths {
        let file = resolve_task_path(root, path);
        if let Ok(metadata) = file.metadata() {
            metadatas.insert(file, metadata);
        }
    }

    let metadatas = metadatas
        .into_iter()
        .filter(|(_, m)| m.is_file())
        .filter(|(p, _)| is_source(matcher, p))
        .collect_vec();

    Ok(metadatas)
}

/// Convert file metadata to a hash string for comparison
///
/// Includes path, file size and mtime. Without the mtime, a change that keeps the file size — a
/// version bump from `1.2.3` to `1.2.4`, say — and lands an mtime no newer than the output falls
/// through to the mtime comparison below, which then reports the task as fresh and leaves a stale
/// output in place. That is what tar, unzip, `rsync -a` and `cp -p` do when they restore an older
/// tree; `git checkout` is unaffected because it always writes with the current time.
///
/// The [`SystemTime`] is hashed as it is rather than as a duration since the epoch: converting
/// would fold every pre-epoch mtime into the same value as "this filesystem reports no mtime",
/// making two distinct timestamps indistinguishable. `None` therefore means only that the mtime is
/// unavailable.
fn file_metadatas_to_hash(metadatas: &[(PathBuf, fs::Metadata)]) -> String {
    let stat_info: Vec<_> = metadatas
        .iter()
        .map(|(p, m)| (p, m.len(), m.modified().ok()))
        .collect();
    hash::hash_to_str(&stat_info)
}

/// Per-file content hash cache entry. The `(size, mtime_secs, mtime_nanos)`
/// tuple is the cache key (in the git-style "stat-info" sense): when those
/// three match, we reuse `hash` without re-reading the file.
#[derive(Debug, Serialize, Deserialize)]
struct CachedFileHash {
    mtime_secs: i64,
    mtime_nanos: u32,
    size: u64,
    hash: String,
}

type ContentHashCache = BTreeMap<PathBuf, CachedFileHash>;

/// Path to the per-task content-hash cache file. Shares `task_state_key`
/// with `sources_hash_path` so changes to the task definition invalidate
/// both in lock-step.
fn content_hash_cache_path(task: &Task, root: &Path) -> PathBuf {
    dirs::STATE
        .join("task-sources")
        .join(format!("{}-content-cache", task_state_key(task, root)))
}

fn load_content_hash_cache(path: &Path) -> ContentHashCache {
    (|| -> Result<ContentHashCache> {
        let mut zlib = ZlibDecoder::new(File::open(path)?);
        let mut bytes = Vec::new();
        zlib.read_to_end(&mut bytes)?;
        Ok(rmp_serde::from_slice(&bytes)?)
    })()
    .unwrap_or_default()
}

fn save_content_hash_cache(path: &Path, cache: &ContentHashCache) -> Result<()> {
    if let Some(parent) = path.parent() {
        file::create_dir_all(parent)?;
    }
    let partial = path.with_extension(format!("part-{}", random_string(8)));
    {
        let mut zlib = ZlibEncoder::new(File::create(&partial)?, Compression::fast());
        zlib.write_all(&rmp_serde::to_vec_named(cache)?)?;
        // Propagate finalization errors explicitly — ZlibEncoder's Drop impl
        // would silently discard them, leaving a truncated partial file that
        // we'd then rename into place as a poisoned cache.
        zlib.finish()?;
    }
    file::rename(&partial, path)?;
    Ok(())
}

fn cached_entry_matches(entry: &CachedFileHash, metadata: &fs::Metadata) -> bool {
    let Ok(mtime) = metadata.modified() else {
        return false;
    };
    let Ok(dur) = mtime.duration_since(UNIX_EPOCH) else {
        return false;
    };
    entry.size == metadata.len()
        && entry.mtime_secs == dur.as_secs() as i64
        && entry.mtime_nanos == dur.subsec_nanos()
}

fn make_cache_entry(metadata: &fs::Metadata, hash: String) -> CachedFileHash {
    let dur = metadata
        .modified()
        .ok()
        .and_then(|m| m.duration_since(UNIX_EPOCH).ok());
    CachedFileHash {
        mtime_secs: dur.map(|d| d.as_secs() as i64).unwrap_or(0),
        mtime_nanos: dur.map(|d| d.subsec_nanos()).unwrap_or(0),
        size: metadata.len(),
        hash,
    }
}

/// Convert file contents to a hash string for comparison using blake3.
///
/// More accurate than metadata hashing but slower since it reads all file
/// contents. `cache` is consulted first: if a file's `(size, mtime_secs,
/// mtime_nanos)` match the cached entry, the stored hash is reused and the
/// file is not re-read. On return, `cache` is rebuilt from scratch with one
/// entry per current source file — entries for files no longer in `sources`
/// are pruned so the cache file size stays bounded.
fn file_contents_to_hash(
    metadatas: &[(PathBuf, fs::Metadata)],
    cache: &mut ContentHashCache,
) -> Result<String> {
    let mut content_hashes: Vec<(&PathBuf, String)> = Vec::new();
    let mut next: ContentHashCache = BTreeMap::new();
    for (path, metadata) in metadatas {
        let hash = match cache.get(path) {
            Some(entry) if cached_entry_matches(entry, metadata) => entry.hash.clone(),
            _ => hash::file_hash_blake3(path, None)?,
        };
        next.insert(path.clone(), make_cache_entry(metadata, hash.clone()));
        content_hashes.push((path, hash));
    }
    *cache = next;
    Ok(hash::hash_to_str(&content_hashes))
}

/// Get the last modified time from file metadata
fn get_last_modified_from_metadatas(metadatas: &[(PathBuf, fs::Metadata)]) -> Option<SystemTime> {
    metadatas.iter().flat_map(|(_, m)| m.modified()).max()
}

/// Get the last modified time from selected task outputs.
fn get_last_modified(root: &Path, patterns_or_paths: &[String]) -> Result<Option<SystemTime>> {
    if patterns_or_paths.is_empty() {
        return Ok(None);
    }
    let matcher = build_output_matcher(root, patterns_or_paths)?;
    let mut file_modified = Vec::new();
    let mut directory_modified = Vec::new();
    for pattern in output_glob_patterns(patterns_or_paths) {
        let is_glob = is_glob_pattern(&pattern);
        let candidates = if is_glob {
            let mut candidates = Vec::new();
            for expanded in expand_enumeration_patterns(&pattern)? {
                let expanded = resolve_task_path(root, expanded);
                for entry in glob_walk(&expanded, false)? {
                    if let Some(entry) = prune_symlink_walk_error(entry)? {
                        candidates.push(entry.into_path());
                    }
                }
            }
            candidates
        } else {
            vec![resolve_task_path(root, &pattern)]
        };
        let mut found_candidate = false;
        for candidate in candidates {
            if fs::symlink_metadata(&candidate).is_err() {
                continue;
            }
            found_candidate = true;
            for entry in WalkDir::new(candidate).follow_links(true) {
                let Some(entry) = prune_symlink_walk_error(entry)? else {
                    continue;
                };
                let metadata = entry.metadata()?;
                if is_output(&matcher, entry.path(), metadata.is_dir()) {
                    if metadata.is_dir() {
                        directory_modified.push(metadata.modified()?);
                    } else {
                        file_modified.push(metadata.modified()?);
                    }
                }
            }
        }
        // Every positive output pattern represents a required artifact root.
        // Excluded static paths are the exception; the ordered matcher makes
        // those optional even though they remain in the enumeration list.
        if !found_candidate
            && (is_glob || {
                let path = resolve_task_path(root, &pattern);
                is_output(&matcher, &path, false) || is_output(&matcher, &path, true)
            })
        {
            return Ok(None);
        }
    }
    let last_mod = file_modified.into_iter().chain(directory_modified).max();

    trace!(
        "last_modified of {}: {last_mod:?}",
        patterns_or_paths.iter().join(" ")
    );
    Ok(last_mod)
}

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

    #[cfg(unix)]
    #[test]
    fn glob_walk_skips_symlink_loops() -> Result<()> {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir()?;
        let tree = temp.path().join("tree");
        fs::create_dir(&tree)?;
        fs::write(tree.join("input.txt"), "input")?;
        symlink(".", tree.join("a"))?;
        symlink(".", tree.join("b"))?;

        let pattern = tree.join("**/*");
        let entries = glob_walk(&pattern, false)?.collect_vec();
        let paths = entries
            .iter()
            .filter_map(|entry| entry.as_ref().ok())
            .map(|entry| entry.path())
            .collect_vec();

        assert!(paths.contains(&tree.join("input.txt").as_path()));
        assert_eq!(entries.iter().filter(|entry| entry.is_err()).count(), 2);
        assert!(
            entries.len() < 10,
            "loop expansion was not bounded: {entries:?}"
        );
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn glob_walk_skips_broken_symlinks() -> Result<()> {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir()?;
        let tree = temp.path().join("tree");
        fs::create_dir(&tree)?;
        fs::write(tree.join("input.txt"), "input")?;
        symlink("missing", tree.join("dangling"))?;
        symlink("self", tree.join("self"))?;

        let paths = glob_walk(&tree.join("**/*"), false)?
            .filter_map(|entry| prune_symlink_walk_error(entry).transpose())
            .map(|entry| entry.map(|entry| entry.into_path()))
            .collect::<Result<Vec<_>>>()?;

        assert_eq!(paths, [tree.join("input.txt")]);
        Ok(())
    }

    #[cfg(unix)]
    #[test]
    fn glob_walk_follows_non_looping_directory_symlinks() -> Result<()> {
        use std::os::unix::fs::symlink;

        let temp = tempfile::tempdir()?;
        let tree = temp.path().join("tree");
        let actual = temp.path().join("actual");
        fs::create_dir(&tree)?;
        fs::create_dir(&actual)?;
        fs::write(actual.join("input.txt"), "input")?;
        symlink("../actual", tree.join("linked"))?;

        let paths = glob_walk(&tree.join("**/*"), false)?
            .map(|entry| entry.map(|entry| entry.into_path()))
            .collect::<Result<Vec<_>, _>>()?;

        assert!(paths.contains(&tree.join("linked/input.txt")));
        Ok(())
    }

    #[test]
    fn glob_walk_preserves_non_recursive_depth_and_order() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let tree = temp.path().join("tree");
        fs::create_dir_all(tree.join("nested"))?;
        fs::write(tree.join("b.txt"), "b")?;
        fs::write(tree.join("a.txt"), "a")?;
        fs::write(tree.join("nested/deep.txt"), "deep")?;

        let paths = glob_walk(&tree.join("*.txt"), false)?
            .map(|entry| entry.map(|entry| entry.into_path()))
            .collect::<Result<Vec<_>, _>>()?;

        assert_eq!(paths, [tree.join("a.txt"), tree.join("b.txt")]);
        Ok(())
    }

    #[test]
    fn glob_walk_treats_missing_literal_prefix_as_no_matches() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let entries = glob_walk(&temp.path().join("missing/**/*.txt"), false)?.collect_vec();

        assert!(entries.is_empty());
        Ok(())
    }

    fn matches(sources: &[&str], path: &str) -> bool {
        let sources: Vec<String> = sources.iter().map(|s| s.to_string()).collect();
        let root = Path::new(".");
        let matcher = build_source_matcher(root, root, &sources);
        is_source(&matcher, Path::new(path))
    }

    /// Gitignore patterns are `/`-separated on every platform, but `Path`
    /// renders `\` on Windows and `globset` reads that as an escape. A pattern
    /// rebuilt from a `PathBuf` there stops meaning what it says: a negated
    /// entry no longer excludes, so the matcher widens instead of narrowing.
    /// This only bites on Windows, so it is asserted rather than left to the
    /// platform-specific tests that happen to cover it.
    #[test]
    fn patterns_stay_slash_separated_on_every_platform() {
        let joined = Path::new("dist").join("**").join("*.map");
        assert_eq!(pattern_from_path(&joined).unwrap(), "dist/**/*.map");

        let root = Path::new("/project");
        let normalized = normalize_pattern(root, root, "!dist/**/*.map");
        assert_eq!(normalized, "!dist/**/*.map");
    }

    #[test]
    fn output_matcher_excludes_and_reincludes_descendants() {
        let root = Path::new("/project");
        let patterns = vec![
            "dist".to_string(),
            "!dist/**/*.map".to_string(),
            "dist/keep.map".to_string(),
        ];
        let matcher = build_output_matcher(root, &patterns).unwrap();

        assert!(is_output(&matcher, &root.join("dist/app.js"), false));
        assert!(!is_output(&matcher, &root.join("dist/app.map"), false));
        assert!(is_output(&matcher, &root.join("dist/nested/app.js"), false));
        assert!(is_output(&matcher, &root.join("dist/keep.map"), false));
    }

    #[test]
    fn output_matcher_normalizes_absolute_patterns_under_root() {
        let root = tempfile::tempdir().unwrap();
        let output = root.path().join("dist/result.txt");
        let patterns = vec![format!("{}/dist/**/*", root.path().display())];
        let matcher = build_output_matcher(root.path(), &patterns).unwrap();

        assert!(is_output(&matcher, &output, false));
    }

    /// Output enumeration resolves candidates from the raw pattern, so the
    /// `..` the matcher resolved away is still present in the path it is asked
    /// about. Both sides must normalize or the output never matches and the
    /// task stays permanently stale.
    ///
    /// The pattern has to contain a slash to pin this down: a slashless
    /// gitignore pattern matches at any depth, so an un-normalized path would
    /// match on its basename alone and hide the difference.
    #[test]
    fn output_matcher_normalizes_parent_traversal() {
        let root = tempfile::tempdir().unwrap();
        let patterns = vec!["dist/../out/result.txt".to_string()];
        let matcher = build_output_matcher(root.path(), &patterns).unwrap();

        assert!(is_output(
            &matcher,
            &root.path().join("dist/../out/result.txt"),
            false
        ));
        assert!(is_output(
            &matcher,
            &root.path().join("out/result.txt"),
            false
        ));
    }

    #[test]
    fn metadata_hash_notices_a_same_size_change_with_an_older_mtime() {
        // https://github.com/jdx/mise/discussions/4209 — restoring an older tree with tar,
        // `rsync -a` or `cp -p` keeps the recorded mtime, so a same-size edit is invisible to a
        // hash built from the path and size alone and the mtime comparison then calls it fresh.
        let root = tempfile::tempdir().unwrap();
        let p = root.path().join("pin.txt");
        fs::write(&p, "1.2.3").unwrap();
        let before = file_metadatas_to_hash(&[(p.clone(), fs::metadata(&p).unwrap())]);

        fs::write(&p, "1.2.4").unwrap();
        let restored = filetime::FileTime::from_unix_time(1_000_000, 0);
        filetime::set_file_times(&p, restored, restored).unwrap();
        let after = file_metadatas_to_hash(&[(p.clone(), fs::metadata(&p).unwrap())]);

        assert_eq!(
            fs::metadata(&p).unwrap().len(),
            5,
            "the fixture only exercises the bug while both versions are the same size"
        );
        assert_ne!(before, after, "the mtime change should be part of the hash");
    }

    #[test]
    fn metadata_hash_separates_pre_epoch_mtimes() {
        // mtimes from before 1970 must stay distinct from each other, and from "the filesystem
        // reports no mtime" — folding them together would hide a change the same way the missing
        // mtime did.
        let root = tempfile::tempdir().unwrap();
        let p = root.path().join("ancient.txt");
        fs::write(&p, "x").unwrap();

        let stamp = |secs: i64| {
            let t = filetime::FileTime::from_unix_time(secs, 0);
            // a filesystem that cannot store a pre-epoch timestamp is not what this pins down
            filetime::set_file_times(&p, t, t).ok()?;
            let metadata = fs::metadata(&p).unwrap();
            let mtime = metadata.modified().ok()?;
            Some((mtime, file_metadatas_to_hash(&[(p.clone(), metadata)])))
        };
        let (Some((first_mtime, first)), Some((second_mtime, second))) =
            (stamp(-2_000_000), stamp(-1_000_000))
        else {
            return;
        };
        if first_mtime == second_mtime {
            return;
        }

        assert_ne!(
            first, second,
            "two different pre-epoch mtimes should hash differently"
        );
    }

    #[test]
    fn output_globs_ignore_excludes_and_unescape_literal_bangs() {
        assert_eq!(
            output_glob_patterns(&[
                "dist".to_string(),
                "!dist/**/*.map".to_string(),
                "\\!important".to_string(),
            ]),
            ["dist", "!important"]
        );
    }

    /// A trailing `**` must enumerate files. The `glob` crate matches it against
    /// directories only, so without the expansion `src/**` yields subdirectories
    /// and no files at all — a `sources` entry that contributes nothing to
    /// freshness and an `outputs` entry that archives nothing.
    #[test]
    fn trailing_globstar_expands_to_reach_files() {
        assert_eq!(expand_trailing_globstar("src/**"), "src/**/*");
        assert_eq!(expand_trailing_globstar("**"), "**/*");
        assert_eq!(expand_enumeration_patterns("src/**").unwrap(), ["src/**/*"]);
    }

    /// The expansion runs on each brace alternative. `{src/**,dist/**}` ends in
    /// `}`, so a check against the whole pattern never sees the `**` and every
    /// alternative would go on enumerating directories only.
    #[test]
    fn trailing_globstar_expands_inside_brace_alternatives() {
        assert_eq!(
            expand_enumeration_patterns("{src,dist}/**").unwrap(),
            ["src/**/*", "dist/**/*"]
        );
        assert_eq!(
            expand_enumeration_patterns("{src/**,dist/**,docs/*.md}").unwrap(),
            ["src/**/*", "dist/**/*", "docs/*.md"]
        );
    }

    /// `\` is a path separator on Windows, so `src\**` is a trailing globstar
    /// there and carries the same defect. On unix the same string is an escape
    /// that `glob` rejects outright, so it must be left alone.
    #[test]
    fn trailing_globstar_follows_platform_separators() {
        if cfg!(windows) {
            assert_eq!(expand_trailing_globstar(r"src\**"), r"src\**/*");
        } else {
            assert_eq!(expand_trailing_globstar(r"src\**"), r"src\**");
        }
    }

    /// Only a *trailing* `**` is wrong. In the interior it already spans
    /// directories correctly, and rewriting it would change what the pattern
    /// selects rather than fixing what it enumerates.
    #[test]
    fn interior_globstar_and_other_patterns_are_untouched() {
        for pattern in [
            "src/**/foo.rs",
            "src/**/*.ts",
            "src/*",
            "dist",
            "src/**/*",
            "**/*",
            "a**",
        ] {
            assert_eq!(expand_trailing_globstar(pattern), pattern);
        }
    }

    #[test]
    fn glob_braces_expand_nested_and_multiple_alternates() {
        assert_eq!(
            expand_glob_braces("src/{a,{b,c}}/{one,two}.txt").unwrap(),
            [
                "src/a/one.txt",
                "src/a/two.txt",
                "src/b/one.txt",
                "src/b/two.txt",
                "src/c/one.txt",
                "src/c/two.txt",
            ]
        );
        assert_eq!(expand_glob_braces("{,a}.txt").unwrap(), ["a.txt"]);
        assert!(expand_glob_braces("src/{a,b.txt").is_err());
        assert!(expand_glob_braces(&"{a,b}".repeat(11)).is_err());
    }

    #[test]
    fn glob_braces_preserve_literal_singleton_groups() {
        assert_eq!(
            expand_glob_braces("{generated}.txt").unwrap(),
            ["[{]generated[}].txt"]
        );
        assert_eq!(
            expand_glob_braces("{generated}/{a,b}.txt").unwrap(),
            ["[{]generated[}]/a.txt", "[{]generated[}]/b.txt"]
        );
        assert_eq!(
            expand_glob_braces("{generated}.{txt,out}").unwrap(),
            ["[{]generated[}].txt", "[{]generated[}].out"]
        );
        assert_eq!(
            expand_glob_braces("{prefix-{a,b}}.txt").unwrap(),
            ["[{]prefix-a[}].txt", "[{]prefix-b[}].txt"]
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn glob_braces_preserve_escaped_unix_braces() {
        assert_eq!(
            expand_glob_braces(r"src/\{literal\}/[{}].txt").unwrap(),
            [r"src/\{literal\}/[{}].txt"]
        );
    }

    #[cfg(windows)]
    #[test]
    fn glob_braces_treat_windows_backslashes_as_separators() {
        assert_eq!(
            expand_glob_braces(r"C:\build\{debug,release}\*.exe").unwrap(),
            [r"C:\build\debug\*.exe", r"C:\build\release\*.exe"]
        );
    }

    #[test]
    fn source_and_output_matchers_support_ordered_brace_globs() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR"));
        let source_matcher = build_source_matcher(
            root,
            root,
            &[
                "{Cargo.toml,README.md}".to_string(),
                "!README.md".to_string(),
                "README.md".to_string(),
            ],
        );
        let output_matcher = build_output_matcher(
            root,
            &[
                "{Cargo.toml,README.md}".to_string(),
                "!README.md".to_string(),
            ],
        )
        .unwrap();

        assert!(is_source(&source_matcher, &root.join("Cargo.toml")));
        assert!(is_source(&source_matcher, &root.join("README.md")));
        assert!(is_output(&output_matcher, &root.join("Cargo.toml"), false));
        assert!(!is_output(&output_matcher, &root.join("README.md"), false));
    }

    #[test]
    fn output_hash_supports_brace_globs() {
        let root = tempfile::tempdir().unwrap();
        fs::write(root.path().join("a.out"), "a").unwrap();
        fs::write(root.path().join("b.out"), "b").unwrap();
        let task = Task {
            outputs: crate::task::task_sources::TaskOutputs::Files(vec!["{a,b}.out".to_string()]),
            ..Default::default()
        };

        assert!(compute_output_hash(&task, root.path()).unwrap().is_some());
    }

    #[test]
    fn output_mtime_includes_selected_directories() {
        let root = tempfile::tempdir().unwrap();
        let dist = root.path().join("dist");
        let output = dist.join("result.txt");
        fs::create_dir(&dist).unwrap();
        fs::write(&output, "result").unwrap();
        let file_mtime = filetime::FileTime::from_unix_time(100, 0);
        let directory_mtime = filetime::FileTime::from_unix_time(200, 0);
        filetime::set_file_mtime(&output, file_mtime).unwrap();
        filetime::set_file_mtime(&dist, directory_mtime).unwrap();

        let modified = get_last_modified(root.path(), &["dist".to_string()])
            .unwrap()
            .unwrap();

        assert_eq!(modified, SystemTime::from(directory_mtime));
    }

    #[test]
    fn output_mtime_requires_all_selected_static_paths() {
        let root = tempfile::tempdir().unwrap();
        fs::write(root.path().join("present.txt"), "present").unwrap();

        let modified = get_last_modified(
            root.path(),
            &["present.txt".to_string(), "missing.txt".to_string()],
        )
        .unwrap();

        assert!(modified.is_none());
    }

    #[test]
    fn output_mtime_requires_each_positive_glob_to_match() {
        let root = tempfile::tempdir().unwrap();
        fs::write(root.path().join("present.txt"), "present").unwrap();

        let modified = get_last_modified(
            root.path(),
            &["present.txt".to_string(), "*.generated".to_string()],
        )
        .unwrap();

        assert!(modified.is_none());
    }

    #[test]
    fn output_mtime_allows_missing_excluded_static_paths() {
        let root = tempfile::tempdir().unwrap();
        fs::write(root.path().join("present.txt"), "present").unwrap();

        let modified = get_last_modified(
            root.path(),
            &[
                "present.txt".to_string(),
                "missing.txt".to_string(),
                "!missing.txt".to_string(),
            ],
        )
        .unwrap();

        assert!(modified.is_some());
    }

    #[test]
    fn output_mtime_brace_alternatives_require_any_match() {
        let root = tempfile::tempdir().unwrap();
        fs::write(root.path().join("a.out"), "a").unwrap();

        let modified = get_last_modified(root.path(), &["{a,b}.out".to_string()]).unwrap();

        assert!(modified.is_some());
    }

    #[test]
    fn output_mtime_allows_glob_matches_that_are_all_excluded() {
        let root = tempfile::tempdir().unwrap();
        fs::write(root.path().join("present.txt"), "present").unwrap();
        fs::create_dir(root.path().join("dist")).unwrap();
        fs::write(root.path().join("dist/vendor.js"), "vendor").unwrap();

        let modified = get_last_modified(
            root.path(),
            &[
                "present.txt".to_string(),
                "dist/*.js".to_string(),
                "!dist/vendor.js".to_string(),
            ],
        )
        .unwrap();

        assert!(modified.is_some());
    }

    #[test]
    fn output_hash_allows_missing_excluded_static_paths() {
        let root = tempfile::tempdir().unwrap();
        let task = Task {
            outputs: crate::task::task_sources::TaskOutputs::Files(vec![
                "missing.txt".to_string(),
                "!missing.txt".to_string(),
            ]),
            ..Default::default()
        };

        assert!(compute_output_hash(&task, root.path()).unwrap().is_some());
    }

    #[test]
    fn output_hash_allows_glob_matches_that_are_all_excluded() {
        let root = tempfile::tempdir().unwrap();
        fs::create_dir(root.path().join("dist")).unwrap();
        fs::write(root.path().join("dist/vendor.js"), "vendor").unwrap();
        let task = Task {
            outputs: crate::task::task_sources::TaskOutputs::Files(vec![
                "dist/*.js".to_string(),
                "!dist/vendor.js".to_string(),
            ]),
            ..Default::default()
        };

        assert!(compute_output_hash(&task, root.path()).unwrap().is_some());
    }

    #[test]
    fn task_state_key_includes_all_definition_sources() {
        let root = Path::new("/project");
        let mut task = Task {
            name: "build".to_string(),
            config_source: PathBuf::from(".mise/tasks/build"),
            ..Default::default()
        };
        let primary_key = task_state_key(&task, root);

        task.additional_config_sources
            .push(PathBuf::from("mise.toml"));

        assert_ne!(primary_key, task_state_key(&task, root));
    }

    #[test]
    fn task_state_key_changes_when_run_changes() {
        use crate::task::RunEntry;
        let root = Path::new("/project");
        let mut task = Task {
            name: "build".to_string(),
            config_source: PathBuf::from("mise.toml"),
            run: vec![RunEntry::Script("echo v1".to_string())],
            ..Default::default()
        };
        let key_v1 = task_state_key(&task, root);
        task.run = vec![RunEntry::Script("echo v2".to_string())];
        assert_ne!(key_v1, task_state_key(&task, root));
    }

    #[test]
    fn task_state_key_changes_when_sources_change() {
        let root = Path::new("/project");
        let mut task = Task {
            name: "build".to_string(),
            config_source: PathBuf::from("mise.toml"),
            sources: vec!["src.txt".to_string()],
            ..Default::default()
        };
        let key_v1 = task_state_key(&task, root);
        task.sources = vec!["other.txt".to_string()];
        assert_ne!(key_v1, task_state_key(&task, root));
    }

    #[test]
    fn glob_patterns_drops_excludes_and_unescapes() {
        let inputs = vec![
            "src/**/*.ts".to_string(),
            "!src/**/*.test.ts".to_string(),
            "\\!literal.txt".to_string(),
            "tsconfig.json".to_string(),
        ];
        assert_eq!(
            source_glob_patterns(&inputs),
            vec!["src/**/*.ts", "!literal.txt", "tsconfig.json"],
        );
    }

    #[test]
    fn matcher_includes_plain_pattern() {
        assert!(matches(&["src/**/*.ts"], "src/foo.ts"));
        assert!(matches(&["src/**/*.ts"], "src/sub/foo.ts"));
        assert!(!matches(&["src/**/*.ts"], "lib/foo.ts"));
    }

    #[test]
    fn matcher_negation_excludes() {
        let pats = &["src/**/*.ts", "!src/**/*.test.ts"];
        assert!(matches(pats, "src/foo.ts"));
        assert!(!matches(pats, "src/foo.test.ts"));
    }

    #[test]
    fn matcher_reincludes_after_negation() {
        // Re-inclusion semantics: a later non-negated entry wins over an
        // earlier `!`-negation, just like a gitignore whitelist.
        let pats = &["src/**/*.ts", "!src/**/*.test.ts", "src/keep.test.ts"];
        assert!(matches(pats, "src/foo.ts"));
        assert!(!matches(pats, "src/foo.test.ts"));
        assert!(matches(pats, "src/keep.test.ts"));
    }

    #[test]
    fn matcher_escaped_literal_bang() {
        let pats = &["\\!important.txt", "!ignored.txt"];
        assert!(matches(pats, "!important.txt"));
        assert!(!matches(pats, "ignored.txt"));
    }

    #[test]
    #[cfg(unix)]
    fn matcher_absolute_literal_bang_under_root() {
        let root = Path::new("/project");
        let sources = vec!["/project/!important.txt".to_string()];
        let matcher = build_source_matcher(root, root, &sources);
        assert!(is_source(&matcher, Path::new("/project/!important.txt")));
        assert!(!is_source(&matcher, Path::new("/project/other.txt")));
    }

    #[test]
    #[cfg(unix)]
    fn matcher_absolute_pattern_under_root() {
        // Patterns that resolve to absolute paths under the matcher root
        // (e.g. from `{{cwd}}/input` after templating) are normalized to
        // root-relative so gitignore semantics work correctly.
        // Unix-only because Windows uses `C:\...` for absolute paths and
        // `Path::is_absolute` returns false for `/proj` there.
        let root = Path::new("/proj");
        let sources = vec!["/proj/input".to_string()];
        let matcher = build_source_matcher(root, root, &sources);
        assert!(is_source(&matcher, Path::new("/proj/input")));
        assert!(!is_source(&matcher, Path::new("/proj/other")));
    }

    #[test]
    #[cfg(unix)]
    fn matcher_absolute_negation_under_root() {
        let root = Path::new("/proj");
        let sources = vec![
            "/proj/src/**/*.ts".to_string(),
            "!/proj/src/**/*.test.ts".to_string(),
        ];
        let matcher = build_source_matcher(root, root, &sources);
        assert!(is_source(&matcher, Path::new("/proj/src/foo.ts")));
        assert!(!is_source(&matcher, Path::new("/proj/src/foo.test.ts")));
    }

    /// Regression: an absolute path outside the matcher's root must not be
    /// silently dropped. `Override::matched` returns `Match::None` for such
    /// paths and (with positive patterns present) promotes them to
    /// `Match::Ignore`, which would silently exclude legitimate sources
    /// (e.g. a workspace-root file referenced from a sub-package task).
    #[test]
    #[cfg(unix)]
    fn matcher_absolute_path_outside_root_passes_through() {
        let root = Path::new("/proj");
        let sources = vec!["/elsewhere/Cargo.toml".to_string()];
        let matcher = build_source_matcher(root, root, &sources);
        assert!(is_source(&matcher, Path::new("/elsewhere/Cargo.toml")));
    }

    /// Workspace-rooted absolute pattern in a subproject task must match files
    /// both inside and outside the subproject CWD.
    #[test]
    #[cfg(unix)]
    fn matcher_subproject_absolute_workspace_pattern() {
        let match_root = Path::new("/workspace");
        let task_cwd = Path::new("/workspace/lib/worker");
        let sources = vec!["/workspace/lib/**/*".to_string()];
        let matcher = build_source_matcher(match_root, task_cwd, &sources);
        assert!(is_source(
            &matcher,
            Path::new("/workspace/lib/worker/worker.go")
        ));
        assert!(is_source(&matcher, Path::new("/workspace/lib/shared.go")));
        assert!(!is_source(&matcher, Path::new("/workspace/other/file.go")));
    }

    #[test]
    fn absolute_source_patterns_are_enumerated_from_a_subproject() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path();
        let task_cwd = workspace.join("packages/app");
        let source = task_cwd.join("src/input.txt");
        let global = workspace.join("workspace.txt");
        fs::create_dir_all(source.parent().unwrap())?;
        fs::write(&source, "source")?;
        fs::write(&global, "global")?;

        let sources = vec![
            format!("{}/packages/app/src/**/*", workspace.display()),
            global.to_string_lossy().to_string(),
        ];
        let matcher = build_source_matcher(workspace, &task_cwd, &sources);
        let metadatas = get_file_metadatas(&task_cwd, &source_glob_patterns(&sources), &matcher)?;
        let paths = metadatas
            .into_iter()
            .map(|(path, _)| path)
            .collect::<Vec<_>>();

        assert!(paths.contains(&source), "{paths:?}");
        assert!(paths.contains(&global), "{paths:?}");
        Ok(())
    }

    /// Relative pattern in a subproject task must be anchored at the task CWD,
    /// not the workspace root.
    #[test]
    #[cfg(unix)]
    fn matcher_subproject_relative_pattern() {
        let match_root = Path::new("/workspace");
        let task_cwd = Path::new("/workspace/lib/worker");
        let sources = vec!["src/**/*.go".to_string()];
        let matcher = build_source_matcher(match_root, task_cwd, &sources);
        assert!(is_source(
            &matcher,
            Path::new("/workspace/lib/worker/src/main.go")
        ));
        assert!(!is_source(&matcher, Path::new("/workspace/src/other.go")));
    }

    /// `..` in a relative pattern climbs out of the task CWD while the pattern
    /// stays anchored inside the workspace root.
    #[test]
    #[cfg(unix)]
    fn matcher_subproject_parent_relative_pattern() {
        let match_root = Path::new("/workspace");
        let task_cwd = Path::new("/workspace/lib/worker");
        let sources = vec!["../shared/**/*.go".to_string()];
        let matcher = build_source_matcher(match_root, task_cwd, &sources);
        assert!(is_source(
            &matcher,
            Path::new("/workspace/lib/shared/util.go")
        ));
        assert!(!is_source(&matcher, Path::new("/workspace/other.go")));
    }

    /// `glob` builds its results from the raw pattern, so a `../` source
    /// enumerates paths that still contain `..`. They must survive the matcher
    /// that no longer holds one.
    #[test]
    #[cfg(unix)]
    fn matcher_accepts_enumerated_paths_containing_parent_dirs() {
        let match_root = Path::new("/workspace");
        let task_cwd = Path::new("/workspace/lib/worker");
        let sources = vec!["../shared/**/*.go".to_string()];
        let matcher = build_source_matcher(match_root, task_cwd, &sources);
        assert!(is_source(
            &matcher,
            Path::new("/workspace/lib/worker/../shared/util.go")
        ));
    }

    #[test]
    #[cfg(unix)]
    fn matcher_parent_pattern_above_match_root_passes_through() {
        let match_root = Path::new("/workspace");
        let task_cwd = Path::new("/workspace/lib");
        let sources = vec!["../../outside/**".to_string()];
        let matcher = build_source_matcher(match_root, task_cwd, &sources);
        assert!(is_source(&matcher, Path::new("/outside/x")));
    }

    #[test]
    #[cfg(unix)]
    fn matcher_leaves_parent_dirs_that_would_collapse_a_glob() {
        let root = Path::new("/workspace");
        let sources = vec!["**/../x".to_string()];
        let matcher = build_source_matcher(root, root, &sources);
        assert!(!is_source(&matcher, Path::new("/workspace/x")));
    }

    /// The glob guard inspects the pattern as written. A task directory may
    /// contain a glob metacharacter as a literal name, and folding it into the
    /// inspected path would make this ordinary `../` entry look like a `..`
    /// popping a glob, silently leaving the pattern unanchored.
    #[test]
    #[cfg(unix)]
    fn matcher_parent_relative_pattern_from_a_task_dir_containing_a_glob_char() {
        let match_root = Path::new("/workspace");
        let task_cwd = Path::new("/workspace/pkg*");
        let sources = vec!["../shared/**".to_string()];
        let matcher = build_source_matcher(match_root, task_cwd, &sources);
        assert!(is_source(&matcher, Path::new("/workspace/shared/util.go")));
    }

    /// `[task_config.input_groups]` anchors a group entry by joining it onto
    /// the defining config's root without normalizing, so absolute patterns
    /// reach the matcher with `..` still in them.
    #[test]
    #[cfg(unix)]
    fn matcher_normalizes_absolute_pattern_with_parent_dirs() {
        let root = Path::new("/workspace");
        let sources = vec!["/workspace/lib/../shared/x".to_string()];
        let matcher = build_source_matcher(root, root, &sources);
        assert!(is_source(&matcher, Path::new("/workspace/shared/x")));
    }

    #[test]
    fn lexical_normalize_resolves_dot_segments() {
        assert_eq!(lexical_normalize(Path::new("../x")), PathBuf::from("../x"));
        assert_eq!(
            lexical_normalize(Path::new("a/b/../c")),
            PathBuf::from("a/c")
        );
        assert_eq!(lexical_normalize(Path::new("./a")), PathBuf::from("a"));
    }

    #[test]
    #[cfg(unix)]
    fn lexical_normalize_stops_climbing_at_the_root() {
        assert_eq!(lexical_normalize(Path::new("/a/../..")), PathBuf::from("/"));
    }

    #[test]
    fn relative_sources_match_when_task_dir_starts_with_dot() -> Result<()> {
        let temp = tempfile::tempdir()?;
        let workspace = temp.path();
        let task_cwd = normalize_task_cwd(workspace.join("./sub"));
        let source = workspace.join("sub/input.txt");
        fs::create_dir_all(source.parent().unwrap())?;
        fs::write(&source, "source")?;

        let sources = vec!["input.txt".to_string()];
        let matcher = build_source_matcher(workspace, &task_cwd, &sources);
        let metadatas = get_file_metadatas(&task_cwd, &sources, &matcher)?;

        assert_eq!(
            metadatas.into_iter().map(|(path, _)| path).collect_vec(),
            [source]
        );
        Ok(())
    }

    #[test]
    fn content_hash_cache_reuses_unchanged_files() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.txt");
        let b = tmp.path().join("b.txt");
        std::fs::write(&a, "hello").unwrap();
        std::fs::write(&b, "world").unwrap();
        let metadatas = vec![
            (a.clone(), a.metadata().unwrap()),
            (b.clone(), b.metadata().unwrap()),
        ];

        let mut cache = ContentHashCache::new();
        let first = file_contents_to_hash(&metadatas, &mut cache).unwrap();
        assert_eq!(cache.len(), 2);
        let a_hash_v1 = cache.get(&a).unwrap().hash.clone();

        // Re-run with same files: hashes should be reused, aggregate unchanged.
        let second = file_contents_to_hash(&metadatas, &mut cache).unwrap();
        assert_eq!(first, second);
        assert_eq!(cache.get(&a).unwrap().hash, a_hash_v1);

        // Mutate `a` so size differs; aggregate hash must change.
        std::fs::write(&a, "hello world").unwrap();
        let metadatas = vec![
            (a.clone(), a.metadata().unwrap()),
            (b.clone(), b.metadata().unwrap()),
        ];
        let third = file_contents_to_hash(&metadatas, &mut cache).unwrap();
        assert_ne!(second, third);
        assert_ne!(cache.get(&a).unwrap().hash, a_hash_v1);
    }

    #[test]
    fn content_hash_cache_prunes_dropped_files() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.txt");
        let b = tmp.path().join("b.txt");
        std::fs::write(&a, "hello").unwrap();
        std::fs::write(&b, "world").unwrap();

        let mut cache = ContentHashCache::new();
        let metadatas = vec![
            (a.clone(), a.metadata().unwrap()),
            (b.clone(), b.metadata().unwrap()),
        ];
        file_contents_to_hash(&metadatas, &mut cache).unwrap();
        assert_eq!(cache.len(), 2);

        // Only `a` is a source this run — `b` should drop out of the cache.
        let metadatas = vec![(a.clone(), a.metadata().unwrap())];
        file_contents_to_hash(&metadatas, &mut cache).unwrap();
        assert_eq!(cache.len(), 1);
        assert!(cache.contains_key(&a));
        assert!(!cache.contains_key(&b));
    }

    #[test]
    fn content_hash_cache_round_trips_through_disk() {
        let tmp = tempfile::tempdir().unwrap();
        let a = tmp.path().join("a.txt");
        std::fs::write(&a, "hello").unwrap();

        let mut cache = ContentHashCache::new();
        let metadatas = vec![(a.clone(), a.metadata().unwrap())];
        file_contents_to_hash(&metadatas, &mut cache).unwrap();

        let cache_path = tmp.path().join("cache.bin");
        save_content_hash_cache(&cache_path, &cache).unwrap();
        let loaded = load_content_hash_cache(&cache_path);
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded.get(&a).unwrap().hash, cache.get(&a).unwrap().hash,);

        // Corrupt the file: loader must silently fall back to empty.
        std::fs::write(&cache_path, b"not a valid msgpack stream").unwrap();
        let loaded = load_content_hash_cache(&cache_path);
        assert!(loaded.is_empty());
    }
}