stuffr-core 0.23.0

Core traits, stream ladder and resource governor for the stuffr toolkit
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
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
//! Format detection and pipeline resolution.
//!
//! Streams have no filename, so extensions are a hint and never the decision.
//!
//! [`resolve_chain`] is the single-layer resolution: outer format only, with
//! the inner layer decided from the path's remaining extensions when one is
//! given (`inner_from_path`) and [`Chain::Raw`] otherwise. [`resolve_chain_deep`]
//! closes that gap: whenever the outer layer is a codec and the inner layer
//! is still [`Chain::Raw`] — no path at all (stdin), or a path whose
//! extensions ran out — it decodes that layer, peeks [`PROBE_LEN`] of the
//! *decoded* bytes, and resolves again — recursively, bounded by
//! [`MAX_CHAIN_DEPTH`] on both routes, so that neither a piped stream nor a
//! misleadingly-named file can turn re-probing a decoded stream into an
//! unbounded decompression-nesting attack. Either way the source it returns
//! is already decoded through every codec layer named in the resolved
//! `Chain`, so a caller never has to guess which route produced it.

use std::path::Path;

use crate::archive::DecodeOpts;
use crate::error::{Error, Result};
use crate::format::{FormatId, FormatKind};
use crate::registry::Registry;
use crate::source::{DecodeSideSource, PeekSource, Source};

/// The detection window, per the spec.
pub const PROBE_LEN: usize = 4096;

/// Maximum layers when re-probing a decoded stream.
///
/// Four, chosen against real shapes: `.tar.gz` is depth 2 and `.tar.gz.gz` at
/// depth 3 is already pathological, so this leaves headroom without admitting
/// a decompression-nesting bomb. `Chain` is recursive, so the bound lives at
/// the resolution site rather than in the type.
pub const MAX_CHAIN_DEPTH: usize = 4;

/// How many bytes [`read_tail`] reads from the END of a seekable input: the
/// size of the one trailer [`foreign_from_tail`] knows, UDIF's `koly` block.
pub const TAIL_LEN: usize = 512;

/// A format stuffr recognises in order to refuse it, rather than to open it.
///
/// Exists because some files' first bytes carry a magic stuffr DOES open: an
/// Apple disk image (UDZO) begins with a zlib stream, so without this check
/// `stuffr ls` listed it as `zlib` and every other verb took it for a zlib
/// stream. Recognising the container from its own trailer is cheaper and
/// truer than teaching zlib's check to guess.
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Foreign {
    /// An Apple disk image (UDIF: `.dmg`), identified by its `koly` trailer.
    AppleDiskImage,
}

impl std::fmt::Display for Foreign {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Foreign::AppleDiskImage => f.write_str("an Apple disk image (UDIF)"),
        }
    }
}

/// Recognises a foreign format from the last [`TAIL_LEN`] bytes of a file.
///
/// UDIF's trailer is the last 512 bytes: `koly`, then a big-endian u32
/// version (4), then a big-endian u32 header size (512). All three are
/// required — the four-letter signature alone is 32 bits of evidence, and
/// the version and size fields turn it into 96 that no ordinary file's tail
/// matches by accident. Anything but exactly [`TAIL_LEN`] bytes is `None`:
/// a shorter tail is not where the trailer lives.
pub fn foreign_from_tail(tail: &[u8]) -> Option<Foreign> {
    (tail.len() == TAIL_LEN
        && tail[0..4] == *b"koly"
        && tail[4..8] == [0, 0, 0, 4]
        && tail[8..12] == [0, 0, 2, 0])
    .then_some(Foreign::AppleDiskImage)
}

/// Reads the last [`TAIL_LEN`] bytes of a seekable source and rewinds it to
/// byte zero.
///
/// `None` — having read nothing — for a source that cannot seek (a pipe has
/// no end to look at without consuming it, and buffering a whole pipe to
/// learn its last 512 bytes is not a probe), and for one shorter than
/// [`TAIL_LEN`], which cannot hold the trailer. Also `None` if the source
/// delivers fewer bytes than its own length promised (a file shrinking under
/// the read): no tail is better evidence than a torn one.
///
/// The position afterwards is byte zero in every case that seeked at all,
/// which is where [`probe`] expects its source to start.
pub fn read_tail(src: &mut dyn Source) -> Result<Option<Vec<u8>>> {
    if !src.caps().seekable {
        return Ok(None);
    }
    // A source that claims to seek and has no seek view is `probe`'s to
    // refuse (`NotSeekable`); this function only declines to look.
    let Some(seek) = src.as_seek() else {
        return Ok(None);
    };
    use std::io::SeekFrom;
    let len = seek.seek(SeekFrom::End(0))?;
    if len < TAIL_LEN as u64 {
        seek.seek(SeekFrom::Start(0))?;
        return Ok(None);
    }
    seek.seek(SeekFrom::Start(len - TAIL_LEN as u64))?;
    let mut tail = vec![0u8; TAIL_LEN];
    let mut filled = 0;
    while filled < TAIL_LEN {
        match seek.read(&mut tail[filled..])? {
            0 => break,
            n => filled += n,
        }
    }
    seek.seek(SeekFrom::Start(0))?;
    Ok((filled == TAIL_LEN).then_some(tail))
}

/// Reads a bounded prefix without consuming it.
///
/// A seekable source is rewound; a pipe is wrapped in a [`PeekSource`] that
/// replays the prefix. Either way the caller still sees byte zero.
///
/// A seekable source has its last [`TAIL_LEN`] bytes read first
/// ([`read_tail`]), and a foreign trailer ([`foreign_from_tail`]) is
/// [`Error::ForeignFormat`] — exit 3 — before any magic is consulted. Every
/// verb that identifies its input goes through here, so an Apple disk image
/// is refused by name everywhere rather than decoded as the zlib stream it
/// begins with. A pipe's tail is never read: that would consume it. A caller
/// that must not refuse (`--format`, `salvage`) must not call `probe`.
///
/// Reading the tail first also means a seekable source that cannot really
/// seek (a FIFO opened by path) fails before a byte of it is consumed, where
/// it used to fail on the rewind after the prefix — the same `Error::Io`.
pub fn probe(mut src: Box<dyn Source>) -> Result<(Vec<u8>, Box<dyn Source>)> {
    if src.caps().seekable {
        if let Some(foreign) = read_tail(src.as_mut())?
            .as_deref()
            .and_then(foreign_from_tail)
        {
            return Err(Error::ForeignFormat(foreign));
        }
        let mut prefix = vec![0u8; PROBE_LEN];
        // `caps().seekable` is the `Source`'s own claim; `as_seek()` is a
        // second, independent method on the same trait, and `Source` is
        // public — a third-party codec (Phase 2+) can implement one without
        // honouring the other. Trusting the claim with `.expect(..)` turned a
        // buggy-but-foreign `Source` impl into a panic reachable through this
        // crate's own public `probe`; surfacing it as a typed error instead
        // lets a caller match on it same as any other seek failure. There is
        // no format to name yet at this stage of detection, so the sentinel
        // id below is a placeholder, not a registered format.
        let Some(seek) = src.as_seek() else {
            return Err(Error::NotSeekable {
                format: FormatId::new("<probe>"),
            });
        };
        let mut filled = 0;
        while filled < PROBE_LEN {
            match std::io::Read::read(seek, &mut prefix[filled..])? {
                0 => break,
                n => filled += n,
            }
        }
        prefix.truncate(filled);
        std::io::Seek::seek(seek, std::io::SeekFrom::Start(0))?;
        return Ok((prefix, src));
    }

    let peek = PeekSource::fill(src, PROBE_LEN)?;
    let prefix = peek.prefix().to_vec();
    Ok((prefix, Box::new(peek)))
}

/// A resolved decode pipeline.
#[non_exhaustive]
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Chain {
    /// A codec wrapping something else. Decode order: this codec, then `inner`.
    Codec { codec: FormatId, inner: Box<Chain> },
    /// A container of entries.
    Container { container: FormatId },
    /// Opaque bytes. The terminal case for a bare compressed file.
    Raw,
}

impl Chain {
    /// The container this chain resolves to, if any, at ANY depth.
    ///
    /// `Some(tar)` for `tar over gzip` as well as for a bare `tar`: however
    /// many codec layers sit above it, the entries live in a container, and a
    /// caller that has not OPENED that container cannot speak for its
    /// fidelity. That is the whole use — `ops::inspect` identifies a stream
    /// WITHOUT decoding it, so it never opens the container and must not
    /// report a fidelity conclusion it did not reach. See
    /// `ops::Inspection::fidelity_evaluated`.
    ///
    /// The `_` arm covers [`Chain::Raw`] and anything added later: `Chain` is
    /// `#[non_exhaustive]`, and "no container" is the right answer for a
    /// shape this method does not recognise, since the caller's only use of
    /// `Some` is to withhold a claim.
    pub fn container(&self) -> Option<FormatId> {
        match self {
            Chain::Container { container } => Some(*container),
            Chain::Codec { inner, .. } => inner.container(),
            _ => None,
        }
    }

    /// The outermost codec, if any — the layer a writer must create FIRST,
    /// because the container writes into it.
    ///
    /// Deliberately only the outermost, and deliberately NOT recursive the
    /// way [`Chain::container`] is: a write-side chain is at most one codec
    /// deep. `MAX_CHAIN_DEPTH` bounds the READ side, where deeper nesting is
    /// a hostile-input concern rather than a shape stuffr emits, and a
    /// recursive answer here would let a caller silently write only the
    /// innermost of several codecs.
    pub fn outermost_codec(&self) -> Option<FormatId> {
        match self {
            Chain::Codec { codec, .. } => Some(*codec),
            _ => None,
        }
    }

    /// Human-readable form, innermost first: `"tar over gzip"`.
    pub fn describe(&self) -> String {
        match self {
            Chain::Raw => "raw".to_string(),
            Chain::Container { container } => container.to_string(),
            Chain::Codec { codec, inner } => match inner.as_ref() {
                Chain::Raw => codec.to_string(),
                other => format!("{} over {}", other.describe(), codec),
            },
        }
    }
}

fn hex_prefix(bytes: &[u8]) -> String {
    if bytes.is_empty() {
        return "empty input".to_string();
    }
    bytes
        .iter()
        .take(8)
        .map(|b| format!("{b:02x}"))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Lowercase extension components of a path, outermost last.
/// `"out.tar.gz"` → `["tar", "gz"]`.
fn extensions(path: &Path) -> Vec<String> {
    let name = path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or_default();
    name.split('.')
        .skip(1)
        .map(|s| s.to_ascii_lowercase())
        .collect()
}

/// Resolves the inner layer beneath an outer codec, using the path's remaining
/// extensions. `.tar.gz` → tar; `.tgz` → tar; `.gz` or no path → Raw.
fn inner_from_path(reg: &Registry, path: Option<&Path>, outer: FormatId) -> Chain {
    let Some(path) = path else {
        return Chain::Raw;
    };
    let exts = extensions(path);

    // `.tgz` and friends: one extension meaning "tar inside <codec>", spelled
    // as "t" + the codec's own extension. Resolved through the SAME
    // [`compound_alias`] the write side uses, never a second copy of the strip
    // rule — the copy is how `.tbz` came to mean tar-over-bzip2 when reading
    // and a bare gzip when writing, which is the exact defect class
    // `chain_for_new_path` shares this function to prevent.
    if let Some(last) = exts.last()
        && compound_alias(reg, last) == Some(outer)
        && let Some(id) = reg.by_extension("tar")
        && reg.container(id).is_some()
    {
        return Chain::Container { container: id };
    }

    // Otherwise look one extension inwards.
    if exts.len() >= 2
        && let Some(id) = reg.by_extension(&exts[exts.len() - 2])
        && reg.container(id).is_some()
    {
        return Chain::Container { container: id };
    }
    Chain::Raw
}

/// The codec a `.tgz`-style compound extension names — "t" + the codec's own
/// extension, meaning "tar inside <codec>".
///
/// Needed only on the write side. The read side takes the outer codec from
/// the magic bytes and never has to parse `tgz` at all; a file being created
/// has no magic, so the name is the only evidence there is. No codec
/// registers its own compound alias and none should — `tar::meta` spells out
/// why registering `tgz` on tar would make a `.tgz` resolve to a bare tar —
/// so the suffix is stripped here instead, and `inner_from_path` calls this
/// same function when deciding what is inside.
///
/// # `.tlz` means tar-over-**lzip** here, and that is a decision
///
/// The strip rule sends `.tlz` to `lz`, which lzip registers, so stuffr reads
/// and writes `.tlz` as `tar.lz` — lzip. **GNU tar and libarchive both read
/// `.tlz` as `tar.lzma`** (LZMA1, the `.lzma` alone-format), so an archive
/// stuffr writes as `.tlz` will not open in GNU tar, and one GNU tar wrote
/// will not open here.
///
/// It is left as it is, deliberately and for now: `lzip` is the format
/// actually worth writing of the two (it carries a CRC and a recognised
/// magic, where `.lzma` has neither), the spelling is genuinely contested
/// rather than settled — `.tlz` predates lzip and both readings are in the
/// wild — and changing it would silently reinterpret existing files. What is
/// NOT acceptable is that the answer was an accident of which extension
/// happened to be registered; it is written down here so the next change to
/// it is a decision rather than a side effect. If it is ever revisited, the
/// honest options are to refuse `.tlz` outright as ambiguous, or to add it to
/// [`COMPOUND_SPELLINGS`] pointing at `lzma`.
fn compound_alias(reg: &Registry, ext: &str) -> Option<FormatId> {
    let stripped = ext.strip_prefix(['t', 'T'])?;
    if stripped.is_empty() {
        return None;
    }
    let stripped = stripped.to_ascii_lowercase();
    let spelling = COMPOUND_SPELLINGS
        .iter()
        .find(|(alias, _)| *alias == stripped)
        .map_or(stripped.as_str(), |(_, real)| *real);
    let id = reg.by_extension(spelling)?;
    // A container never sits inside itself: `.tar` is resolved by the direct
    // lookup above, and anything reached through the alias must be a codec.
    reg.container(id).is_none().then_some(id)
}

/// The compound spellings whose remainder after the `t` is NOT the codec's
/// own registered extension, and what it really means.
///
/// Without this table the strip rule simply fails to find a codec and the
/// whole name resolves to [`Chain::Raw`] — which on the write side is not a
/// refusal but a silent fallback to `default_format()`, so **`stuffr pack
/// notes.txt -o f.tbz` wrote a gzip stream, with no tar inside it, at exit
/// 0.** A name promising one thing and bytes that are another, reported as
/// success, is the defect class the write-side chain resolution exists to
/// close, and `.tbz` was its last surviving member.
///
/// The table lives here rather than in the registry ON PURPOSE. Registering
/// `bz` as an extension of bzip2 would fix `.tbz` and simultaneously make a
/// plain `.bz` writable — and `.bz` is **bzip1**, a different, obsolete
/// format this build cannot produce. The alias is only ever consulted in the
/// `t`-prefixed compound position, so `stuffr pack notes.txt -o f.bz` still
/// finds no format for `bz` and behaves exactly as it did.
///
/// GNU tar and libarchive both read `.tbz` as `tar.bz2`; `.tbz2` needs no
/// entry, because stripping its `t` already yields bzip2's registered `bz2`.
const COMPOUND_SPELLINGS: &[(&str, &str)] = &[("bz", "bz2")];

/// The chain an OUTPUT path names, from its extensions alone.
///
/// The write-side twin of [`resolve_chain`], which cannot serve here: that one
/// sniffs magic bytes, and a file about to be created has none. Shares
/// `inner_from_path` with the read side deliberately — a second, write-side
/// extension table would drift, and `.tar.gz` resolving one way for reading
/// and another for writing is the whole class of bug this exists to prevent.
///
/// Never fails: an unknown or absent extension is [`Chain::Raw`], which every
/// caller already has to handle.
pub fn chain_for_new_path(reg: &Registry, path: &Path) -> Chain {
    let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
        return Chain::Raw;
    };
    let Some(outer) = reg.by_extension(ext).or_else(|| compound_alias(reg, ext)) else {
        return Chain::Raw;
    };
    // `x.tar` — a container with nothing above it.
    if reg.container(outer).is_some() {
        return Chain::Container { container: outer };
    }
    // `outer` is a codec. `x.tar.gz` and `x.tgz` both name a container inside
    // it; `x.gz` names nothing, and resolves to a bare codec over Raw.
    let inner = inner_from_path(reg, Some(path), outer);
    Chain::Codec {
        codec: outer,
        inner: Box::new(inner),
    }
}

/// Turns a path and/or a probed prefix into a concrete pipeline.
///
/// The extension is consulted first, against the full magic-hit set; priority
/// decides only when the path is silent or names a format whose magic did not
/// match. Failure names the bytes actually seen so a misdetection is
/// debuggable without library prints.
///
/// The lenient resolution every verb given a file uses: a magic hit its
/// format does not confirm still resolves (see [`resolve_chain_checked`]),
/// so a damaged archive the user names reaches its reader and is reported
/// corrupt (exit 5) rather than unknown.
pub fn resolve_chain(reg: &Registry, path: Option<&Path>, prefix: &[u8]) -> Result<Chain> {
    resolve_chain_checked(reg, path, prefix).map(|(chain, _)| chain)
}

/// How the outer layer of a resolved [`Chain`] was reached.
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Evidence {
    /// A magic hit (or, for a magicless format, the extension) that the
    /// format's own [`crate::format::ConfirmFn`] accepted — or that has no
    /// such function, which counts as accepting.
    Confirmed,
    /// Only magic hits (or an extension) that the format's function refused.
    /// Still resolved, because the lenient verbs must reach a damaged file's
    /// reader; [`identify_strict`] refuses it.
    Unconfirmed,
    /// No magic matched, and the extension named a format that has no
    /// confirmation function: a name, and nothing else (brotli, raw deflate).
    ByName,
}

/// [`resolve_chain`], also saying how the outer layer was reached.
///
/// Candidates are ranked by confirmation before anything else: the magic
/// hits whose format confirms the prefix (or registered no function) are
/// selected among exactly as `resolve_chain` always selected — the extension
/// first, then priority, [`Error::AmbiguousFormat`] on a tie — and the
/// answer is [`Evidence::Confirmed`]. Only when no hit confirms are all the
/// hits selected among the same way, [`Evidence::Unconfirmed`]. So a
/// refused hit can no longer tie with, or outrank, a confirmed one: two
/// formats sharing a magic are separated by their bytes, not by an error.
///
/// With no magic hit at all the extension decides, and its format's function
/// (if any) grades it: `Confirmed`, `Unconfirmed`, or [`Evidence::ByName`]
/// when there is none. Every error is the one `resolve_chain` raised before
/// confirmation existed.
///
/// `prefix` is a probe prefix: shorter than [`PROBE_LEN`] means it is the
/// whole stream, which every confirmation is told (see
/// [`crate::format::ConfirmFn`]).
pub fn resolve_chain_checked(
    reg: &Registry,
    path: Option<&Path>,
    prefix: &[u8],
) -> Result<(Chain, Evidence)> {
    resolve_checked(reg, path, prefix, prefix.len() < PROBE_LEN)
}

/// [`resolve_chain_checked`] with the "these bytes are the whole stream"
/// flag given rather than read off the length: a decoded layer that stopped
/// on an error is short without being whole.
fn resolve_checked(
    reg: &Registry,
    path: Option<&Path>,
    prefix: &[u8],
    whole: bool,
) -> Result<(Chain, Evidence)> {
    let hits = reg.match_magic(prefix);
    // `match_magic`'s order (priority descending) survives the filter, which
    // the tie-break below relies on.
    let confirmed: Vec<FormatId> = hits
        .iter()
        .copied()
        .filter(|id| reg.confirm(*id, prefix, whole) != Some(false))
        .collect();
    let (mut candidates, mut evidence) = if confirmed.is_empty() {
        (hits, Evidence::Unconfirmed)
    } else {
        (confirmed, Evidence::Confirmed)
    };

    if candidates.len() > 1 {
        // The extension is consulted FIRST, and against every magic hit — a
        // path saying `.apk` must reach apk even though zip outranks it. That
        // is the spec's own worked example, and ranking cannot be allowed to
        // pre-empt an explicit filename. Priority decides only when the path
        // is silent, or names a format whose magic never matched.
        let by_ext =
            path.and_then(|p| extensions(p).iter().rev().find_map(|e| reg.by_extension(e)));
        match by_ext.filter(|id| candidates.contains(id)) {
            Some(id) => candidates = vec![id],
            None => {
                let top = reg.priority_of(candidates[0]);
                let tied: Vec<FormatId> = candidates
                    .iter()
                    .copied()
                    .filter(|id| reg.priority_of(*id) == top)
                    .collect();
                if tied.len() == 1 {
                    candidates = tied;
                } else {
                    let names: Vec<&str> = tied.iter().map(|id| id.as_str()).collect();
                    return Err(Error::AmbiguousFormat {
                        candidates: names.join(", "),
                    });
                }
            }
        }
    }

    let outer = match candidates.first() {
        Some(id) => Some(*id),
        None => {
            let by_name =
                path.and_then(|p| extensions(p).iter().rev().find_map(|e| reg.by_extension(e)));
            if let Some(id) = by_name {
                evidence = match reg.confirm(id, prefix, whole) {
                    Some(true) => Evidence::Confirmed,
                    Some(false) => Evidence::Unconfirmed,
                    None => Evidence::ByName,
                };
            }
            by_name
        }
    };

    let Some(outer) = outer else {
        return Err(Error::UnknownFormat {
            seen: hex_prefix(prefix),
        });
    };

    let kind = if reg.container(outer).is_some() {
        FormatKind::Container
    } else if reg.codec(outer).is_some() {
        FormatKind::Codec
    } else {
        return Err(Error::FormatNotEnabled(outer));
    };

    let chain = match kind {
        FormatKind::Container => Chain::Container { container: outer },
        FormatKind::Codec => Chain::Codec {
            codec: outer,
            inner: Box::new(inner_from_path(reg, path, outer)),
        },
    };
    Ok((chain, evidence))
}

/// Builds `innermost` back up under each codec in `layers`, outermost last so
/// the final fold produces the correct nesting order.
fn wrap_layers(layers: &[FormatId], innermost: Chain) -> Chain {
    layers
        .iter()
        .rev()
        .fold(innermost, |inner, codec| Chain::Codec {
            codec: *codec,
            inner: Box::new(inner),
        })
}

/// Decodes `src` through every [`Chain::Codec`] layer named in `chain`,
/// outermost first, so the returned source is positioned exactly where
/// `chain`'s innermost entry (a [`Chain::Container`] or [`Chain::Raw`])
/// begins. A chain with no codec layers at all (a bare container) hands
/// `src` back untouched.
/// Builds one codec layer's decoder and marks its output as decode-side.
///
/// The ONE place in this crate that turns a [`Source`] into a decoded one, so
/// it is also the one place that has to remember the marking — see
/// [`crate::source::decode_side`] for why the marking exists at all, and for
/// the four downstream `?`s it retroactively makes correct.
///
/// Two things happen here, and they cover the two moments a codec can fail:
///
/// * **Construction.** A codec that validates its header eagerly can fail
///   inside `decoder()` itself, reading the source that is about to become
///   decode-side but is not yet wrapped. That error is folded through
///   [`Error::from_decode_io`] here. No registered codec takes this branch
///   today (`CLAUDE.md`'s Phase 3c backlog records the same gap against
///   `conformance.rs:393`), which is exactly why it is worth closing before
///   one does: an unreached branch that is wrong by default is how this class
///   keeps recurring.
/// * **Reading.** Every later `read` is marked by [`DecodeSideSource`].
///
/// Wrapping is idempotent, so a three-layer chain pays one tag allocation per
/// error rather than three.
fn build_decoder(
    reg: &Registry,
    codec: FormatId,
    src: Box<dyn Source>,
    opts: &DecodeOpts,
) -> Result<Box<dyn Source>> {
    let decoded = reg
        .require_codec(codec)?
        .decoder(src, opts)
        .map_err(|e| match e {
            Error::Io(io_err) => Error::from_decode_io(io_err),
            other => other,
        })?;
    Ok(DecodeSideSource::wrap(decoded))
}

fn decode_through_chain(
    reg: &Registry,
    chain: &Chain,
    src: Box<dyn Source>,
    opts: &DecodeOpts,
) -> Result<Box<dyn Source>> {
    match chain {
        Chain::Codec { codec, inner } => {
            let decoded = build_decoder(reg, *codec, src, opts)?;
            decode_through_chain(reg, inner, decoded, opts)
        }
        Chain::Container { .. } | Chain::Raw => Ok(src),
    }
}

/// [`resolve_chain`], but when the outer layer is a codec whose inner the
/// path left as [`Chain::Raw`] — whether because there was no path at all,
/// or because the path's own extensions ran out before naming a container —
/// keeps going: decodes that layer, peeks [`PROBE_LEN`] of the *decoded*
/// bytes, and resolves again from the decoded bytes' own magic. Closes the
/// Phase 0 limitation where a codec on stdin always bottomed out at Raw
/// purely for lack of an extension.
///
/// The path still gets first say: `resolve_chain` runs once with it, and if
/// that alone already resolves the full chain (a bare container, or a codec
/// whose inner the extensions named directly — `.tar.gz`), peeking never
/// happens. Peeking is what runs when the path is silent, or was not enough.
///
/// Bounded by [`MAX_CHAIN_DEPTH`] on **both** routes, because re-probing a
/// *decoded* stream is exactly what makes unbounded nesting attackable: each
/// layer is cheap to produce and expensive to expand. A path is a name, not
/// a proof — `a.gz.gz.gz.gz.gz` is refused the same way piped bytes with the
/// identical shape are, and exceeding the bound is a typed
/// [`Error::ChainTooDeep`], never a panic and never a silent stop.
///
/// Returns the resolved [`Chain`] alongside a [`Source`] **already decoded
/// through every codec layer named in that `Chain`** — positioned exactly
/// where the chain's innermost entry begins, ready to hand straight to a
/// container or to read as raw bytes. This holds on both routes: a path
/// that resolves in one step (no peeking needed) still gets its codec
/// layers decoded before the source comes back, so a caller never has to
/// ask whether the source it received happens to be raw or already decoded.
pub fn resolve_chain_deep(
    reg: &Registry,
    path: Option<&Path>,
    src: Box<dyn Source>,
) -> Result<(Chain, Box<dyn Source>)> {
    resolve_chain_deep_with(reg, path, src, &DecodeOpts::default())
}

/// [`resolve_chain_deep`], but with the [`DecodeOpts`] every codec layer's
/// decoder is built from spelled out by the caller instead of defaulted.
///
/// This exists because [`DecodeOpts::memory_limit`] is the ONLY guard that
/// can see a pure codec's pre-output dictionary allocation — the one sized
/// from a value the file declares in its own header, before a single decoded
/// byte exists. `--max-ratio` counts decoded output bytes and so cannot see
/// it at all. Resolving a chain builds a decoder per codec layer, so a
/// resolver that defaults its opts leaves every entry-aware verb (`list`,
/// `test`, `cat`, `unpack -C`) unbounded against a crafted `.tar.lz` whose
/// header declares a 512 MiB dictionary, while the single-stream path
/// refuses the same bytes at exit 6.
///
/// `resolve_chain_deep` remains as the "library default" spelling —
/// unbounded, matching `DecodeOpts::default()` everywhere else — but no CLI
/// path should use it: the CLI always has a resolved limit to pass.
pub fn resolve_chain_deep_with(
    reg: &Registry,
    path: Option<&Path>,
    src: Box<dyn Source>,
    opts: &DecodeOpts,
) -> Result<(Chain, Box<dyn Source>)> {
    let (prefix, src) = probe(src)?;
    let chain = resolve_chain(reg, path, &prefix)?;

    // Either a bare container, or a codec whose inner the path already named
    // (e.g. `.tar.gz`) — the path (if any) is done contributing. Decode
    // through whatever codec layers `chain` names and stop; there is nothing
    // left to peek.
    if !matches!(&chain, Chain::Codec { inner, .. } if matches!(inner.as_ref(), Chain::Raw)) {
        let decoded = decode_through_chain(reg, &chain, src, opts)?;
        return Ok((chain, decoded));
    }

    // The chain bottoms out at Raw. From here, only the decoded bytes' own
    // magic decides — the path, if there was one, already had its say above
    // and found nothing further.
    let Chain::Codec { codec, .. } = chain else {
        unreachable!("guarded above: chain is Chain::Codec with a Raw inner")
    };
    let mut layers: Vec<FormatId> = vec![codec];
    let mut current_codec = codec;
    let mut src = src;
    let mut depth = 1usize;

    loop {
        if depth >= MAX_CHAIN_DEPTH {
            return Err(Error::ChainTooDeep {
                depth: MAX_CHAIN_DEPTH,
            });
        }

        let decoded = build_decoder(reg, current_codec, src, opts)?;
        // This `probe` reads through a DECODER — unlike the one at the top
        // of this function, and unlike `resolve_chain_deep_with`'s own
        // `probe(src)` two calls up, both of which read the RAW,
        // undecoded source. An `io::Error` here means the bytes this codec
        // just produced are malformed, not that the raw source or the
        // environment failed, so it is reclassified via
        // `Error::from_decode_io` exactly like every other decoder-side
        // read in this crate (`ops.rs`, `entries.rs`, `conformance.rs`).
        //
        // Left as a bare `?` (as it was until Task 4b), a truncated `.zz`
        // or an empty `.lz` — a codec stream with no container above it, so
        // resolution bottoms out in this very loop re-probing the decoded
        // bytes — surfaced as `Error::Io`: exit 1, "stuffr failed", for
        // input that is simply corrupt. `ops::decompress` decodes the
        // identical bytes through a call already wired to
        // `Error::from_decode_io`, so `cat` and `list` disagreed on the
        // exit code for the same input; see `error.rs`'s doc comment on
        // `from_decode_io` for the convention this leans on, and
        // `Error::exit_code`'s comment for this wildcard's history.
        //
        // Do NOT widen this to `probe(src)` above (raw source) or to
        // `probe`/`PeekSource::fill` themselves — either would reclassify a
        // genuine i/o failure on the raw source (a real disk error, a
        // permission failure, a broken pipe) as `Corrupt`, which is a new
        // lie in the opposite direction.
        //
        // As of the decode-side marker (see `crate::source::decode_side`),
        // `build_decoder` has already tagged this source, so `probe`'s own
        // internal `?` would classify it anyway and this `map_err` sees an
        // `Error::Corrupt` and passes it through. Kept rather than deleted:
        // it is the site Task 4b's regression tests name, and a belt that
        // does not depend on the marker being applied one call up.
        let (next_prefix, next_src) = probe(decoded).map_err(|e| match e {
            Error::Io(io_err) => Error::from_decode_io(io_err),
            other => other,
        })?;
        depth += 1;

        let next_chain = match resolve_chain(reg, None, &next_prefix) {
            Ok(chain) => chain,
            Err(Error::UnknownFormat { .. }) => {
                return Ok((wrap_layers(&layers, Chain::Raw), next_src));
            }
            Err(e) => return Err(e),
        };

        let Chain::Codec { codec: nested, .. } = next_chain else {
            return Ok((wrap_layers(&layers, next_chain), next_src));
        };

        layers.push(nested);
        current_codec = nested;
        src = next_src;
    }
}

/// Identifies an input for a listing that must not claim what it cannot
/// show: `Some(chain)` only when every layer is confirmed, `None` for "not
/// something stuffr opens".
///
/// The strict twin of [`resolve_chain`], for `stuffr ls`, which reads a
/// folder of arbitrary files and has no user naming any of them: a lenient
/// answer there is a false positive in a list, where for a verb given a file
/// it is the route to an honest exit 5. Reads nothing — the caller supplies
/// the probe prefix and, for a seekable file, [`read_tail`]'s tail.
///
/// * A foreign tail ([`foreign_from_tail`]) is `None` before anything else.
/// * The outer layer comes from [`resolve_chain_checked`]; an error or
///   [`Evidence::Unconfirmed`] is `None`. [`Evidence::ByName`] is accepted:
///   a magicless format has nothing more to show.
/// * A container is the answer.
/// * A codec is decoded from the prefix itself — never from the file — up to
///   [`PROBE_LEN`] output bytes, keeping what arrives before any error (a
///   prefix is a truncated stream, so an error at its end is expected). What
///   came out is resolved with no path; a confirmed codec or container
///   becomes the inner layer (a codec recursively), anything else is
///   [`Chain::Raw`]. The decoded bytes are the whole inner stream when they
///   stop short of [`PROBE_LEN`] without an error, and their confirmation is
///   told so.
/// * Decoded bytes that match no magic at all fall back to the container
///   the path names for the outermost codec (`inner_from_path`, as
///   [`resolve_chain`] answers), but only when that container's own check
///   accepts the bytes (or it has none): a v7 tar carries no `ustar` magic
///   and `v7.tar.gz` is still tar over gzip, while a text file named
///   `y.tar.gz` fails tar's checksum and is a gzip, whatever its name says.
///   Decoded bytes whose magic matched but did not confirm get no such
///   fallback.
/// * A codec that decodes **nothing** depends on whether the prefix was the
///   whole file. A cut-off read (`prefix.len() == PROBE_LEN`) can simply be
///   shorter than the codec's first block — measured on a real 168 KB `.bz2`
///   and on `.zst`, and true of lz4 and framed snappy whenever the first
///   block is larger than the window — so the codec, already confirmed by
///   its magic and check, is kept, over the inner layer its path names
///   (exactly what [`resolve_chain`] answers: `big.tar.bz2` stays tar over
///   bzip2). The whole file decoding nothing before an error is `None`; the
///   whole file decoding nothing and ending cleanly is an empty stream, a
///   codec over `Raw`. A decoder refused at construction is `None` either
///   way.
///
/// Nested layers follow the same rule, with "cut off" meaning the bytes fed
/// in were themselves incomplete — the layer above filled the window or
/// stopped on an error. Their fallback is `Raw`, not the path: a name speaks
/// for the outermost layers, and which of its extensions belongs to a layer
/// this deep is a guess.
///
/// The nesting is bounded below [`MAX_CHAIN_DEPTH`] codec layers — the most
/// [`resolve_chain_deep_with`] will open — and a deeper stack stops at
/// `Raw` rather than failing, because the outer layers did decode.
pub fn identify_strict(
    reg: &Registry,
    path: Option<&Path>,
    prefix: &[u8],
    tail: Option<&[u8]>,
    opts: &DecodeOpts,
) -> Option<Chain> {
    if tail.and_then(foreign_from_tail).is_some() {
        return None;
    }
    let (chain, evidence) = resolve_chain_checked(reg, path, prefix).ok()?;
    if evidence == Evidence::Unconfirmed {
        return None;
    }
    match chain {
        Chain::Container { .. } => Some(chain),
        Chain::Codec { codec, inner } => {
            let layer = StrictInput {
                bytes: prefix,
                cut: prefix.len() == PROBE_LEN,
                unseen_inner: *inner,
            };
            strict_codec_layer(reg, codec, layer, opts, 1)
        }
        // `resolve_chain_checked` answers a container or a codec; anything
        // added to `Chain` later is not something this function can vouch for.
        _ => None,
    }
}

/// The outermost layer of `chain` whose format's header check refuses the
/// bytes that layer begins with, or `None` when every layer it can see
/// checks out.
///
/// For `stuffr info`, which names a lenient chain (the one every verb given
/// the file would read) and must still say which of its layers did not check
/// out: a `.tar.gz` whose tar header fails its checksum resolves as tar over
/// gzip, and this answers `tar`. Reads nothing — `prefix` is the probe
/// prefix, and each codec layer is decoded from it as [`identify_strict`]
/// decodes it, up to [`PROBE_LEN`] output bytes.
///
/// A layer it cannot see says nothing: a codec whose decoder refuses at
/// construction, or whose prefix decodes to no bytes at all (a cut-off read
/// shorter than its first block), ends the walk with `None`. A format with no
/// check function counts as checking out, as it does everywhere else.
pub fn first_unconfirmed_layer(
    reg: &Registry,
    chain: &Chain,
    prefix: &[u8],
    opts: &DecodeOpts,
) -> Option<FormatId> {
    let mut layer = chain;
    let mut owned: Vec<u8>;
    let mut bytes = prefix;
    // A probe prefix short of the window is the whole stream; a decoded
    // layer is whole when it ended cleanly inside the window.
    let mut whole = prefix.len() < PROBE_LEN;
    for _ in 0..MAX_CHAIN_DEPTH {
        match layer {
            Chain::Container { container } => {
                return (reg.confirm(*container, bytes, whole) == Some(false))
                    .then_some(*container);
            }
            Chain::Codec { codec, inner } => {
                if reg.confirm(*codec, bytes, whole) == Some(false) {
                    return Some(*codec);
                }
                if matches!(**inner, Chain::Raw) {
                    return None;
                }
                let decoded = decode_prefix(reg, *codec, bytes, opts)?;
                if decoded.bytes.is_empty() {
                    return None;
                }
                whole = decoded.is_whole();
                owned = decoded.bytes;
                bytes = &owned;
                layer = inner;
            }
            _ => return None,
        }
    }
    None
}

/// What one codec layer of [`identify_strict`] is given to decode.
struct StrictInput<'a> {
    bytes: &'a [u8],
    /// `bytes` stop short of the stream's real end.
    cut: bool,
    /// The path's answer for the outermost layer, `Raw` below it: claimed
    /// when `cut` and nothing decodes, and the fallback (when its check
    /// accepts) for decoded bytes that match no magic.
    unseen_inner: Chain,
}

/// One codec layer of [`identify_strict`]: decodes `input.bytes` through
/// `codec` and resolves what comes out. `depth` counts the codec layers down
/// to and including this one.
fn strict_codec_layer(
    reg: &Registry,
    codec: FormatId,
    input: StrictInput<'_>,
    opts: &DecodeOpts,
    depth: usize,
) -> Option<Chain> {
    let decoded = decode_prefix(reg, codec, input.bytes, opts)?;
    let whole = decoded.is_whole();
    let inner = if decoded.bytes.is_empty() {
        match (input.cut, decoded.failed) {
            // Too little input for the codec's first block: the window, not
            // the file, ran out.
            (true, _) => input.unseen_inner,
            // The whole stream, and it decodes to nothing but an error.
            (false, true) => return None,
            // The whole stream, cleanly empty.
            (false, false) => Chain::Raw,
        }
    } else {
        match resolve_checked(reg, None, &decoded.bytes, whole) {
            Ok((inner @ Chain::Container { .. }, Evidence::Confirmed)) => inner,
            Ok((Chain::Codec { codec: nested, .. }, Evidence::Confirmed))
                if depth + 1 < MAX_CHAIN_DEPTH =>
            {
                let nested_input = StrictInput {
                    bytes: &decoded.bytes,
                    cut: !whole,
                    unseen_inner: Chain::Raw,
                };
                // A nested codec whose own bytes decode to nothing is not a
                // reason to disown the layer above, which did decode: that
                // layer is then a codec over opaque bytes.
                strict_codec_layer(reg, nested, nested_input, opts, depth + 1).unwrap_or(Chain::Raw)
            }
            // No magic at all in what came out: the name may still speak for
            // a magicless inner layer (a v7 tar has no `ustar`), but only
            // where that layer's own check accepts the bytes.
            _ if reg.match_magic(&decoded.bytes).is_empty() => match input.unseen_inner {
                Chain::Container { container }
                    if reg.confirm(container, &decoded.bytes, whole) != Some(false) =>
                {
                    Chain::Container { container }
                }
                _ => Chain::Raw,
            },
            _ => Chain::Raw,
        }
    };
    Some(Chain::Codec {
        codec,
        inner: Box::new(inner),
    })
}

/// What [`decode_prefix`] got out of a decoder.
struct DecodedPrefix {
    /// Up to [`PROBE_LEN`] decoded bytes.
    bytes: Vec<u8>,
    /// The read stopped on an error rather than at the window or at EOF.
    failed: bool,
}

impl DecodedPrefix {
    /// The decoded bytes are the layer's entire stream: it ended cleanly
    /// before filling the window.
    fn is_whole(&self) -> bool {
        !self.failed && self.bytes.len() < PROBE_LEN
    }
}

/// How many `Interrupted` reads in a row [`decode_prefix`] retries before
/// taking the decoder at its word that it cannot make progress. A real
/// `EINTR` clears on the next call; a decoder that answers `Interrupted`
/// forever would otherwise hang a folder listing on one file.
const MAX_INTERRUPTED_RETRIES: usize = 64;

/// Up to [`PROBE_LEN`] bytes of `codec`'s decoding of `bytes`, keeping what
/// arrives before any read error. `None` only when the decoder refuses at
/// construction.
fn decode_prefix(
    reg: &Registry,
    codec: FormatId,
    bytes: &[u8],
    opts: &DecodeOpts,
) -> Option<DecodedPrefix> {
    // Copied because a decoder takes a `Box<dyn Source>`, which is `'static`:
    // it cannot borrow the caller's prefix. At most `PROBE_LEN` bytes.
    let src = Box::new(crate::source::ReaderSource::new(std::io::Cursor::new(
        bytes.to_vec(),
    )));
    let mut decoder = build_decoder(reg, codec, src, opts).ok()?;
    let mut out = vec![0u8; PROBE_LEN];
    let mut filled = 0;
    let mut failed = false;
    let mut interrupted = 0;
    while filled < PROBE_LEN {
        match std::io::Read::read(&mut decoder, &mut out[filled..]) {
            Ok(0) => break,
            Ok(n) => {
                filled += n;
                interrupted = 0;
            }
            Err(e)
                if e.kind() == std::io::ErrorKind::Interrupted
                    && interrupted < MAX_INTERRUPTED_RETRIES =>
            {
                interrupted += 1;
            }
            Err(_) => {
                failed = true;
                break;
            }
        }
    }
    out.truncate(filled);
    Some(DecodedPrefix { bytes: out, failed })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::archive::{Codec, DecodeOpts, EncodeOpts, Sink};
    use crate::format::{CodecCaps, FormatId, FormatMeta, MagicRule};
    use crate::registry::Registry;
    use crate::source::{ReaderSource, Source, StreamOnly};
    use crate::testing::{
        MOCK_CODEC, MOCK_CONTAINER, MockCodec, MockContainer, SharedBuf, mock_archive_bytes,
    };
    use std::io;
    use std::io::{Read, Write};
    use std::path::Path;
    use std::sync::Arc;

    const GZIP: FormatId = FormatId::new("gzip");
    const TAR: FormatId = FormatId::new("tar");

    const GZIP_MAGIC: &[MagicRule] = &[MagicRule {
        offset: 0,
        bytes: &[0x1f, 0x8b],
        format: GZIP,
    }];
    const TAR_MAGIC: &[MagicRule] = &[MagicRule {
        offset: 257,
        bytes: b"ustar",
        format: TAR,
    }];

    fn registry() -> Registry {
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(GZIP, &["gz", "tgz"], GZIP_MAGIC),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(TAR, &["tar"], TAR_MAGIC),
        );
        r
    }

    /// `registry()` above registers the mock codec under BOTH `gz` and `tgz`,
    /// and the mock container under `tar` — exactly the shape the compound
    /// alias needs, so no new fixture is required here.
    #[test]
    fn an_output_path_resolves_to_the_chain_its_name_promises() {
        let reg = registry();
        let c = |p: &str| chain_for_new_path(&reg, Path::new(p)).describe();
        assert_eq!(c("x.tar"), "tar");
        assert_eq!(c("x.gz"), "gzip");
        assert_eq!(c("x.tar.gz"), "tar over gzip");
        assert_eq!(
            c("x.tgz"),
            "tar over gzip",
            "the compound alias must resolve too"
        );
        assert_eq!(c("x.TAR.GZ"), "tar over gzip", "extensions are caseless");
        assert_eq!(c("x.txt"), "raw");
        assert_eq!(c("x"), "raw");
    }

    /// Finding 4 of the Phase 2c final review. `bzip2` registers `bz2` and
    /// nothing else, so stripping `.tbz`'s `t` looked up `bz`, found no
    /// format, and resolved the whole name to [`Chain::Raw`] — which on the
    /// write side is not a refusal but a silent fall back to the default
    /// codec, so `-o f.tbz` wrote a gzip with no tar inside it at exit 0.
    ///
    /// The registry is deliberately the one place NOT fixed: `.bz` is bzip1.
    #[test]
    fn tbz_means_tar_over_bzip2_without_making_plain_bz_writable() {
        const BZIP2: FormatId = FormatId::new("bzip2");
        const BZIP2_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"BZh",
            format: BZIP2,
        }];
        let mut reg = Registry::new();
        // `bz2` ONLY — the real bzip2 codec's whole extension list.
        reg.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(BZIP2, &["bz2"], BZIP2_MAGIC),
        );
        reg.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(TAR, &["tar"], TAR_MAGIC),
        );

        let c = |p: &str| chain_for_new_path(&reg, Path::new(p)).describe();
        assert_eq!(
            c("f.tbz"),
            "tar over bzip2",
            "GNU tar and libarchive both read .tbz as tar.bz2"
        );
        assert_eq!(c("f.TBZ"), "tar over bzip2", "and extensions are caseless");
        assert_eq!(
            c("f.tbz2"),
            "tar over bzip2",
            "the spelling that always worked must keep working"
        );
        assert_eq!(
            c("f.tar.bz2"),
            "tar over bzip2",
            "and so must the long form"
        );

        // The half that says WHERE the fix lives. `bz` is bzip1, a different
        // and obsolete format: registering it on bzip2 would have fixed
        // `.tbz` and simultaneously made `-o f.bz` write a bzip2 stream under
        // a name that promises bzip1.
        assert_eq!(
            c("f.bz"),
            "raw",
            "`bz` must resolve to nothing outside the t-prefixed compound form"
        );

        // The READ side resolves the same name through the same function —
        // that sharing is the point, and a second write-side table is what
        // would let `.tbz` mean one thing to `pack` and another to `list`.
        let chain = resolve_chain(&reg, Some(Path::new("f.tbz")), b"BZh\0").unwrap();
        assert_eq!(
            chain.describe(),
            "tar over bzip2",
            "reading a .tbz must agree with writing one"
        );
    }

    /// The pair a writer actually consumes: the container to create, and the
    /// codec to create FIRST because the container writes into it.
    #[test]
    fn the_outermost_codec_is_the_layer_a_writer_creates_first() {
        let reg = registry();
        let pair = |p: &str| {
            let c = chain_for_new_path(&reg, Path::new(p));
            (c.container(), c.outermost_codec())
        };
        assert_eq!(pair("x.tar"), (Some(TAR), None));
        assert_eq!(pair("x.gz"), (None, Some(GZIP)));
        assert_eq!(pair("x.tar.gz"), (Some(TAR), Some(GZIP)));
        assert_eq!(pair("x.tgz"), (Some(TAR), Some(GZIP)));
        assert_eq!(pair("x.txt"), (None, None));
    }

    #[test]
    fn probe_does_not_consume_the_stream() {
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(
            b"HEADERbody".to_vec(),
        )));
        let (prefix, mut rest) = probe(src).unwrap();
        assert_eq!(&prefix[..6], b"HEADER");

        let mut all = Vec::new();
        rest.read_to_end(&mut all).unwrap();
        assert_eq!(all, b"HEADERbody", "the consumer must still see byte zero");
    }

    #[test]
    fn probe_reads_at_most_the_window() {
        let big = vec![b'x'; PROBE_LEN * 3];
        let src: Box<dyn Source> = Box::new(ReaderSource::new(std::io::Cursor::new(big)));
        let (prefix, _) = probe(src).unwrap();
        assert_eq!(prefix.len(), PROBE_LEN);
    }

    #[test]
    fn magic_identifies_a_bare_codec_stream() {
        let r = registry();
        let chain = resolve_chain(&r, Some(Path::new("blob.gz")), &[0x1f, 0x8b, 0x08]).unwrap();
        assert_eq!(
            chain,
            Chain::Codec {
                codec: GZIP,
                inner: Box::new(Chain::Raw)
            }
        );
        assert_eq!(chain.describe(), "gzip");
    }

    #[test]
    fn a_double_extension_nests_the_container_inside_the_codec() {
        let r = registry();
        let chain = resolve_chain(&r, Some(Path::new("out.tar.gz")), &[0x1f, 0x8b, 0x08]).unwrap();
        assert_eq!(
            chain,
            Chain::Codec {
                codec: GZIP,
                inner: Box::new(Chain::Container { container: TAR })
            }
        );
        assert_eq!(chain.describe(), "tar over gzip");
    }

    #[test]
    fn a_codec_on_stdin_resolves_to_raw_inner() {
        // No path means no extension hint. Phase 2 refines this by peeking
        // after the first decoded block; until then Raw is the honest answer.
        let r = registry();
        let chain = resolve_chain(&r, None, &[0x1f, 0x8b, 0x08]).unwrap();
        assert_eq!(
            chain,
            Chain::Codec {
                codec: GZIP,
                inner: Box::new(Chain::Raw)
            }
        );
    }

    #[test]
    fn container_magic_resolves_directly() {
        let r = registry();
        let mut prefix = vec![0u8; 512];
        prefix[257..262].copy_from_slice(b"ustar");
        let chain = resolve_chain(&r, Some(Path::new("x.tar")), &prefix).unwrap();
        assert_eq!(chain, Chain::Container { container: TAR });
        assert_eq!(chain.describe(), "tar");
    }

    #[test]
    fn extension_is_the_fallback_when_magic_says_nothing() {
        let r = registry();
        let chain = resolve_chain(&r, Some(Path::new("mystery.tar")), b"no magic here").unwrap();
        assert_eq!(chain, Chain::Container { container: TAR });
    }

    /// `Chain::container` must see THROUGH codec layers, not only name a
    /// bare container. `ops::inspect` uses it to decide whether it may report
    /// a fidelity conclusion, and `backup.tar.gz` has a container it has not
    /// opened just as surely as `backup.tar` does — a non-recursive version
    /// would quietly re-introduce the false negative for every `.tar.gz`.
    #[test]
    fn chain_container_sees_through_codec_layers() {
        let tar = FormatId::new("tar");
        assert_eq!(Chain::Container { container: tar }.container(), Some(tar));
        assert_eq!(
            Chain::Codec {
                codec: GZIP,
                inner: Box::new(Chain::Container { container: tar }),
            }
            .container(),
            Some(tar),
            "tar over gzip still has a container nobody has opened"
        );
        assert_eq!(
            Chain::Codec {
                codec: GZIP,
                inner: Box::new(Chain::Raw),
            }
            .container(),
            None,
            "a bare codec stream has no container, so an empty warning list is a real finding"
        );
        assert_eq!(Chain::Raw.container(), None);
    }

    #[test]
    fn tgz_single_extension_still_nests_tar_inside_gzip() {
        let r = registry();
        let chain = resolve_chain(&r, Some(Path::new("a.tgz")), &[0x1f, 0x8b]).unwrap();
        assert_eq!(
            chain,
            Chain::Codec {
                codec: GZIP,
                inner: Box::new(Chain::Container { container: TAR })
            }
        );
    }

    #[test]
    fn a_compound_extension_resolves_without_a_registered_compound_alias() {
        // `.tgz` means "t" + gzip's own extension. Resolving it must not depend
        // on gzip having separately registered "tgz" itself: a codec that
        // forgets that alias would otherwise silently yield Raw instead of
        // tar-over-<codec>, with no error raised.
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(GZIP, &["gz"], GZIP_MAGIC), // deliberately NO "tgz" alias
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(TAR, &["tar"], TAR_MAGIC),
        );

        let chain = resolve_chain(&r, Some(Path::new("a.tgz")), &[0x1f, 0x8b]).unwrap();
        assert_eq!(
            chain,
            Chain::Codec {
                codec: GZIP,
                inner: Box::new(Chain::Container { container: TAR })
            }
        );
    }

    #[test]
    fn probe_does_not_consume_a_seekable_stream_either() {
        // Non-consumption has two implementations — rewind for a seekable
        // source, replay for a pipe. Only the pipe path was covered.
        let mut f = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut f, b"HEADERbody").unwrap();
        let (_, path) = f.keep().unwrap();
        let src: Box<dyn Source> = Box::new(crate::source::FileSource::open(&path).unwrap());

        let (prefix, mut rest) = probe(src).unwrap();
        assert_eq!(&prefix[..6], b"HEADER");

        let mut all = Vec::new();
        rest.read_to_end(&mut all).unwrap();
        assert_eq!(
            all, b"HEADERbody",
            "a seekable source must be rewound to byte zero"
        );
    }

    #[test]
    fn probe_bounds_the_window_on_a_seekable_stream_too() {
        let big = vec![b'x'; PROBE_LEN * 3];
        let mut f = tempfile::NamedTempFile::new().unwrap();
        std::io::Write::write_all(&mut f, &big).unwrap();
        let (_, path) = f.keep().unwrap();
        let src: Box<dyn Source> = Box::new(crate::source::FileSource::open(&path).unwrap());

        let (prefix, _) = probe(src).unwrap();
        assert_eq!(prefix.len(), PROBE_LEN);
    }

    #[test]
    fn unknown_input_names_the_bytes_it_actually_saw() {
        // Debugging a misdetection must not require adding prints to the library.
        let r = registry();
        let err = resolve_chain(&r, None, &[0xde, 0xad, 0xbe, 0xef]).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("de ad be ef"), "message was: {msg}");
        assert!(matches!(err, crate::Error::UnknownFormat { .. }));
    }

    #[test]
    fn unknown_empty_input_still_produces_a_usable_message() {
        let r = registry();
        let err = resolve_chain(&r, None, b"").unwrap_err();
        assert!(err.to_string().contains("empty"));
    }

    #[test]
    fn equally_ranked_candidates_with_no_extension_are_an_error_not_a_guess() {
        // A piped stream has no path to disambiguate with. Guessing silently is
        // how a zip becomes an apk.
        const A: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("alpha"),
        }];
        const B: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("beta"),
        }];
        let mut r = Registry::new();
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("alpha"), &["alpha"], A),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("beta"), &["beta"], B),
        );

        let err = resolve_chain(&r, None, b"PKrest").unwrap_err();
        assert!(matches!(err, crate::Error::AmbiguousFormat { .. }));
        let msg = err.to_string();
        assert!(
            msg.contains("alpha") && msg.contains("beta"),
            "must name the candidates: {msg}"
        );
        // Exit 2, not 1. The message says "Pass `--format` to choose" —
        // actionable advice, so this is the caller pointing stuffr at
        // something it cannot resolve alone, the same class as
        // `UnknownFormat` and `NotAnArchive`. It fell through
        // `exit_code`'s wildcard to 1 (an internal failure) until the
        // Phase 2 final review; see `error.rs`'s
        // `pointing_a_verb_at_the_wrong_file_is_always_exit_two`.
        assert_eq!(err.exit_code(), 2);
    }

    #[test]
    fn a_higher_priority_candidate_resolves_without_an_extension() {
        const A: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("alpha"),
        }];
        const B: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("beta"),
        }];
        let mut r = Registry::new();
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("alpha"), &["alpha"], A).with_priority(-5),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("beta"), &["beta"], B),
        );

        let chain = resolve_chain(&r, None, b"PKrest").unwrap();
        assert_eq!(
            chain,
            Chain::Container {
                container: FormatId::new("beta")
            }
        );
    }

    #[test]
    fn an_extension_still_disambiguates_equal_candidates() {
        const A: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("alpha"),
        }];
        const B: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("beta"),
        }];
        let mut r = Registry::new();
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("alpha"), &["alpha"], A),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("beta"), &["beta"], B),
        );

        let chain = resolve_chain(&r, Some(Path::new("x.beta")), b"PKrest").unwrap();
        assert_eq!(
            chain,
            Chain::Container {
                container: FormatId::new("beta")
            }
        );
    }

    #[test]
    fn an_extension_outside_the_tied_set_does_not_break_the_tie() {
        // A tie between two formats sharing a magic, with a path whose
        // extension names a THIRD format that does not share it. The extension
        // must not select a format whose magic never matched, and the error
        // must name the genuinely tied candidates rather than the irrelevant
        // one.
        const A: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("alpha"),
        }];
        const B: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("beta"),
        }];
        const C: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"GZ",
            format: FormatId::new("gamma"),
        }];
        let mut r = Registry::new();
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("alpha"), &["alpha"], A),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("beta"), &["beta"], B),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("gamma"), &["gamma"], C),
        );

        let err = resolve_chain(&r, Some(Path::new("x.gamma")), b"PKrest").unwrap_err();
        assert!(matches!(err, crate::Error::AmbiguousFormat { .. }));
        let msg = err.to_string();
        assert!(
            msg.contains("alpha") && msg.contains("beta"),
            "must name the tied candidates: {msg}"
        );
        assert!(
            !msg.contains("gamma"),
            "must not name the irrelevant extension: {msg}"
        );
    }

    #[test]
    fn an_extension_reaches_a_lower_priority_format_that_shares_the_magic() {
        // The spec's worked example: zip outranks apk on a bare stream, but a
        // path saying `.apk` must still reach apk. Ranking must not override an
        // explicit filename.
        const ZIP_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("zip"),
        }];
        const APK_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"PK",
            format: FormatId::new("apk"),
        }];
        let mut r = Registry::new();
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("zip"), &["zip"], ZIP_MAGIC),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(FormatId::new("apk"), &["apk"], APK_MAGIC).with_priority(-5),
        );

        // With no path, the higher-priority zip wins on the bare magic hit.
        let chain = resolve_chain(&r, None, b"PKrest").unwrap();
        assert_eq!(
            chain,
            Chain::Container {
                container: FormatId::new("zip")
            }
        );

        // Same bytes, but the path names apk — the lower-ranked candidate must
        // still be reached; ranking cannot pre-empt an explicit filename.
        let chain = resolve_chain(&r, Some(Path::new("archive.apk")), b"PKrest").unwrap();
        assert_eq!(
            chain,
            Chain::Container {
                container: FormatId::new("apk")
            }
        );
    }

    /// A `Source` that lies: it claims `seekable: true` but `as_seek()`
    /// always returns `None`. Nothing in this crate can implement `Source`
    /// this way today, but the trait is public and a third-party codec could
    /// — the point of this test is that `probe` must survive that instead of
    /// panicking.
    struct LiesAboutSeekability(std::io::Cursor<Vec<u8>>);

    impl Read for LiesAboutSeekability {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            std::io::Read::read(&mut self.0, buf)
        }
    }

    impl Source for LiesAboutSeekability {
        fn caps(&self) -> crate::source::SourceCaps {
            crate::source::SourceCaps {
                seekable: true,
                len: Some(self.0.get_ref().len() as u64),
            }
        }

        fn as_seek(&mut self) -> Option<&mut dyn crate::source::SeekRead> {
            None
        }
    }

    #[test]
    fn a_source_that_claims_seekable_but_has_no_seek_view_errors_instead_of_panicking() {
        let src: Box<dyn Source> = Box::new(LiesAboutSeekability(std::io::Cursor::new(
            b"payload".to_vec(),
        )));
        // Not `.unwrap_err()`: the `Ok` side is `(Vec<u8>, Box<dyn Source>)`,
        // and `Source` is not `Debug`, so `Result::unwrap_err`'s `T: Debug`
        // bound can't be satisfied here.
        match probe(src) {
            Err(err) => assert!(
                matches!(err, crate::Error::NotSeekable { .. }),
                "must be NotSeekable, not a panic: {err:?}"
            ),
            Ok(_) => panic!("expected NotSeekable, got Ok"),
        }
    }

    // --- Peek-based inner resolution (Task 4) -----------------------------
    //
    // `testing::MockCodec`'s bitwise-NOT transform is its own inverse:
    // encoding through it an EVEN number of times reproduces the original
    // bytes exactly, which would make a nesting-depth test silently
    // degenerate (the "6-deep" stream would collapse back to the bare
    // container and never exercise the bound at all). `PrefixedMockCodec`
    // instead prepends a fixed magic and passes the payload through
    // unchanged, so decoding always strips exactly one layer no matter how
    // many are stacked.
    const NESTED_MAGIC: &[u8] = b"MOCK";

    struct PrefixedMockCodec;

    impl Codec for PrefixedMockCodec {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps {
                encode: true,
                decode: true,
                ..Default::default()
            }
        }

        fn decoder<'a>(
            &self,
            mut src: Box<dyn Source + 'a>,
            _o: &DecodeOpts,
        ) -> Result<Box<dyn Source + 'a>> {
            let mut discard = vec![0u8; NESTED_MAGIC.len()];
            src.read_exact(&mut discard)?;
            Ok(Box::new(StreamOnly::new(src)))
        }

        fn encoder(
            &self,
            mut dst: Box<dyn Write + Send>,
            _o: &EncodeOpts,
        ) -> Result<Box<dyn Sink>> {
            dst.write_all(NESTED_MAGIC)?;
            Ok(Box::new(PassthroughSink(dst)))
        }
    }

    struct PassthroughSink(Box<dyn Write + Send>);

    impl Write for PassthroughSink {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0.write(buf)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.0.flush()
        }
    }

    impl Sink for PassthroughSink {
        fn finish(mut self: Box<Self>) -> Result<()> {
            self.0.flush()?;
            Ok(())
        }
    }

    fn mock_registry_with_codec_and_container() -> Registry {
        const CODEC_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: NESTED_MAGIC,
            format: MOCK_CODEC,
        }];
        const CONTAINER_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"ME",
            format: MOCK_CONTAINER,
        }];
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(PrefixedMockCodec),
            FormatMeta::codec(MOCK_CODEC, &["mock"], CODEC_MAGIC),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(MOCK_CONTAINER, &["mar"], CONTAINER_MAGIC),
        );
        r
    }

    /// Wraps `payload` in one `PrefixedMockCodec` layer, via the codec's own
    /// `encoder` rather than hand-building the bytes, so the fixture is
    /// provably decodable by the exact codec `resolve_chain_deep` will call.
    fn mock_codec_encode(payload: &[u8]) -> Vec<u8> {
        let sink = SharedBuf::new();
        let mut s = PrefixedMockCodec
            .encoder(Box::new(sink.clone()), &EncodeOpts::default())
            .unwrap();
        s.write_all(payload).unwrap();
        s.finish().unwrap();
        sink.contents()
    }

    #[test]
    fn a_container_inside_a_codec_resolves_from_the_stream_with_no_path() {
        let reg = mock_registry_with_codec_and_container();
        let inner = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let outer = mock_codec_encode(&inner);

        let (chain, _src) = resolve_chain_deep(
            &reg,
            None,
            Box::new(ReaderSource::new(io::Cursor::new(outer))),
        )
        .expect("resolve");

        // Before this task the inner layer was Chain::Raw, because no path meant
        // no extension to consult. The prefix of the DECODED stream now decides.
        assert_eq!(
            chain,
            Chain::Codec {
                codec: MOCK_CODEC,
                inner: Box::new(Chain::Container {
                    container: MOCK_CONTAINER
                }),
            },
            "a container nested inside a codec must be found by peeking the decoded stream"
        );
    }

    #[test]
    fn nesting_beyond_the_depth_bound_is_a_typed_error_naming_the_depth() {
        let reg = mock_registry_with_codec_and_container();
        let mut bytes = mock_archive_bytes(&[("a.txt", b"alpha")]);
        for _ in 0..MAX_CHAIN_DEPTH + 2 {
            bytes = mock_codec_encode(&bytes);
        }

        // Not `.expect_err(..)`: the `Ok` side is `(Chain, Box<dyn Source>)`,
        // and `Source` is not `Debug`, so `Result::expect_err`'s `T: Debug`
        // bound can't be satisfied here — same reason as
        // `a_source_that_claims_seekable_but_has_no_seek_view_errors_instead_of_panicking`
        // above.
        match resolve_chain_deep(
            &reg,
            None,
            Box::new(ReaderSource::new(io::Cursor::new(bytes))),
        ) {
            Err(Error::ChainTooDeep { depth }) => assert_eq!(depth, MAX_CHAIN_DEPTH),
            Err(other) => panic!("expected ChainTooDeep, got {other:?}"),
            Ok(_) => panic!("nesting past the bound must be refused"),
        }
    }

    #[test]
    fn nesting_beyond_the_depth_bound_is_refused_via_the_path_route_too() {
        // A path is a name, not a proof: `a.gz.gz.gz.gz.gz` must be refused
        // exactly like the identical bytes arriving with no path at all.
        // `mock_registry_with_codec_and_container` only ever exposes a
        // single extension per format ("mock"), so a path naming it gives
        // `inner_from_path` nothing to find a container with — the chain
        // still bottoms out at Raw, and peeking (and the bound) must engage
        // all the same.
        let reg = mock_registry_with_codec_and_container();
        let mut bytes = mock_archive_bytes(&[("a.txt", b"alpha")]);
        for _ in 0..MAX_CHAIN_DEPTH + 2 {
            bytes = mock_codec_encode(&bytes);
        }

        match resolve_chain_deep(
            &reg,
            Some(Path::new("nested.mock")),
            Box::new(ReaderSource::new(io::Cursor::new(bytes))),
        ) {
            Err(Error::ChainTooDeep { depth }) => assert_eq!(depth, MAX_CHAIN_DEPTH),
            Err(other) => panic!("expected ChainTooDeep, got {other:?}"),
            Ok(_) => panic!("nesting past the bound must be refused, path or no path"),
        }
    }

    // --- Task 4b: a decoder-side io::Error must reclassify; a raw-source
    // one must not -------------------------------------------------------

    /// A `Source` whose every read raises `InvalidData` — used two ways
    /// below: wrapped as the return of a codec's own `decoder()` (so the
    /// failure looks exactly like a corrupt payload discovered only once
    /// something reads the decoded bytes), and handed directly to
    /// `resolve_chain_deep` as the RAW top-level source (so the identical
    /// error kind arises before any codec is even involved). The two tests
    /// using it must disagree on the resulting `Error` variant — that
    /// disagreement is the whole point of Task 4b's fix.
    struct AlwaysInvalidData;

    impl Read for AlwaysInvalidData {
        fn read(&mut self, _buf: &mut [u8]) -> std::io::Result<usize> {
            Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "decoded bytes are malformed",
            ))
        }
    }

    impl Source for AlwaysInvalidData {
        fn caps(&self) -> crate::source::SourceCaps {
            crate::source::SourceCaps {
                seekable: false,
                len: None,
            }
        }

        fn as_seek(&mut self) -> Option<&mut dyn crate::source::SeekRead> {
            None
        }
    }

    /// A codec whose `decoder()` construction always succeeds but whose FIRST
    /// read fails with `InvalidData`, standing in for a corrupt payload behind
    /// an intact-looking header.
    ///
    /// `zlib.rs` is the lazy shape this models. Do NOT read it as "every real
    /// codec constructs lazily" — `xz_pure.rs` and `lzip.rs` both read at
    /// construction (`fill_buf()`), and reach the same place only because they
    /// end in `.unwrap_or(&[])`, which swallows the failure and defers it to
    /// the re-probe read this module classifies. An earlier version of this
    /// comment named `lzip.rs` as an example of the convention it contradicts.
    struct FailingDecodeCodec;

    impl Codec for FailingDecodeCodec {
        fn id(&self) -> FormatId {
            FormatId::new("always-fails-to-decode")
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps {
                encode: false,
                decode: true,
                ..Default::default()
            }
        }

        fn decoder<'a>(
            &self,
            _src: Box<dyn Source + 'a>,
            _o: &DecodeOpts,
        ) -> Result<Box<dyn Source + 'a>> {
            Ok(Box::new(AlwaysInvalidData))
        }

        fn encoder(&self, _dst: Box<dyn Write + Send>, _o: &EncodeOpts) -> Result<Box<dyn Sink>> {
            unimplemented!("this test never encodes")
        }
    }

    /// The fix itself: a codec stream with no container above it (so
    /// resolution bottoms out at `Chain::Raw` and re-probes the decoded
    /// bytes, per `resolve_chain_deep_with`'s own doc comment) whose decoded
    /// bytes turn out to be malformed must report `Error::Corrupt` — exit 5
    /// — not `Error::Io`. Before Task 4b's fix this was `Err(Error::Io(_))`,
    /// the identical bug `list_reports_a_truncated_codec_stream_as_corrupt_
    /// not_as_an_io_failure` and `list_reports_an_empty_lzip_stream_as_
    /// corrupt_not_as_an_io_failure` pin at the CLI level with the real
    /// zlib and lzip codecs.
    #[test]
    fn a_decoder_side_io_error_while_re_probing_becomes_corrupt() {
        let mut reg = Registry::new();
        const FAILING: FormatId = FormatId::new("always-fails-to-decode");
        const FAILING_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: &[0xab, 0xcd],
            format: FAILING,
        }];
        reg.register_codec(
            Arc::new(FailingDecodeCodec),
            FormatMeta::codec(FAILING, &["fail"], FAILING_MAGIC),
        );

        // Real, readable bytes for the RAW top-level probe to sniff magic
        // from — only the DECODED stream (`AlwaysInvalidData`) ever fails.
        let bytes = vec![0xab, 0xcd, 0x00, 0x00];
        match resolve_chain_deep(
            &reg,
            None,
            Box::new(ReaderSource::new(io::Cursor::new(bytes))),
        ) {
            Err(Error::Corrupt(msg)) => assert!(
                msg.contains("malformed"),
                "must carry the decoder's own message via Error::from_decode_io: {msg}"
            ),
            Err(other) => panic!("expected Corrupt (a decoder-side read failed), got {other:?}"),
            Ok(_) => panic!("a decoder that always fails to read cannot resolve successfully"),
        }
    }

    /// A codec that validates its header inside `decoder()` and REFUSES
    /// there — before a single decoded byte exists, so before
    /// [`crate::source::DecodeSideSource`] can mark anything — must still
    /// report `Error::Corrupt`.
    ///
    /// No registered codec takes this branch today; `.Z` parses its header
    /// lazily and every other decoder here is a `Read` adapter built without
    /// touching the source. It is pinned anyway, and `build_decoder` folds it
    /// anyway, because "unreached and wrong by default" is precisely the
    /// shape this class keeps recurring in: Task 4b closed the re-probe call,
    /// the ladder's spool was still open, and the enumeration that found the
    /// spool found this too. `CLAUDE.md`'s Phase 3c backlog records the same
    /// gap from the other side, against `conformance.rs:393`.
    #[test]
    fn a_decoder_that_refuses_at_construction_is_corrupt_not_an_io_failure() {
        struct RefusesToBuild;

        impl Codec for RefusesToBuild {
            fn id(&self) -> FormatId {
                FormatId::new("refuses-to-build")
            }

            fn caps(&self) -> CodecCaps {
                CodecCaps {
                    encode: false,
                    decode: true,
                    ..Default::default()
                }
            }

            fn decoder<'a>(
                &self,
                _src: Box<dyn Source + 'a>,
                _o: &DecodeOpts,
            ) -> Result<Box<dyn Source + 'a>> {
                Err(Error::Io(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "the header is malformed and I will not build a decoder for it",
                )))
            }

            fn encoder(
                &self,
                _dst: Box<dyn Write + Send>,
                _o: &EncodeOpts,
            ) -> Result<Box<dyn Sink>> {
                unimplemented!("this test never encodes")
            }
        }

        const REFUSES: FormatId = FormatId::new("refuses-to-build");
        const REFUSES_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: &[0xab, 0xcd],
            format: REFUSES,
        }];

        let mut reg = Registry::new();
        reg.register_codec(
            Arc::new(RefusesToBuild),
            FormatMeta::codec(REFUSES, &["refuse"], REFUSES_MAGIC),
        );

        // Both routes through `resolve_chain_deep_with` build a decoder — the
        // path route via `decode_through_chain`, the pathless one via the
        // re-probe loop — so both are checked, and both go through
        // `build_decoder`.
        for path in [None, Some(Path::new("thing.refuse"))] {
            let bytes = vec![0xab, 0xcd, 0x00, 0x00];
            match resolve_chain_deep(
                &reg,
                path,
                Box::new(ReaderSource::new(io::Cursor::new(bytes))),
            ) {
                Err(Error::Corrupt(msg)) => assert!(
                    msg.contains("malformed"),
                    "must carry the codec's own message: {msg}"
                ),
                Err(other) => panic!("expected Corrupt for path {path:?}, got {other:?}"),
                Ok(_) => panic!("a codec that refuses to build cannot resolve successfully"),
            }
        }
    }

    /// The hazard side: the SAME `InvalidData` error kind, but raised by the
    /// RAW source before any codec is even chosen, must stay `Error::Io` —
    /// exit 1 — never `Error::Corrupt`. This is what a fix that reclassified
    /// too broadly (inside `probe`/`PeekSource::fill` themselves, or at
    /// `resolve_chain_deep_with`'s own top-level `probe(src)` call) would
    /// get wrong: it has nothing to do with the error's `ErrorKind`, only
    /// with WHICH read produced it, so this guard cannot be satisfied by
    /// checking the kind alone the way the CLI-level directory test does.
    #[test]
    fn a_raw_source_io_error_of_the_identical_kind_stays_io_not_corrupt() {
        let reg = mock_registry_with_codec_and_container();
        match resolve_chain_deep(&reg, None, Box::new(AlwaysInvalidData)) {
            Err(Error::Io(io_err)) => assert_eq!(
                io_err.kind(),
                std::io::ErrorKind::InvalidData,
                "sanity: this must be the same error kind the test above reclassifies, so the \
                 two tests differ only in WHERE the read happened"
            ),
            Err(other) => panic!(
                "a raw-source failure must stay Io, not become {other:?} — reclassifying it \
                 would be a lie in the opposite direction from Task 4b's bug"
            ),
            Ok(_) => panic!("a raw source that always errors cannot resolve successfully"),
        }
    }

    #[test]
    fn the_returned_source_is_decoded_through_every_codec_layer_on_both_routes() {
        // The defect this pins: the path route used to return the PRISTINE,
        // undecoded source (resolve_chain alone tells you the shape, nothing
        // decodes anything), while the no-path route returned the source
        // already peeled past every codec layer. A caller of
        // `resolve_chain_deep` cannot be expected to inspect `path.is_some()`
        // itself to know which kind of source it was just handed — both
        // routes must leave the source in the identical state: decoded
        // through every codec layer named in the returned `Chain`, ready to
        // hand straight to the container.
        //
        // "thing.mar.mock" mirrors `.tar.gz`: `inner_from_path` finds the
        // container ("mar") one extension in from the codec ("mock"), so
        // this path resolves the FULL chain in one `resolve_chain` call,
        // with no peeking at all — the route this test must prove decodes
        // its codec layer exactly as the peeling route does.
        let reg = mock_registry_with_codec_and_container();
        let inner = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let outer = mock_codec_encode(&inner);

        let (chain_with_path, mut src_with_path) = resolve_chain_deep(
            &reg,
            Some(Path::new("thing.mar.mock")),
            Box::new(ReaderSource::new(io::Cursor::new(outer.clone()))),
        )
        .expect("resolve with path");
        let (chain_no_path, mut src_no_path) = resolve_chain_deep(
            &reg,
            None,
            Box::new(ReaderSource::new(io::Cursor::new(outer))),
        )
        .expect("resolve without path");

        let expected_chain = Chain::Codec {
            codec: MOCK_CODEC,
            inner: Box::new(Chain::Container {
                container: MOCK_CONTAINER,
            }),
        };
        assert_eq!(chain_with_path, expected_chain);
        assert_eq!(chain_no_path, expected_chain);

        let mut bytes_with_path = Vec::new();
        src_with_path.read_to_end(&mut bytes_with_path).unwrap();
        let mut bytes_no_path = Vec::new();
        src_no_path.read_to_end(&mut bytes_no_path).unwrap();

        assert_eq!(
            bytes_with_path, inner,
            "the path route must decode through the codec layer, not return raw bytes"
        );
        assert_eq!(
            bytes_with_path, bytes_no_path,
            "both routes must leave the source in the identical, already-decoded state"
        );
    }
}

#[cfg(test)]
mod truthful_identification_tests {
    //! The confirmation hook, [`Evidence`], [`identify_strict`] and the
    //! foreign tail. Mock formats only: core has no real format to confirm.
    use super::*;
    use crate::archive::{Codec, DecodeOpts, EncodeOpts, Sink};
    use crate::format::{CodecCaps, ConfirmFn, FormatId, FormatMeta, MagicRule};
    use crate::registry::Registry;
    use crate::source::{ReaderSource, SeekRead, Source, SourceCaps, StreamOnly};
    use crate::testing::{
        MOCK_CODEC, MOCK_CONTAINER, MockCodec, MockContainer, mock_archive_bytes,
    };
    use std::io::{self, Read, Write};
    use std::path::Path;
    use std::sync::Arc;

    fn yes(_: &[u8], _: bool) -> bool {
        true
    }

    fn no(_: &[u8], _: bool) -> bool {
        false
    }

    /// The UDIF trailer, as the spec states it: `koly`, big-endian version 4,
    /// big-endian header size 512, zeros for the rest.
    fn koly(version: u32, size: u32) -> Vec<u8> {
        let mut t = vec![0u8; TAIL_LEN];
        t[0..4].copy_from_slice(b"koly");
        t[4..8].copy_from_slice(&version.to_be_bytes());
        t[8..12].copy_from_slice(&size.to_be_bytes());
        t
    }

    /// An in-memory seekable source: `FileSource` without the file.
    struct SeekCursor(io::Cursor<Vec<u8>>);

    impl Read for SeekCursor {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            self.0.read(buf)
        }
    }

    impl Source for SeekCursor {
        fn caps(&self) -> SourceCaps {
            SourceCaps {
                seekable: true,
                len: Some(self.0.get_ref().len() as u64),
            }
        }

        fn as_seek(&mut self) -> Option<&mut dyn SeekRead> {
            Some(&mut self.0)
        }
    }

    fn zlib_ish_image() -> Vec<u8> {
        let mut bytes = vec![0x78, 0x9c];
        bytes.extend(std::iter::repeat_n(0xa5, 1000));
        bytes.extend(koly(4, 512));
        bytes
    }

    #[test]
    fn foreign_tail_needs_signature_version_and_size() {
        assert_eq!(
            foreign_from_tail(&koly(4, 512)),
            Some(Foreign::AppleDiskImage)
        );
        assert_eq!(foreign_from_tail(&koly(3, 512)), None, "version 3");
        assert_eq!(foreign_from_tail(&koly(4, 256)), None, "header size 256");
        assert_eq!(foreign_from_tail(&koly(4, 512)[..511]), None, "511 bytes");
        let mut kolx = koly(4, 512);
        kolx[3] = b'x';
        assert_eq!(foreign_from_tail(&kolx), None, "kolx");
        assert_eq!(
            Foreign::AppleDiskImage.to_string(),
            "an Apple disk image (UDIF)"
        );
    }

    #[test]
    fn probe_refuses_a_seekable_source_with_a_koly_tail() {
        let src: Box<dyn Source> = Box::new(SeekCursor(io::Cursor::new(zlib_ish_image())));
        match probe(src) {
            Err(e) => {
                assert!(
                    matches!(e, Error::ForeignFormat(Foreign::AppleDiskImage)),
                    "{e:?}"
                );
                assert_eq!(e.exit_code(), 3);
                assert_eq!(
                    e.to_string(),
                    "this is an Apple disk image (UDIF), which stuffr cannot open"
                );
            }
            Ok(_) => panic!("a koly tail must be refused"),
        }
    }

    #[test]
    fn probe_does_not_read_the_tail_of_a_pipe() {
        let src: Box<dyn Source> = Box::new(ReaderSource::new(io::Cursor::new(zlib_ish_image())));
        let Ok((prefix, _)) = probe(src) else {
            panic!("a pipe has no tail to read, so it must probe as before");
        };
        assert_eq!(&prefix[..2], &[0x78, 0x9c]);
    }

    #[test]
    fn read_tail_leaves_a_seekable_source_at_zero() {
        let mut bytes = b"HEAD".to_vec();
        bytes.extend(vec![7u8; 600]);
        let mut src = SeekCursor(io::Cursor::new(bytes.clone()));
        let tail = read_tail(&mut src)
            .unwrap()
            .expect("600+ bytes have a tail");
        assert_eq!(tail.len(), TAIL_LEN);
        assert_eq!(tail, bytes[bytes.len() - TAIL_LEN..]);
        let mut all = Vec::new();
        src.read_to_end(&mut all).unwrap();
        assert_eq!(all, bytes, "the position must be back at byte zero");

        // Shorter than a tail: nothing read, still at zero.
        let mut short = SeekCursor(io::Cursor::new(b"tiny".to_vec()));
        assert_eq!(read_tail(&mut short).unwrap(), None);
        let mut all = Vec::new();
        short.read_to_end(&mut all).unwrap();
        assert_eq!(all, b"tiny");

        // A pipe: nothing read.
        let mut pipe = ReaderSource::new(io::Cursor::new(bytes));
        assert_eq!(read_tail(&mut pipe).unwrap(), None);
    }

    const ALPHA: FormatId = FormatId::new("alpha");
    const BETA: FormatId = FormatId::new("beta");
    const SHARED_MAGIC: &[MagicRule] = &[
        MagicRule {
            offset: 0,
            bytes: b"SH",
            format: ALPHA,
        },
        MagicRule {
            offset: 0,
            bytes: b"SH",
            format: BETA,
        },
    ];

    #[test]
    fn confirmed_candidate_beats_an_unconfirmed_one() {
        // Equal priority and no path: without confirmation this is an
        // `AmbiguousFormat`. Each way round, so the answer is not an accident
        // of id order.
        for (alpha_ok, winner) in [(true, ALPHA), (false, BETA)] {
            let mut r = Registry::new();
            let (a, b): (ConfirmFn, ConfirmFn) = if alpha_ok { (yes, no) } else { (no, yes) };
            r.register_codec(
                Arc::new(MockCodec),
                FormatMeta::codec(ALPHA, &[], SHARED_MAGIC).with_confirm(a),
            );
            r.register_codec(
                Arc::new(MockCodec),
                FormatMeta::codec(BETA, &[], SHARED_MAGIC).with_confirm(b),
            );
            let (chain, ev) = resolve_chain_checked(&r, None, b"SH..").expect("no ambiguity");
            assert_eq!(chain.outermost_codec(), Some(winner));
            assert_eq!(ev, Evidence::Confirmed);
        }
    }

    #[test]
    fn a_format_with_no_confirm_function_counts_as_confirmed() {
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(ALPHA, &[], SHARED_MAGIC).with_confirm(no),
        );
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(BETA, &[], SHARED_MAGIC),
        );
        let (chain, ev) = resolve_chain_checked(&r, None, b"SH..").unwrap();
        assert_eq!(chain.outermost_codec(), Some(BETA));
        assert_eq!(ev, Evidence::Confirmed);
    }

    #[test]
    fn unconfirmed_magic_still_resolves_leniently() {
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(ALPHA, &["al"], &SHARED_MAGIC[..1]).with_confirm(no),
        );
        let chain = resolve_chain(&r, None, b"SH..").expect("lenient resolution keeps it");
        assert_eq!(chain.outermost_codec(), Some(ALPHA));
        let (_, ev) = resolve_chain_checked(&r, None, b"SH..").unwrap();
        assert_eq!(ev, Evidence::Unconfirmed);
    }

    #[test]
    fn extension_without_confirm_is_by_name() {
        let mut r = Registry::new();
        r.register_codec(Arc::new(MockCodec), FormatMeta::codec(ALPHA, &["al"], &[]));
        let (chain, ev) = resolve_chain_checked(&r, Some(Path::new("x.al")), b"whatever").unwrap();
        assert_eq!(chain.outermost_codec(), Some(ALPHA));
        assert_eq!(ev, Evidence::ByName);
    }

    #[test]
    fn extension_with_failing_confirm_is_unconfirmed() {
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(ALPHA, &["al"], &[]).with_confirm(no),
        );
        let (_, ev) = resolve_chain_checked(&r, Some(Path::new("x.al")), b"whatever").unwrap();
        assert_eq!(ev, Evidence::Unconfirmed);

        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(ALPHA, &["al"], &[]).with_confirm(yes),
        );
        let (_, ev) = resolve_chain_checked(&r, Some(Path::new("x.al")), b"whatever").unwrap();
        assert_eq!(ev, Evidence::Confirmed);
    }

    #[test]
    fn errors_are_unchanged() {
        let r = Registry::new();
        assert!(matches!(
            resolve_chain_checked(&r, None, b"??"),
            Err(Error::UnknownFormat { .. })
        ));
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(ALPHA, &[], SHARED_MAGIC).with_confirm(no),
        );
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(BETA, &[], SHARED_MAGIC).with_confirm(no),
        );
        assert!(matches!(
            resolve_chain_checked(&r, None, b"SH"),
            Err(Error::AmbiguousFormat { .. })
        ));
    }

    // --- identify_strict -------------------------------------------------

    const LAYER_MAGIC: &[u8] = b"MOCK";

    /// Strips `LAYER_MAGIC` and passes the rest through — one layer peeled
    /// per decode, however many are stacked (`MockCodec`'s XOR would undo
    /// itself every second layer).
    struct LayerCodec;

    impl Codec for LayerCodec {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps::round_trip()
        }

        fn decoder<'a>(
            &self,
            mut src: Box<dyn Source + 'a>,
            _o: &DecodeOpts,
        ) -> Result<Box<dyn Source + 'a>> {
            let mut discard = [0u8; 4];
            src.read_exact(&mut discard)?;
            Ok(Box::new(StreamOnly::new(src)))
        }

        fn encoder(&self, _dst: Box<dyn Write + Send>, _o: &EncodeOpts) -> Result<Box<dyn Sink>> {
            unreachable!("identification never encodes")
        }
    }

    /// The mock container's record header is `ME` + a little-endian u16 name
    /// length; a name that runs past the prefix is not a mock archive.
    fn mock_archive_confirms(p: &[u8], _whole: bool) -> bool {
        p.len() >= 4 && {
            let n = u16::from_le_bytes([p[2], p[3]]) as usize;
            n > 0 && 4 + n <= p.len()
        }
    }

    fn strict_registry() -> Registry {
        const CODEC_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: LAYER_MAGIC,
            format: MOCK_CODEC,
        }];
        const CONTAINER_MAGIC: &[MagicRule] = &[MagicRule {
            offset: 0,
            bytes: b"ME",
            format: MOCK_CONTAINER,
        }];
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(LayerCodec),
            FormatMeta::codec(MOCK_CODEC, &["mock"], CODEC_MAGIC)
                .with_confirm(|p, _| p.starts_with(LAYER_MAGIC)),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(MOCK_CONTAINER, &["mar"], CONTAINER_MAGIC)
                .with_confirm(mock_archive_confirms),
        );
        r
    }

    fn layered(layers: usize, inner: &[u8]) -> Vec<u8> {
        let mut out = LAYER_MAGIC.repeat(layers);
        out.extend_from_slice(inner);
        out
    }

    fn strict(
        r: &Registry,
        path: Option<&str>,
        prefix: &[u8],
        tail: Option<&[u8]>,
    ) -> Option<Chain> {
        identify_strict(r, path.map(Path::new), prefix, tail, &DecodeOpts::default())
    }

    #[test]
    fn identify_strict_rejects_unconfirmed_and_foreign() {
        let r = strict_registry();
        assert_eq!(
            strict(&r, None, b"ME\xff\xffabc", None),
            None,
            "a magic hit whose confirmation fails is not openable"
        );
        let archive = mock_archive_bytes(&[("a.txt", b"alpha")]);
        assert_eq!(
            strict(&r, None, &archive, None),
            Some(Chain::Container {
                container: MOCK_CONTAINER
            })
        );
        assert_eq!(
            strict(&r, None, &archive, Some(&koly(4, 512))),
            None,
            "a koly tail outranks a confirmed prefix"
        );
        assert_eq!(strict(&r, None, b"nothing", None), None, "unknown");
    }

    #[test]
    fn identify_strict_decodes_the_inner_layer_from_the_prefix() {
        let r = strict_registry();
        let archive = mock_archive_bytes(&[("a.txt", b"alpha")]);
        assert_eq!(
            strict(&r, None, &layered(1, &archive), None),
            Some(Chain::Codec {
                codec: MOCK_CODEC,
                inner: Box::new(Chain::Container {
                    container: MOCK_CONTAINER
                }),
            })
        );
        assert_eq!(
            strict(&r, Some("x.mar.mock"), &layered(1, b"ME\xff\xffabc"), None),
            Some(Chain::Codec {
                codec: MOCK_CODEC,
                inner: Box::new(Chain::Raw),
            }),
            "an inner layer failing confirmation is Raw, whatever the path says"
        );
    }

    #[test]
    fn identify_strict_bounds_the_nesting() {
        let r = strict_registry();
        let archive = mock_archive_bytes(&[("a.txt", b"alpha")]);
        let depth = |c: &Chain| {
            let mut n = 0;
            let mut c = c;
            while let Chain::Codec { inner, .. } = c {
                n += 1;
                c = inner;
            }
            n
        };
        let three = strict(&r, None, &layered(3, &archive), None).unwrap();
        assert_eq!(depth(&three), 3);
        assert_eq!(three.container(), Some(MOCK_CONTAINER));
        let many = strict(&r, None, &layered(10, &archive), None).unwrap();
        assert!(depth(&many) < MAX_CHAIN_DEPTH, "{many:?}");
        assert_eq!(many.container(), None, "stopped with Raw at the bound");
    }

    /// A codec whose decoder yields `yields` and then either errors or ends.
    struct Scripted {
        yields: &'static [u8],
        then_error: bool,
    }

    struct ScriptedSource {
        rest: &'static [u8],
        then_error: bool,
    }

    impl Read for ScriptedSource {
        fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
            if self.rest.is_empty() {
                return if self.then_error {
                    Err(io::Error::new(io::ErrorKind::InvalidData, "bad stream"))
                } else {
                    Ok(0)
                };
            }
            let n = buf.len().min(self.rest.len());
            buf[..n].copy_from_slice(&self.rest[..n]);
            self.rest = &self.rest[n..];
            Ok(n)
        }
    }

    impl Source for ScriptedSource {
        fn caps(&self) -> SourceCaps {
            SourceCaps::default()
        }

        fn as_seek(&mut self) -> Option<&mut dyn SeekRead> {
            None
        }
    }

    impl Codec for Scripted {
        fn id(&self) -> FormatId {
            MOCK_CODEC
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps::decode_only()
        }

        fn decoder<'a>(
            &self,
            _src: Box<dyn Source + 'a>,
            _o: &DecodeOpts,
        ) -> Result<Box<dyn Source + 'a>> {
            Ok(Box::new(ScriptedSource {
                rest: self.yields,
                then_error: self.then_error,
            }))
        }

        fn encoder(&self, _dst: Box<dyn Write + Send>, _o: &EncodeOpts) -> Result<Box<dyn Sink>> {
            unreachable!("identification never encodes")
        }
    }

    fn scripted_registry(yields: &'static [u8], then_error: bool) -> Registry {
        let mut r = strict_registry();
        r.register_codec(
            Arc::new(Scripted { yields, then_error }),
            FormatMeta::codec(
                MOCK_CODEC,
                &["mock"],
                &[MagicRule {
                    offset: 0,
                    bytes: LAYER_MAGIC,
                    format: MOCK_CODEC,
                }],
            )
            .with_confirm(yes),
        );
        r
    }

    #[test]
    fn identify_strict_drops_a_codec_that_decodes_nothing() {
        let raw = Some(Chain::Codec {
            codec: MOCK_CODEC,
            inner: Box::new(Chain::Raw),
        });
        assert_eq!(
            strict(&scripted_registry(b"", true), None, b"MOCKjunk", None),
            None,
            "an error before the first byte: nothing here decodes"
        );
        assert_eq!(
            strict(&scripted_registry(b"", false), None, b"MOCKjunk", None),
            raw,
            "a clean, empty stream is still a stream"
        );
        assert_eq!(
            strict(
                &scripted_registry(b"plain text", true),
                None,
                b"MOCKjunk",
                None
            ),
            raw,
            "what arrived before the error is kept"
        );
    }

    /// A codec whose first block is larger than the probe window: its
    /// decoder drains the source and, short of `NEEDS` bytes, yields nothing
    /// and errors — bzip2's and zstd's behaviour on a 4096-byte prefix of a
    /// real file.
    struct NeedsMore;

    const NEEDS: usize = PROBE_LEN * 2;
    const SLOW: FormatId = FormatId::new("slow");
    const TAR: FormatId = FormatId::new("tar");

    impl Codec for NeedsMore {
        fn id(&self) -> FormatId {
            SLOW
        }

        fn caps(&self) -> CodecCaps {
            CodecCaps::decode_only()
        }

        fn decoder<'a>(
            &self,
            mut src: Box<dyn Source + 'a>,
            _o: &DecodeOpts,
        ) -> Result<Box<dyn Source + 'a>> {
            let mut all = Vec::new();
            src.read_to_end(&mut all)?;
            Ok(Box::new(ScriptedSource {
                rest: if all.len() >= NEEDS { b"payload" } else { b"" },
                then_error: all.len() < NEEDS,
            }))
        }

        fn encoder(&self, _dst: Box<dyn Write + Send>, _o: &EncodeOpts) -> Result<Box<dyn Sink>> {
            unreachable!("identification never encodes")
        }
    }

    fn needs_more_registry() -> Registry {
        let mut r = strict_registry();
        r.register_codec(
            Arc::new(NeedsMore),
            FormatMeta::codec(
                SLOW,
                &["slow"],
                &[MagicRule {
                    offset: 0,
                    bytes: b"SLOW",
                    format: SLOW,
                }],
            )
            .with_confirm(yes),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(TAR, &["tar"], &[]),
        );
        r
    }

    fn slow_prefix(len: usize) -> Vec<u8> {
        let mut p = b"SLOW".to_vec();
        p.resize(len, 0x5a);
        p
    }

    #[test]
    fn a_cut_off_prefix_that_decodes_nothing_keeps_the_codec_over_the_paths_inner() {
        let r = needs_more_registry();
        assert_eq!(
            strict(&r, Some("big.tar.slow"), &slow_prefix(PROBE_LEN), None),
            Some(Chain::Codec {
                codec: SLOW,
                inner: Box::new(Chain::Container { container: TAR }),
            }),
            "the window ran out, not the file: as 0.21.0 listed it"
        );
        assert_eq!(
            strict(&r, Some("big.slow"), &slow_prefix(PROBE_LEN), None),
            Some(Chain::Codec {
                codec: SLOW,
                inner: Box::new(Chain::Raw),
            }),
        );
    }

    #[test]
    fn a_whole_file_that_decodes_nothing_before_an_error_is_not_openable() {
        let r = needs_more_registry();
        assert_eq!(
            strict(&r, Some("small.tar.slow"), &slow_prefix(100), None),
            None,
            "the prefix is the whole file, and it decodes to nothing but an error"
        );
    }

    #[test]
    fn an_extension_naming_a_refused_hit_falls_to_the_confirmed_ones() {
        const ZIP: FormatId = FormatId::new("zip");
        const JAR: FormatId = FormatId::new("jar");
        const APK: FormatId = FormatId::new("apk");
        const PK: &[MagicRule] = &[
            MagicRule {
                offset: 0,
                bytes: b"PK",
                format: ZIP,
            },
            MagicRule {
                offset: 0,
                bytes: b"PK",
                format: JAR,
            },
            MagicRule {
                offset: 0,
                bytes: b"PK",
                format: APK,
            },
        ];
        let mut r = Registry::new();
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(ZIP, &["zip"], PK)
                .with_priority(1)
                .with_confirm(yes),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(JAR, &["jar"], PK).with_confirm(yes),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(APK, &["apk"], PK).with_confirm(no),
        );
        let (chain, ev) = resolve_chain_checked(&r, Some(Path::new("x.apk")), b"PK..").unwrap();
        assert_eq!(chain, Chain::Container { container: ZIP });
        assert_eq!(ev, Evidence::Confirmed);
    }
    // --- whole streams ----------------------------------------------------

    /// Refuses exactly what is whole and shorter than eight bytes.
    fn eight_when_whole(p: &[u8], whole: bool) -> bool {
        !whole || p.len() >= 8
    }

    #[test]
    fn a_probe_prefix_short_of_the_window_is_confirmed_as_the_whole_stream() {
        let mut r = Registry::new();
        r.register_codec(
            Arc::new(MockCodec),
            FormatMeta::codec(ALPHA, &[], &SHARED_MAGIC[..1]).with_confirm(eight_when_whole),
        );
        let ev = |prefix: &[u8]| resolve_chain_checked(&r, None, prefix).unwrap().1;
        assert_eq!(ev(b"SH"), Evidence::Unconfirmed, "a two-byte file is whole");
        assert_eq!(ev(b"SH345678"), Evidence::Confirmed);
        // A full window is never whole, however little of it the check reads.
        let mut window = vec![0u8; PROBE_LEN];
        window[..2].copy_from_slice(b"SH");
        assert_eq!(ev(&window), Evidence::Confirmed);
    }

    const PLAIN: FormatId = FormatId::new("plain");
    const WHOLE: FormatId = FormatId::new("wholecheck");

    /// `scripted_registry` plus a magicless container (`.pln`, confirmed by
    /// a leading `PL`) and one whose magic `WH` is refused only when whole.
    fn layered_registry(yields: &'static [u8], then_error: bool) -> Registry {
        let mut r = scripted_registry(yields, then_error);
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(PLAIN, &["pln"], &[]).with_confirm(|p, _| p.starts_with(b"PL")),
        );
        r.register_container(
            Arc::new(MockContainer),
            FormatMeta::container(
                WHOLE,
                &["wh"],
                &[MagicRule {
                    offset: 0,
                    bytes: b"WH",
                    format: WHOLE,
                }],
            )
            .with_confirm(eight_when_whole),
        );
        r
    }

    fn over(inner: Chain) -> Option<Chain> {
        Some(Chain::Codec {
            codec: MOCK_CODEC,
            inner: Box::new(inner),
        })
    }

    #[test]
    fn a_decoded_layer_is_whole_only_when_it_ended_cleanly_inside_the_window() {
        // Ended cleanly at two bytes: the whole inner stream, refused.
        let r = layered_registry(b"WH", false);
        assert_eq!(strict(&r, None, b"MOCKjunk", None), over(Chain::Raw));
        let chain = over(Chain::Container { container: WHOLE }).unwrap();
        assert_eq!(
            first_unconfirmed_layer(&r, &chain, b"MOCKjunk", &DecodeOpts::default()),
            Some(WHOLE)
        );
        // Stopped on an error: a cut stream, judged as one.
        let r = layered_registry(b"WH", true);
        assert_eq!(
            strict(&r, None, b"MOCKjunk", None),
            over(Chain::Container { container: WHOLE })
        );
        assert_eq!(
            first_unconfirmed_layer(&r, &chain, b"MOCKjunk", &DecodeOpts::default()),
            None
        );
    }

    #[test]
    fn decoded_bytes_with_no_magic_take_the_paths_container_when_it_confirms() {
        let plain = Chain::Container { container: PLAIN };
        let r = layered_registry(b"PLAIN DATA", false);
        assert_eq!(
            strict(&r, Some("x.pln.mock"), b"MOCKjunk", None),
            over(plain.clone()),
            "a magicless inner layer the name gives and the bytes confirm"
        );
        assert_eq!(
            strict(&r, None, b"MOCKjunk", None),
            over(Chain::Raw),
            "no name"
        );
        assert_eq!(
            strict(&r, Some("x.mock"), b"MOCKjunk", None),
            over(Chain::Raw),
            "a name with nothing inside"
        );
        let r = layered_registry(b"just text", false);
        assert_eq!(
            strict(&r, Some("x.pln.mock"), b"MOCKjunk", None),
            over(Chain::Raw),
            "the name alone is not enough when the check refuses the bytes"
        );
        // `info`'s chain for the same file names the same layer as refused.
        let (chain, _) =
            resolve_chain_checked(&r, Some(Path::new("x.pln.mock")), b"MOCKjunk").unwrap();
        assert_eq!(chain, over(plain).unwrap());
        assert_eq!(
            first_unconfirmed_layer(&r, &chain, b"MOCKjunk", &DecodeOpts::default()),
            Some(PLAIN)
        );
    }
}