git-xcrypt 0.1.1

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

mod harness;

use std::fs;

use harness::{MAGIC, OVERHEAD, TestRepo};
use tempfile::TempDir;

/// Text content with CRLF throughout, so normalisation is observable.
const CRLF: &[u8] = b"line one\r\nline two\r\n";

/// The same content after normalisation — what clean must store.
const LF: &[u8] = b"line one\nline two\n";

/// Content no rule can call text: a NUL, plus CRLF pairs so "left alone" means
/// something.
const BINARY: &[u8] = b"\x00\x90raw\r\nbytes\r\n\x00";

/// One declared path and everything the declaration promises about it.
struct Case {
    path: &'static str,
    /// What is written into the working tree.
    written: &'static [u8],
    /// The plaintext clean must encrypt.
    stored: &'static [u8],
    /// Whether the header records "this was normalised to LF".
    normalised: bool,
    /// What `git check-attr diff` must answer.
    diff: &'static str,
    /// What a checkout must put back, when the declaration pins it.
    checked_out: &'static [u8],
}

#[test]
fn every_declared_attribute_reaches_the_header_the_rendered_line_and_the_round_trip() {
    // `core.autocrlf=false` with `core.eol=lf` pins the two rows whose answer
    // would otherwise be the machine's to give (`text` and `text=auto` with no
    // `eol=`), so this test asserts the same bytes on all three platforms. The
    // configuration-driven half of the table is `tests/line_endings.rs`.
    let repo = TestRepo::init();
    repo.set_eol_config("false", "lf");
    repo.init_xcrypt();
    repo.write_xcrypt_config(
        "secrets/\n\
         secrets/always.txt   text\n\
         secrets/never.bin    -text\n\
         secrets/store.p12    binary\n\
         secrets/auto.txt     text=auto\n\
         secrets/unix.sh      text eol=lf\n\
         secrets/dos.ps1      text eol=crlf\n\
         !secrets/README.md\n",
    );
    repo.xcrypt_ok(["sync"]);

    let cases = [
        Case {
            // `text`: normalise whatever the content looks like.
            path: "secrets/always.txt",
            written: CRLF,
            stored: LF,
            normalised: true,
            diff: "git-xcrypt",
            checked_out: LF,
        },
        Case {
            // `-text`: never convert, in either direction.
            path: "secrets/never.bin",
            written: CRLF,
            stored: CRLF,
            normalised: false,
            diff: "git-xcrypt",
            checked_out: CRLF,
        },
        Case {
            // `binary`: `-text` plus "leave the diff driver off", the way git's
            // own `binary` macro means `-text -diff`.
            path: "secrets/store.p12",
            written: BINARY,
            stored: BINARY,
            normalised: false,
            diff: "unset",
            checked_out: BINARY,
        },
        Case {
            // `text=auto` on content that is text: the default, spelled out.
            path: "secrets/auto.txt",
            written: CRLF,
            stored: LF,
            normalised: true,
            diff: "git-xcrypt",
            checked_out: LF,
        },
        Case {
            // `text=auto` on content that is not: same declaration, opposite
            // verdict, decided by content alone.
            path: "secrets/keystore.env",
            written: BINARY,
            stored: BINARY,
            normalised: false,
            diff: "git-xcrypt",
            checked_out: BINARY,
        },
        Case {
            // `eol=lf`: the working tree gets LF whatever the machine says.
            path: "secrets/unix.sh",
            written: CRLF,
            stored: LF,
            normalised: true,
            diff: "git-xcrypt",
            checked_out: LF,
        },
        Case {
            // `eol=crlf`: and CRLF, likewise — this is the row a Unix machine
            // would otherwise never see, since it is the declaration rather
            // than the platform that decides.
            path: "secrets/dos.ps1",
            written: CRLF,
            stored: LF,
            normalised: true,
            diff: "git-xcrypt",
            checked_out: CRLF,
        },
    ];

    for case in &cases {
        repo.write_file(case.path, case.written);
    }
    // The negation: declared out of the encrypted set by the last matching
    // line, so it must stay readable — and git must be handed it back.
    repo.write_file("secrets/README.md", b"nothing secret here\n");
    repo.commit_all("one file per attribute");
    repo.assert_status_clean();

    for case in &cases {
        let path = case.path;

        // 1. The header.
        let blob = repo.blob_bytes(path);
        assert!(blob.starts_with(MAGIC), "{path}: the filter did not run");
        assert_eq!(
            blob.len(),
            OVERHEAD + case.stored.len(),
            "{path}: the encrypted plaintext is not what the declaration asks \
             clean to store"
        );
        assert_eq!(
            repo.blob_records_normalisation(path),
            case.normalised,
            "{path}: the header records the wrong verdict, so smudge will \
             convert a file it must not — or fail to convert one it must"
        );

        // 2. The rendered line, graded by git itself. `-text` is what keeps
        //    git's own CRLF conversion off the ciphertext; without it a 2 MB
        //    blob loses `CR` bytes and the file is unrecoverable at checkout.
        assert_eq!(
            repo.check_attr("filter", path),
            "git-xcrypt",
            "{path}: git would not run the filter for a declared path"
        );
        assert_eq!(
            repo.check_attr("text", path),
            "unset",
            "{path}: git may convert this ciphertext, which destroys it"
        );
        assert_eq!(
            repo.check_attr("diff", path),
            case.diff,
            "{path}: the rendered diff attribute is not what the declaration says"
        );

        // 3. The round trip.
        repo.recheckout(path);
        assert_eq!(
            repo.worktree_bytes(path),
            case.checked_out,
            "{path}: the checkout did not honour the declaration"
        );
    }

    // The negation, in all three places: readable in the object database, and
    // handed back to git's own defaults rather than carrying our attributes.
    let readable = repo.blob_bytes("secrets/README.md");
    assert!(
        !readable.starts_with(MAGIC),
        "a negated path was encrypted anyway"
    );
    assert_eq!(readable, b"nothing secret here\n");
    assert_eq!(
        repo.check_attr("text", "secrets/README.md"),
        "unspecified",
        "a file stored in the clear must be git's to manage, `-text` included"
    );
    assert_eq!(
        repo.check_attr("diff", "secrets/README.md"),
        "unspecified",
        "a decrypting diff driver has nothing to do on a plaintext file"
    );

    repo.assert_status_clean();
    repo.git_ok(["add", "-A"]);
    repo.assert_status_clean();
}

/// The paths a floating declaration selects, and what git must answer for each.
///
/// Every one of these is a path the *filter* encrypts, because `.gitignore`
/// floats a pattern that carries no slash of its own and `*.env` can name a
/// directory as readily as a file. The rendered section has to reach exactly
/// this far and no further: narrower leaves ciphertext without `-text`, which
/// was measured costing a 2 MB file at checkout; broader puts `-text` on files
/// stored in the clear.
const REACHED: &[&str] = &[
    "secrets/a.txt",
    "app/secrets/a.txt",
    "a/b/secrets/c/d.txt",
    "deep/one.env",
    "config.env/inner.txt",
];

/// And the path next door, which the same declaration must not touch.
const UNTOUCHED: &str = "notsecrets/a.txt";

#[test]
fn a_forgotten_sync_fails_the_gate_and_running_it_reaches_the_whole_subtree() {
    // The flow FR-003 is written about: a pattern is added, `sync` is forgotten,
    // and CI is the thing that says so. Then the section is regenerated and has
    // to reach every path the filter reaches — including the nested ones, which
    // are the half that no root-level declaration can tell apart. Measured in
    // S-02: a directory pattern rendered as `secrets/**` instead of
    // `**/secrets/**` looks right, agrees with every root-level check, and drops
    // `-text` from exactly the deep paths it was protecting.
    let repo = TestRepo::init();
    repo.init_xcrypt();
    repo.write_xcrypt_config("secrets/\n");
    repo.xcrypt_ok(["sync"]);

    let checked = repo.xcrypt(["sync", "--check"]);
    assert_eq!(
        checked.status.code(),
        Some(0),
        "a section that was just written must satisfy its own check:\n{}",
        String::from_utf8_lossy(&checked.stderr)
    );

    // --- A second pattern is declared, and `sync` is forgotten. -------------
    let before = repo.worktree_bytes(".gitattributes");
    repo.write_xcrypt_config("secrets/\n*.env\n");

    let stale = repo.xcrypt(["sync", "--check"]);
    assert_eq!(
        stale.status.code(),
        Some(2),
        "a stale section passed the gate, so CI would never notice:\n{}",
        String::from_utf8_lossy(&stale.stderr)
    );

    // …and `sync`'s own help has to name that number, provoked rather than
    // spelled out — the same rule `tests/odd_repositories.rs` applies to
    // `status`, and for the same reason: a flag's description is where a person
    // writing a CI job looks the code up, and it is the one part of a program
    // nothing checks. Measured on 2026-08-07, the day after the code became `2`:
    // `git-xcrypt sync --help` still said "Exits 0 when it is current and 1 when
    // it is not", while the binary's own `--help` epilogue said `2`. A job
    // written from the flag's documentation tests for `1` and never fires.
    let code = stale.status.code().expect("sync --check reports a code");
    let help = String::from_utf8(repo.xcrypt(["sync", "--help"]).stdout).expect("help is text");
    assert!(
        help.contains(&format!("`{code}`")),
        "`sync --check` exits {code} on a stale section and its own help never \
         mentions that number:\n{help}"
    );

    // `2`, not `1`, since 2026-08-06 — open decision 11. Code `1` carried five
    // answers at once, a mistyped flag among them, so a CI job could not tell
    // "the section is stale" from "you called me wrong" and the two need
    // opposite fixes. What settles which code it should be is the agreement
    // below: `status` answers the same thing about the same state, and until
    // this change it exited `0` here saying `VERDICT: no findings.`
    let seen = repo.xcrypt(["status"]);
    assert_eq!(
        seen.status.code(),
        Some(2),
        "`sync --check` calls this section stale and `status` does not — one \
         tool, one state, two verdicts, and a CI job gets whichever it ran:\n{}",
        String::from_utf8_lossy(&seen.stdout)
    );
    let said = String::from_utf8_lossy(&seen.stdout).into_owned();
    assert!(
        said.contains("no longer matches") && said.contains("sync"),
        "the gap has to name the file and the one command that settles it:\n{said}"
    );
    assert_eq!(
        repo.worktree_bytes(".gitattributes"),
        before,
        "`--check` wrote to the working tree, which is the one thing a check \
         must never do"
    );

    // The filter, meanwhile, is already encrypting under the new pattern:
    // selection is immediate and the section is what lags behind.
    repo.write_file("deep/one.env", b"api_key = deep\n");
    repo.commit_all("a secret under the undeclared-in-gitattributes pattern");
    assert!(
        repo.blob_is_encrypted("deep/one.env"),
        "the filter reads `.git-xcrypt` directly, so this must not wait for sync"
    );

    // --- `sync` closes it. ---------------------------------------------------
    repo.xcrypt_ok(["sync"]);
    assert_eq!(
        repo.xcrypt(["sync", "--check"]).status.code(),
        Some(0),
        "`sync` left a section its own check still calls stale"
    );

    // --- And git agrees, at every depth. ------------------------------------
    for path in REACHED {
        assert_eq!(
            repo.check_attr("filter", path),
            "git-xcrypt",
            "{path}: the filter encrypts this path, so git must run it here"
        );
        assert_eq!(
            repo.check_attr("text", path),
            "unset",
            "{path}: the filter encrypts this path and the rendered line does \
             not reach it, so git may convert its ciphertext and destroy it"
        );
    }
    assert_eq!(
        repo.check_attr("text", UNTOUCHED),
        "unspecified",
        "{UNTOUCHED}: the line reaches past what the filter encrypts, so a file \
         stored in the clear is carrying `-text`"
    );

    // The reach is not a claim about attributes alone: a nested secret has to
    // make the whole round trip.
    for path in REACHED {
        repo.write_file(path, b"api_key = nested\n");
    }
    repo.write_file(UNTOUCHED, b"nothing secret here\n");
    repo.commit_all("one secret per depth");
    repo.assert_status_clean();

    for path in REACHED {
        assert!(
            repo.blob_is_encrypted(path),
            "{path}: a declared path was stored in the clear"
        );
        repo.recheckout(path);
        repo.assert_worktree_eq(path, b"api_key = nested\n");
    }
    assert!(
        !repo.blob_is_encrypted(UNTOUCHED),
        "{UNTOUCHED}: an undeclared path was encrypted"
    );
    repo.assert_status_clean();
}

/// A section this build cannot compare is not a section it may call current.
///
/// Two shapes reach it, and the first is ordinary: a merge conflict on
/// `.gitattributes` resolved by keeping both sides leaves two managed sections,
/// and an interrupted hand-edit leaves an opening marker with no closing one.
/// `attributes::upsert` refuses both — git takes the **last** matching line, so
/// the copy nobody maintains is the one that decides — and every command that
/// writes the file says so: measured on git 2.55, `sync --check`, `sync`, `init`
/// and `unlock` all exit `2` over a doubled section, and `unlock` cannot open
/// such a clone at all.
///
/// `status` was the one command that said nothing. `stale_section_gap` compared
/// the file against each rendering, took a refusal as "does not match", then
/// asked for the reason with `.ok()?` — which threw the refusal away and
/// returned "no gap". Measured before this test: `VERDICT: no findings.`, exit
/// `0`, on the repository `unlock` had just refused to open. That is the one
/// answer `AGENTS.md` says this command may never give: "I could not tell" must
/// never be reported as "nothing is wrong."
///
/// **`undetermined`, not a setup gap**, and the distinction is not a technicality.
/// Two identical sections enforce exactly what one does — `git check-attr` gives
/// the same answers — so claiming git is not enforcing the declarations would be
/// an over-claim, and `Report::stores_in_the_clear` would then print "committing
/// a declared file stores it in the clear", which is false and is the sentence
/// the 2026-08-05 precedence change exists to prevent. What is provably true is
/// that this run could not compare the section, which is exit `6` and fails the
/// gate.
#[test]
fn a_section_that_cannot_be_compared_is_never_reported_as_current() {
    for (label, break_it) in [
        (
            "a merge that kept both sides",
            &(|section: &[u8]| [section, section].concat()) as &dyn Fn(&[u8]) -> Vec<u8>,
        ),
        (
            "an opening marker with no closing one",
            // By line rather than by `replace`, because the terminator is the
            // file's own: `line_ending_of` reproduces CRLF where the file
            // already uses it, so a substring ending in `\n` would match
            // nothing on a checkout that spells them `\r\n` — and the test
            // would pass having changed no byte. `str::lines` takes both.
            &|section: &[u8]| {
                let text = String::from_utf8(section.to_vec()).expect("the section is text");
                text.lines()
                    .filter(|line| line.trim_end() != "# <<< git-xcrypt <<<")
                    .fold(String::new(), |mut out, line| {
                        out.push_str(line);
                        out.push('\n');
                        out
                    })
                    .into_bytes()
            },
        ),
    ] {
        let repo = TestRepo::init();
        repo.init_xcrypt();
        repo.write_xcrypt_config("secrets/\n");
        repo.xcrypt_ok(["sync"]);
        repo.write_file("secrets/db.env", SECRET);
        repo.commit_all("a secret");

        // The baseline, so everything below is about the section and nothing
        // else. A run that started red would prove nothing.
        assert_eq!(
            repo.xcrypt(["status"]).status.code(),
            Some(0),
            "{label}: the repository was not clean before the section was broken"
        );

        let section = repo.worktree_bytes(".gitattributes");
        let broken = break_it(&section);
        // The premise, asserted rather than assumed. A shape built by editing
        // text is only a shape while the edit lands, and an edit that quietly
        // matched nothing would leave the rest of this run asserting that a
        // healthy repository is healthy — a test passing for the wrong reason
        // on whichever platform the premise does not hold.
        assert_ne!(
            broken, section,
            "{label}: the section came back unchanged, so this run asks nothing"
        );
        repo.write_file(".gitattributes", &broken);

        // The writing side's verdict, which is what `status` has to stop
        // contradicting. `2` is a state conflict, and the message names the
        // repair by hand.
        let checked = repo.xcrypt(["sync", "--check"]);
        assert_eq!(
            checked.status.code(),
            Some(2),
            "{label}: `sync --check` stopped calling this a state conflict, so \
             this test no longer asks anything"
        );

        let seen = repo.xcrypt(["status"]);
        let said = String::from_utf8_lossy(&seen.stdout).into_owned();
        assert_ne!(
            seen.status.code(),
            Some(0),
            "{label}: `status` passed the gate over a section it could not \
             compare, while every command that writes the file refuses over \
             it:\n{said}"
        );
        assert!(
            said.contains("undetermined"),
            "{label}: a check that could not run has to be said out loud, or \
             the report reads as a clean bill of health it did not earn:\n{said}"
        );
        assert!(
            said.contains("git-xcrypt"),
            "{label}: the reason has to name the section, or a reader has \
             nothing to act on:\n{said}"
        );
        // And it must not over-claim: git *is* running the filter here, so the
        // sentence that sends a user to rotate secrets must stay off the page.
        assert!(
            !said.contains("stores it in the clear"),
            "{label}: a section this build cannot read is not evidence that \
             anything was stored in the clear:\n{said}"
        );
    }
}

/// The filter says the section is stale, on the one path that can act on it.
///
/// `sync` has no automatic trigger, and the three candidates were measured
/// before this settled on a warning:
///
/// * a `pre-commit` hook is bypassed by `--no-verify`, switched off by a
///   checkbox in JetBrains, is not versioned and does not survive a clone — and
///   arrives after `git add` has already stored the content anyway;
/// * rewriting the section from here would take effect only from the *next*
///   command. Measured on git 2.55, 2026-08-06 with a stand-in filter that
///   rewrote `.gitattributes` while `git add` was running: the third file went
///   through the filter regardless, so git reads attributes **once per
///   operation**. It would also dirty a tracked file in the middle of a command
///   that was only asked to add one;
/// * a line on `stderr` costs 2.6 ms, once per git operation rather than once
///   per file, and leaves the decision where it belongs.
///
/// Gated on a path that genuinely becomes ciphertext, for the same reason the
/// conversion refusal is: a repository storing nothing encrypted is not hurt by
/// a stale section and must not pay to be told.
#[test]
fn the_filter_names_a_stale_section_without_refusing_over_it() {
    let repo = TestRepo::init();
    repo.init_xcrypt();
    repo.write_xcrypt_config("secrets/\n");
    repo.xcrypt_ok(["sync"]);
    repo.write_file("secrets/db.env", SECRET);
    repo.write_file("notes.txt", b"an ordinary file\n");
    repo.commit_all("a secret and an ordinary file");

    // Past git's racy-clean window, and this is not decoration: inside the same
    // second git re-runs the filter over files it has just committed to settle
    // an uncertain `stat`, so the "nothing encrypted here" case below would see
    // the secret filtered anyway and the assertion would be about git's
    // timekeeping rather than about the gate. Measured — inside the window it
    // warns, outside it does not.
    std::thread::sleep(std::time::Duration::from_millis(1100));
    repo.git_ok(["update-index", "--refresh"]);

    // Current section: nothing to say.
    repo.write_file("secrets/db.env", b"api_key = second\n");
    let quiet = repo.git(["add", "-A"]);
    assert!(
        quiet.status.success(),
        "a healthy repository was refused:\n{}",
        String::from_utf8_lossy(&quiet.stderr)
    );
    assert!(
        !String::from_utf8_lossy(&quiet.stderr).contains("no longer matches"),
        "a current section was called stale:\n{}",
        String::from_utf8_lossy(&quiet.stderr)
    );
    repo.commit_all("second");

    // The declaration moves and `sync` is forgotten.
    repo.write_xcrypt_config("secrets/\nvault/\n");
    repo.git_ok(["add", ".git-xcrypt"]);
    repo.git_ok(["commit", "-q", "-m", "declare more"]);
    std::thread::sleep(std::time::Duration::from_millis(1100));
    repo.git_ok(["update-index", "--refresh"]);

    // An ordinary file still says nothing: this repository is not storing
    // ciphertext in this operation, so the stale lines cost it nothing yet.
    repo.write_file("notes.txt", b"an ordinary file, edited\n");
    let unencrypted = repo.git(["add", "notes.txt"]);
    assert!(
        !String::from_utf8_lossy(&unencrypted.stderr).contains("no longer matches"),
        "an operation that encrypted nothing was charged for the answer:\n{}",
        String::from_utf8_lossy(&unencrypted.stderr)
    );

    // A path that becomes ciphertext does say something — and still succeeds,
    // which is the half that matters most: with `required = true` a refusal
    // here would stop every git operation over a section that loses nobody a
    // byte today.
    repo.write_file("secrets/db.env", b"api_key = third\n");
    let warned = repo.git(["add", "-A"]);
    let said = String::from_utf8_lossy(&warned.stderr).into_owned();
    assert!(
        warned.status.success(),
        "a stale section refused a `git add`, which it must never do:\n{said}"
    );
    assert_eq!(
        said.matches("no longer matches").count(),
        1,
        "the warning must be said once per operation, not once per file:\n{said}"
    );
    assert!(
        said.contains("git-xcrypt sync"),
        "the warning must name the command that settles it:\n{said}"
    );
    assert!(
        repo.blob_is_encrypted("secrets/db.env"),
        "the warning came instead of the encryption rather than beside it"
    );

    // And `sync` settles it.
    repo.xcrypt_ok(["sync"]);
    repo.commit_all("sync");
    std::thread::sleep(std::time::Duration::from_millis(1100));
    repo.git_ok(["update-index", "--refresh"]);
    repo.write_file("secrets/db.env", b"api_key = fourth\n");
    let settled = repo.git(["add", "-A"]);
    assert!(
        !String::from_utf8_lossy(&settled.stderr).contains("no longer matches"),
        "the warning survived the command that was supposed to settle it:\n{}",
        String::from_utf8_lossy(&settled.stderr)
    );
}

/// A secret worth spelling out, so a plaintext blob is recognisable on sight.
const SECRET: &[u8] = b"AWS_SECRET=hunter2\n";

/// Paths spelled in a case no line of `.git-xcrypt` uses, and what selects them.
///
/// One spelling per directory, deliberately: on APFS and on NTFS `mkdir secrets`
/// and `mkdir Secrets` make **one** directory, so a fixture holding two spellings
/// of the same name cannot exist on two of the three platforms. One file whose
/// spelling differs from the pattern's is enough, and it is portable.
const OTHER_SPELLINGS: &[&str] = &[
    // The directory pattern `secrets/`, reached through a directory whose name
    // is spelled differently. `.txt` rather than `.env` so nothing but the
    // directory pattern can select it.
    "SEcrets/db.txt",
    // The floating pattern `*.env`, reached through the extension.
    "top.ENV",
    // …and at depth, so the `**/` the renderer adds is exercised too.
    "app/nested/Deploy.Env",
];

#[test]
fn a_case_spelled_attributes_file_is_read_exactly_where_git_reads_it() {
    // On APFS and NTFS a file *stored* as `.GITATTRIBUTES` is the attributes
    // file to git — it opens `<dir>/.gitattributes` by name and the filesystem
    // resolves the case — measured on git 2.55. The resolver used to compare
    // directory-listing entries against the exact name, so a `text` line in
    // such a file converted the ciphertext with no gate firing anywhere.
    //
    // Asserted as *parity* rather than as either absolute, so the test runs on
    // all three platforms: wherever git honours the file, the refusal must
    // fire; wherever git does not (ext4), nothing converts and nothing may
    // refuse.
    let repo = TestRepo::init();
    repo.init_xcrypt();
    repo.write_xcrypt_config("secrets/\n");
    repo.xcrypt_ok(["sync"]);

    repo.write_file("secrets/.GITATTRIBUTES", b"* text\n");
    let honoured = repo.check_attr("text", "secrets/db.env") == "set";

    repo.write_file("secrets/store.p12", &two_megabytes());
    let add = repo.git(["add", "secrets/store.p12"]);
    assert_eq!(
        add.status.success(),
        !honoured,
        "git {} the case-spelled attributes file, and the gate read the stack \
         differently:\n{}",
        if honoured { "honours" } else { "ignores" },
        String::from_utf8_lossy(&add.stderr)
    );
}

#[test]
fn a_pattern_reaches_every_ascii_spelling_of_a_name_and_the_rendered_line_keeps_up() {
    // Open decision 13, settled on 2026-08-05: pattern matching folds ASCII case,
    // unconditionally. The measured failure it closes: `.git-xcrypt` declares
    // `secrets/`, the user creates `Secrets/db.env`, and on APFS and NTFS those
    // are *one* directory — `cd secrets` enters `Secrets`, `ls` shows a single
    // entry, and there is no way to see the mistake. The filter left the file
    // alone, `git add` exited 0 and `AWS_SECRET=hunter2` went into the object
    // database in the clear.
    //
    // Both axes are asserted for every spelling, because closing one alone opens
    // the other. Selection folding without the rendering folding means the filter
    // encrypts a path the managed `-text` does not reach — measured elsewhere in
    // this file as 34 `CR` bytes eaten out of a ciphertext and the file
    // unrecoverable at checkout.
    //
    // **Since 2026-08-06 the rendered half is `sync --ignorecase`, not the
    // default.** Owner's call, with the cost measured and accepted: in practice
    // a project spells its paths one way, so the folded line buys coverage for a
    // mistake that in most repositories never happens, at the price of a section
    // no human can read. Selection still folds unconditionally — that half is
    // what keeps a plaintext secret out of the object database, and it is not
    // negotiable. The default rendering is checked at the bottom of this test,
    // where the same paths are asked again without the flag.
    let repo = TestRepo::init();
    repo.init_xcrypt();
    repo.write_xcrypt_config(
        "secrets/\n\
         *.env\n\
         !secrets/README.md\n\
         \u{142}\u{105}ka/\n",
    );
    repo.xcrypt_ok(["sync", "--ignorecase"]);

    for path in OTHER_SPELLINGS {
        repo.write_file(path, SECRET);
    }
    // The negation, spelled differently too: a hole punched in a declaration has
    // to stay a hole whichever way the file is spelled, or the file the user
    // deliberately kept readable becomes unreadable instead.
    repo.write_file("SEcrets/README.MD", b"nothing secret here\n");
    // The name next door, which no pattern reaches in any spelling.
    repo.write_file("notsecrets/a.txt", b"nothing secret here\n");
    // The documented boundary: folding is ASCII, exactly as far as git folds.
    // Measured on git 2.55 with `core.ignorecase=true` — `łąka/**` matches
    // neither `ŁĄKA/a.env` nor `Łąka/a.env`. It cannot be pushed further from
    // here either: `.gitattributes` matches bytes, so `[łŁ]` is a set of four
    // bytes rather than two characters and matches no spelling at all. This row
    // pins the boundary so nobody closes it by accident on one side only.
    repo.write_file(
        "\u{141}\u{104}KA/a.env.txt",
        b"outside the ASCII boundary\n",
    );
    repo.commit_all("one file per spelling");
    repo.assert_status_clean();

    for path in OTHER_SPELLINGS {
        assert!(
            repo.blob_is_encrypted(path),
            "{path}: a declared path spelled in another case was stored in the \
             clear, which is the whole failure open decision 13 closed"
        );
        assert!(
            !repo.object_exists_for(SECRET),
            "{path}: the plaintext of a declared secret reached the object database"
        );
    }
    assert!(
        !repo.blob_is_encrypted("SEcrets/README.MD"),
        "a negation stopped applying because the file is spelled differently"
    );
    assert!(
        !repo.blob_is_encrypted("notsecrets/a.txt"),
        "the folded pattern reached past what it declares"
    );
    assert!(
        !repo.blob_is_encrypted("\u{141}\u{104}KA/a.env.txt"),
        "folding reached beyond ASCII, which git does not do and \
         `.gitattributes` cannot express"
    );

    // The second axis. `core.ignorecase=false` first, and that is what makes this
    // half mean anything: with it true git folds the managed section's patterns
    // itself, so a renderer that emits nothing of the sort still answers `unset`
    // and the assertion proves nothing. False leaves the rendered spelling as the
    // only thing that can reach these paths — measured on git 2.55, a plain
    // `**/secrets/**` answers `unspecified` for `SEcrets/db.txt` there.
    //
    // Then true, because the rendered line must not depend on a setting that is
    // not versioned and that git decides for itself by probing the filesystem.
    for ignore_case in ["false", "true"] {
        repo.set_config("core.ignorecase", ignore_case);

        for path in OTHER_SPELLINGS {
            assert_eq!(
                repo.check_attr("filter", path),
                "git-xcrypt",
                "{path}: with core.ignorecase={ignore_case} git would not run the \
                 filter for a path the filter encrypts"
            );
            assert_eq!(
                repo.check_attr("text", path),
                "unset",
                "{path}: with core.ignorecase={ignore_case} the rendered line does \
                 not reach a path the filter encrypts, so git may convert its \
                 ciphertext and destroy it"
            );
            assert_eq!(
                repo.check_attr("diff", path),
                "git-xcrypt",
                "{path}: with core.ignorecase={ignore_case} `git diff` would show \
                 ciphertext for a path the filter encrypts"
            );
        }

        assert_eq!(
            repo.check_attr("text", "SEcrets/README.MD"),
            "unspecified",
            "with core.ignorecase={ignore_case} a file stored in the clear by a \
             negation is carrying `-text`"
        );
        assert_eq!(
            repo.check_attr("text", "notsecrets/a.txt"),
            "unspecified",
            "with core.ignorecase={ignore_case} the rendered line reaches past \
             what the filter encrypts"
        );
        assert_eq!(
            repo.check_attr("text", "\u{141}\u{104}KA/a.env.txt"),
            "unspecified",
            "with core.ignorecase={ignore_case} the rendered line folds beyond \
             ASCII while the filter does not, so a file stored in the clear is \
             carrying `-text`"
        );
    }
    repo.set_config("core.ignorecase", "false");

    // And the round trip, because an encrypted path is only encrypted if it comes
    // back byte for byte.
    for path in OTHER_SPELLINGS {
        repo.recheckout(path);
        repo.assert_worktree_eq(path, SECRET);
    }
    repo.assert_status_clean();
}

/// The default section, which is one line and needs no `sync` at all.
///
/// Settled 2026-08-06. `init` writes `* -text diff=git-xcrypt` beside the
/// catch-all, and that is the whole managed section: it says nothing about the
/// declaration, so no change to `.git-xcrypt` can make it wrong and `sync`
/// stops being something to remember. Which paths are encrypted still takes
/// effect at once, because the filter reads the declaration itself.
///
/// Both halves of the trade are asserted here, because the cost is real and
/// belongs next to the benefit. `-text` and the diff driver land on **every**
/// file, declared or not — so git stops normalising line endings anywhere, and
/// `git diff` spawns the driver per blob. Measured on git 2.55: a 1000-file
/// diff takes 8461 ms against 23 ms with the driver unregistered, while a
/// five-file diff takes 72 ms against 21 ms. Running `sync` at all replaces
/// this with a line per pattern, which is what the scenarios above cover.
#[test]
fn the_default_section_is_one_line_and_needs_no_sync() {
    let repo = TestRepo::init();
    repo.init_xcrypt();
    // No `sync` anywhere in this test, deliberately.
    repo.write_xcrypt_config("*.env\n");

    let section = String::from_utf8(repo.worktree_bytes(".gitattributes")).expect("text");
    assert!(
        section.contains("* filter=git-xcrypt") && section.contains("* -text diff=git-xcrypt"),
        "the default section is not the two global lines:\n{section}"
    );
    assert!(
        !section.contains("*.env"),
        "the default section names a declared pattern, so it can go stale:\n{section}"
    );

    // `core.ignorecase=false` so the rendered spelling is the only thing that
    // can reach these paths — the point being that `*` reaches all of them.
    repo.set_config("core.ignorecase", "false");
    repo.write_file("db.env", SECRET);
    repo.write_file("TOP.ENV", SECRET);
    repo.write_file("notes.txt", b"an ordinary file\n");
    repo.commit_all("a declared path, another spelling of it, and neither");

    for path in ["db.env", "TOP.ENV"] {
        assert!(
            repo.blob_is_encrypted(path),
            "{path}: a declared path was stored in the clear"
        );
        assert_eq!(
            repo.check_attr("text", path),
            "unset",
            "{path}: the ciphertext is not protected from git's CRLF conversion"
        );
        assert_eq!(
            repo.check_attr("diff", path),
            "git-xcrypt",
            "{path}: `git diff` would show ciphertext"
        );
    }
    assert!(
        !repo.object_exists_for(SECRET),
        "the plaintext of a declared secret reached the object database"
    );

    // The cost, asserted rather than described: an undeclared file gets the
    // same two attributes. Whoever narrows this later has to change this line
    // and will read why.
    assert!(
        !repo.blob_is_encrypted("notes.txt"),
        "an undeclared file was encrypted"
    );
    assert_eq!(
        repo.check_attr("text", "notes.txt"),
        "unset",
        "git still normalises an undeclared file, so this test no longer \
         describes what the global section costs"
    );
    assert_eq!(
        repo.check_attr("diff", "notes.txt"),
        "git-xcrypt",
        "the diff driver stopped covering undeclared files, so the measured \
         cost above no longer applies"
    );

    // And it round-trips, which is what separates "broader" from "broken".
    repo.recheckout("db.env");
    repo.recheckout("TOP.ENV");
    repo.assert_worktree_eq("db.env", SECRET);
    repo.assert_worktree_eq("TOP.ENV", SECRET);
    repo.assert_worktree_eq("notes.txt", b"an ordinary file\n");
    repo.assert_status_clean();
}

/// 2 MB whose bytes cover the whole range.
///
/// The plaintext shape barely matters — what git would convert is the
/// *ciphertext*, which is pseudorandom and so carries a `CRLF` pair every 64 KiB
/// or so. The size is what makes the damage certain rather than probable.
fn two_megabytes() -> Vec<u8> {
    (0..2 * 1024 * 1024u32)
        .map(|index| u8::try_from(index % 251).expect("a byte"))
        .collect()
}

/// The attribute shapes that make git convert a ciphertext, and nothing else —
/// paired with what `git check-attr text` answers for each, so the fixture can
/// prove it still reproduces the shape it exists to catch.
///
/// All measured on git 2.55 by the only test that settles it — a byte-for-byte
/// round trip through `git add`, `git commit`, `rm` and `git checkout`:
///
/// * `secrets/** text` — `git check-attr text` answers `set`, 32 `CR` bytes are
///   eaten out of the ciphertext and the file is gone at checkout;
/// * `secrets/** !text` with `secrets/** eol=lf` — the one nobody expects, and
///   it is git's own rule, not an accident: an `eol` attribute promotes an
///   undefined `crlf_action` straight to `CRLF_TEXT_INPUT`, and only the
///   `CRLF_AUTO*` actions consult binary detection. Measured the same way, 39
///   bytes short and the file gone;
/// * `secrets/** text=input` — the one value besides `auto` that
///   `git_path_check_crlf` recognises, and it converts without binary
///   detection. It used to be read as `text=auto` and pass the gate;
/// * `secrets/** !text` with `secrets/** crlf` — the pre-1.7.2 spelling, which
///   git still honours whenever `text` says nothing. A bare `crlf` below a
///   *current* managed section is neutralised by the managed `-text` (the
///   `text` axis wins), so the dangerous shape needs `text` silenced first —
///   the same structure as the bare-`eol=` row. It used to not be resolved at
///   all.
///
/// `-text`, `binary`, `text=auto`, `text=<junk>`, `-crlf` and `crlf=auto` are
/// exempt, at every `core.autocrlf` value.
const DANGEROUS: [(&[u8], &str); 4] = [
    (b"secrets/** text\n", "set"),
    (b"secrets/** !text\nsecrets/** eol=lf\n", "unspecified"),
    (b"secrets/** text=input\n", "input"),
    (b"secrets/** !text\nsecrets/** crlf\n", "unspecified"),
];

#[test]
fn a_foreign_text_line_below_the_managed_section_is_refused_before_the_file_is_lost() {
    // The managed section is *current* here: `sync` has run and the `-text`
    // line is exactly right. One line below it puts `text` back on, and git
    // takes the last match.
    //
    // Measured on git 2.55: `git check-attr text` answers `set`, git runs its
    // own CRLF conversion over the ciphertext, `CR` bytes are eaten out of the
    // blob, `git add` and `git commit` both exit 0, and the checkout fails the
    // authentication tag and leaves no file at all. Nobody can decrypt what was
    // committed, ever.
    //
    // **Since 2026-08-05 the filter refuses instead.** Git's order leaves room
    // for exactly that: clean runs *before* git converts, so at the moment the
    // filter is asked, nothing is damaged yet and a `status=error` costs a
    // refused `git add` rather than a file. `status` reporting it afterwards was
    // never enough on its own — it only resolves paths the index already knows,
    // so on a *new* file the first warning arrives when the file is already
    // gone.
    for (foreign, expected_text) in DANGEROUS {
        let secret = two_megabytes();

        let repo = TestRepo::init();
        repo.init_xcrypt();
        repo.write_xcrypt_config("secrets/\n");
        repo.xcrypt_ok(["sync"]);

        // Committed while the configuration is still healthy, so there is an
        // intact blob to prove nothing damaged it later — and so the index knows
        // the path, which is what `status` needs to have anything to resolve.
        repo.write_file("secrets/store.p12", &secret);
        repo.commit_all("a secret, while the attributes are still right");
        assert_eq!(
            repo.blob_bytes("secrets/store.p12").len(),
            OVERHEAD + secret.len(),
            "the fixture did not store an intact ciphertext to begin with"
        );

        let mut attributes = repo.worktree_bytes(".gitattributes");
        attributes.extend_from_slice(foreign);
        repo.write_file(".gitattributes", &attributes);

        // The premise really is the failure mode, not a story about one.
        assert_eq!(
            repo.check_attr("text", "secrets/store.p12"),
            expected_text,
            "the fixture no longer reproduces the shape it exists to catch"
        );

        // Touching the file is what puts it back through the filter: git's
        // cached `stat` skips a file it considers unchanged, so the damage can
        // only happen on a path that is cleaned again.
        let mut modified = secret.clone();
        modified.extend_from_slice(b"one more line\r\n");
        repo.write_file("secrets/store.p12", &modified);

        let add = repo.git(["add", "-A"]);
        let complaint = String::from_utf8_lossy(&add.stderr).into_owned();
        assert!(
            !add.status.success(),
            "`git add` stored a ciphertext git is about to convert, and exited \
             {:?}:\n{complaint}",
            add.status.code()
        );
        assert!(
            complaint.contains("secrets/store.p12"),
            "the refusal must name the path it is about:\n{complaint}"
        );
        assert!(
            complaint.contains(".gitattributes:"),
            "the refusal must name the file and line that outrank the managed \
             section, or nobody can find it:\n{complaint}"
        );
        assert!(
            complaint.contains("-text"),
            "the refusal must name the attribute that prevents it:\n{complaint}"
        );

        // Nothing was stored, so nothing is lost: the intact blob is still what
        // `HEAD` holds, and it still checks out byte for byte.
        assert_eq!(
            repo.blob_bytes("secrets/store.p12").len(),
            OVERHEAD + secret.len(),
            "the committed ciphertext was damaged after all"
        );
        std::fs::remove_file(repo.path().join("secrets/store.p12")).expect("could not remove");
        repo.git_ok(["checkout", "--", "secrets/store.p12"]);
        assert_eq!(
            repo.worktree_bytes("secrets/store.p12"),
            secret,
            "the file did not survive the round trip the refusal exists to protect"
        );

        // And `status` still says so, with the exit code a CI gate reads — the
        // refusal stops the damage, it does not repair the configuration.
        let output = repo.xcrypt(["status"]);
        let text = String::from_utf8_lossy(&output.stdout).into_owned();

        // Code `2`, not `5`: since 2026-08-05 a setup gap is a configuration
        // finding, and the remedy here is an attribute line, not a rotated
        // secret. Nothing was stored in the clear over this — what it costs is
        // the ciphertext — so the exit code and the wording have to agree.
        assert_eq!(
            output.status.code(),
            Some(CONFIG_ERROR),
            "a repository whose ciphertext git converts must fail the gate as a \
             configuration problem:\n{text}"
        );
        assert!(
            text.contains("secrets/store.p12"),
            "the report must name the path whose ciphertext git converts:\n{text}"
        );
        assert!(
            text.contains("-text"),
            "the report must name the attribute that prevents it:\n{text}"
        );
    }
}

/// Stages `contents` as the index copy of `.gitattributes`, bypassing filters.
///
/// `git update-index --cacheinfo` neither runs the clean filter nor re-examines
/// any other index entry, so the staged copy lands deterministically — a plain
/// `git add .gitattributes` can re-clean a racy-clean secret in the same
/// operation and trip the refusal this fixture exists to place, at a moment the
/// test does not control.
fn stage_attributes_copy(repo: &TestRepo, contents: &[u8]) {
    let hashed = repo.git_with_stdin(["hash-object", "-w", "-t", "blob", "--stdin"], contents);
    assert!(
        hashed.status.success(),
        "git hash-object failed: {}",
        String::from_utf8_lossy(&hashed.stderr)
    );
    let id = String::from_utf8(hashed.stdout)
        .expect("git prints a hash")
        .trim()
        .to_string();
    repo.git_ok([
        "update-index",
        "--add",
        "--cacheinfo",
        &format!("100644,{id},.gitattributes"),
    ]);
}

/// What `git check-attr --cached` answers — the index copy alone.
fn check_attr_cached(repo: &TestRepo, attribute: &str, path: &str) -> String {
    let output = repo.git(["check-attr", "--cached", attribute, "--", path]);
    String::from_utf8(output.stdout)
        .expect("check-attr prints text")
        .rsplit(": ")
        .next()
        .expect("check-attr always prints a value")
        .trim()
        .to_string()
}

#[test]
fn a_dangerous_line_kept_only_in_the_index_still_refuses_after_the_file_is_deleted() {
    // Git's check-in attribute stack reads the working-tree `.gitattributes`
    // first and, when the file is gone, falls back to the **index** copy —
    // measured on git 2.55: with `secrets/** text` staged and the file deleted,
    // `git add` converted the filter's output (7003 `CR` bytes eaten out of a
    // 512 KiB ciphertext), exited 0, and the checkout later fails the
    // authentication tag and leaves no file. The refusal used to read only the
    // working tree, so deleting the file — the very move its own message can
    // prompt, when it says to delete the offending *line* — silenced the gate
    // at the exact moment git kept converting.
    let (repo, secret, blob) = repository_with_one_intact_secret();

    let mut dangerous = repo.worktree_bytes(".gitattributes");
    dangerous.extend_from_slice(b"secrets/** text\n");
    stage_attributes_copy(&repo, &dangerous);
    fs::remove_file(repo.path().join(".gitattributes")).expect("could not remove the file");

    // The premise: the copy git falls back to really does carry the line.
    assert_eq!(
        check_attr_cached(&repo, "text", "secrets/store.p12"),
        "set",
        "the fixture no longer stages the shape it exists to catch"
    );

    let mut modified = secret.clone();
    modified.extend_from_slice(b"one more line\r\n");
    repo.write_file("secrets/store.p12", &modified);

    let add = repo.git(["add", "secrets/store.p12"]);
    let complaint = String::from_utf8_lossy(&add.stderr).into_owned();
    assert!(
        !add.status.success(),
        "`git add` stored a ciphertext git converts via the index copy of a \
         deleted `.gitattributes`, and exited {:?}:\n{complaint}",
        add.status.code()
    );
    assert!(
        complaint.contains(".gitattributes:") && complaint.contains("secrets/** text"),
        "the refusal must name the staged line even though the file is gone \
         from the working tree:\n{complaint}"
    );

    // Nothing was stored, so nothing is lost.
    assert_eq!(
        repo.blob_bytes("secrets/store.p12"),
        blob,
        "the committed ciphertext was damaged after all"
    );
}

#[test]
fn a_deleted_or_outranked_index_copy_never_provokes_a_refusal() {
    // The other half, at the usual weight: with `required = true` a refusal one
    // shape too wide blocks every git operation in the repository.

    // 1. The file deleted while the index copy is *healthy*: git falls back to
    //    a copy whose managed `-text` covers the path, so nothing converts and
    //    nothing may refuse.
    {
        let (repo, secret, _blob) = repository_with_one_intact_secret();
        fs::remove_file(repo.path().join(".gitattributes")).expect("could not remove the file");

        let mut modified = secret.clone();
        modified.extend_from_slice(b"one more line\r\n");
        repo.write_file("secrets/store.p12", &modified);
        let add = repo.git(["add", "secrets/store.p12"]);
        assert!(
            add.status.success(),
            "a healthy index copy provoked a refusal:\n{}",
            String::from_utf8_lossy(&add.stderr)
        );
        // The *staged* blob — nothing here commits, so `HEAD` still holds the
        // old one.
        let staged = repo.git_ok(["cat-file", "blob", ":secrets/store.p12"]);
        assert_eq!(
            staged.stdout.len(),
            OVERHEAD + modified.len(),
            "the ciphertext was converted after all, so the fallback did not \
             reproduce what git reads"
        );
    }

    // 2. A dangerous line staged but *removed from the working-tree file*: on
    //    the check-in side the file outranks the index copy — measured on git
    //    2.55, `git check-attr text` answers `unset` in this state — so the
    //    staged copy must stay out of the stack entirely.
    {
        let (repo, secret, _blob) = repository_with_one_intact_secret();
        let mut dangerous = repo.worktree_bytes(".gitattributes");
        dangerous.extend_from_slice(b"secrets/** text\n");
        stage_attributes_copy(&repo, &dangerous);

        // The premises, one per source: the staged copy carries the line, the
        // working tree does not, and git's check-in answer follows the file.
        assert_eq!(
            check_attr_cached(&repo, "text", "secrets/store.p12"),
            "set",
            "the fixture no longer stages the shape whose precedence it checks"
        );
        assert_eq!(
            repo.check_attr("text", "secrets/store.p12"),
            "unset",
            "git no longer lets the working-tree file outrank the index copy, \
             so this fixture proves the wrong thing"
        );

        let mut modified = secret.clone();
        modified.extend_from_slice(b"one more line\r\n");
        repo.write_file("secrets/store.p12", &modified);
        let add = repo.git(["add", "secrets/store.p12"]);
        assert!(
            add.status.success(),
            "the staged copy outranked the working-tree file in the refusal, \
             which git does not let it do on check-in:\n{}",
            String::from_utf8_lossy(&add.stderr)
        );
    }
}

/// Where a global attributes file can live, and how git is told about it.
///
/// Both are resolved by git and neither is a path we can read verbatim: the
/// first is a default nothing in the configuration mentions, the second needs
/// `~` expanded. Measured on git 2.55 — the third row, an absolute path, always
/// worked and is here so a regression in the other two cannot hide behind it.
const GLOBAL_SOURCES: [&str; 3] = ["xdg-default", "tilde", "absolute"];

#[test]
fn a_text_line_in_the_users_global_attributes_file_is_refused_like_any_other() {
    // The same rule as the test above, from the one source that used to be
    // invisible. `core.attributesFile` was read verbatim, so `~/attrs` looked
    // for a directory literally named `~`, and with the key unset the XDG
    // default was not consulted at all — while git reads both.
    //
    // Measured on git 2.55, 2026-08-05, 2 MB, the line in
    // `~/.config/git/attributes` while the identical line in the tree was
    // already refused: `git add` exited **0**, 27 `CR` bytes were eaten out of
    // the blob, `git commit` exited 0, and the checkout left **no file at all**.
    // `status` said `VERDICT: no findings.` over it. Both halves of the tool
    // that exist to catch this resolve the stack correctly; neither was being
    // handed this file.
    //
    // The declaration is deliberately one `sync` behind, because that is the
    // only state where a global line can win: it sits *below* the tree in git's
    // precedence, so a current managed section's `-text` covers the path and
    // nothing outside can reach it. Forgetting `sync` is what opens the door —
    // and a global `*.sh text eol=lf` is an ordinary thing to have.
    for source in GLOBAL_SOURCES {
        let home = TempDir::new().expect("could not create a home directory");
        let secret = two_megabytes();

        let repo = TestRepo::init().with_home(home.path());
        repo.init_xcrypt();
        repo.write_xcrypt_config("secrets/\n");
        repo.xcrypt_ok(["sync"]);

        // Declared after the last `sync`, so the managed section says nothing
        // about this subtree and the global file is free to.
        repo.write_xcrypt_config("secrets/\nvault/\n");
        repo.write_file("vault/deploy.sh", &secret);
        repo.commit_all("a secret, while nothing yet converts it");
        assert_eq!(
            repo.blob_bytes("vault/deploy.sh").len(),
            OVERHEAD + secret.len(),
            "the fixture did not store an intact ciphertext to begin with"
        );

        let line = b"vault/** text\n";
        // Kept, because the refusal has to name *this* file: a message that
        // merely says one exists leaves the user with nothing to act on.
        let global = match source {
            "xdg-default" => {
                let dir = home.path().join(".config").join("git");
                fs::create_dir_all(&dir).expect("could not create the XDG directory");
                dir.join("attributes")
            }
            "tilde" => {
                repo.git_ok(["config", "--global", "core.attributesFile", "~/attrs"]);
                home.path().join("attrs")
            }
            _ => {
                let path = home.path().join("attrs");
                repo.git_ok([
                    "config",
                    "--global",
                    "core.attributesFile",
                    &path.to_string_lossy(),
                ]);
                path
            }
        };
        fs::write(&global, line).expect("could not write the global attributes file");

        // The premise is the failure mode itself: if git does not resolve `text`
        // to `set` here, this loop is proving nothing about anything.
        assert_eq!(
            repo.check_attr("text", "vault/deploy.sh"),
            "set",
            "[{source}] the fixture no longer reproduces the shape it exists to catch"
        );

        // Git's cached `stat` skips a file it considers unchanged, so only a
        // path that is cleaned again can reach the filter at all.
        let mut modified = secret.clone();
        modified.extend_from_slice(b"one more line\r\n");
        repo.write_file("vault/deploy.sh", &modified);

        let add = repo.git(["add", "-A"]);
        assert!(
            !add.status.success(),
            "[{source}] `git add` stored a ciphertext git is about to convert, \
             and exited {:?}:\n{}",
            add.status.code(),
            String::from_utf8_lossy(&add.stderr)
        );

        // Naming the winning line is the whole remedy: no command of this tool
        // edits a file the user wrote, so the report has to say which one.
        let complaint = String::from_utf8_lossy(&add.stderr).into_owned();
        let named = global.file_name().expect("the global file has a name");
        assert!(
            complaint.contains(&named.to_string_lossy().into_owned()),
            "[{source}] the refusal does not name the file that caused it \
             ({}):\n{complaint}",
            global.display()
        );
        assert!(
            complaint.contains("vault/** text"),
            "[{source}] the refusal does not quote the winning line:\n{complaint}"
        );

        // And the gate agrees, over a path the index already knows.
        let status = repo.xcrypt(["status"]);
        let text = String::from_utf8_lossy(&status.stdout).into_owned();
        assert_eq!(
            status.status.code(),
            Some(CONFIG_ERROR),
            "[{source}] the gate passed a repository whose ciphertext git \
             converts:\n{text}"
        );
        assert!(
            text.contains("vault/deploy.sh"),
            "[{source}] the report must name the path git converts:\n{text}"
        );
    }
}

#[test]
fn a_linked_worktrees_own_config_is_the_one_that_counts() {
    // `config.worktree` is per-checkout: git reads it from `$GIT_DIR`, which for
    // a linked worktree is `…/.git/worktrees/<name>`, not from the common
    // directory. This build read both files from the common directory, so a
    // linked worktree was resolved against the *main* checkout's per-worktree
    // configuration — nobody's configuration.
    //
    // Measured on git 2.55, 2026-08-05, 2 MB: with the linked worktree's
    // `config.worktree` pointing `core.attributesFile` at a file declaring
    // `vault/** text`, `git check-attr text` answered `set` there and
    // `unspecified` in the main checkout. `git add` exited **0**, 40 bytes were
    // eaten out of the blob, and the checkout left no file at all.
    let home = TempDir::new().expect("could not create a home directory");
    let repo = TestRepo::init().with_home(home.path());
    repo.init_xcrypt();
    repo.write_xcrypt_config("secrets/\n");
    repo.xcrypt_ok(["sync"]);
    // Declared after the last `sync`, the only state in which a source below the
    // tree can win — see the global-file scenario above.
    repo.write_xcrypt_config("secrets/\nvault/\n");

    let secret = two_megabytes();
    repo.write_file("vault/deploy.sh", &secret);
    repo.commit_all("a secret, while nothing yet converts it");

    let side = repo.add_worktree("side");
    let attributes = home.path().join("side-attrs");
    fs::write(&attributes, b"vault/** text\n").expect("could not write the attributes file");
    side.git_ok(["config", "extensions.worktreeConfig", "true"]);
    side.git_ok([
        "config",
        "--worktree",
        "core.attributesFile",
        &attributes.to_string_lossy(),
    ]);

    // The premise: git disagrees between the two checkouts, which is the whole
    // point of a per-worktree setting.
    assert_eq!(
        side.check_attr("text", "vault/deploy.sh"),
        "set",
        "the fixture no longer reproduces the shape it exists to catch"
    );
    assert_eq!(
        repo.check_attr("text", "vault/deploy.sh"),
        "unspecified",
        "the per-worktree setting leaked into the main checkout, so this proves \
         nothing about which file was read"
    );

    let mut modified = secret.clone();
    modified.extend_from_slice(b"one more line\r\n");
    side.write_file("vault/deploy.sh", &modified);
    let added = side.git(["add", "-A"]);
    assert!(
        !added.status.success(),
        "`git add` in the linked worktree stored a ciphertext git is about to \
         convert, and exited {:?}:\n{}",
        added.status.code(),
        String::from_utf8_lossy(&added.stderr)
    );

    // And the main checkout, which that line does not reach, keeps working —
    // a refusal that spread to every checkout would be its own outage.
    repo.write_file("vault/deploy.sh", &modified);
    let untouched = repo.git(["add", "-A"]);
    assert!(
        untouched.status.success(),
        "the main checkout was refused over a setting that belongs to another \
         one:\n{}",
        String::from_utf8_lossy(&untouched.stderr)
    );
}

#[test]
fn a_global_attributes_file_that_is_harmless_never_provokes_a_refusal() {
    // The other half, and it carries more weight here than usual. A global
    // attributes file is shared by every repository on the machine, so a
    // predicate one shape too wide does not break one project — it breaks all
    // of them at once, and with `required = true` it breaks *every* git
    // operation in each. `* text=auto` is what people actually have in that
    // file.
    let home = TempDir::new().expect("could not create a home directory");
    let dir = home.path().join(".config").join("git");
    fs::create_dir_all(&dir).expect("could not create the XDG directory");
    fs::write(dir.join("attributes"), b"* text=auto\n*.md text\n")
        .expect("could not write attributes");

    let repo = TestRepo::init().with_home(home.path());
    repo.init_xcrypt();
    repo.write_xcrypt_config("secrets/\nvault/\n");

    let secret = two_megabytes();
    repo.write_file("vault/deploy.sh", &secret);
    repo.commit_all("an ordinary machine with an ordinary global file");

    assert_eq!(
        repo.blob_bytes("vault/deploy.sh").len(),
        OVERHEAD + secret.len(),
        "a harmless global attributes file changed the stored ciphertext"
    );
    repo.recheckout("vault/deploy.sh");
    repo.assert_worktree_eq("vault/deploy.sh", &secret);

    let status = repo.xcrypt(["status"]);
    assert_eq!(
        status.status.code(),
        Some(0),
        "a harmless global attributes file failed the gate:\n{}",
        String::from_utf8_lossy(&status.stdout)
    );
}

#[test]
fn the_shapes_git_leaves_alone_never_provoke_a_refusal() {
    // The other half, and it carries the same weight: with `required = true` a
    // refusal blocks *every* git operation in the repository, so a predicate one
    // shape too wide is its own outage. Every line below is ordinary — this
    // repository has to commit, check out and round-trip exactly as it would
    // with no foreign line at all.
    let repo = TestRepo::init();
    repo.init_xcrypt();
    // `binary` on one declared pattern, plain selection on the other, so the
    // managed section renders both `-text` and the `-diff` variant.
    repo.write_xcrypt_config("secrets/\nvault/  binary\n");
    repo.xcrypt_ok(["sync"]);

    let mut attributes = repo.worktree_bytes(".gitattributes");
    attributes.extend_from_slice(
        // Every line below outranks the managed section, and every one of them
        // is measured harmless.
        b"# `text=auto` winning outright on a declared path: git keeps binary\n\
          # detection, and the leading NUL of our magic answers it\n\
          vault/** text=auto\n\
          # a foreign driver on a path of its own is the ordinary case\n\
          *.psd filter=lfs\n\
          # one restating what the managed section already says\n\
          secrets/** -text\n\
          # and the shape that matters most: a bare `eol=`, the very assignment\n\
          # that is fatal over a ciphertext, on a path stored in the clear,\n\
          # where it is git doing exactly its job. `notes/` is in no declaration,\n\
          # so a gate that asked about every file instead of every *encrypted*\n\
          # file would refuse here and take the repository down with it.\n\
          notes/** eol=lf\n",
    );
    repo.write_file(".gitattributes", &attributes);
    // The machine's own answer taken out of it, then put back the other way
    // round below.
    repo.set_eol_config("true", "");

    let secret = two_megabytes();
    repo.write_file("secrets/store.p12", &secret);
    repo.write_file("vault/keys.bin", BINARY);
    repo.write_file("notes/readme.txt", CRLF);
    repo.commit_all("ordinary attribute lines everywhere");

    // The premises, so this test cannot quietly stop covering what it names.
    assert_eq!(
        repo.check_attr("text", "vault/keys.bin"),
        "auto",
        "`text=auto` no longer wins on the declared path it is here to cover"
    );
    assert_eq!(
        repo.check_attr("eol", "notes/readme.txt"),
        "lf",
        "the bare `eol=` no longer reaches the path stored in the clear"
    );
    assert_eq!(
        repo.check_attr("text", "notes/readme.txt"),
        "unspecified",
        "something now sets `text` on that path, so it is no longer the shape \
         that would be fatal over a ciphertext"
    );

    assert!(
        repo.blob_is_encrypted("secrets/store.p12"),
        "a healthy repository stopped encrypting"
    );
    assert!(
        repo.blob_is_encrypted("vault/keys.bin"),
        "the path `text=auto` reaches stopped being encrypted"
    );
    assert_eq!(
        repo.blob_bytes("vault/keys.bin").len(),
        OVERHEAD + BINARY.len(),
        "the ciphertext under `text=auto` was converted after all"
    );
    assert_eq!(
        repo.blob_bytes("secrets/store.p12").len(),
        OVERHEAD + secret.len(),
        "the ciphertext was converted after all, so one of these lines is not \
         as harmless as it looks"
    );
    repo.recheckout("secrets/store.p12");
    repo.assert_worktree_eq("secrets/store.p12", &secret);
    repo.assert_status_clean();

    // `core.autocrlf=input` too: the gate must not depend on the machine's
    // line-ending configuration, because that configuration cannot reach the
    // ciphertext at all once `-text` is on it.
    repo.set_eol_config("input", "");
    repo.write_file("secrets/store.p12", &secret);
    repo.git_ok(["add", "-A"]);
    repo.assert_status_clean();
}

/// The exit code the frozen table gives to a configuration error.
const CONFIG_ERROR: i32 = 2;

/// A secret under a directory whose name carries a space.
const SPACED: &[u8] = b"DATABASE_URL=postgres://user:hunter2@localhost/app\n";

/// The base64 line of an exported key file.
fn key_material(path: &std::path::Path) -> String {
    let text = std::fs::read_to_string(path).expect("the export must be readable text");
    text.lines()
        .nth(1)
        .expect("an export has a header and a key")
        .to_string()
}

#[test]
fn a_name_with_a_space_is_declared_in_quotes_and_lives_the_whole_cycle() {
    // Whitespace separates a pattern from its attributes, so a name that
    // contains a space needs a way of saying "this space is part of the name".
    // Until 2026-08-05 that was a backslash — which meant the character carried
    // two jobs at once, its own and wildmatch's — and since then it is quotes,
    // the way `.gitattributes` has always spelled it.
    //
    // Every stage of the tool has to agree about which paths that pattern names,
    // and the two that can disagree in silence are the ones this exercises: the
    // filter, which reads `.git-xcrypt`, and the rendered `.gitattributes` line,
    // which has to be quoted again on the way out and is graded here by real
    // `git check-attr`. A pattern that reaches the filter but not the rendered
    // line leaves ciphertext without `-text`, and that was measured destroying a
    // 2 MB file at checkout.
    let repo = TestRepo::init();
    repo.set_eol_config("false", "lf");
    repo.init_xcrypt();

    // --- The line as it used to be written: refused, and told why. ----------
    //
    // Split by today's rule it falls apart into the pattern `my\` and the
    // unknown attribute `secrets/`, so the file is refused either way — but a
    // reader of "unknown attribute" has no way to learn what changed under a
    // file they wrote once and have not opened since.
    repo.write_xcrypt_config("my\\ secrets/\n");
    let refused = repo.xcrypt(["sync"]);
    let complaint = String::from_utf8_lossy(&refused.stderr).into_owned();

    assert_eq!(
        refused.status.code(),
        Some(CONFIG_ERROR),
        "the old spelling was accepted, so a declared path silently stopped \
         being encrypted:\n{complaint}"
    );
    assert!(
        complaint.contains("2026-08-05") && complaint.contains("\"my secrets/\""),
        "the refusal must say that the syntax changed and how the line reads \
         now, or it is indistinguishable from a typo:\n{complaint}"
    );

    // Nor does anything reach the object database while the file is unreadable:
    // a refusal that let `git add` through would be the failure mode this
    // whole product exists to prevent.
    repo.write_file("my secrets/db.env", SPACED);
    let added = repo.git(["add", "-A"]);
    assert!(
        !added.status.success(),
        "`git add` went through on an unparsable declaration:\n{}",
        String::from_utf8_lossy(&added.stderr)
    );
    assert!(
        !repo.object_exists_for(SPACED),
        "the plaintext of a declared secret reached the object database while \
         the declaration could not be read"
    );

    // Quoting the whole old line instead — pattern and attributes together — is
    // the other way to reach for the new syntax and get it wrong, and it is the
    // dangerous one: the pattern would simply match nothing.
    repo.write_xcrypt_config("\"my secrets/*.sh   text eol=lf\"\n");
    let wrapped = repo.xcrypt(["sync"]);
    let complaint = String::from_utf8_lossy(&wrapped.stderr).into_owned();
    assert_eq!(
        wrapped.status.code(),
        Some(CONFIG_ERROR),
        "an old line quoted whole was accepted as a pattern, so it matches \
         nothing and the path it named is stored in the clear:\n{complaint}"
    );
    assert!(
        complaint.contains("\"my secrets/*.sh\" text eol=lf"),
        "the refusal must show where the quotes belong:\n{complaint}"
    );

    // --- Written the way it is written now. ---------------------------------
    //
    // `"!weird.env"` rides along because quoting is what made it spellable: the
    // parser stopped reading a quoted `!` as the negation marker, so the leading
    // `!` is part of a real file name and the filter encrypts it. The rendered
    // line is where that goes wrong in silence — git discards a `.gitattributes`
    // line opening with `!` (`warning: Negative patterns are ignored`), quoting
    // does not rescue it, and the path is left carrying ciphertext with no
    // `-text`. Measured on git 2.55: 35 CR bytes eaten out of a 2 MB blob, `git
    // add` exit 0, and the file unrecoverable at checkout.
    repo.write_xcrypt_config(
        "\"my secrets/\"\n\
         \"my secrets/*.sh\"   text eol=lf\n\
         !\"my secrets/README.md\"\n\
         \"!weird.env\"\n",
    );
    repo.xcrypt_ok(["sync"]);

    repo.write_file("my secrets/deploy.sh", CRLF);
    repo.write_file("app/my secrets/nested.env", SPACED);
    repo.write_file("my secrets/README.md", b"nothing secret here\n");
    repo.write_file("!weird.env", SPACED);
    repo.commit_all("a secret under a name with a space");
    repo.assert_status_clean();

    for path in [
        "my secrets/db.env",
        "app/my secrets/nested.env",
        "!weird.env",
    ] {
        assert!(
            repo.blob_is_encrypted(path),
            "{path}: a declared path was stored in the clear"
        );
        assert_eq!(
            repo.check_attr("filter", path),
            "git-xcrypt",
            "{path}: git would not run the filter for a declared path"
        );
        assert_eq!(
            repo.check_attr("text", path),
            "unset",
            "{path}: the rendered line does not reach a path the filter \
             encrypts, so git may convert its ciphertext and destroy it"
        );
    }

    // The attribute half of the split, on a quoted pattern: `text eol=lf` has
    // to survive being separated from a pattern that itself contains spaces.
    assert!(repo.blob_records_normalisation("my secrets/deploy.sh"));
    assert_eq!(
        repo.blob_bytes("my secrets/deploy.sh").len(),
        OVERHEAD + LF.len(),
        "the CRLF was not normalised, so the attributes were lost behind the \
         quotes"
    );

    // And the negation, whose `!` stands outside the quotes.
    assert!(
        !repo.blob_is_encrypted("my secrets/README.md"),
        "a negated path was encrypted anyway"
    );
    assert_eq!(
        repo.check_attr("text", "my secrets/README.md"),
        "unspecified"
    );

    // --- Closed and opened again, byte for byte. ----------------------------
    let vault = TempDir::new().expect("could not create a temporary directory");
    let key_file = vault.path().join("repo.key");
    repo.xcrypt_ok(["export-key", &key_file.to_string_lossy()]);
    let secret = key_material(&key_file);

    let locked = repo.xcrypt_ok(["lock", "--yes"]);
    assert!(
        !String::from_utf8_lossy(&locked.stderr).contains(&secret),
        "the key itself appeared in `lock`'s own warning"
    );
    assert!(
        repo.worktree_bytes("my secrets/db.env").starts_with(MAGIC),
        "a path with a space in it was left in the clear behind a command that \
         deleted the key"
    );

    repo.xcrypt_ok(["unlock", &key_file.to_string_lossy()]);
    repo.assert_worktree_eq("my secrets/db.env", SPACED);
    repo.assert_worktree_eq("my secrets/deploy.sh", LF);
    repo.assert_worktree_eq("app/my secrets/nested.env", SPACED);
    repo.assert_worktree_eq("!weird.env", SPACED);
    repo.assert_status_clean();
}

/// A name that ends in a space, which is the shape a backslash never closed.
///
/// **Unix only, and not for want of trying.** Win32 strips a trailing space from
/// every path it is handed, so the directory cannot be created there and there is
/// nothing to declare — the same reason `AGENTS.md` gives for the other
/// `#[cfg(unix)]` guards. What the quoting itself does is covered on all three
/// platforms by the space in the middle of `my secrets/` above; what only this
/// can show is the shape the old escape could not express at all, because the
/// line had to end `my secrets\ ` and every editor that strips trailing
/// whitespace deleted it without a word.
#[test]
#[cfg(unix)]
fn a_name_that_ends_in_a_space_is_expressible_at_last() {
    let repo = TestRepo::init();
    repo.init_xcrypt();
    repo.write_xcrypt_config("\"secrets /\"\n");
    repo.xcrypt_ok(["sync"]);

    repo.write_file("secrets /db.env", SPACED);
    // The name next door, one byte shorter, which must stay in the clear: a
    // pattern that quietly loses its trailing space matches this instead.
    repo.write_file("secrets/db.env", b"nothing secret here\n");
    repo.commit_all("a secret under a name that ends in a space");
    repo.assert_status_clean();

    assert!(
        repo.blob_is_encrypted("secrets /db.env"),
        "the trailing space was lost, so the declared path is stored in the clear"
    );
    assert!(
        !repo.blob_is_encrypted("secrets/db.env"),
        "the pattern reached past the name it declares"
    );
    assert_eq!(
        repo.check_attr("text", "secrets /db.env"),
        "unset",
        "the rendered line does not reach the path the filter encrypts, so git \
         may convert its ciphertext and destroy it"
    );
    assert_eq!(
        repo.check_attr("text", "secrets/db.env"),
        "unspecified",
        "the rendered line reaches past what the filter encrypts, so a file \
         stored in the clear is carrying `-text`"
    );

    repo.recheckout("secrets /db.env");
    repo.assert_worktree_eq("secrets /db.env", SPACED);
    repo.assert_status_clean();
}

/// 8 KiB whose bytes cover the whole range.
///
/// The plaintext shape is irrelevant — what git converts is the *ciphertext*,
/// which is pseudorandom, so roughly one byte in 256 is an `LF` and this size
/// carries about 32 of them. A draw with none at all has probability `e^-32`, and
/// the tests below assert the premise anyway rather than trusting the arithmetic.
/// Small enough that five repositories' worth costs nothing, unlike the 2 MB the
/// check-in tests need to make *damage* certain.
fn eight_kilobytes() -> Vec<u8> {
    (0..8 * 1024u32)
        .map(|index| u8::try_from(index % 251).expect("a byte"))
        .collect()
}

/// `LF` bytes not preceded by `CR` — the ones git's check-out conversion expands.
fn lone_line_feeds(bytes: &[u8]) -> usize {
    bytes
        .iter()
        .enumerate()
        .filter(|&(index, &byte)| byte == b'\n' && (index == 0 || bytes[index - 1] != b'\r'))
        .count()
}

/// Git's own `crlf_to_worktree`: every lone `LF` becomes `CRLF`, `CRLF` stays.
///
/// Used to build a blob that already wears the fingerprint of a converted
/// checkout, so a test can hold the fingerprint fixed and vary nothing but which
/// direction git would convert in.
fn expand_lone_line_feeds(bytes: &[u8]) -> Vec<u8> {
    let mut out = Vec::with_capacity(bytes.len());
    for (index, &byte) in bytes.iter().enumerate() {
        if byte == b'\n' && (index == 0 || bytes[index - 1] != b'\r') {
            out.push(b'\r');
        }
        out.push(byte);
    }
    out
}

/// A repository with one 8 KiB secret committed while the attributes are right.
///
/// Returns the plaintext and the intact blob, so every test below can prove both
/// that its fixture started healthy and that it stayed that way.
///
/// **The key is fixed, and that closes a real flake, not a nicety.** Two of the
/// altered-ciphertext cases below mutate the *whole* blob — `0x0a` → `0x0b`,
/// and the lone-`LF` expansion — header included. With a key generated freshly
/// per run, the 8 random `key_id` bytes contain `0x0a` in about 3% of runs;
/// the mutation then changes the key id and smudge answers "encrypted with
/// another key" instead of "the file has been altered", which is a *correct*
/// verdict over a different fixture than the test meant to build. Reproduced:
/// twice during the 2026-08-05 review run, and once in this round's 20-run
/// loop, always in this file, at no particular thread count. A fixed key makes
/// every byte of the blob — IV included, SIV is deterministic — identical in
/// every run, so the premise assertions in the cases below settle the shape
/// once and for all runs. The seed's derived key id, `8f72bb7e5c3ab4dd`,
/// carries no `0x0a` and no `0x0d`.
fn repository_with_one_intact_secret() -> (TestRepo, Vec<u8>, Vec<u8>) {
    let repo = TestRepo::init();
    let vault = TempDir::new().expect("could not create a temporary directory");
    let key_file = vault.path().join("fixed.key");
    fs::write(
        &key_file,
        "git-xcrypt-key-v1 8f72bb7e5c3ab4dd\n\
         ERERERERERERERERERERERERERERERERERERERERERE=\n",
    )
    .expect("could not write the fixed key");
    repo.xcrypt_ok(["unlock", "--key-only", &key_file.to_string_lossy()]);
    repo.init_xcrypt();
    repo.write_xcrypt_config("secrets/\n");
    repo.xcrypt_ok(["sync"]);

    let secret = eight_kilobytes();
    repo.write_file("secrets/store.p12", &secret);
    repo.commit_all("a secret, while the attributes are still right");

    let blob = repo.blob_bytes("secrets/store.p12");
    assert_eq!(
        blob.len(),
        OVERHEAD + secret.len(),
        "the fixture did not store an intact ciphertext to begin with"
    );
    assert!(
        lone_line_feeds(&blob) > 0,
        "the fixture's ciphertext holds no lone `LF`, so git's check-out \
         conversion would have nothing to expand and the shape under test \
         cannot occur"
    );
    (repo, secret, blob)
}

/// Appends `line` to the managed `.gitattributes`, where git takes it last.
fn append_attribute_line(repo: &TestRepo, line: &[u8]) {
    let mut attributes = repo.worktree_bytes(".gitattributes");
    attributes.extend_from_slice(line);
    repo.write_file(".gitattributes", &attributes);
}

/// Deletes `path` and checks it out again, returning whatever git said.
fn failing_checkout(repo: &TestRepo, path: &str) -> String {
    std::fs::remove_file(repo.path().join(path)).expect("could not remove the file");
    let checkout = repo.git(["checkout", "--", path]);
    let complaint = String::from_utf8_lossy(&checkout.stderr).into_owned();
    assert!(
        !checkout.status.success(),
        "the checkout succeeded, so the fixture no longer reproduces a failing \
         authentication tag:\n{complaint}"
    );
    complaint
}

/// Commits `blob` under `path` byte for byte, with no filter in the way.
///
/// `git hash-object --stdin` takes no path, so no attribute and no filter apply
/// to it: the object database ends up holding exactly these bytes. It is the only
/// way to stage a ciphertext the clean path would refuse — which it does, since
/// 2026-08-05, for every shape this needs.
fn commit_blob_verbatim(repo: &TestRepo, path: &str, blob: &[u8]) {
    let hashed = repo.git_with_stdin(["hash-object", "-w", "-t", "blob", "--stdin"], blob);
    assert!(
        hashed.status.success(),
        "git hash-object failed: {}",
        String::from_utf8_lossy(&hashed.stderr)
    );
    let id = String::from_utf8(hashed.stdout)
        .expect("git prints a hash")
        .trim()
        .to_string();
    repo.git_ok([
        "update-index",
        "--add",
        "--cacheinfo",
        &format!("100644,{id},{path}"),
    ]);
    repo.git_ok(["commit", "-q", "-m", "a ciphertext nobody can decrypt"]);
}

#[test]
fn a_check_out_git_converted_names_the_line_instead_of_accusing_the_file() {
    // The other end of the refusal above, and the one nobody can act on today.
    // Git's check-out order is blob, then git's own conversion, then smudge, so
    // a `text` line that outranks the managed `-text` hands the authentication
    // tag bytes that were never stored: measured on git 2.55 with a filter that
    // copied its stdin aside, a 4118-byte blob holding 18 lone `LF` arrived as
    // 4136 bytes holding 18 `CRLF` and no lone `LF` at all.
    //
    // The tag is right to refuse that, and the file is right to be missing —
    // what was wrong was the sentence. `the file has been altered` over a blob
    // that is intact to the byte reads as "your repository is corrupt and the
    // data is gone", at the exact moment a user is least able to check.
    let (repo, secret, blob) = repository_with_one_intact_secret();

    append_attribute_line(&repo, b"secrets/** text\n");
    // `core.autocrlf=true` is Git for Windows' own default, and it is what turns
    // the `text` line into an expansion rather than a no-op.
    repo.set_eol_config("true", "");
    assert_eq!(
        repo.check_attr("text", "secrets/store.p12"),
        "set",
        "the fixture no longer reproduces the shape it exists to catch"
    );

    let complaint = failing_checkout(&repo, "secrets/store.p12");

    assert!(
        !complaint.contains("the file has been altered"),
        "the checkout still accuses a file that is intact:\n{complaint}"
    );
    assert!(
        complaint.contains("Nothing is lost"),
        "the message must say outright that nothing was lost, because the user \
         has every reason to believe otherwise:\n{complaint}"
    );
    assert!(
        complaint.contains(".gitattributes:") && complaint.contains("secrets/** text"),
        "the message must name the file, the line and the assignment, the same \
         way the check-in refusal does:\n{complaint}"
    );
    assert!(
        complaint.contains("git-xcrypt sync"),
        "the message must say what to do about it:\n{complaint}"
    );

    // The claim the message makes, checked rather than asserted in prose.
    assert_eq!(
        repo.blob_bytes("secrets/store.p12"),
        blob,
        "the blob changed under a checkout, which only reads"
    );

    // And the instruction works: with the line gone the file comes back whole.
    let attributes = repo.worktree_bytes(".gitattributes");
    let repaired = attributes
        .split(|&byte| byte == b'\n')
        .filter(|line| line != b"secrets/** text")
        .map(<[u8]>::to_vec)
        .collect::<Vec<_>>()
        .join(&b'\n');
    repo.write_file(".gitattributes", &repaired);
    assert_eq!(
        repo.check_attr("text", "secrets/store.p12"),
        "unset",
        "the repair did not put the managed `-text` back in charge"
    );
    // No `recheckout` here: the failed checkout left no file to delete, which is
    // precisely the state the message has to talk a reader out of panicking over.
    repo.git_ok(["checkout", "--", "secrets/store.p12"]);
    repo.assert_worktree_eq("secrets/store.p12", &secret);
}

#[test]
fn a_ciphertext_that_really_was_altered_is_still_reported_as_altered() {
    // The half that matters more. A wrong "this is only configuration, nothing
    // is lost" over a repository that genuinely lost something is worse than the
    // blunt message it replaces, so every shape below has to keep saying the
    // blunt thing.

    // 1. An altered body under healthy attributes: nothing converts anything,
    //    and the file really is not what was encrypted.
    {
        let (repo, _secret, blob) = repository_with_one_intact_secret();
        let mut altered = blob.clone();
        altered[OVERHEAD + 5] ^= 0xff;
        commit_blob_verbatim(&repo, "secrets/store.p12", &altered);

        let complaint = failing_checkout(&repo, "secrets/store.p12");
        assert!(
            complaint.contains("the file has been altered"),
            "a genuinely altered ciphertext must still be called altered:\n{complaint}"
        );
        assert!(
            !complaint.contains("Nothing is lost"),
            "a genuinely altered ciphertext was reported as safe:\n{complaint}"
        );
    }

    // 2. The same alteration, with `secrets/** text` and `core.autocrlf=true`
    //    in force — but on a ciphertext holding no `LF` at all, so git expands
    //    nothing and the bytes that reached the tag *are* the stored bytes. The
    //    attribute line alone must never be enough to claim the file is safe.
    {
        let (repo, _secret, blob) = repository_with_one_intact_secret();
        let unexpandable: Vec<u8> = blob
            .iter()
            .map(|&byte| if byte == b'\n' { 0x0b } else { byte })
            .collect();
        assert_eq!(
            lone_line_feeds(&unexpandable),
            0,
            "the fixture still holds an `LF`, so git would expand something"
        );
        commit_blob_verbatim(&repo, "secrets/store.p12", &unexpandable);
        append_attribute_line(&repo, b"secrets/** text\n");
        repo.set_eol_config("true", "");

        let complaint = failing_checkout(&repo, "secrets/store.p12");
        assert!(
            complaint.contains("the file has been altered"),
            "a ciphertext git could not have expanded was blamed on git:\n{complaint}"
        );
        assert!(
            !complaint.contains("Nothing is lost"),
            "an altered ciphertext was reported as safe because a `text` line \
             happened to be present:\n{complaint}"
        );
    }

    // 3. The damage already in the blob, under `secrets/** text eol=lf` — a line
    //    that converts on the way *in* and writes the stored bytes out
    //    untouched. Measured on git 2.55 with `core.autocrlf=true`: a blob full
    //    of lone `LF` checks out byte for byte under it.
    //
    //    The blob here is the expanded ciphertext itself, so it wears the exact
    //    fingerprint an expansion leaves — no lone `LF`, plenty of `CRLF` — and
    //    git expands nothing on top of it. Only the check-out *direction* tells
    //    the two apart, which is what makes this the shape that guards it: a
    //    predicate reusing the check-in verdict calls this file safe, and it is
    //    not, because nothing about fixing that line brings its plaintext back.
    {
        let (repo, _secret, blob) = repository_with_one_intact_secret();
        let already_expanded = expand_lone_line_feeds(&blob);
        assert_eq!(
            lone_line_feeds(&already_expanded),
            0,
            "the fixture does not wear the fingerprint it exists to wear"
        );
        commit_blob_verbatim(&repo, "secrets/store.p12", &already_expanded);
        append_attribute_line(&repo, b"secrets/** text eol=lf\n");
        repo.set_eol_config("true", "");
        assert_eq!(
            repo.check_attr("eol", "secrets/store.p12"),
            "lf",
            "the fixture no longer pins the check-out direction"
        );
        assert_eq!(
            repo.check_attr("text", "secrets/store.p12"),
            "set",
            "the fixture no longer makes the check-in verdict say `convert`"
        );

        let complaint = failing_checkout(&repo, "secrets/store.p12");
        assert!(
            complaint.contains("the file has been altered"),
            "an altered ciphertext was blamed on a line that does not convert \
             at check-out:\n{complaint}"
        );
        assert!(
            !complaint.contains("Nothing is lost"),
            "the check-in verdict was reused for the check-out direction, so a \
             file whose plaintext really is gone was reported as safe:\n{complaint}"
        );
    }

    // 4. Another key's file, under the same converting line. Only a failed
    //    authentication tag may be re-explained; a header that belongs to a
    //    different key is not something a `.gitattributes` line can cause.
    {
        let (repo, _secret, blob) = repository_with_one_intact_secret();
        let mut foreign = blob.clone();
        // Byte 14 opens the frozen 8-byte `key_id`, which sits inside the
        // authenticated header.
        foreign[14] ^= 0xff;
        commit_blob_verbatim(&repo, "secrets/store.p12", &foreign);
        append_attribute_line(&repo, b"secrets/** text\n");
        repo.set_eol_config("true", "");

        let complaint = failing_checkout(&repo, "secrets/store.p12");
        assert!(
            complaint.contains("was encrypted with key"),
            "a file belonging to another key must still say so:\n{complaint}"
        );
        assert!(
            !complaint.contains("Nothing is lost"),
            "a foreign key's file was reported as a configuration problem:\n{complaint}"
        );
    }
}

/// `sync` points at `status` when something outside its section could outrank it.
///
/// The section this command writes is the last word only until a line below it
/// says otherwise — measured on git 2.55, a `secrets/** -filter` under the
/// managed markers took `git add` to exit 0 with the plain text stored, and
/// `sync` itself said nothing at all because its own question is only "does the
/// section match the declaration".
///
/// One sentence, and deliberately not a verdict. Whether such a line actually
/// reaches a declared path takes git's whole attribute stack to answer, and
/// `status` answers it by running that stack; a second spelling here would be
/// one too many. The price of not resolving is a sentence that also fires for a
/// perfectly ordinary `*.psd filter=lfs` — which is why it says *may* outrank
/// and names the command that knows, rather than quoting the line as a problem.
///
/// The silent half matters as much: `diff` is on nobody's list because a
/// foreign line setting it costs a readable `git diff` and not one byte in the
/// repository, measured 2026-08-05.
#[test]
fn sync_says_when_a_line_outside_its_section_might_outrank_it() {
    const SPEAKS: [&str; 4] = [
        "secrets/** -filter",
        "*.psd filter=lfs",
        "*.md text",
        "*.sh eol=lf",
    ];
    const SILENT: [&str; 3] = ["*.png -diff", "# just a note", ""];

    for line in SPEAKS.into_iter().chain(SILENT) {
        let repo = TestRepo::init();
        repo.init_xcrypt();
        repo.write_xcrypt_config("secrets/\n");
        if !line.is_empty() {
            let mut attributes = repo.worktree_bytes(".gitattributes");
            attributes.extend_from_slice(line.as_bytes());
            attributes.push(b'\n');
            repo.write_file(".gitattributes", &attributes);
        }

        let said = String::from_utf8_lossy(&repo.xcrypt_ok(["sync"]).stderr).into_owned();
        let mentioned = said.contains("outside the managed section");
        if SPEAKS.contains(&line) {
            assert!(
                mentioned,
                "{line:?}: a line that can outrank the managed section went unmentioned:\n{said}"
            );
            assert!(
                said.contains("git-xcrypt status"),
                "{line:?}: the sentence must name the command that can actually \
                 answer:\n{said}"
            );
        } else {
            assert!(
                !mentioned,
                "{line:?}: an ordinary line provoked a warning, which is how a \
                 warning stops being read:\n{said}"
            );
        }
    }
}

/// The note about foreign `filter` lines still sees the whole tree.
///
/// The resolver's discovery went lazy on 2026-08-07 — it probes
/// `.gitattributes` only on the ancestor chains of the paths it resolves — and
/// this note is the one consumer that must not narrow with it. It exists to
/// name an attributes file that reaches paths the index does not hold yet, and
/// such a file can sit in a directory with no tracked path at all: exactly the
/// directory no ancestor probe ever visits. `status` therefore walks the tree
/// for the note deliberately, and this scenario is what keeps that walk from
/// being "simplified" back to the resolver's consulted sources.
#[test]
fn the_note_about_foreign_filter_lines_sees_a_directory_the_index_does_not_hold() {
    let repo = TestRepo::init();
    repo.init_xcrypt();
    repo.write_xcrypt_config("secrets/\n");
    repo.xcrypt_ok(["sync"]);
    repo.write_file("secrets/db.env", b"api_key = value\n");
    repo.commit_all("a secret");

    // A `filter` line in a directory git tracks nothing under. The lazy
    // resolver never probes `vendor/`: no declared path leads through it.
    repo.write_file("vendor/.gitattributes", b"*.blob filter=lfs\n");

    let output = repo.xcrypt(["status"]);
    let text = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert_eq!(
        output.status.code(),
        Some(0),
        "an untracked foreign line reaching no declared path is a note, \
         never a finding:\n{text}"
    );
    assert!(
        text.contains("vendor/.gitattributes"),
        "the note lost sight of an attributes file outside every tracked \
         chain:\n{text}"
    );
}