stuffr-cli 0.10.4

The stuffr command line interface
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
//! The `stuffr` command.

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{CommandFactory, Parser};
use stuffr::entries::{self, ConvertOpts, ExtractOpts, SalvageOpts, Selection};
use stuffr::ops::{self, CompressOpts, DecompressOpts, Input, Output, RecompressOpts};
use stuffr::{Chain, FormatId};
use stuffr_cli::cli::{Cli, Command};

/// The `--examples` page. A static asset rather than an inline literal so it
/// reads (and diffs) like the terminal page it is, not like Rust source.
const EXAMPLES: &str = include_str!("examples.txt");

/// `-` means the stream, everywhere.
fn input_of(s: &str) -> Input {
    if s == "-" {
        Input::Stdin
    } else {
        Input::Path(PathBuf::from(s))
    }
}

fn output_of(s: &str) -> Output {
    if s == "-" {
        Output::Stdout
    } else {
        Output::Path(PathBuf::from(s))
    }
}

fn main() -> ExitCode {
    let cli = Cli::parse();

    if cli.examples {
        print!("{EXAMPLES}");
        return ExitCode::SUCCESS;
    }

    let command = match cli.command {
        Some(c) => c,
        // `command` is `Option` (rather than clap enforcing a required
        // subcommand itself) purely so `--examples` can be given with no
        // subcommand at all. Absent both, reproduce clap's own behaviour for
        // a missing required subcommand by hand: the full help, on exit 2.
        None => {
            let _ = Cli::command().print_help();
            println!();
            return ExitCode::from(2);
        }
    };

    match run(command) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("stuffr: {e}");
            ExitCode::from(e.exit_code() as u8)
        }
    }
}

/// Whether a command's output goes to stdout — the only case in which a
/// `BrokenPipe` is the reader's decision rather than this program's failure.
///
/// `Cat`, `Info`, `Formats` and `List` never write anywhere else — `List`
/// prints one line per entry (or a JSON array) straight to stdout, the same
/// early-closing-reader shape as `Cat` (e.g. `stuffr list big.tar | head`).
/// `Pack`, `Unpack` and `Convert` write to stdout only when `-o -` was passed
/// explicitly (`Convert` also takes it as its second positional); every other
/// destination is a real file, where a `BrokenPipe`
/// mid-write would mean something is actually wrong and must not be
/// swallowed (see `run`).
fn destination_is_stdout(cmd: &Command) -> bool {
    match cmd {
        Command::Cat { .. } | Command::Info { .. } | Command::Formats | Command::List { .. } => {
            true
        }
        // Only the `--list` row-per-record report is the "big data to
        // stdout" shape `Cat`/`List` are; the default summary line goes to
        // stderr the same way `unpack`/`test` print theirs.
        Command::Salvage { list, .. } => *list,
        Command::Pack {
            output: Some(o), ..
        }
        | Command::Unpack {
            output: Some(o), ..
        }
        | Command::Convert {
            output: Some(o), ..
        }
        | Command::Convert {
            output_pos: Some(o),
            ..
        } => o == "-",
        _ => false,
    }
}

fn run(command: Command) -> stuffr::Result<()> {
    let stdout_dest = destination_is_stdout(&command);
    match dispatch(command) {
        Ok(()) => Ok(()),
        // Rust ignores SIGPIPE, so a write to a closed stdout surfaces as an
        // EPIPE `io::Error` rather than terminating the process outright. An
        // early-exiting consumer — `stuffr cat huge.gz | head`, `| grep -m1`,
        // `| less` — is the flagship workflow for a `cat`-shaped tool, and
        // every conventional Unix filter (zcat, gzip -d, cat itself) treats
        // that as normal termination, not a failure. Success, no message: the
        // consumer closing the pipe is the party that decided it had seen
        // enough.
        //
        // This must NOT fire for a file destination: `stuffr unpack a.gz -o
        // file` hitting BrokenPipe (e.g. a full disk manifesting oddly) would
        // otherwise map a real failure to exit 0 — `run` returning `Err`
        // still triggers `discard`, so the temp file is removed and the
        // process would report success having produced nothing at all.
        Err(stuffr::Error::Io(e)) if stdout_dest && e.kind() == std::io::ErrorKind::BrokenPipe => {
            Ok(())
        }
        Err(e) => Err(e),
    }
}

/// Parses `--memory-limit` once, so all four subcommands report the same
/// message for the same bad input.
///
/// Was duplicated verbatim across every `dispatch` arm. Kept as a named
/// function rather than inlined because a size that parses differently
/// depending on which subcommand you typed would be a genuinely confusing bug,
/// and one copy cannot drift from another.
fn parse_memory_limit(raw: Option<String>) -> stuffr::Result<Option<u64>> {
    match raw {
        Some(s) => Ok(Some(
            stuffr_cli::size::parse_size(&s).map_err(stuffr::Error::Usage)?,
        )),
        None => Ok(None),
    }
}

fn dispatch(command: Command) -> stuffr::Result<()> {
    match command {
        Command::Pack {
            paths,
            output,
            format,
            level,
            force,
            no_sync,
            allow_weak_encoder,
            threads,
            turbo,
            memory_limit,
            strict_fidelity,
        } => {
            // Parsing (and thus validating) `--memory-limit` here, ahead of
            // `ops::resolved_budget`, is deliberate: a malformed value must
            // be caught before anything else runs.
            let memory_limit = parse_memory_limit(memory_limit)?;
            let fmt = match format.as_deref() {
                Some(name) => Some(format_by_name(name)?),
                None => None,
            };
            let opts = CompressOpts {
                format: fmt,
                level,
                force,
                sync: !no_sync,
                allow_weak_encoder,
                threads,
                turbo,
                memory_limit,
            };

            // A container output collects every path into one archive; a
            // codec output compresses exactly one stream.
            if let Some((container, codec)) = resolve_pack_chain(fmt, output.as_deref())? {
                refuse_unhonoured_encoder_flags(
                    EncoderFlags::of(&opts),
                    codec.is_some(),
                    NoCodecLayer::PackContainer,
                )?;
                let inputs = pack_inputs(&paths)?;
                let dst = match output {
                    Some(o) => output_of(&o),
                    // One path can still name its own archive
                    // (`notes.txt` + `--format tar` -> `notes.txt.tar`);
                    // several have no single name to derive from.
                    None if inputs.len() == 1 => {
                        Output::Path(ops::suggest_packed(&inputs[0], container)?)
                    }
                    None => {
                        return Err(stuffr::Error::Usage(
                            "collecting several paths into an archive needs an explicit \
                             -o NAME.tar"
                                .into(),
                        ));
                    }
                };
                let out = entries::create_archive(&inputs, dst, container, codec, &opts)?;
                // `inputs.len()` is the number of paths NAMED, which since
                // Phase 2c is no longer the number of entries written: one
                // named directory is a whole tree. Saying "paths" rather than
                // "entries" is the one-word fix; the entry count is not on
                // `Outcome` and is not worth a field there.
                // NOT `out.fidelity.rung`. `Rung` describes the adaptive READ
                // ladder; on the write side `entries::create_archive` sets it
                // to the constant `Rung::Exact`, so printing it made
                // `pack proj -o out.ar` announce "exact fidelity" and then
                // name four losses on the next four lines. A count of what
                // was actually lost is the one number here that is true, and
                // it agrees with the list `report_fidelity` prints below it.
                eprintln!(
                    "{} path(s) -> {} ({} -> {} bytes, {})",
                    inputs.len(),
                    out.format,
                    out.bytes_in,
                    out.bytes_out,
                    write_fidelity_summary(&out.fidelity)
                );
                // Said every run, and deliberately NOT routed through
                // `report_fidelity`: a note is something stuffr did correctly
                // that the user should know about, not something they lost,
                // so it must not reach the --strict-fidelity gate. See
                // `Outcome::notes`.
                for note in &out.notes {
                    eprintln!("stuffr: note: {note}");
                }
                // The same call the read side makes, not a second printer:
                // pack's fidelity report now carries real warnings (what the
                // walk could not store, what this container has no shape
                // for), and --strict-fidelity turns them into exit 4 here
                // exactly as it does for `unpack -C` and `test`.
                return report_fidelity(&out.fidelity, strict_fidelity);
            }

            if paths.len() > 1 {
                return Err(stuffr::Error::Usage(format!(
                    "packing {} paths needs an output naming a container (`-o bundle.tar`, \
                     or --format tar); a codec compresses one stream and has nowhere to \
                     put a second. A container INSIDE a codec does work in one step — \
                     `-o bundle.tar.gz` and `-o bundle.tgz` both name a container.",
                    paths.len()
                )));
            }
            let input = paths.into_iter().next().expect("clap requires one path");
            let dst = match output {
                Some(o) => output_of(&o),
                None => {
                    let path = match input_of(&input) {
                        Input::Path(p) => p,
                        Input::Stdin => {
                            return Err(stuffr::Error::Usage(
                                "reading stdin needs an explicit -o".into(),
                            ));
                        }
                    };
                    let chosen = match fmt {
                        Some(f) => f,
                        None => ops::default_format()?,
                    };
                    Output::Path(ops::suggest_packed(&path, chosen)?)
                }
            };
            let out = ops::compress(input_of(&input), dst, &opts)?;
            eprintln!(
                "{} -> {} ({} -> {} bytes, {})",
                input,
                out.format,
                out.bytes_in,
                out.bytes_out,
                write_fidelity_summary(&out.fidelity)
            );
            // Honoured on the single-stream path too, rather than accepted
            // and ignored — the tree's rule for a flag that would otherwise
            // mislead. A codec encode loses nothing today, so this reports
            // nothing today; a codec that ever does will be heard.
            report_fidelity(&out.fidelity, strict_fidelity)
        }
        Command::Unpack {
            input,
            patterns,
            index,
            directory,
            output,
            force,
            format,
            max_ratio,
            no_sync,
            memory_limit,
            strict_fidelity,
        } => {
            let named_entries = !patterns.is_empty() || !index.is_empty();
            // -C is what asks for entry-aware extraction. It is a flag rather
            // than something inferred from the input because the decision has
            // to be made before a byte is read: a pipe cannot be probed and
            // then re-dispatched.
            if let Some(dir) = directory {
                let selection = selection_of(patterns, index)?;
                refuse_unhonoured_extract_flags(output.is_some(), format.is_some())?;
                let opts = ExtractOpts {
                    max_ratio: max_ratio.unwrap_or(stuffr::DEFAULT_MAX_RATIO),
                    force,
                    // Honoured now, not refused: `open_archive` threads it
                    // into `resolve_chain_deep_with`, so the codec layer
                    // beneath the container gets the same bound the
                    // single-stream path has always had. As there, the CLI
                    // default is the bound rather than unbounded.
                    memory_limit: Some(
                        parse_memory_limit(memory_limit)?
                            .unwrap_or_else(stuffr::default_memory_limit),
                    ),
                    ..Default::default()
                };
                let out = entries::extract(input_of(&input), Path::new(&dir), &selection, &opts)?;
                eprintln!(
                    "{} -> {} bytes extracted into {dir} ({} fidelity)",
                    out.format, out.bytes_out, out.fidelity.rung
                );
                return report_fidelity(&out.fidelity, strict_fidelity);
            }
            if named_entries {
                // `--index 6` needs the same refusal a pattern gets, and for
                // the same reason: it selects entries, and without -C there is
                // nowhere for entries to go. Naming the selector the user
                // actually typed keeps the message actionable.
                let named = match patterns.first() {
                    Some(p) => format!("`{p}`"),
                    None => format!("`--index {}`", index[0]),
                };
                return Err(stuffr::Error::Usage(format!(
                    "{named} names an archive entry; pass -C DIR to say where entries \
                     should be extracted to"
                )));
            }
            // Decode has no worker count to govern (multi-threaded decode is
            // out of scope this phase), but it does bound dictionary
            // allocation for the pure codecs that size a buffer from a value
            // the file declares in its own header — see
            // `stuffr_core::DecodeOpts::memory_limit`. The CLI default is
            // the bound, not unbounded: a bound that defaults off closes
            // nothing.
            let memory_limit = Some(
                parse_memory_limit(memory_limit)?.unwrap_or_else(stuffr::default_memory_limit),
            );
            let fmt = match format.as_deref() {
                Some(name) => Some(format_by_name(name)?),
                None => None,
            };
            let mut opts = DecompressOpts {
                force,
                sync: !no_sync,
                memory_limit,
                ..Default::default()
            };
            opts.format = fmt;
            if let Some(r) = max_ratio {
                opts.max_ratio = r;
            }
            ops::refuse_directory_for(&input_of(&input), "unpack")?;
            let dst = match output {
                Some(o) => output_of(&o),
                None => match input_of(&input) {
                    Input::Path(p) => Output::Path(ops::suggest_unpacked(&p)?),
                    Input::Stdin => {
                        return Err(stuffr::Error::Usage(
                            "reading stdin needs an explicit -o".into(),
                        ));
                    }
                },
            };
            let out = ops::decompress(input_of(&input), dst, &opts)?;
            eprintln!("{} -> {} bytes", out.format, out.bytes_out);
            report_fidelity(&out.fidelity, strict_fidelity)
        }
        Command::Convert {
            input,
            output_pos,
            output,
            format,
            level,
            threads,
            turbo,
            allow_weak_encoder,
            force,
            strict_fidelity,
            max_ratio,
            memory_limit,
            no_sync,
        } => {
            // Bounds every source codec layer's decoder, as on `unpack`; the
            // CLI default is the bound, not unbounded.
            let memory_limit = Some(
                parse_memory_limit(memory_limit)?.unwrap_or_else(stuffr::default_memory_limit),
            );
            let fmt = match format.as_deref() {
                Some(name) => Some(format_by_name(name)?),
                None => None,
            };
            let out_arg = match (output_pos, output) {
                (Some(_), Some(_)) => {
                    return Err(stuffr::Error::Usage(
                        "convert takes its destination once: as a second positional OUT or \
                         as -o OUT, not both"
                            .into(),
                    ));
                }
                (None, None) => {
                    return Err(stuffr::Error::Usage(
                        "convert needs a destination: `stuffr convert IN OUT` or \
                         `stuffr convert IN -o OUT`"
                            .into(),
                    ));
                }
                (Some(o), None) | (None, Some(o)) => o,
            };
            let dst = output_of(&out_arg);
            let out_name = match dst {
                Output::Path(_) => Some(out_arg.as_str()),
                Output::Stdout => None,
            };
            if out_name.is_none() && fmt.is_none() {
                return Err(stuffr::Error::Usage(
                    "-o - writes to stdout, which has no name to take the target format \
                     from; pass --format"
                        .into(),
                ));
            }

            // Everything decided from the command line alone comes first, so
            // a refusal costs no read of the input — which on stdin would be
            // bytes nobody can give back.
            let target = convert_target_chain(fmt, out_name)?;
            refuse_unhonoured_encoder_flags(
                EncoderFlags {
                    threads: threads.is_some(),
                    turbo,
                    allow_weak_encoder,
                },
                target.outermost_codec().is_some(),
                NoCodecLayer::ConvertTarget(&target),
            )?;
            let src = input_of(&input);
            if let (Input::Path(i), Output::Path(o)) = (&src, &dst) {
                refuse_converting_onto_itself(i, o)?;
            }
            #[cfg(unix)]
            if let (Input::Stdin, Output::Path(o)) = (&src, &dst) {
                refuse_stdin_redirected_from(o)?;
            }

            let mut opts = RecompressOpts {
                codec: target.outermost_codec(),
                level,
                force,
                sync: !no_sync,
                allow_weak_encoder,
                threads,
                turbo,
                memory_limit,
                ..Default::default()
            };
            if let Some(r) = max_ratio {
                opts.max_ratio = r;
            }
            // Level range, weak-encoder consent and a missing encoder are
            // command-line errors too: refused before the input is opened, so
            // a corrupt input cannot mask them with exit 5 and stdin is not
            // consumed. `ops` owns the checks; this only asks them early.
            ops::check_recompress_target(&opts)?;
            // Entry mode's write side, built from the same flags. Checked
            // here too, for the same reason: a target container this build
            // cannot write must not cost a read of stdin either.
            let convert_opts = ConvertOpts {
                level,
                force,
                sync: !no_sync,
                allow_weak_encoder,
                threads,
                turbo,
                max_ratio: opts.max_ratio,
                memory_limit,
                spill: stuffr::SpillPolicy::default(),
            };
            if let Some(container) = target.container() {
                match entries::check_convert_target(
                    container,
                    target.outermost_codec(),
                    &convert_opts,
                ) {
                    // A read-only container (arc, zoo) is still a legal
                    // CODEC-mode target — `x.arc.gz -> x.arc` only removes
                    // the gzip — and which mode applies is known only once
                    // the source is open. That one refusal waits:
                    // `convert_archive_source` raises it again in entry mode.
                    Err(stuffr::Error::CapabilityUnavailable { format, .. })
                        if format == container => {}
                    other => other?,
                }
            }

            // Opened ONCE: the mode is chosen from this source's own chain
            // and the same value is then converted, so stdin is read once
            // and the CLI cannot disagree with the library about what the
            // input is (`ops::resolve_source_chain` is that rule's owner).
            let source = match ops::ConvertSource::open(src, memory_limit) {
                Err(stuffr::Error::UnknownFormat { seen }) => {
                    return Err(stuffr::Error::Usage(format!(
                        "`{input}` is not in any format this build recognises (leading \
                         bytes were {seen}). convert changes a format; to compress a plain \
                         file use `stuffr pack`"
                    )));
                }
                other => other?,
            };
            let reencode = level.is_some() || threads.is_some() || turbo;
            let out = match convert_mode(
                source.chain(),
                &target,
                reencode,
                matches!(dst, Output::Stdout),
            )? {
                ConvertMode::Codec => ops::recompress_source(source, dst, &opts)?,
                ConvertMode::Entry => {
                    let container = target
                        .container()
                        .expect("convert_mode answers Entry only for a container target");
                    entries::convert_archive_source(
                        source,
                        dst,
                        container,
                        target.outermost_codec(),
                        &convert_opts,
                    )?
                }
            };
            // The TARGET chain, never `out.format`: for a bare stream with no
            // codec that names the codec just removed.
            eprintln!(
                "{input} -> {} ({} -> {} bytes, {})",
                target.describe(),
                out.bytes_in,
                out.bytes_out,
                write_fidelity_summary(&out.fidelity)
            );
            // One gate for both modes, and it judges the WARNINGS only
            // (`report_fidelity` reads `has_warnings`, never `is_lossless`).
            // Entry mode's report merges the source reader's rung, and a
            // tar or cpio on a pipe reads forward-only — at full data
            // fidelity (`ContainerCaps::forward_parse`); every real loss,
            // the reader's or the writer's, is a warning. So a lossless
            // conversion from stdin is exit 0 under --strict-fidelity.
            report_fidelity(&out.fidelity, strict_fidelity)
        }
        Command::Cat {
            input,
            patterns,
            index,
            format,
            max_ratio,
            memory_limit,
        } => {
            // Naming an entry is what asks for entry-aware streaming — the
            // same "decide before reading a byte" reasoning as `unpack`'s -C.
            // `--index 6` says it just as explicitly as a name does.
            if !patterns.is_empty() || !index.is_empty() {
                let selection = selection_of(patterns, index)?;
                refuse_unhonoured_extract_flags(false, format.is_some())?;
                // Honoured now, not refused — see `unpack -C` above.
                let memory_limit = Some(
                    parse_memory_limit(memory_limit)?.unwrap_or_else(stuffr::default_memory_limit),
                );
                // The motivating case: `curl … | stuffr cat - log.txt`.
                let mut out = std::io::stdout();
                entries::cat(
                    input_of(&input),
                    &selection,
                    max_ratio.unwrap_or(stuffr::DEFAULT_MAX_RATIO),
                    memory_limit,
                    &mut out,
                )?;
                return Ok(());
            }
            // Same as `unpack`: bounds dictionary allocation for the pure
            // codecs; the CLI default is the bound, not unbounded.
            let memory_limit = Some(
                parse_memory_limit(memory_limit)?.unwrap_or_else(stuffr::default_memory_limit),
            );
            let fmt = match format.as_deref() {
                Some(name) => Some(format_by_name(name)?),
                None => None,
            };
            let mut opts = DecompressOpts {
                format: fmt,
                memory_limit,
                ..Default::default()
            };
            if let Some(r) = max_ratio {
                opts.max_ratio = r;
            }
            // The motivating case: `curl … | stuffr cat - | grep pattern`.
            ops::refuse_directory_for(&input_of(&input), "cat")?;
            ops::decompress(input_of(&input), Output::Stdout, &opts)?;
            Ok(())
        }
        Command::Info {
            input,
            json,
            memory_limit,
        } => {
            use std::io::Write;
            // `info` takes no `--threads`, so there is no worker count to
            // resolve or print here — only the memory limit a subsequent
            // pack/unpack would use, the same value `--memory-limit`
            // resolves to on those subcommands (an explicit value, or
            // `default_memory_limit()`'s 25%-of-available-RAM reading).
            let memory_limit =
                parse_memory_limit(memory_limit)?.unwrap_or_else(stuffr::default_memory_limit);
            let i = ops::inspect(input_of(&input))?;
            let mut out = std::io::stdout();
            if json {
                let mut v = serde_json::to_value(&i).expect("Inspection serializes");
                if let serde_json::Value::Object(ref mut map) = v {
                    map.insert("memory_limit".into(), serde_json::json!(memory_limit));
                }
                writeln!(out, "{v}")?;
            } else {
                writeln!(out, "format:   {}", i.format)?;
                writeln!(out, "chain:    {}", i.chain)?;
                writeln!(out, "rung:     {}", i.fidelity.rung)?;
                match i.bytes_in {
                    Some(n) => writeln!(out, "size:     {n} bytes")?,
                    None => writeln!(out, "size:     unknown (stream)")?,
                }
                // Three cases, not two. `info` identifies a stream without
                // decoding it, so where a forward read of the container COULD
                // have approximated something it has not looked and must not
                // say — asserting "nothing approximated" there was a false
                // positive, contradicted by `stuffr test` on the very same
                // bytes for a piped zip. Withholding it for every container
                // instead would be a false NEGATIVE, since a forward read of
                // a tar genuinely loses nothing; the rule is narrowed to the
                // cases where loss is possible. The rung above is real in all
                // three. See `ops::Inspection::fidelity_evaluated`.
                if !i.fidelity_evaluated {
                    writeln!(
                        out,
                        "fidelity: not evaluated (info does not open the archive; \
                         run `stuffr test` for that)"
                    )?;
                } else if i.fidelity.has_warnings() {
                    writeln!(out, "fidelity: {} warning(s)", i.fidelity.warnings.len())?;
                    for w in &i.fidelity.warnings {
                        writeln!(out, "  - {w}")?;
                    }
                } else {
                    writeln!(out, "fidelity: nothing approximated")?;
                }
                writeln!(
                    out,
                    "memory:   {}",
                    stuffr_cli::size::format_size(memory_limit)
                )?;
            }
            Ok(())
        }
        Command::Formats => print_formats(),
        Command::List {
            input,
            json,
            max_ratio,
            memory_limit,
            strict_fidelity,
        } => {
            // `list` advertises reading nothing and extracting nothing, but
            // reaching the container's first header still decodes whatever
            // codec sits above it — so it needs the same bound every other
            // decoding verb has, defaulted the same way.
            let memory_limit = Some(
                parse_memory_limit(memory_limit)?.unwrap_or_else(stuffr::default_memory_limit),
            );
            print_list(
                input_of(&input),
                json,
                max_ratio.unwrap_or(stuffr::DEFAULT_MAX_RATIO),
                memory_limit,
                strict_fidelity,
            )
        }
        Command::Test {
            input,
            max_ratio,
            memory_limit,
            strict_fidelity,
        } => {
            let memory_limit = Some(
                parse_memory_limit(memory_limit)?.unwrap_or_else(stuffr::default_memory_limit),
            );
            let out = entries::test(
                input_of(&input),
                max_ratio.unwrap_or(stuffr::DEFAULT_MAX_RATIO),
                memory_limit,
            )?;
            // The rung is worth printing here, unlike on the write side where
            // it is a constant — a read really did land on one of four rungs,
            // and which one it was is diagnostic. What it must not do is
            // stand in for the LOSS. "exact fidelity" describes the access
            // path, and an exact read of a zip whose index shadows two of its
            // own records loses those two records anyway, so announcing
            // "exact fidelity" on a report that carries warnings makes
            // exactly the claim this tool exists not to make. Same ruling
            // `pack`'s summary line already carries, for the same reason: when
            // something was lost, the honest number is how much.
            eprintln!(
                "{} -> {} bytes verified ({})",
                out.format,
                out.bytes_out,
                read_fidelity_summary(&out.fidelity)
            );
            report_fidelity(&out.fidelity, strict_fidelity)
        }
        Command::Salvage {
            input,
            list,
            directory,
            output,
            index,
            partial,
            max_entry,
            strict,
            format,
        } => {
            let code = dispatch_salvage(SalvageArgs {
                input,
                list,
                directory,
                output,
                index,
                partial,
                max_entry,
                strict,
                format,
            })?;
            // `code` is the aggregate bucket `entries::salvage_exit_code`
            // computed over a run that COMPLETED (`Ok`) — 0, 3, 4 or 5, per
            // Ruling R-N. It is not an `Error`: a completed salvage run that
            // recovered something partial or skipped a shadow is not this
            // program failing, so there is no `stuffr::Error` variant to
            // carry the number honestly (every existing one whose exit code
            // matches also carries a Display string tied to a DIFFERENT
            // shape, e.g. `FidelityDegraded`'s "under strict mode", which
            // salvage's own `--strict` does not mean). `run`'s own
            // Ok/Err-to-`ExitCode` mapping has no third option, so a
            // non-zero bucket here exits directly rather than round-tripping
            // through it — the report was already printed by
            // `dispatch_salvage`, so nothing is lost by not returning.
            //
            // Exit 7 (path escape) never reaches here: `entries::salvage`
            // raises it as `Err` before a `SalvageOutcome` exists at all
            // (see `salvage_exit_code`'s own doc), and the `?` above already
            // propagated it through the normal `Error::exit_code` path.
            // Exit 6 used to be in this sentence — an entry over the ceiling
            // aborted the run the same way — and since Task 3c's fix round 3
            // it is not raised by salvage at all: such an entry is reported
            // `Unverified (over the ceiling)` and lands in bucket 3, so one
            // oversized declaration no longer costs every other entry.
            //
            // Safe despite every `--list` row having already gone to stdout
            // by this point: `std::io::Stdout` is an unconditional
            // `LineWriter`, never block-buffered even for a pipe (unlike C's
            // stdio), and every row this module prints ends in `\n` — so the
            // bytes are already on the fd before `process::exit` runs.
            // Measured directly, not merely reasoned about: 8 rows and 501
            // rows (a 500-file archive), through both a pipe and a file
            // redirect, landed every row with the correct trailing content
            // and exit code. The safety is INCIDENTAL to every write ending
            // in a newline, not structural — a future edit that writes a
            // partial line on this path (a `write!` in place of a
            // `writeln!`) would silently reintroduce the hazard, with
            // nothing here to catch it.
            if code == 0 {
                Ok(())
            } else {
                std::process::exit(code)
            }
        }
    }
}

/// One record's status, named the way [`stuffr::salvage::SalvageStatus`]
/// itself is proven, before anything the write side decided is layered on.
///
/// `Partial` carries no cause on the status alone — [`describe_salvage_row`]
/// overrides it with one whenever [`entries::SalvageDisposition::
/// WrittenPartial`] or (fix round 1, REQUIRED 3)
/// [`entries::SalvageDisposition::SkippedPartial`] has one to give, which is
/// always, now that both variants carry a cause. `Unverified` is different:
/// its cause is part of the status itself, proven at scan time, so it is
/// always known here directly.
fn describe_salvage_status(status: stuffr::salvage::SalvageStatus) -> &'static str {
    use stuffr::salvage::{SalvageStatus, UnverifiedCause};
    match status {
        SalvageStatus::Intact => "Intact",
        SalvageStatus::Complete => "Complete",
        // Salvage Stage 3. The entry IS written, under its real name — the
        // reason lands as a tag on the row rather than as a refusal, and
        // the run exits 4. See [`describe_salvage_row`] for the tag, and
        // [`stuffr::salvage::SalvageStatus::Unattested`] for why this sits
        // beside `Unverified` and means something else entirely.
        SalvageStatus::Unattested => "Unattested",
        SalvageStatus::Partial => "Partial",
        SalvageStatus::Unverified(UnverifiedCause::UndecodableMethod) => {
            "Unverified (undecodable method)"
        }
        SalvageStatus::Unverified(UnverifiedCause::NoDeclaredLength) => {
            "Unverified (no declared length)"
        }
        // The entry is larger than this run will read for one entry
        // (`--max-entry`, narrowed by a whole-decoding container's own
        // ceiling), so nothing was read and nothing was decoded. It used to
        // be reported by ABORTING at exit 6 with a sentence naming both
        // figures, which cost every other entry in the archive; it is a row
        // like any other now. The two FIGURES are not dropped with the
        // sentence — [`describe_salvage_row`] appends them as a tag, so the
        // status column stays the fixed width every other row uses while a
        // user still learns what the entry needed and what the run allowed.
        SalvageStatus::Unverified(UnverifiedCause::OverEntryCeiling { .. }) => {
            "Unverified (over the ceiling)"
        }
    }
}

/// One `--list` row: scan position, status (refined with a `Partial` cause
/// whenever the disposition has one to give — [`entries::SalvageDisposition::
/// WrittenPartial`] or, since fix round 1's REQUIRED 3,
/// [`entries::SalvageDisposition::SkippedPartial`] too, so `--partial=skip
/// --list` no longer shows bare "Partial" with no "why" on exactly the
/// entries the flag caused to be dropped), name, and — the naming rule this
/// whole feature is built around — a `[shadowed: dup of #N]` suffix naming
/// the EARLIER scan position, never "index", when this record shadows one.
/// `[not selected]` marks a scan position `--index` excluded.
///
/// `[name collision: #N uses this name too]` is the SECOND, weaker
/// annotation, and the two never appear on one row: a shadow is a record
/// measured to be a byte-identical copy, a collision is a record whose name
/// an earlier one already used and whose content was not proven identical.
/// Until the final whole-branch review they shared one word, and the cost
/// was measurable: on an archive whose duplicates differ, `stuffr list`
/// warned that two records repeat a name and were shadowed, while this row
/// marked nothing at all.
///
/// `[deleted: the archive marks this entry removed]` is Ruling S-R (Salvage
/// Stage 2 Task 4). ZOO is the first format here whose records carry a
/// deleted flag, and `salvage` reports such a record where every other verb
/// skips it — `zoo d` leaves the payload in the file, and one flipped byte
/// in that flag turns a live entry into one the ordinary reader will never
/// hand back. Reporting it is right; reporting it as a bare `Intact` under
/// its real name at exit 0 was not, because it made this the ONE place
/// salvage's leniency carried no marker at all. **The exit code does not
/// move** — recovering a deleted record is the verb working as designed,
/// not degraded fidelity — so the annotation is the whole signal, which is
/// why it is worth having.
fn describe_salvage_row(record: &entries::SalvagedRecord) -> String {
    let status = match &record.disposition {
        entries::SalvageDisposition::WrittenPartial { cause, .. }
        | entries::SalvageDisposition::SkippedPartial(cause)
        | entries::SalvageDisposition::WrittenDisambiguated {
            partial: Some(cause),
            ..
        } => match cause {
            entries::PartialCause::Truncated => "Partial (truncated)",
            // Ruling S-AA. Distinct from `truncated` because nothing is
            // missing from the FILE — every declared byte is there and the
            // decoder could not turn them into the declared content. The
            // row used to say `truncated` for this, over archives from
            // which nothing had been cut.
            entries::PartialCause::DecodeFailed => "Partial (decode failed)",
            entries::PartialCause::ChecksumMismatch => "Partial (checksum mismatch)",
        },
        entries::SalvageDisposition::WrittenDisambiguated { partial: None, .. }
        | entries::SalvageDisposition::Written(_)
        | entries::SalvageDisposition::Directory(_)
        | entries::SalvageDisposition::SkippedUnverified
        | entries::SalvageDisposition::SkippedUnattested
        | entries::SalvageDisposition::SkippedNotBuiltIn
        | entries::SalvageDisposition::SkippedShadow(_)
        | entries::SalvageDisposition::SkippedUnsupportedKind
        | entries::SalvageDisposition::SkippedUnwritable { .. }
        | entries::SalvageDisposition::SkippedUnsafePath { .. }
        | entries::SalvageDisposition::NotSelected
        | entries::SalvageDisposition::NotWritten => describe_salvage_status(record.status),
    };
    let mut line = format!(
        "{:<4} {:<32} {}",
        record.scan_position,
        status,
        stuffr::fmt_name(&record.name)
    );
    if let Some(earlier) = record.shadows {
        line.push_str(&format!(" [shadowed: dup of #{earlier}]"));
    }
    if let Some(earlier) = record.collides_with {
        line.push_str(&format!(" [name collision: #{earlier} uses this name too]"));
    }
    if record.marked_deleted {
        line.push_str(" [deleted: the archive marks this entry removed]");
    }
    // Salvage Stage 3: a user meets the REASON where they meet the entry.
    // The status column says `Unattested`, which names the tier but not why
    // this archive is in it — and unlike every other tag on this row, this
    // one is a fact about the FORMAT rather than about the record, so a
    // user who has never met `cpio` or `ar` has nowhere else to learn it.
    // The entry is still written under its real name; the run exits 4.
    if record.status == stuffr::salvage::SalvageStatus::Unattested {
        line.push_str(" [no checksum and no header self-check in this format]");
    }
    // Ruling 3-H: the entry above was NOT written, and the reason is the
    // caller's own flag rather than anything about the archive — so the row
    // names the flag, which is also the remedy.
    if matches!(
        record.disposition,
        entries::SalvageDisposition::SkippedUnattested
    ) {
        line.push_str(" [not written: --strict demands proof this format cannot give]");
    }
    // The path actually written, named only when it is NOT the entry's own
    // name — a row a user reads to find their file must say where it went.
    if let entries::SalvageDisposition::WrittenDisambiguated { path, .. } = &record.disposition {
        line.push_str(&format!(
            " [written as {}]",
            stuffr::fmt_name(
                &path
                    .file_name()
                    .unwrap_or(path.as_os_str())
                    .to_string_lossy()
            )
        ));
    }
    if matches!(record.disposition, entries::SalvageDisposition::NotSelected) {
        line.push_str(" [not selected]");
    }
    // Fix round 4, NEW-F: the two figures the old exit-6 sentence carried.
    // Without them a user meeting a whole-decoding container's own fixed
    // ceiling learns neither what the entry needed nor what the run allowed,
    // and cannot tell whether `--max-entry` would help — which is the whole
    // difference between the two ceilings that compose here.
    if let stuffr::salvage::SalvageStatus::Unverified(
        stuffr::salvage::UnverifiedCause::OverEntryCeiling { needed, ceiling },
    ) = record.status
    {
        line.push_str(&format!(
            " [needs {needed} bytes; this run reads at most {ceiling} per entry]"
        ));
    }
    // Fix round 4, NEW-B: an entry whose bytes could not be placed on disk
    // names the reason on its own row. It used to end the run instead — at
    // exit 1, on a name the ARCHIVE chose.
    if let entries::SalvageDisposition::SkippedUnwritable { reason } = &record.disposition {
        line.push_str(&format!(" [not written: {reason}]"));
    }
    // Final fix wave, F1: the same shape, for the refusal stuffr makes
    // itself rather than the one the OS hands back. Worded "refused" rather
    // than "not written" precisely so the two are distinguishable on a row:
    // one is a destination that would not take the name, the other is this
    // tool declining to write outside where it was pointed.
    if let entries::SalvageDisposition::SkippedUnsafePath { reason } = &record.disposition {
        line.push_str(&format!(" [refused: unsafe entry path: {reason}]"));
    }
    line
}

/// `--list`: one line per scanned record, to stdout — the same destination
/// `stuffr list` itself writes to, and for the same reason (`stuffr salvage
/// … --list | head` is as legitimate a pipeline as `stuffr list x | head`).
///
/// Fix round 1, REQUIRED 2: always the FULL scan (`&outcome.entries`
/// directly, never a caller-filtered slice) — `--index` narrows what is
/// WRITTEN, never what `--list` reports, so a selection is visible here only
/// as the `[not selected]` tag [`describe_salvage_row`] adds.
fn print_salvage_list(entries: &[entries::SalvagedRecord]) -> stuffr::Result<()> {
    use std::io::Write;
    let mut out = std::io::stdout();
    for record in entries {
        writeln!(out, "{}", describe_salvage_row(record))?;
    }
    Ok(())
}

/// Names every entry this run could not place on disk, on **stderr, every
/// run** — not only under `--list`.
///
/// # Why this exists (fix round 5, NEW-G)
///
/// Task 3c's fix round 4 made a filesystem failure a per-entry skip instead
/// of an aborted run, and rested that ruling on "the reason is on its own
/// row, so nothing is silent". It was on its own row **only under
/// `--list`**. Measured on the shipped binary against a `chmod 555`
/// destination and against a genuine ENOSPC volume, plain `salvage -C DIR`
/// — the invocation somebody recovering an archive actually types —
/// printed:
///
/// ```text
/// salvage -> 3 scanned: 0 written, … 3 skipped, 0 unverified, …
/// exit=4                                          # and nothing else
/// ```
///
/// A wholly unusable destination was a bare `3 skipped`, where before the
/// fold it was `stuffr: i/o error: Permission denied (os error 13)` at
/// exit 1 — so a user could not tell a full disk from an entry the archive
/// itself made unwritable, which is the exact question the fold's own trade
/// turns on. A skip nobody can see is Stage 1's vanishing truncated tail
/// wearing a different hat.
///
/// `pack`'s directory walk is the precedent the ruling already cited, and it
/// prints its skips on stderr every run — which is what makes `CLAUDE.md`'s
/// "the skip is named, not silent" true there. This is the same, in the same
/// shape [`report_fidelity`] uses for the same reason: a count, up to ten
/// lines, then how many were elided.
///
/// **Printed even under `--list`, which also tags these rows.** The rows go
/// to stdout and this goes to stderr, so `salvage --list … | less` still
/// shows the failure, and a terminal user reading both sees one restated
/// fact rather than a missing one.
///
/// Takes the FULL scan rather than `--index`'s subset, and nothing is lost
/// by that: an unselected position is reported `NotSelected` and never
/// reaches a filesystem call, so it can never be one of these.
fn print_salvage_write_failures(entries: &[entries::SalvagedRecord]) {
    // Final fix wave, F1: BOTH placement failures, not only the OS's. A
    // containment refusal used to end the run with its own message on
    // stderr, so widening this filter alongside that change is what keeps
    // "nothing is silent" true — a refusal that became a row and nothing
    // else would be NEW-G's defect reintroduced through the door F1 opened.
    let failed: Vec<&entries::SalvagedRecord> = entries
        .iter()
        .filter(|r| {
            matches!(
                r.disposition,
                entries::SalvageDisposition::SkippedUnwritable { .. }
                    | entries::SalvageDisposition::SkippedUnsafePath { .. }
            )
        })
        .collect();
    if failed.is_empty() {
        return;
    }
    const SHOWN: usize = 10;
    eprintln!(
        "salvage -> {} entr{} could not be written:",
        failed.len(),
        if failed.len() == 1 { "y" } else { "ies" }
    );
    for record in failed.iter().take(SHOWN) {
        // One arm each, no wildcard: a third placement outcome added later
        // must decide how it prints rather than inheriting a default.
        let reason = match &record.disposition {
            entries::SalvageDisposition::SkippedUnwritable { reason } => reason.clone(),
            entries::SalvageDisposition::SkippedUnsafePath { reason } => {
                format!("refused: unsafe entry path: {reason}")
            }
            other => unreachable!("filtered above, got {other:?}"),
        };
        // `reason` may be an `io::Error`'s text; `fmt_name` is idempotent on
        // an already-escaped string (a backslash is written unchanged).
        eprintln!(
            "  - #{} {}: {}",
            record.scan_position,
            stuffr::fmt_name(&record.name),
            stuffr::fmt_name(&reason)
        );
    }
    if let Some(rest) = failed.len().checked_sub(SHOWN).filter(|n| *n > 0) {
        eprintln!("  … and {rest} more");
    }
}

/// The default (non-`--list`) report: counts only, to stderr — the same
/// destination `unpack`'s and `test`'s own summary lines use. Takes whatever
/// slice the caller passes — [`dispatch_salvage`] narrows it to `--index`'s
/// selection when one was given, unlike [`print_salvage_list`], which always
/// takes the full scan.
fn print_salvage_summary(entries: &[entries::SalvagedRecord]) {
    for line in salvage_summary_lines(entries) {
        eprintln!("{line}");
    }
}

/// [`print_salvage_summary`]'s text, separated from the printing so the
/// lines themselves can be pinned by a unit test. `Unattested` was
/// reachable end to end from no scanner when this was written; `cpio`
/// (Salvage Stage 3 Task 3) reaches it now, and `cli.rs` observes it too.
///
/// # Why an `Unattested` run gets a line of its own (Salvage Stage 3 Task 1, F2)
///
/// An `Unattested` entry is WRITTEN, so it lands in the `written` count
/// beside every clean entry, and the run exits 4. Without more, plain
/// `salvage x.cpio -C out` would print "N written, 0 skipped" and exit 4
/// with nothing on stderr saying why — the "exit code with empty stderr"
/// shape Stage 2 already paid for once, when a full disk and one
/// unwritable name printed the same skip count and a user could not tell
/// which they had. The row tag carries the reason under `--list`; this
/// carries it on the path most runs take. The `unattested` count is an
/// ADDITIONAL tally, like `renamed`, so the first six counts still sum to
/// the number of rows.
fn salvage_summary_lines(entries: &[entries::SalvagedRecord]) -> Vec<String> {
    let (mut written, mut partial, mut skipped, mut unverified, mut not_selected, mut not_written) =
        (0, 0, 0, 0, 0, 0);
    // An ADDITIONAL tally, not a bucket of its own: a disambiguated record
    // is already counted as written (or as a `.partial`), so the first six
    // counts still sum to the number of rows. Disambiguation is a fact
    // ABOUT a write, the same way a `Partial` cause is a fact about one —
    // giving it its own bucket would make the summary stop adding up, which
    // is precisely the defect this whole change exists to fix.
    let mut renamed = 0;
    // The same shape, for the same reason: `Unattested` is a fact about the
    // FORMAT behind a record, whatever became of the record.
    let mut unattested = 0;
    // How many of those were actually put on disk — the note below says
    // what was kept, and must not say it of an entry that was skipped (Task
    // 3 review, M3: a skipped symlink was reported "kept").
    let mut unattested_kept = 0;
    for record in entries {
        if record.status == stuffr::salvage::SalvageStatus::Unattested {
            unattested += 1;
            if matches!(
                record.disposition,
                entries::SalvageDisposition::Written(_)
                    | entries::SalvageDisposition::WrittenDisambiguated { .. }
                    | entries::SalvageDisposition::WrittenPartial { .. }
                    | entries::SalvageDisposition::Directory(_)
            ) {
                unattested_kept += 1;
            }
        }
        match &record.disposition {
            entries::SalvageDisposition::Written(_) | entries::SalvageDisposition::Directory(_) => {
                written += 1;
            }
            entries::SalvageDisposition::WrittenDisambiguated { partial: cause, .. } => {
                renamed += 1;
                match cause {
                    Some(_) => partial += 1,
                    None => written += 1,
                }
            }
            entries::SalvageDisposition::WrittenPartial { .. } => partial += 1,
            entries::SalvageDisposition::SkippedPartial(_)
            | entries::SalvageDisposition::SkippedNotBuiltIn
            | entries::SalvageDisposition::SkippedShadow(_)
            | entries::SalvageDisposition::SkippedUnsupportedKind
            // Ruling 3-H: declined under `--strict`. A skip, not a new
            // bucket — the `unattested` tally already says what kind.
            | entries::SalvageDisposition::SkippedUnattested
            // Counted as skipped, not as a bucket of its own: the summary's
            // six counts must keep summing to the number of rows, and the
            // per-entry reason is on the row (`[not written: …]`).
            | entries::SalvageDisposition::SkippedUnwritable { .. }
            // Counted as skipped for the same reason, and the exit code —
            // not the summary — is what carries the severity: a containment
            // refusal is bucket 7 in `salvage_exit_code`, above every other.
            | entries::SalvageDisposition::SkippedUnsafePath { .. } => skipped += 1,
            entries::SalvageDisposition::SkippedUnverified => unverified += 1,
            entries::SalvageDisposition::NotSelected => not_selected += 1,
            entries::SalvageDisposition::NotWritten => not_written += 1,
        }
    }
    let mut lines = vec![format!(
        "salvage -> {} scanned: {written} written, {partial} written as .partial, {skipped} \
         skipped, {unverified} unverified, {not_selected} not selected, {not_written} not \
         written (no destination), {renamed} renamed to avoid a name collision, {unattested} \
         unattested",
        entries.len()
    )];
    if unattested > 0 {
        lines.push(unattested_note(unattested, unattested_kept));
    }
    lines
}

/// Why `count` entries are `Unattested`, of which `kept` were put on disk —
/// the one sentence both the default summary ([`salvage_summary_lines`])
/// and `-o FILE` ([`finish_single_file_recovery`]) print, so the two paths
/// cannot explain the same exit 4 two ways. It says "kept under the real
/// name" only of what was kept: an `Unattested` symlink is skipped like any
/// other symlink, and `--strict` declines them all.
fn unattested_note(count: usize, kept: usize) -> String {
    let fate = if kept == count {
        "kept under the real name unless --strict".to_string()
    } else {
        format!(
            "{kept} kept under the real name and {} not written",
            count - kept
        )
    };
    format!(
        "salvage -> {count} entr{} unattested: this format carries no checksum and no header \
         self-check, so nothing proves a recovered record is a real entry rather than a \
         coincidental header match — {fate}, and the run exits 4",
        if count == 1 { "y is" } else { "ies are" }
    )
}

/// Validates `--index` against the scan positions the archive actually has.
///
/// Lenient the same way `unpack --index`/`cat --index` already are (see
/// `entries::extract`'s own `Selection::missed`): refuses only when NONE of
/// the requested positions exist at all, rather than the first one that
/// doesn't — a mix of a real position and a typo silently recovers the real
/// one, the same bargain `unpack` already makes. Names the mistake as a scan
/// position — never "index" — per this feature's own naming rule: `stuffr
/// list`'s numbering and salvage's are two different things, and a message
/// that said "index" here could be misread as `list`'s.
fn validate_scan_positions(requested: &[usize], total: usize) -> stuffr::Result<()> {
    if !requested.is_empty() && requested.iter().all(|&pos| pos >= total) {
        return Err(stuffr::Error::Usage(format!(
            "no requested scan position exists; this archive's scan found {total} record(s) \
             (valid scan positions are 0-{})",
            total.saturating_sub(1)
        )));
    }
    Ok(())
}

/// Removes a temporary directory when dropped. `-o FILE` recovers into one
/// of these (via [`entries::salvage`]'s ordinary directory mode, `select`
/// narrowed to the one requested entry) and then moves the single result
/// out to `FILE`; wrapping the directory in a guard means an early return
/// through `?` anywhere in between — a validation failure, an I/O error —
/// still cleans it up, without a `remove_dir_all` at every return site.
struct TempDirGuard(PathBuf);

impl Drop for TempDirGuard {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// A fresh, empty directory under the system temp root, for [`TempDirGuard`]
/// to own. No dependency on the `tempfile` crate: that is a dev-dependency
/// of `stuffr` (used by `entries.rs`'s own unit tests), not available to
/// this crate's production code.
fn fresh_temp_dir(label: &str) -> stuffr::Result<TempDirGuard> {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let mut dir = std::env::temp_dir();
    dir.push(format!(
        "stuffr-salvage-{label}-{}-{nanos}",
        std::process::id()
    ));
    std::fs::create_dir_all(&dir)?;
    Ok(TempDirGuard(dir))
}

/// `-o FILE`'s second half: given the outcome of a `select = {scan_position}`
/// run into a temporary directory, moves that one entry's recovered bytes
/// (if any) out to `output_path` and reports what happened.
///
/// A `Partial` entry still lands under `output_path` with `.partial`
/// appended, never `output_path` itself — the exact rule `-C` already
/// follows (see [`entries::salvage`]'s own doc and Ruling R-J), applied to a
/// caller-named path instead of an entry-named one for the identical reason:
/// a truncated file under the name asked for is indistinguishable from a
/// whole one to every tool downstream.
fn finish_single_file_recovery(
    outcome: &entries::SalvageOutcome,
    scan_position: usize,
    output_path: &Path,
) -> stuffr::Result<()> {
    let record = outcome
        .entries
        .iter()
        .find(|r| r.scan_position == scan_position)
        .expect("validate_scan_positions already confirmed this scan position was scanned");

    let (from, is_partial) = match &record.disposition {
        entries::SalvageDisposition::Written(path) => (path.clone(), false),
        entries::SalvageDisposition::WrittenPartial { path, .. } => (path.clone(), true),
        // Unreachable in practice — `-o` narrows `select` to exactly one
        // scan position and recovers into a FRESH temporary directory, so
        // no earlier entry in the run can have claimed a name. Handled
        // rather than lumped into the "nothing written" arm below, which
        // would silently report a recovered file as not recovered if that
        // ever stopped being true. The disambiguated on-disk name does not
        // survive the move: `-o FILE` means FILE, and the caller named one
        // entry, so there is nothing left to disambiguate against.
        entries::SalvageDisposition::WrittenDisambiguated { path, partial, .. } => {
            (path.clone(), partial.is_some())
        }
        entries::SalvageDisposition::Directory(_) => {
            return Err(stuffr::Error::Usage(format!(
                "scan position {scan_position} is a directory entry; -o recovers one file's \
                 bytes — use -C to recover a directory"
            )));
        }
        entries::SalvageDisposition::SkippedShadow(_)
        | entries::SalvageDisposition::SkippedUnverified
        | entries::SalvageDisposition::SkippedUnattested
        | entries::SalvageDisposition::SkippedNotBuiltIn
        | entries::SalvageDisposition::SkippedPartial(_)
        | entries::SalvageDisposition::SkippedUnsupportedKind
        | entries::SalvageDisposition::SkippedUnwritable { .. }
        // Final fix wave, F1. Reached under `-o FILE` the same way every
        // other skip is: `describe_salvage_row` names the refusal, and the
        // run still exits 7 because `salvage_exit_code` gives this variant
        // its own bucket — so `-o` on an escaping name reports exactly what
        // it did before, minus the aborted run.
        | entries::SalvageDisposition::SkippedUnsafePath { .. }
        | entries::SalvageDisposition::NotSelected
        | entries::SalvageDisposition::NotWritten => {
            eprintln!(
                "salvage -> nothing written for scan position {scan_position}: {}",
                describe_salvage_row(record)
            );
            return Ok(());
        }
    };

    let mut final_path = output_path.to_path_buf();
    if is_partial {
        let mut name = final_path
            .file_name()
            .map(std::ffi::OsStr::to_os_string)
            .unwrap_or_default();
        name.push(".partial");
        final_path = final_path.with_file_name(name);
    }
    if let Some(parent) = final_path.parent()
        && !parent.as_os_str().is_empty()
    {
        std::fs::create_dir_all(parent)?;
    }
    // No `--force` concept exists for salvage, same as `-C`'s own write path:
    // recovery is meant to be re-run, and a stale file from a previous
    // attempt must not block this one.
    let _ = std::fs::remove_file(&final_path);
    if std::fs::rename(&from, &final_path).is_err() {
        // `from` lives in a temp directory that may sit on a different
        // filesystem than `final_path`'s — `rename(2)` refuses that
        // (`EXDEV`), so fall back to copying the bytes across and removing
        // the source.
        std::fs::copy(&from, &final_path)?;
        std::fs::remove_file(&from)?;
    }
    eprintln!("salvage -> wrote {}", final_path.display());
    // Salvage Stage 3 Task 3, R1 (routed from Task 1): an `Unattested`
    // entry written through `-o` exits 4, and until this line nothing said
    // why — `wrote FILE` alone, then a non-zero status. `-C` and `--list`
    // already explain it; this is their sentence, not a third wording.
    if record.status == stuffr::salvage::SalvageStatus::Unattested {
        eprintln!("{}", unattested_note(1, 1));
    }
    Ok(())
}

/// [`Command::Salvage`]'s fields, bundled so [`dispatch_salvage`] takes one
/// argument instead of nine (clippy's own `too_many_arguments` threshold).
struct SalvageArgs {
    input: String,
    list: bool,
    directory: Option<String>,
    output: Option<String>,
    index: Vec<usize>,
    partial: Option<String>,
    max_entry: Option<String>,
    strict: bool,
    format: Option<String>,
}

/// Implements `salvage` end to end: builds the policy, runs the scan-and-
/// recover engine (`entries::salvage`), prints the report, and returns the
/// aggregate exit-code bucket (0/3/4/5) for the calling match arm to act on.
///
/// A plain function rather than inlined in the `dispatch` arm purely so the
/// arm above reads as a dispatch table, matching the shape every other verb
/// here already has.
///
/// # The three surface forms (fix round 1, REQUIRED 2)
///
/// - `--list` alone: report-only, `dest: None` — nothing touches the
///   filesystem, not even to create a directory.
/// - `-C DIR`: recover a whole tree (optionally narrowed by `--index`,
///   repeatable) into `DIR`.
/// - `-o FILE --index N`: recover exactly the one entry at scan position `N`
///   to `FILE`. There is no separate single-file write path in
///   `entries.rs`: this still goes through `entries::salvage`'s ordinary
///   directory mode, into a [`TempDirGuard`]'s temporary directory with
///   `select` narrowed to `{N}`, and [`finish_single_file_recovery`] moves
///   the single result out to `FILE` afterward.
///
/// # `--list` reports the full scan; the summary and exit code report the selection
///
/// `entries::salvage` always returns a record for every scan position, `-o`
/// included — an unselected one comes back `NotSelected` rather than
/// omitted. `--list` prints exactly that full outcome, unfiltered, because a
/// diagnostic listing must not narrow just because `--index` narrowed what
/// gets WRITTEN. The default summary and the exit code below are the other
/// way around: both are filtered down to `select` when one was given
/// (`None` when it was not, so the whole scan either way), because those two
/// answer "how did the entries I asked to recover fare", not "what does this
/// archive hold" — `--index 6` on an otherwise-clean archive reports
/// `1 scanned, 1 skipped` and exits 4 even though the archive's OTHER seven
/// entries are all fine, because entry 6 is the only one the caller asked
/// about.
///
/// At least one of `-C`, `-o` or `--list` is required; `-C` and `-o` are
/// mutually exclusive; `-o` requires exactly one `--index`.
fn dispatch_salvage(args: SalvageArgs) -> stuffr::Result<i32> {
    let SalvageArgs {
        input,
        list,
        directory,
        output,
        index,
        partial,
        max_entry,
        strict,
        format,
    } = args;
    let format = match format.as_deref() {
        Some(name) => Some(salvage_format_by_name(name)?),
        None => None,
    };
    if directory.is_some() && output.is_some() {
        return Err(stuffr::Error::Usage(
            "-C and -o both name a destination; pass one or the other, not both".into(),
        ));
    }
    if directory.is_none() && output.is_none() && !list {
        return Err(stuffr::Error::Usage(
            "pass -C DIR to recover into a directory, -o FILE to recover one entry by \
             --index, or --list to see what the scan found without writing anything"
                .into(),
        ));
    }
    if output.is_some() && index.len() != 1 {
        return Err(stuffr::Error::Usage(
            "-o recovers exactly one entry; pass exactly one --index N naming its scan \
             position"
                .into(),
        ));
    }
    let path = match input_of(&input) {
        Input::Path(p) => p,
        Input::Stdin => {
            return Err(stuffr::Error::Usage(
                "salvage scans back and forth over the archive, which needs a real seekable \
                 file; pass a path, not `-`"
                    .into(),
            ));
        }
    };
    let partial_policy = match partial.as_deref() {
        None | Some("keep") => stuffr::salvage::PartialPolicy::Keep,
        Some("skip") => stuffr::salvage::PartialPolicy::Skip,
        Some("ask") => stuffr::salvage::PartialPolicy::Ask,
        Some(other) => {
            return Err(stuffr::Error::Usage(format!(
                "unknown --partial value `{other}`; expected keep, skip or ask"
            )));
        }
    };
    let mut policy = stuffr::salvage::SalvagePolicy {
        partial: partial_policy,
        strict,
        ..Default::default()
    };
    if let Some(raw) = max_entry {
        policy.max_entry = stuffr_cli::size::parse_size(&raw).map_err(stuffr::Error::Usage)?;
    }

    let select: Option<HashSet<usize>> = if index.is_empty() {
        None
    } else {
        Some(index.iter().copied().collect())
    };

    // `-o` recovers into a throwaway directory (cleaned up on every path out
    // of this function, including an early `?`, by `TempDirGuard`'s `Drop`)
    // and moves the one result out afterward; `-C` recovers directly into
    // the caller's own directory; `--list` alone recovers nowhere.
    let temp_guard = if output.is_some() {
        Some(fresh_temp_dir("one")?)
    } else {
        None
    };
    let dest = match (&directory, &temp_guard) {
        (Some(dir), _) => Some(PathBuf::from(dir)),
        (None, Some(guard)) => Some(guard.0.clone()),
        (None, None) => None,
    };

    let opts = SalvageOpts {
        dest,
        policy,
        select: select.clone(),
        format,
    };
    let outcome = entries::salvage(&path, &opts)?;

    // Task 2-N: a header the scanner SAW and could not gate is never a row,
    // so this line is the only trace of WHICH header it was — printed on
    // every run that has one, `--list`, `-C` and `-o` alike. Before it, a
    // mixed run lost an entry `stuffr list` shows at exit 0 with an empty
    // stderr. Nothing prints for a run with none. A non-selective run also
    // exits at least 4 for it (the final review's I-1; see the subset below).
    if let Some(note) = stuffr::salvage::describe_sightings(&outcome.sightings) {
        eprintln!("salvage -> {note}");
    }
    // Salvage Stage 3 Task 4: where a sequential-only scanner (`ar`) had to
    // stop. The entries behind a hole are unreachable by construction, not
    // absent, and no row or summary count can say so — so this line does, on
    // every run that has one, `--list`, `-C` and `-o` alike, and before the
    // "nothing recoverable" line below when the walk stopped at the first
    // header. It never moves the exit code (Ruling S-X).
    if let Some(stop) = &outcome.walk_stop {
        eprintln!("salvage -> {}", stuffr::salvage::describe_walk_stop(stop));
    }

    // Computed on the FULL scan: "nothing recoverable at all" is a fact
    // about the archive, not about which scan positions the caller happened
    // to ask for.
    if entries::salvage_exit_code(&outcome) == 5 {
        eprintln!("salvage -> the scan found nothing recoverable in this archive");
        return Ok(5);
    }

    validate_scan_positions(&index, outcome.entries.len())?;

    // Before anything else this run prints but the sighting note above: an
    // entry that could not be put on disk is named on stderr on EVERY
    // invocation, not only under `--list`. See `print_salvage_write_failures` for what a missing
    // stderr line measured before this existed.
    print_salvage_write_failures(&outcome.entries);

    // `--list` always reports the FULL scan, `--index` included — narrowing
    // WHAT IS WRITTEN must never narrow what a diagnostic listing shows.
    if list {
        print_salvage_list(&outcome.entries)?;
    }

    if let Some(output_path) = &output {
        finish_single_file_recovery(&outcome, index[0], Path::new(output_path))?;
    } else if !list {
        // The default summary — like the exit code below — reports on what
        // the CALLER asked about: the whole scan when no `--index` was
        // given, or just the selected subset when it was. `--list` above is
        // the one place the full scan is shown regardless of `--index`.
        let subset: Vec<entries::SalvagedRecord> = match &select {
            None => outcome.entries.clone(),
            Some(set) => outcome
                .entries
                .iter()
                .filter(|r| set.contains(&r.scan_position))
                .cloned()
                .collect(),
        };
        print_salvage_summary(&subset);
    }

    // Same reasoning as the summary: the exit code is about what the caller
    // asked to recover, not the whole archive. `-o` already narrowed
    // `select` to exactly the one requested entry, so this naturally
    // matches what `finish_single_file_recovery` just reported.
    //
    // Sightings follow the same rule (the final review's I-1): a whole-
    // archive run carries them and exits at least 4, while a selective run
    // drops them — a sighting has no scan position, so `--index` cannot
    // have asked for it, exactly as a `NotSelected` entry does not count.
    // The note above has already named it either way.
    let (subset, sightings): (Vec<entries::SalvagedRecord>, _) = match &select {
        None => (outcome.entries, outcome.sightings),
        Some(set) => (
            outcome
                .entries
                .into_iter()
                .filter(|r| set.contains(&r.scan_position))
                .collect(),
            Vec::new(),
        ),
    };
    Ok(entries::salvage_exit_code(&entries::SalvageOutcome {
        entries: subset,
        sightings,
        walk_stop: outcome.walk_stop,
    }))
}

/// The parenthesised fidelity phrase of a read-side summary line: `exact
/// fidelity` when clean, `exact access, N fidelity loss(es)` otherwise —
/// never the rung alone over a report that carries warnings. `test` and
/// `convert` print it; the rationale is `test`'s comment above.
fn read_fidelity_summary(report: &stuffr::FidelityReport) -> String {
    match report.warnings.len() {
        0 => format!("{} fidelity", report.rung),
        n => format!("{} access, {n} fidelity loss(es)", report.rung),
    }
}

/// The parenthesised fidelity phrase of a WRITE-side summary line (`pack`,
/// `convert`): `no fidelity loss`, or `N fidelity loss(es)`. Never the rung —
/// `Rung` describes the adaptive READ ladder and is a constant on a write, so
/// it would claim `exact` / `forward-only` about something that was not read.
fn write_fidelity_summary(report: &stuffr::FidelityReport) -> String {
    match report.warnings.len() {
        0 => "no fidelity loss".to_string(),
        n => format!("{n} fidelity loss(es)"),
    }
}

/// Prints what an operation approximated, and fails under --strict-fidelity.
///
/// The report is printed either way: a caller who did not ask for the gate
/// still needs to be able to SEE that an entry's mode was dropped, and a
/// caller who did needs to know which entries to look at — `FidelityDegraded`
/// carries only a count.
///
/// Capped at ten lines: an archive of ten thousand symlinks would otherwise
/// bury the summary line under ten thousand identical ones. The count in the
/// header is the complete figure regardless.
fn report_fidelity(report: &stuffr::FidelityReport, strict: bool) -> stuffr::Result<()> {
    if !report.has_warnings() {
        return Ok(());
    }
    const SHOWN: usize = 10;
    eprintln!("stuffr: {} fidelity warning(s):", report.warnings.len());
    for w in report.warnings.iter().take(SHOWN) {
        eprintln!("  - {w}");
    }
    if let Some(rest) = report.warnings.len().checked_sub(SHOWN).filter(|n| *n > 0) {
        eprintln!("  … and {rest} more");
    }
    if strict {
        return Err(stuffr::Error::FidelityDegraded(report.warnings.len()));
    }
    Ok(())
}

/// The `(container, codec)` pair a pack output names, if it names a container
/// at all — `--format tar`, or an extension chain that resolves to one
/// (`-o bundle.tar`, `-o bundle.tar.gz`, `-o bundle.tgz`).
///
/// `None` means the output names a codec (or nothing yet), which is the
/// single-stream path `pack` has always taken.
///
/// `Path::extension()` is NOT enough, and was the bug: for `x.tar.gz` it
/// returns `"gz"`, so the whole command took the single-stream codec path and
/// the `.tar` was never honoured — v0.2.0 wrote a plain gzip under a name
/// promising a tar, at exit 0. With an explicit `--format tar` the mirror
/// image happened: an uncompressed tar named `.tar.gz`, which `gunzip`
/// rejects. `chain_for_new_path` reads the whole chain, and shares its
/// extension table with the read side so `.tar.gz` cannot mean one thing to
/// `pack` and another to `list`.
///
/// `Err` is the case where the two sources of truth CONTRADICT each other:
/// `--format zip -o x.tar.gz` asks for a zip inside gzip under a name
/// promising a tar. Writing it is worse than refusing — the file is perfectly
/// good gzip, so `pack` exits 0 and `list` on the very same path then exits 5
/// calling stuffr's own output corrupt, because reading resolves the outer
/// layer by magic and the inner one by name. Exit 2 before anything is
/// written is the only honest answer.
fn resolve_pack_chain(
    fmt: Option<FormatId>,
    output: Option<&str>,
) -> stuffr::Result<Option<(FormatId, Option<FormatId>)>> {
    let registry = stuffr::registry();

    // An explicit --format names the CONTAINER; any codec still comes from
    // the output's name, so `--format tar -o x.gz` is tar over gzip.
    if let Some(id) = fmt {
        if registry.container(id).is_none() {
            return Ok(None);
        }
        let chain = output.map(|o| stuffr::chain_for_new_path(registry, Path::new(o)));
        if let Some(chain) = &chain
            && let Some(named) = chain.container()
            && named != id
        {
            let out = output.unwrap_or_default();
            return Err(stuffr::Error::Usage(format!(
                "--format {id} asks for a {id} archive, but the output name `{out}` says \
                 {named}. Writing it would exit 0 and leave a file `stuffr list` \
                 then calls corrupt, because a reader takes the container from \
                 the name. Rename the output, or drop --format and let the name \
                 decide."
            )));
        }
        let codec = chain.and_then(|c| c.outermost_codec());
        return Ok(Some((id, codec)));
    }

    // Otherwise the output name carries the whole chain, and the two cannot
    // disagree because there is only one of them.
    let Some(output) = output else {
        return Ok(None);
    };
    let chain = stuffr::chain_for_new_path(registry, Path::new(output));
    match chain.container() {
        Some(container) => Ok(Some((container, chain.outermost_codec()))),
        None => Ok(None),
    }
}

/// The paths `pack` will store as entries.
///
/// `-` is refused here: a pipe has no name, and every entry in an archive
/// needs one. The single-stream path still accepts it.
fn pack_inputs(paths: &[String]) -> stuffr::Result<Vec<PathBuf>> {
    if paths.iter().any(|p| p == "-") {
        return Err(stuffr::Error::Usage(
            "stdin has no name to store an entry under; name files instead of `-`".into(),
        ));
    }
    Ok(paths.iter().map(PathBuf::from).collect())
}

/// Refuses the flags the entry-aware path cannot honour.
///
/// The tree's rule, already applied to `--threads` on the decode subcommands:
/// a flag that would be silently accepted and ignored is refused instead.
///
/// `--no-sync` is deliberately NOT in this list. Extraction writes each entry
/// straight to its final path with no fsync at all, so "skip the fsync" is
/// already what happens — a flag asking for the behaviour you are getting
/// cannot mislead anybody.
fn refuse_unhonoured_extract_flags(output: bool, format: bool) -> stuffr::Result<()> {
    if output {
        return Err(stuffr::Error::Usage(
            "-o writes one decoded stream to one file; -C extracts entries into a \
             directory. Pass one or the other."
                .into(),
        ));
    }
    if format {
        return Err(stuffr::Error::Usage(
            "--format names a codec for a single-stream decode; entry-aware extraction \
             detects the container (and any codec above it) from the archive itself"
                .into(),
        ));
    }
    Ok(())
}

/// Refuses encoder flags only where the resolved chain has no codec layer to
/// hand them to.
///
/// Phase 2 refused these for any container output, correctly at the time:
/// none of the four registered containers compresses anything itself, so
/// there was genuinely nothing to hand a worker count, a CPU-cap lift or a
/// weak-encoder consent to. Accepting them there and silently dropping them
/// is the exact shape `refuse_unhonoured_extract_flags` above exists to
/// prevent.
///
/// Phase 2c makes `-o out.tar.xz` a real composed write with a codec layer
/// underneath the container, and that codec DOES honour a worker count —
/// `entries::create_archive` now builds its `EncodeOpts.governor` from
/// `ops::resolved_budget(o)` exactly as the single-stream path does. An
/// unconditional refusal would now reject a legitimate command, the shape
/// this project has hit repeatedly. `has_codec` is `resolve_pack_chain`'s
/// second tuple element: `Some` means the chain has a codec above the
/// container, `None` means a bare container with nothing to compress it.
///
/// `--memory-limit` is deliberately NOT here, in either case: it is honoured
/// on every decode path, and on a bare container pack it is simply inert in
/// the same way `--no-sync` is (nothing allocates a dictionary), so it costs
/// nothing to accept.
///
/// **All three sentences used to say "no container in this build compresses
/// anything itself", and that was already false when it was written:** `zip`
/// deflates its entries. Phase 3c Task 6 made it plainly false — `pack -o
/// x.lzh` runs a real `-lh5-` compressor (measured: 100 KB of text → 315
/// bytes) and `-o x.lzh --threads 4` meets this refusal. The honest reason
/// is narrower and is what they say now: no container here has a PARALLEL
/// encoder, so `--threads`/`--turbo` have nothing to govern, and none has a
/// weak fallback encoder for `--allow-weak-encoder` to consent to. The
/// refusals themselves are unchanged and still correct.
///
/// Worth recording because of what did NOT catch this: the examples-page
/// count guard derives its numbers from the LIVE registry, but the registry
/// tells it how many rows there are, never what any row's WRITE column says.
/// Every stale "read-only" sentence in this task had to be found by hand for
/// the same reason.
///
/// `convert` (Phase 5a) applies the same rule to its target chain, so the
/// logic — which flags, in which order — has one owner and only the reason
/// clause differs by `NoCodecLayer`. `pack`'s messages are byte-identical to
/// what they were before the generalisation; its tests pin them.
fn refuse_unhonoured_encoder_flags(
    flags: EncoderFlags,
    has_codec: bool,
    target: NoCodecLayer<'_>,
) -> stuffr::Result<()> {
    if has_codec {
        return Ok(());
    }
    // Only the reason after the semicolon depends on the verb: `pack`'s target
    // is a container it is building, `convert`'s is whatever chain is left
    // once the codec is removed (`.tar.gz` -> `.tar`, `.gz` -> a bare stream).
    let (threads_why, turbo_why, weak_why) = match target {
        NoCodecLayer::PackContainer => (
            "no container in this build has a parallel encoder of its own, so there is no \
             worker count to hand it"
                .to_string(),
            "no container in this build has a parallel encoder of its own".to_string(),
            "no container in this build has an encoder that can fall back".to_string(),
        ),
        NoCodecLayer::ConvertTarget(chain) => {
            let d = chain.describe();
            (
                format!(
                    "the target, {d}, has no codec layer, so there is no encoder to hand a \
                     worker count to"
                ),
                format!("the target, {d}, has no codec layer, so there is no encoder to run"),
                format!("the target, {d}, has no codec layer, so there is no encoder to fall back"),
            )
        }
    };
    if flags.threads {
        return Err(stuffr::Error::Usage(format!(
            "--threads governs a codec's parallel encoder; {threads_why}"
        )));
    }
    if flags.turbo {
        return Err(stuffr::Error::Usage(format!(
            "--turbo lifts the CPU cap for a codec's parallel encoder; {turbo_why}"
        )));
    }
    if flags.allow_weak_encoder {
        return Err(stuffr::Error::Usage(format!(
            "--allow-weak-encoder consents to a codec's fallback encoder; {weak_why}"
        )));
    }
    Ok(())
}

/// The encoder flags [`refuse_unhonoured_encoder_flags`] judges — whether
/// each was given, which is all the refusal needs.
///
/// `--level` is deliberately absent, as it always was from pack's list: `pack
/// -o x.tar --level 9` accepts it and it is inert, and `convert` to a
/// codec-less target does exactly the same rather than invent a second rule.
struct EncoderFlags {
    threads: bool,
    turbo: bool,
    allow_weak_encoder: bool,
}

impl EncoderFlags {
    fn of(opts: &CompressOpts) -> Self {
        Self {
            threads: opts.threads.is_some(),
            turbo: opts.turbo,
            allow_weak_encoder: opts.allow_weak_encoder,
        }
    }
}

/// What has no codec layer, for [`refuse_unhonoured_encoder_flags`]' wording.
enum NoCodecLayer<'a> {
    /// `pack` to a bare container. Its messages are pinned by its tests.
    PackContainer,
    /// `convert` to a target chain with no codec: a bare container, or a
    /// plain stream the codec was removed from.
    ConvertTarget(&'a Chain),
}

/// How `convert` gets from the source chain to the target chain.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ConvertMode {
    /// The container (or the plain stream) is kept byte for byte and only
    /// the codec changes — `ops::recompress_source`.
    Codec,
    /// The container changes; entries are read from one and written into the
    /// other.
    Entry,
}

/// The ONE owner of convert's mode table, applied to the source chain
/// `ops::ConvertSource` resolved by content and the target chain
/// [`convert_target_chain`] resolved from the command line.
///
/// | src -> dst | result |
/// |---|---|
/// | same container (two plain streams count as the same), codec differs | `Codec` |
/// | different containers | `Entry` |
/// | plain stream <-> container | exit 2, naming both chains |
/// | identical chain, no re-encode flag | exit 2, nothing to convert |
/// | identical chain with a codec, with `--level`/`--threads`/`--turbo` | `Codec` |
/// | identical chain with NO codec, whatever the flags | exit 2, nothing to convert |
///
/// "Identical" is whole-chain equality, so a source with several codec
/// layers (`gzip` over `xz` over `tar`) is never identical to a target,
/// which has at most one, and converting it peels them all.
fn convert_mode(
    src: &Chain,
    dst: &Chain,
    reencode: bool,
    dst_is_stdout: bool,
) -> stuffr::Result<ConvertMode> {
    match (src.container(), dst.container()) {
        (Some(a), Some(b)) if a != b => Ok(ConvertMode::Entry),
        (None, Some(_)) => Err(stuffr::Error::Usage(format!(
            "the input is {} and the output would be {}: a plain stream has no entries \
             to put in an archive. Decode it with `stuffr unpack`, then `stuffr pack` the \
             file into the archive.",
            src.describe(),
            dst.describe()
        ))),
        (Some(_), None) => Err(stuffr::Error::Usage(format!(
            "the input is {} and the output would be {}: an archive's entries do not fit \
             in a plain stream. Take them out with `stuffr unpack -C DIR` or `stuffr cat`, \
             or name an output that keeps the container. {}",
            src.describe(),
            dst.describe(),
            if dst_is_stdout {
                format!(
                    "To stream it, pipe through pack: `stuffr convert IN -o - --format {} | \
                     stuffr pack - -o - --format {}`.",
                    src.container().map(|c| c.to_string()).unwrap_or_default(),
                    dst.outermost_codec()
                        .map(|c| c.to_string())
                        .unwrap_or_default()
                )
            } else {
                String::new()
            }
        ))),
        // Re-encoding needs a codec, so an identical chain with none has
        // nothing to re-encode whatever the flags say: no hint.
        _ if src == dst && src.outermost_codec().is_none() => Err(stuffr::Error::Usage(format!(
            "nothing to convert: the input is already {}, which has no codec layer to \
             change.",
            src.describe()
        ))),
        _ if src == dst && !reencode => Err(stuffr::Error::Usage(format!(
            "nothing to convert: the input is already {}. Pass --level, --threads or \
             --turbo to re-encode it anyway.",
            src.describe()
        ))),
        _ => Ok(ConvertMode::Codec),
    }
}

/// The chain `convert` will write: from OUT's name, or from `--format`, with
/// the two refused (exit 2) where they contradict each other.
///
/// A container `--format` (or none at all) goes through `pack`'s own
/// [`resolve_pack_chain`], so `--format zip -o x.tar.gz` is refused by the
/// same code and in the same words for both verbs. A codec `--format` is
/// convert's own case — `pack` hands a codec `--format` straight to the
/// single-stream path without consulting the name at all — and is refused
/// unless the name is silent (`out.bin`, stdout) or names that same codec
/// outermost (`--format xz -o b.tar.xz`). A name saying another codec, or a
/// bare container, would otherwise yield a file whose name lies about it.
fn convert_target_chain(fmt: Option<FormatId>, output: Option<&str>) -> stuffr::Result<Chain> {
    if let Some((container, codec)) = resolve_pack_chain(fmt, output)? {
        let inner = Chain::Container { container };
        return Ok(match codec {
            Some(codec) => Chain::Codec {
                codec,
                inner: Box::new(inner),
            },
            None => inner,
        });
    }
    let named = output.map(|o| stuffr::chain_for_new_path(stuffr::registry(), Path::new(o)));
    let Some(id) = fmt else {
        // No --format and no container in the name: the name's codec, or
        // `Raw` for a name that says nothing (`.gz` -> `x` decodes).
        return Ok(named.unwrap_or(Chain::Raw));
    };
    match named {
        None | Some(Chain::Raw) => Ok(Chain::Codec {
            codec: id,
            inner: Box::new(Chain::Raw),
        }),
        Some(chain) if chain.outermost_codec() == Some(id) => Ok(chain),
        Some(chain) => Err(stuffr::Error::Usage(format!(
            "--format {id} asks for {id}, but the output name `{}` says {}. Rename the \
             output, or drop --format and let the name decide.",
            output.unwrap_or_default(),
            chain.describe()
        ))),
    }
}

/// Refuses (exit 2) a conversion whose output is its own input, before the
/// output is opened.
///
/// With `--force` the temp-file-then-rename write would otherwise replace the
/// input with its own conversion — harmless when it succeeds, but `convert`
/// reads the input WHILE writing, and a symlink destination takes the
/// direct-write branch (`Output::create`), truncating the very file being
/// read. Two tests, because neither alone is enough: canonical paths catch
/// `./a`, `a` and a symlink to `a`; only `(dev, ino)` catches a hard link,
/// whose name canonicalises to itself.
fn refuse_converting_onto_itself(input: &Path, output: &Path) -> stuffr::Result<()> {
    let canonical_match = match (std::fs::canonicalize(input), std::fs::canonicalize(output)) {
        (Ok(a), Ok(b)) => a == b,
        _ => false,
    };
    #[cfg(unix)]
    let inode_match = {
        use std::os::unix::fs::MetadataExt;
        match (std::fs::metadata(input), std::fs::metadata(output)) {
            (Ok(a), Ok(b)) => (a.dev(), a.ino()) == (b.dev(), b.ino()),
            _ => false,
        }
    };
    #[cfg(not(unix))]
    let inode_match = false;
    if canonical_match || inode_match {
        return Err(same_file_error(&input.display().to_string(), output));
    }
    Ok(())
}

fn same_file_error(input: &str, output: &Path) -> stuffr::Error {
    stuffr::Error::Usage(format!(
        "`{input}` and `{}` are the same file; convert reads its input while writing its \
         output, so it cannot convert a file onto itself. Name a different output.",
        output.display()
    ))
}

/// The stdin spelling of [`refuse_converting_onto_itself`]: `convert - -o l.xz
/// < big.xz` with `l.xz` a symlink to `big.xz` would truncate the input the
/// same way. When fd 0 is a regular file and OUT exists, compares `(dev, ino)`
/// (OUT's following symlinks). A pipe, a tty or a missing OUT cannot clash.
///
/// fd 0 is only read through a `dup` (`BorrowedFd::try_clone_to_owned`), so
/// dropping the handle closes the duplicate and never stdin itself; `fstat`
/// reads no bytes, so the stream is untouched.
#[cfg(unix)]
fn refuse_stdin_redirected_from(output: &Path) -> stuffr::Result<()> {
    use std::os::fd::AsFd;
    use std::os::unix::fs::MetadataExt;
    let Ok(fd) = std::io::stdin().as_fd().try_clone_to_owned() else {
        return Ok(());
    };
    let Ok(stdin_meta) = std::fs::File::from(fd).metadata() else {
        return Ok(());
    };
    if !stdin_meta.is_file() {
        return Ok(());
    }
    match std::fs::metadata(output) {
        Ok(o) if (o.dev(), o.ino()) == (stdin_meta.dev(), stdin_meta.ino()) => {
            Err(same_file_error("-", output))
        }
        _ => Ok(()),
    }
}

/// The kind column `list` prints — `EntryKind` is `#[non_exhaustive]`, so a
/// future variant added upstream falls into the wildcard rather than failing
/// to compile.
fn entry_kind_str(kind: &stuffr::EntryKind) -> &'static str {
    match kind {
        stuffr::EntryKind::File => "file",
        stuffr::EntryKind::Dir => "dir",
        stuffr::EntryKind::Symlink { .. } => "symlink",
        stuffr::EntryKind::Hardlink { .. } => "hardlink",
        stuffr::EntryKind::Other => "other",
        _ => "other",
    }
}

/// `list`'s output. Written through `std::io::stdout()` and propagated with
/// `?` rather than `println!`, matching `print_formats`/`Info` above — the
/// same reason: `println!` panics on a write error, which would defeat
/// `run`'s `BrokenPipe`-to-success mapping for `stuffr list big.tar | head`.
///
/// # The index column
///
/// The first column is the entry's 0-based position in archive order. It is
/// simply the position in the `Vec` `entries::list` returned, which that
/// function fills from one forward walk — the same walk `--index` counts. So
/// `list` and `cat --index`/`unpack --index` cannot disagree about what
/// entry 6 is; there is only one enumeration and both read it.
///
/// # The fidelity report
///
/// Printed through `report_fidelity`, the same call `test` and `unpack -C`
/// make, rather than a second printer here. `list` dropped the report
/// entirely until this was added: on a zip whose central directory holds 8
/// records under 6 names, `stuffr test` warned that 2 were shadowed while
/// `stuffr list` printed 6 rows and said nothing — the verb a user reaches
/// for first, silent about the one way its own output was incomplete.
///
/// Warnings go to stderr AFTER the listing goes to stdout, so `stuffr list a
/// | head` is unaffected by them and a redirected listing keeps the warning
/// visible on the terminal.
fn print_list(
    src: Input,
    json: bool,
    max_ratio: u64,
    memory_limit: Option<u64>,
    strict_fidelity: bool,
) -> stuffr::Result<()> {
    use std::io::Write;
    let (entries, outcome) = entries::list(src, max_ratio, memory_limit)?;
    let mut out = std::io::stdout();
    if json {
        let rows: Vec<serde_json::Value> = entries
            .iter()
            .enumerate()
            .map(|(i, e)| {
                serde_json::json!({
                    "index": i,
                    "name": e.name,
                    "kind": entry_kind_str(&e.kind),
                    "size": e.size,
                })
            })
            .collect();
        writeln!(out, "{}", serde_json::Value::Array(rows))?;
    } else {
        for (i, e) in entries.iter().enumerate() {
            match e.size {
                Some(n) => writeln!(out, "{i:>5}  {n:>12}  {}", stuffr::fmt_name(&e.name))?,
                None => writeln!(out, "{i:>5}  {:>12}  {}", "-", stuffr::fmt_name(&e.name))?,
            }
        }
    }
    out.flush()?;
    report_fidelity(&outcome.fidelity, strict_fidelity)
}

/// The one selector a read verb acts on, built from the two spellings a user
/// can type.
///
/// `--index` and PATTERNS are **mutually exclusive**, not combinable. They
/// are two ways of saying "which entries", and a command that says it both
/// ways has no meaning anybody would agree on: is `unpack a.zip README
/// --index 3` the union (two entries) or the intersection (README, but only
/// if it happens to sit at 3)? Either reading silently does something the
/// user did not mean half the time. Exit 2, before a byte is read, is the
/// only answer that cannot be wrong.
///
/// Refused here rather than with clap's own `conflicts_with` so the message
/// is stuffr-shaped and says WHY, the same way
/// `refuse_unhonoured_extract_flags` does; and below this function the
/// ambiguity is unrepresentable, because `stuffr::entries::Selection` has no
/// variant that can hold both.
fn selection_of(patterns: Vec<String>, index: Vec<usize>) -> stuffr::Result<Selection> {
    match (patterns.is_empty(), index.is_empty()) {
        (true, true) => Ok(Selection::All),
        (false, true) => Ok(Selection::Names(patterns)),
        (true, false) => Ok(Selection::Indices(index)),
        (false, false) => Err(stuffr::Error::Usage(
            "--index and entry patterns are two ways of choosing the same thing; \
             pass one or the other, not both"
                .into(),
        )),
    }
}

/// Resolves a `--format` name against the registry.
///
/// `FormatId` holds a `&'static str` so the registry can be built from
/// constants without allocation, but a flag value arrives at runtime as a
/// `String`. Rather than leak it to reach `'static`, look it up: the registry
/// already holds the `'static` id, and an unknown name gets a real error
/// naming what this build does have.
fn format_by_name(name: &str) -> stuffr::Result<FormatId> {
    stuffr::registry()
        .matrix()
        .into_iter()
        .find(|r| r.id.as_str() == name)
        .map(|r| r.id)
        .ok_or_else(|| {
            let known: Vec<&str> = stuffr::registry()
                .matrix()
                .iter()
                .map(|r| r.id.as_str())
                .collect();
            stuffr::Error::Usage(format!(
                "unknown format `{name}`; this build has: {}",
                if known.is_empty() {
                    "none".to_string()
                } else {
                    known.join(", ")
                }
            ))
        })
}

/// Resolves `salvage --format` against the set of container formats salvage
/// could ever be asked to scan — deliberately NOT [`format_by_name`], which
/// only recognises what THIS build's live registry has compiled.
///
/// Salvage's own contract (Task 2) is that naming a format this build has
/// not compiled is still [`stuffr::Error::Unsupported`]/[`stuffr::Error::
/// FormatNotEnabled`] (exit 3, "this build cannot do that") — the same
/// build-capability shape `require_container_writer` answers with elsewhere
/// — never [`stuffr::Error::Usage`] (exit 2, "you typed something wrong").
/// `format_by_name` cannot make that distinction: an uncompiled format is
/// simply absent from its registry lookup, so it reports "unknown format"
/// exactly as it would for a genuine typo. Matching against this fixed,
/// static table instead is also what sidesteps `FormatId`'s `'static`
/// requirement without leaking the runtime `String` — see
/// `format_by_name`'s own doc for the leak this avoids.
///
/// A name outside this table names no archive format `stuffr salvage` will
/// ever recognise, compiled or not, so that case stays [`stuffr::Error::
/// Usage`] — a caller typo, not a build limitation.
fn salvage_format_by_name(name: &str) -> stuffr::Result<FormatId> {
    match name {
        "zip" => Ok(FormatId::new("zip")),
        "tar" => Ok(FormatId::new("tar")),
        "ar" => Ok(FormatId::new("ar")),
        "cpio" => Ok(FormatId::new("cpio")),
        "arc" => Ok(FormatId::new("arc")),
        "zoo" => Ok(FormatId::new("zoo")),
        "lha" => Ok(FormatId::new("lha")),
        "arj" => Ok(FormatId::new("arj")),
        other => Err(stuffr::Error::Usage(format!(
            "unknown format `{other}`; salvage recognizes: zip, tar, ar, cpio, arc, zoo, lha, \
             arj"
        ))),
    }
}

/// Writes through `std::io::stdout()` and propagates a write failure rather
/// than `println!`ing it, so `run`'s `BrokenPipe`-to-success mapping can
/// actually see it.
///
/// `println!`/`print!` panic on a write error instead of returning one — see
/// the doc on `destination_is_stdout` — so `stuffr formats` and `stuffr info`
/// (which `destination_is_stdout` already lists as stdout destinations) used
/// to exit 101 with "failed printing to stdout: Broken pipe" instead of
/// exiting cleanly like every other early-closed-reader case.
fn print_formats() -> stuffr::Result<()> {
    use std::io::Write;
    let mut out = std::io::stdout();
    let rows = stuffr::registry().matrix();
    if rows.is_empty() {
        writeln!(out, "This build contains 0 formats.")?;
        writeln!(
            out,
            "(Phase 0 validates the core against mock formats; Phase 1 adds real ones.)"
        )?;
        return Ok(());
    }
    writeln!(
        out,
        "{:<16} {:<10} {:<5} {:<5} {:<8} {:<7} EXTENSIONS",
        "FORMAT", "KIND", "READ", "WRITE", "PARALLEL", "SALVAGE"
    )?;
    let registry = stuffr::registry();
    for r in rows {
        // A codec's own capabilities, not the matrix row's read/write/parallel
        // summary, are what carry `weak_encoder` — look it up directly rather
        // than growing FormatRow for one column only `stuffr formats` reads.
        let weak = r.write
            && r.kind == stuffr::FormatKind::Codec
            && registry.codec(r.id).is_some_and(|c| c.caps().weak_encoder);
        writeln!(
            out,
            "{:<16} {:<10} {:<5} {:<5} {:<8} {:<7} {}",
            r.id.as_str(),
            match r.kind {
                stuffr::FormatKind::Codec => "codec",
                stuffr::FormatKind::Container => "container",
            },
            if r.read { "yes" } else { "-" },
            if weak {
                "weak"
            } else if r.write {
                "yes"
            } else {
                "-"
            },
            if r.parallel { "yes" } else { "-" },
            salvage_column(registry, r.id),
            r.extensions.join(", "),
        )?;
    }
    // Below the table, not between the header and the first row. Inline, it
    // separated the column headings from the data they label, which made the
    // whole table hard to scan.
    writeln!(out)?;
    writeln!(
        out,
        "(WRITE shows `weak` for a codec whose encoder in this build is a fallback markedly \
         worse than the format's usual one — see --allow-weak-encoder.)"
    )?;
    writeln!(
        out,
        "(SALVAGE shows `yes` where `stuffr salvage` scans, verifies each entry against a \
         checksum the archive carries, and writes; `weak` where it scans and writes but the \
         format checksums nothing an entry's content can be verified against.)"
    )?;
    Ok(())
}

/// `stuffr formats`' SALVAGE cell for one row: `-` where this build has no
/// salvage scanner, `yes` where the format carries a checksum over each
/// entry's content, `weak` where it does not.
///
/// Two facts, each read from its one owner, never restated here: WHETHER
/// salvage is supported is the container's own
/// [`ContainerCaps::salvage`](stuffr::ContainerCaps::salvage); HOW MUCH a
/// recovered entry can be trusted is the format's
/// [`Attestation`](stuffr::salvage::Attestation) class, from
/// [`stuffr::entries::salvage_attestation`]. `weak` is tar (a checksum over
/// each header, none over content — at best `Complete`), cpio and ar (no
/// checksum at all — `Unattested`): salvage still scans and writes them, so
/// `-` would be false, and `yes` would promise a verification they cannot
/// have. The spec's other `weak` case — "this build cannot decode some
/// methods" — has no per-build fact to read and is not guessed at.
///
/// A row with the caps flag but no class cannot occur: `stuffr::entries`'
/// `salvage_caps_tests` pins the flag to the dispatch table the class lives
/// in. It renders `-`, the answer that claims nothing.
fn salvage_column(registry: &stuffr::Registry, id: FormatId) -> &'static str {
    use stuffr::salvage::Attestation;
    let supported = registry.container(id).is_some_and(|c| c.caps().salvage);
    if !supported {
        return "-";
    }
    match stuffr::entries::salvage_attestation(id) {
        Some(Attestation::ContentChecksum) => "yes",
        Some(Attestation::HeaderChecksumOnly | Attestation::Nothing) => "weak",
        None => "-",
    }
}

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

    /// `salvage_format_by_name`'s own doc explains why its table cannot be
    /// gated by feature (naming an uncompiled format must still answer
    /// `Unsupported`/`FormatNotEnabled`, never `Usage`) — but that also
    /// means nothing has ever forced the table to grow alongside the
    /// registry it stands in for. It was a hand-maintained eight-name list
    /// with no test pinning it to anything live. Salvage Stage 2 Task 3
    /// wired a real scanner behind the `arc` entry the table already held,
    /// which is exactly the moment such drift would have gone unnoticed —
    /// so this derives the expectation from the LIVE registry instead of
    /// restating the list by hand: the next container format to register
    /// (`zoo`, most likely) fails THIS test the day it lands, rather than
    /// silently falling through to salvage's own `Usage` catch-all forever.
    #[test]
    fn salvage_format_by_name_recognises_every_registered_container() {
        let containers: Vec<_> = stuffr::registry()
            .matrix()
            .into_iter()
            .filter(|row| row.kind == stuffr::FormatKind::Container)
            .collect();
        assert!(
            !containers.is_empty(),
            "sanity: this build must register at least one container format"
        );
        for row in &containers {
            let name = row.id.as_str();
            assert!(
                salvage_format_by_name(name).is_ok(),
                "salvage_format_by_name does not recognise `{name}`, which this build's own \
                 registry reports as a live container — `salvage_format_by_name` needs a new \
                 arm for it"
            );
        }
    }

    fn record(
        status: stuffr::salvage::SalvageStatus,
        disposition: entries::SalvageDisposition,
    ) -> entries::SalvagedRecord {
        entries::SalvagedRecord {
            scan_position: 0,
            name: "notes.txt".into(),
            status,
            shadows: None,
            collides_with: None,
            marked_deleted: false,
            disposition,
        }
    }

    /// Fix round 1, F2: a plain `salvage x.cpio -C out` must say WHY it exits
    /// 4. An `Unattested` entry is written, so the counts alone read like a
    /// clean run; without the second line the run would exit 4 with nothing
    /// on stderr to explain it — the shape Stage 2 paid for with
    /// `SkippedUnwritable`.
    #[test]
    fn an_unattested_run_says_why_on_the_default_summary() {
        let written = entries::SalvageDisposition::Written(std::path::PathBuf::from("/o/n"));
        let lines = salvage_summary_lines(&[
            record(stuffr::salvage::SalvageStatus::Unattested, written.clone()),
            record(stuffr::salvage::SalvageStatus::Unattested, written.clone()),
        ]);
        assert!(
            lines[0].contains("2 written") && lines[0].contains("2 unattested"),
            "the counts must still add up and name the tally: {lines:?}"
        );
        assert_eq!(
            lines.len(),
            2,
            "a reason line must follow the counts: {lines:?}"
        );
        assert!(
            lines[1].contains("no checksum and no header self-check")
                && lines[1].contains("exits 4"),
            "the reason must name the format's shortcoming and the exit code: {lines:?}"
        );

        // Skipped under `--strict` still counts: the tally is about the
        // format, the skip is about the flag.
        let lines = salvage_summary_lines(&[record(
            stuffr::salvage::SalvageStatus::Unattested,
            entries::SalvageDisposition::SkippedUnattested,
        )]);
        assert!(
            lines[0].contains("1 skipped") && lines[0].contains("1 unattested"),
            "{lines:?}"
        );

        // And the line is specific to the tier: a clean run prints the
        // counts alone, `0 unattested` included, and no reason line.
        let lines =
            salvage_summary_lines(&[record(stuffr::salvage::SalvageStatus::Complete, written)]);
        assert_eq!(lines.len(), 1, "no reason line for a clean run: {lines:?}");
        assert!(lines[0].contains("0 unattested"), "{lines:?}");
    }

    /// Task 3 review, M3: a healthy cpio holding a symlink printed "4
    /// written … 1 skipped … 5 unattested" and then said all five were "kept
    /// under the real name" — the skipped symlink was not kept at all. The
    /// note names what was kept and what was not; the tally is unchanged.
    #[test]
    fn the_unattested_note_counts_only_what_was_kept() {
        let written = entries::SalvageDisposition::Written(std::path::PathBuf::from("/o/n"));
        let mut records =
            vec![record(stuffr::salvage::SalvageStatus::Unattested, written.clone()); 4];
        records.push(record(
            stuffr::salvage::SalvageStatus::Unattested,
            entries::SalvageDisposition::SkippedUnsupportedKind,
        ));
        let lines = salvage_summary_lines(&records);
        assert!(
            lines[0].contains("4 written") && lines[0].contains("5 unattested"),
            "{lines:?}"
        );
        assert!(
            lines[1].contains("5 entries are unattested")
                && lines[1].contains("4 kept under the real name and 1 not written")
                && !lines[1].contains("unless --strict"),
            "{lines:?}"
        );

        // All kept: the sentence the other paths already print, unchanged.
        let lines = salvage_summary_lines(&records[..4]);
        assert!(
            lines[1].contains("4 entries are unattested")
                && lines[1].contains("kept under the real name unless --strict"),
            "{lines:?}"
        );
    }

    /// Ruling 3-H: a row `--strict` declined names the flag, which is also
    /// the remedy.
    #[test]
    fn a_strict_skipped_unattested_row_names_the_flag() {
        let row = describe_salvage_row(&record(
            stuffr::salvage::SalvageStatus::Unattested,
            entries::SalvageDisposition::SkippedUnattested,
        ));
        assert!(row.contains("Unattested"), "{row}");
        assert!(
            row.contains("--strict"),
            "the row must name the flag: {row}"
        );
    }

    /// Salvage Stage 3: the `Unattested` row names the FORMAT's shortcoming
    /// where the user meets the entry.
    ///
    /// Pinned as a unit test because, when it was written, the tier was not
    /// reachable from any scanner. Waiting would have meant shipping the
    /// rendering with nothing exercising it at all, which is how a status
    /// reaches a user as a bare word with no explanation. `cpio` (Task 3)
    /// reaches it now, and `cli.rs`'s
    /// `salvage_recovers_a_damaged_cpio_as_unattested` pins the row end to
    /// end as well.
    ///
    /// Two facts, deliberately: the tier is NAMED (so the row is not just
    /// the entry's name with a mystery column), and the REASON rides along
    /// (because unlike every other tag on the row, this one is a property
    /// of the format rather than of the record, and a user who has never
    /// met `cpio` has nowhere else to learn it).
    #[test]
    fn an_unattested_row_carries_the_reason_beside_the_entry() {
        let record = entries::SalvagedRecord {
            scan_position: 3,
            name: "notes.txt".into(),
            status: stuffr::salvage::SalvageStatus::Unattested,
            shadows: None,
            collides_with: None,
            marked_deleted: false,
            disposition: entries::SalvageDisposition::Written(std::path::PathBuf::from(
                "/out/notes.txt",
            )),
        };
        let row = describe_salvage_row(&record);
        assert!(
            row.contains("Unattested"),
            "the row must name the tier: {row}"
        );
        assert!(
            row.contains("no checksum and no header self-check in this format"),
            "the row must carry the reason, not just the tier: {row}"
        );
        assert!(
            row.contains("notes.txt"),
            "the row must name the entry: {row}"
        );

        // And the tag is specific to this tier, not to "any row salvage
        // prints": a `Complete` entry (tar, whose header DID self-verify)
        // must not be told its format has no header self-check.
        let complete = entries::SalvagedRecord {
            status: stuffr::salvage::SalvageStatus::Complete,
            ..record
        };
        assert!(
            !describe_salvage_row(&complete).contains("no checksum"),
            "the reason tag must not leak onto a tier that does not have that problem"
        );
    }
}