dev-prune 1.23.0

Universal, lockfile-safe workspace pruner and background dependency cleaner
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
// Copyright 2026 VKrishna04
// SPDX-License-Identifier: Apache-2.0

// Handler for `dev-prune caches docker`, `caches podman` and `caches containers`.
//
// A container engine is usually the largest thing on a developer's disk and the last one
// anybody looks at. `devp caches` already answers "how big is the npm cache"; this
// answers the same question about images, stopped containers, dangling volumes and the
// build cache, which between them routinely hold more than every package manager cache
// on the machine combined.
//
// **Nothing on a schedule will ever delete any of it**, and until 1.17.0 nothing here
// deleted it at all. The reasoning behind that has not changed: a container image has no
// lockfile — the registry tag it came from can be retagged or deleted, the Dockerfile
// that built it may not be on this disk — and a named volume is the one thing in the
// whole system that is not reproducible at any price.
//
// What changed is who runs the command. The report used to end by printing four commands
// and asking the reader to go type one in another window, which meant the reclaim was
// theirs to have remembered, and dev-prune could neither count it nor say afterwards what
// it had cost. `caches clear <engine>` now runs the narrow ones itself — build cache,
// unused images, stopped containers — in the foreground, after printing them, after
// asking, and never from the daemon. The bulk volume-deleting variants stay printed and
// unrun: no argv here ever contains `volume prune` or `--volumes`. What `--include-volumes`
// adds is not a bulk delete but a pick list, unused volumes named one per line for a
// person at a terminal to choose from, each choice becoming its own unforced `volume rm`.
// It refuses `--yes`, `--json` and a piped stdin, so no script, scheduler, hook or agent
// can reach it: the typing of each number is the consent. And the list is read before it
// is picked from: the real command only arms within ten minutes of a completed dry run
// for that engine, and outside that window it *is* the dry run, said out loud.
//
// The numbers come from the engine's own `system df`, not from a directory walk. On
// Docker Desktop and Podman the store lives inside a VM disk image that the host cannot
// see, and `~/.docker` is a config directory rather than the data — a size taken from
// the filesystem would be wrong by orders of magnitude, and wrong in the reassuring
// direction. Asking the engine is also the only way to learn what is *reclaimable*,
// which is the figure that decides anything: 40 GB of images with 38 GB dangling is a
// different situation from 40 GB with 2 GB dangling.
//
// Kubernetes is reported as names and no bytes. kind, k3d and minikube run their nodes
// as containers or as a VM disk belonging to an engine that is already in the table
// above, so a size beside a cluster name would be gigabytes counted twice.

use std::path::PathBuf;

use anyhow::Result;
use colored::Colorize;
use serde_json::Value;

use crate::adapters;
use crate::constants;
use crate::json;
use crate::output;

/// A container engine dev-prune knows how to ask about its disk use.
struct Engine {
    /// What it is called in output, and the name accepted on the command line.
    name: &'static str,
    /// The executable to look for and to ask.
    binary: &'static str,
    /// Arguments that make it print its disk usage as JSON.
    ///
    /// Docker, nerdctl and finch take a Go template; Podman and Apple's `container` take
    /// a format name. The first four then produce the same rows in one of two
    /// punctuations, which is why one parser reads either; Apple's is a different
    /// document and [`parse_rows`] says so.
    df_args: &'static [&'static str],
    /// The reclaim commands worth printing, narrowest first, each with what it costs.
    ///
    /// Printed and never run. The order is the order to try them in: the build cache is
    /// almost always the biggest win and the only one that costs nothing but a slower
    /// next build, and the volume-deleting variant is last because it is the one that
    /// destroys data no registry can hand back.
    prune: &'static [(&'static str, &'static str)],
    /// The steps `devp caches clear <engine>` runs, in order.
    ///
    /// A separate table from `prune` on purpose. That one is every command worth knowing
    /// about, including the volume-deleting variant nobody should reach for casually;
    /// this one is only what dev-prune is willing to run itself. There is no argv here
    /// that touches a volume, so "volumes are left alone" is a property of the table
    /// rather than a flag someone can pass or a check that could be forgotten.
    reclaim: &'static [ReclaimStep],
    /// Whether this engine stops to ask before it prunes.
    ///
    /// Docker, Podman, nerdctl and finch all do, and all take `-f` to say the question
    /// has already been asked — which dev-prune has, by name, in the plan it printed
    /// first. Apple's `container` has neither the question nor the flag: `container
    /// prune` removes stopped containers and prints what it reclaimed, and a `-f` it does
    /// not define would turn every step into a usage error. So this is a fact about the
    /// engine, checked in the tests, rather than a habit applied to all of them.
    prompts: bool,
    /// How to name this engine's unused volumes, when it can. See [`VolumeSurface`].
    ///
    /// `None` for the engines that cannot: nerdctl's `volume ls` filters on label, name
    /// and size but not on dangling (its own command reference says "not supported
    /// yet"), finch forwards to nerdctl verbatim, and Apple's `container` exposes no
    /// per-volume usage at all. For those, `--include-volumes` is a usage error that
    /// points at the engine's own `volume ls`, because a pick list dev-prune cannot
    /// prove is unused would be a list of guesses.
    volume_candidates: Option<VolumeSurface>,
}

/// The three commands behind `--include-volumes`, for an engine that has them.
///
/// The only deleting argv in here is `rm_args`, and it is deliberately incomplete: its
/// final argument is one volume's name, appended only after a person picked that volume
/// off a numbered list at a terminal. It is never forced, so a volume something still
/// uses is the engine's own refusal rather than dev-prune's judgement call.
struct VolumeSurface {
    /// Arguments that print one unused volume name per line and nothing else.
    ls_args: &'static [&'static str],
    /// Arguments for the verbose disk usage that sizes volumes individually.
    ///
    /// Decoration on the pick list, not a gate: an answer in a shape
    /// [`parse_volume_sizes`] cannot read degrades to "size unknown" on each row.
    df_args: &'static [&'static str],
    /// The delete, missing its final argument: one picked volume's name.
    rm_args: &'static [&'static str],
}

/// One command `devp caches clear <engine>` runs.
struct ReclaimStep {
    /// What it gives back, in the plan and in the result line.
    what: &'static str,
    /// The engine's own arguments, forced non-interactive.
    ///
    /// `-f` is not a shortcut past a confirmation the user never saw: dev-prune has
    /// already asked, by name, for everything these steps do. What it prevents is the
    /// engine asking a second question at a prompt this process may not own.
    args: &'static [&'static str],
}

/// Width of the command column under "Reclaim it yourself".
///
/// `docker system prune --volumes` is the longest command printed at 29 characters, and
/// every cost string below is written to fit the remainder inside 90 columns.
const COMMAND_WIDTH: usize = 32;

/// Every engine this command knows, in the order they are reported.
const ENGINES: &[Engine] = &[
    Engine {
        name: "docker",
        binary: "docker",
        prompts: true,
        df_args: &["system", "df", "--format", "{{json .}}"],
        prune: &[
            (
                "docker builder prune",
                "the build cache; costs a slower next build",
            ),
            (
                "docker image prune",
                "dangling images no tag points at any more",
            ),
            (
                "docker container prune",
                "stopped containers and each writable layer",
            ),
            (
                "docker system prune",
                "the three above at once; volumes untouched",
            ),
            (
                "docker system prune --volumes",
                "adds unused volumes — the one that deletes data",
            ),
        ],
        reclaim: &[
            ReclaimStep {
                what: "the build cache",
                args: &["builder", "prune", "-a", "-f"],
            },
            ReclaimStep {
                what: "images no container uses",
                args: &["image", "prune", "-a", "-f"],
            },
            ReclaimStep {
                what: "stopped containers and their writable layers",
                args: &["container", "prune", "-f"],
            },
        ],
        volume_candidates: Some(VolumeSurface {
            ls_args: &["volume", "ls", "-q", "--filter", "dangling=true"],
            // `-v` is what puts a per-volume table in the answer; without it the
            // document has only the four summary rows the report already reads.
            df_args: &["system", "df", "-v", "--format", "{{json .}}"],
            rm_args: &["volume", "rm"],
        }),
    },
    Engine {
        name: "podman",
        binary: "podman",
        prompts: true,
        df_args: &["system", "df", "--format", "json"],
        prune: &[
            (
                "podman system prune",
                "stopped containers, networks, dangling images",
            ),
            (
                "podman image prune -a",
                "every image no container uses, tagged or not",
            ),
            (
                "podman system prune --volumes",
                "adds unused volumes — the one that deletes data",
            ),
        ],
        reclaim: &[
            ReclaimStep {
                what: "the build cache",
                args: &["builder", "prune", "-a", "-f"],
            },
            ReclaimStep {
                what: "images no container uses",
                args: &["image", "prune", "-a", "-f"],
            },
            ReclaimStep {
                what: "stopped containers and their writable layers",
                args: &["container", "prune", "-f"],
            },
        ],
        // Podman documents the same `dangling=true` filter as Docker: "matches all
        // volumes not referenced by any containers". Its verbose `system df` names its
        // JSON fields its own way, which is why the size parser reads either spelling.
        volume_candidates: Some(VolumeSurface {
            ls_args: &["volume", "ls", "-q", "--filter", "dangling=true"],
            df_args: &["system", "df", "-v", "--format", "json"],
            rm_args: &["volume", "rm"],
        }),
    },
    Engine {
        name: "nerdctl",
        binary: "nerdctl",
        prompts: true,
        df_args: &["system", "df", "--format", "{{json .}}"],
        prune: &[
            (
                "nerdctl system prune",
                "stopped containers, networks, dangling images",
            ),
            (
                "nerdctl system prune --volumes",
                "adds unused volumes — the one that deletes data",
            ),
        ],
        // One step rather than three: nerdctl spells its narrow prune subcommands
        // differently across versions, and `system prune` has meant the same thing —
        // images, containers, build cache, volumes only with `--volumes` — since it
        // gained the command.
        reclaim: &[ReclaimStep {
            what: "images, stopped containers and the build cache",
            args: &["system", "prune", "-a", "-f"],
        }],
        volume_candidates: None,
    },
    // finch is nerdctl inside a Lima VM, and it forwards `system` to it verbatim with
    // flag parsing turned off — so the nerdctl spellings above are the finch spellings,
    // template and all. Its store is inside that VM's disk image, which is the same
    // reason the host cannot size it and the engine has to be the one asked.
    Engine {
        name: "finch",
        binary: "finch",
        prompts: true,
        df_args: &["system", "df", "--format", "{{json .}}"],
        prune: &[
            (
                "finch system prune",
                "stopped containers, networks, dangling images",
            ),
            (
                "finch system prune --volumes",
                "adds unused volumes — the one that deletes data",
            ),
        ],
        reclaim: &[ReclaimStep {
            what: "images, stopped containers and the build cache",
            args: &["system", "prune", "-a", "-f"],
        }],
        volume_candidates: None,
    },
    // Apple's `container`, on Apple silicon. Named after its binary like the rest, so
    // `devp caches clear container` is the command someone who has been typing
    // `container` all day would guess.
    //
    // It is the odd one here twice over. Its `system df` answers with one object whose
    // fields are the resource types rather than a row each, and its prune subcommands
    // have no confirmation and therefore no `-f`. There is also nothing to clear a build
    // cache with: BuildKit lives in a builder VM, and `container builder delete` removes
    // the builder itself rather than pruning what it cached, which is more than being
    // asked for.
    Engine {
        name: "container",
        binary: "container",
        prompts: false,
        df_args: &["system", "df", "--format", "json"],
        prune: &[
            (
                "container image prune -a",
                "every image no container uses, tagged or not",
            ),
            (
                "container prune",
                "stopped containers and their writable layers",
            ),
            (
                "container volume prune",
                "unused volumes — the one that deletes data",
            ),
        ],
        reclaim: &[
            ReclaimStep {
                what: "images no container uses",
                args: &["image", "prune", "-a"],
            },
            ReclaimStep {
                what: "stopped containers and their writable layers",
                args: &["prune"],
            },
        ],
        volume_candidates: None,
    },
];

/// One line of an engine's own disk-usage report.
pub struct Row {
    /// `Images`, `Containers`, `Local Volumes`, `Build Cache` — the engine's own word
    /// for it, kept verbatim so the row matches what `docker system df` prints.
    pub kind: String,
    /// How many of them there are, when the engine says.
    pub total: Option<u64>,
    /// How many of those are in use.
    pub active: Option<u64>,
    /// Bytes on disk.
    pub bytes: Option<u64>,
    /// Bytes the engine believes it could give back.
    pub reclaimable: Option<u64>,
}

/// What was found for one engine.
pub enum EngineState {
    /// It answered, and this is what it said.
    Ready(Vec<Row>),
    /// The binary is installed and the query did not answer. Almost always a daemon
    /// that is not running, so the engine's own words are carried through rather than
    /// guessed at.
    Unavailable(String),
}

/// One engine's entry in the report. Engines that are not installed produce none.
pub struct EngineReport {
    /// The engine's name.
    pub name: &'static str,
    /// Whether it answered, and what with.
    pub state: EngineState,
}

impl EngineReport {
    /// Total bytes across every row, or `None` when the engine did not answer.
    pub fn total_bytes(&self) -> Option<u64> {
        match &self.state {
            EngineState::Ready(rows) => Some(rows.iter().filter_map(|r| r.bytes).sum()),
            EngineState::Unavailable(_) => None,
        }
    }

    /// Total reclaimable bytes across every row, or `None` when it did not answer.
    pub fn reclaimable_bytes(&self) -> Option<u64> {
        match &self.state {
            EngineState::Ready(rows) => Some(rows.iter().filter_map(|r| r.reclaimable).sum()),
            EngineState::Unavailable(_) => None,
        }
    }
}

/// Ask every installed engine, or only the one named.
///
/// `None` for `only` means every engine found. An engine whose binary is not on `PATH`
/// is absent from the result entirely — there is nothing to say about a tool that is
/// not installed, and a row saying so on every machine without Podman would be noise.
pub fn collect(only: Option<&str>) -> Vec<EngineReport> {
    ENGINES
        .iter()
        .filter(|e| only.is_none_or(|name| e.name.eq_ignore_ascii_case(name)))
        .filter(|e| adapters::binary_available(e.binary))
        .map(probe)
        .collect()
}

/// Ask one engine how much disk it is using.
fn probe(engine: &Engine) -> EngineReport {
    let captured = adapters::capture_allowing_failure(
        engine.binary,
        engine.df_args,
        &query_dir(),
        std::time::Duration::from_secs(constants::CONTAINER_QUERY_TIMEOUT_SECS),
    );

    let state =
        match captured {
            Ok(out) if out.ok => {
                let rows = parse_rows(&out.stdout);
                if rows.is_empty() {
                    // It exited zero and said nothing this parser recognised. Reporting a
                    // total of zero would be a claim about the machine that was never made.
                    EngineState::Unavailable(format!(
                        "{} answered `system df` in a format dev-prune could not read",
                        engine.name
                    ))
                } else {
                    EngineState::Ready(rows)
                }
            }
            Ok(out) => EngineState::Unavailable(first_line(&out.stderr).unwrap_or_else(|| {
                format!("`{} system df` failed without saying why", engine.name)
            })),
            Err(e) => EngineState::Unavailable(
                first_line(&e.to_string())
                    .unwrap_or_else(|| format!("`{} system df` could not be run", engine.name)),
            ),
        };

    EngineReport {
        name: engine.name,
        state,
    }
}

/// The engine's first line of complaint, which is the part a human needs.
///
/// Docker follows "cannot connect to the daemon" with a paragraph about how to start it;
/// Podman follows its own with a stack of socket paths. Neither belongs in a table.
fn first_line(raw: &str) -> Option<String> {
    let line = raw.lines().map(str::trim).find(|l| !l.is_empty())?;
    // Generous, because this is wrapped rather than laid out in a column: Docker's
    // daemon-down message is about 200 characters and saying most of it is worse than
    // saying all of it. The cap is only here so a pathological engine cannot paste a
    // megabyte of one-line output into the report or into `--json`.
    Some(output::truncate_display(line, 400))
}

/// Where to run the queries from.
///
/// The home directory, for the same reason `devp caches` uses it: a project directory
/// can carry a `.dockerignore`, a Compose file or a `DOCKER_HOST` override in a `.env`
/// that would answer for that project rather than for the machine.
fn query_dir() -> PathBuf {
    dirs::home_dir()
        .or_else(|| std::env::current_dir().ok())
        .unwrap_or_else(|| PathBuf::from("."))
}

/// Read an engine's `system df` answer.
///
/// Three shapes. Docker, nerdctl and finch print one JSON object per line; Podman prints
/// a single array of the same objects; Apple's `container` prints one pretty-printed
/// object whose *fields* are the resource types, with no `Type` anywhere to read. The
/// first two differ only in punctuation, which is why one row parser reads either;
/// the third is a different document and gets its own.
///
/// Accepting all three removes an entire class of "works on my machine" from a report
/// whose whole job is to be believed.
fn parse_rows(raw: &str) -> Vec<Row> {
    let trimmed = raw.trim();
    if trimmed.starts_with('[') {
        return match serde_json::from_str::<Value>(trimmed) {
            Ok(Value::Array(items)) => items.iter().filter_map(row_from).collect(),
            _ => Vec::new(),
        };
    }
    // Only a document that is one whole object gets this far as anything but an error:
    // Docker's several-objects-on-several-lines does not parse as one value, and its
    // single-object case has a `Type` and no `images`, so it falls through to the loop.
    if let Ok(v) = serde_json::from_str::<Value>(trimmed)
        && let Some(rows) = apple_rows(&v)
    {
        return rows;
    }
    trimmed
        .lines()
        .filter_map(|l| serde_json::from_str::<Value>(l.trim()).ok())
        .filter_map(|v| row_from(&v))
        .collect()
}

/// Apple's `container system df`, which answers with one object rather than a row each.
///
/// `{"images":{"total":4,"active":2,"sizeInBytes":12345,"reclaimable":678}, "containers":
/// {…}, "volumes":{…}}` — counts and byte counts as numbers, no formatted strings to
/// parse and no percentage to strip. All three keys are required, so anything else that
/// happens to be one JSON object falls through to the row parser instead of becoming a
/// report with holes in it.
///
/// The three labels are the ones the engine's own table prints, so somebody running
/// `container system df` beside `devp caches containers` reads the same words in both.
fn apple_rows(v: &Value) -> Option<Vec<Row>> {
    let mut rows = Vec::new();
    for (key, kind) in [
        ("images", "Images"),
        ("containers", "Containers"),
        ("volumes", "Local Volumes"),
    ] {
        let usage = v.get(key)?.as_object()?;
        rows.push(Row {
            kind: kind.to_string(),
            total: usage.get("total").and_then(Value::as_u64),
            active: usage.get("active").and_then(Value::as_u64),
            bytes: usage.get("sizeInBytes").and_then(Value::as_u64),
            reclaimable: usage.get("reclaimable").and_then(Value::as_u64),
        });
    }
    Some(rows)
}

/// One row, from whichever spelling of the fields this engine uses.
fn row_from(v: &Value) -> Option<Row> {
    let kind = v.get("Type")?.as_str()?.trim().to_string();
    if kind.is_empty() {
        return None;
    }
    Some(Row {
        // Docker calls it `TotalCount`, Podman calls it `Total`.
        total: count(v, "TotalCount").or_else(|| count(v, "Total")),
        active: count(v, "Active"),
        // Where the engine offers the raw byte count, it is the truth and the formatted
        // string is a rounding of it: `1.093GB` has lost three digits before it is read.
        bytes: bytes_at(v, "RawSize", "Size"),
        reclaimable: bytes_at(v, "RawReclaimable", "Reclaimable"),
        kind,
    })
}

/// A count that may be a JSON number or a JSON string, because both are printed.
fn count(v: &Value, key: &str) -> Option<u64> {
    let field = v.get(key)?;
    if let Some(n) = field.as_u64() {
        return Some(n);
    }
    field.as_str()?.trim().parse().ok()
}

/// A size, preferring the engine's raw byte count over its formatted string.
fn bytes_at(v: &Value, raw_key: &str, human_key: &str) -> Option<u64> {
    if let Some(n) = v.get(raw_key).and_then(Value::as_u64) {
        return Some(n);
    }
    parse_size(v.get(human_key)?.as_str()?)
}

/// Bytes out of a size the way a container engine writes one.
///
/// `1.093GB`, `0B`, `987.4MB`, and — for a reclaimable figure — `1.093GB (100%)`, where
/// the percentage restates the same number and is dropped.
fn parse_size(s: &str) -> Option<u64> {
    // The percentage is the same figure expressed a second way.
    let s = s.split('(').next()?.trim();
    let split = s
        .find(|c: char| !(c.is_ascii_digit() || c == '.'))
        .unwrap_or(s.len());
    let (number, unit) = s.split_at(split);
    let value: f64 = number.parse().ok()?;
    if !value.is_finite() || value < 0.0 {
        return None;
    }

    let unit = unit.trim();
    let mut chars = unit.chars();
    let scale = chars.next();
    // `GiB` is 1024-based and `GB` is 1000-based. Docker prints the second, Podman can
    // print either, and across a 40 GB store the difference is about 3 GB — enough to
    // change what someone decides to do about it.
    let rest: String = chars.collect();
    let base: f64 = if rest.eq_ignore_ascii_case("ib") {
        1024.0
    } else {
        1000.0
    };
    let exponent = match scale.map(|c| c.to_ascii_lowercase()) {
        None | Some('b') => 0,
        Some('k') => 1,
        Some('m') => 2,
        Some('g') => 3,
        Some('t') => 4,
        Some('p') => 5,
        _ => return None,
    };

    Some((value * base.powi(exponent)).round() as u64)
}

/// Kubernetes contexts on this machine that run on this machine.
///
/// Read out of the kubeconfig with `kubectl config get-contexts`, which touches no
/// cluster and no network — a context pointing at a production cluster three time zones
/// away is filtered out by name here rather than by being dialled.
fn kube_contexts() -> Vec<String> {
    if !adapters::binary_available("kubectl") {
        return Vec::new();
    }
    let Ok(out) = adapters::capture_allowing_failure(
        "kubectl",
        &["config", "get-contexts", "-o", "name"],
        &query_dir(),
        std::time::Duration::from_secs(constants::CACHE_QUERY_TIMEOUT_SECS),
    ) else {
        return Vec::new();
    };
    if !out.ok {
        return Vec::new();
    }
    out.stdout
        .lines()
        .map(str::trim)
        .filter(|l| is_local_context(l))
        .map(str::to_string)
        .collect()
}

/// Whether a context name is one of the local-cluster tools rather than a remote.
///
/// Name-matching, because the alternative is contacting the cluster to find out, and a
/// disk report has no business dialling a Kubernetes API server. Each of these names is
/// fixed by the tool that writes it: `kind create cluster --name dev` always produces
/// `kind-dev`, and minikube always writes `minikube`.
fn is_local_context(name: &str) -> bool {
    const LOCAL_PREFIXES: [&str; 2] = ["kind-", "k3d-"];
    const LOCAL_EXACT: [&str; 5] = [
        "minikube",
        "docker-desktop",
        "rancher-desktop",
        "colima",
        "microk8s",
    ];
    LOCAL_PREFIXES.iter().any(|p| name.starts_with(p))
        || LOCAL_EXACT.iter().any(|n| name.eq_ignore_ascii_case(n))
}

/// Run `devp caches containers [engine]`, `devp caches docker` and `devp caches podman`.
pub fn run(only: Option<&str>, json_output: bool) -> Result<()> {
    if let Some(name) = only
        && !ENGINES.iter().any(|e| e.name.eq_ignore_ascii_case(name))
    {
        return Err(anyhow::Error::new(crate::UsageError(format!(
            "`{name}` is not a container engine dev-prune knows. Try one of: {}.",
            known_engines().join(", ")
        ))));
    }

    let pb = (!json_output).then(|| output::create_spinner("Asking the container engines..."));
    let reports = collect(only);
    let clusters = kube_contexts();
    if let Some(pb) = pb {
        pb.finish_and_clear();
    }

    if json_output {
        return json::emit(&json::containers_document(&reports, &clusters));
    }

    print_report(&reports, &clusters, only);
    Ok(())
}

/// What one reclaim step actually did.
pub struct StepOutcome {
    /// The command that ran, as a human would type it.
    pub command: String,
    /// What it was asked to give back.
    pub what: &'static str,
    /// `None` when it worked; otherwise the engine's own first line of complaint.
    pub problem: Option<String>,
}

/// What `devp caches clear <engine>` did, measured rather than claimed.
pub struct ClearOutcome {
    /// The engine.
    pub engine: &'static str,
    /// Each step, in the order it ran.
    pub steps: Vec<StepOutcome>,
    /// The engine's own total before, from `system df`.
    pub before: u64,
    /// The engine's own total after, asked again rather than subtracted.
    pub after: u64,
}

impl ClearOutcome {
    /// Bytes given back to the disk.
    pub fn freed(&self) -> u64 {
        self.before.saturating_sub(self.after)
    }
}

/// Run `devp caches clear <engine>`.
///
/// The one thing in this module that deletes. It exists because the alternative was
/// worse: the report ended by printing four commands and asking the reader to run them
/// in another window, which meant the space they reclaimed was theirs to have thought of
/// and dev-prune could not count it, explain it, or put it in a history.
///
/// The rule this tool actually follows is not "never deletes what no lockfile covers" —
/// `devp caches clear npm` has emptied shared caches no lockfile can prove rebuildable
/// since 1.9.0. The rule is that the *unattended* pass deletes only what a lockfile
/// rebuilds, and everything else is asked for by name, in the foreground, with what is
/// about to go printed first. This is that second kind, and it is never schedulable: no
/// daemon path reaches this function.
///
/// Volumes are the exception that stays one. An image can be pulled again and a build
/// cache rebuilt; what is inside a named volume exists nowhere else, and there is no
/// argv in any [`Engine::reclaim`] that touches one. `include_volumes` does not soften
/// that: it appends a phase that lists unused volumes by name and deletes only the ones
/// a person picks off that list at a terminal, one unforced `volume rm` each, and it
/// refuses `--yes`, `--json` and a piped stdin so nothing unattended can reach it.
/// The pick list also only arms within [`constants::VOLUME_PICK_WINDOW_SECS`] of a
/// completed dry run for the engine; any other invocation runs the dry run instead,
/// loudly, and stamps the window so the retyped line goes through.
pub fn run_clear(
    name: &str,
    include_volumes: bool,
    yes: bool,
    dry_run: bool,
    json_output: bool,
) -> Result<()> {
    let Some(engine) = ENGINES.iter().find(|e| e.name.eq_ignore_ascii_case(name)) else {
        return Err(anyhow::Error::new(crate::UsageError(format!(
            "`{name}` is not a container engine dev-prune knows. Try one of: {}.",
            known_engines().join(", ")
        ))));
    };

    // Every one of these is a usage error rather than a silent downgrade, so a script
    // that reaches for the flag learns it is not for scripts instead of quietly getting
    // the volume-free clear it never asked about. Capability first, because "this
    // engine cannot do it at all" outranks how the command was spelled.
    if include_volumes {
        if engine.volume_candidates.is_none() {
            return Err(anyhow::Error::new(crate::UsageError(format!(
                "{} has no way to name only its unused volumes, so dev-prune cannot put \
                 an honest pick list in front of you. Run `{} volume ls` and decide by \
                 name yourself.",
                engine.name, engine.binary
            ))));
        }
        if json_output {
            return Err(anyhow::Error::new(crate::UsageError(
                "`--include-volumes` is a hand-picked deletion at a terminal, and \
                 `--json` is for a program reading the answer. They do not combine; \
                 drop one."
                    .to_string(),
            )));
        }
        if yes {
            return Err(anyhow::Error::new(crate::UsageError(
                "`--include-volumes` has no pre-answered form: the picking is the \
                 point, and a volume goes only when its number is typed at the list. \
                 Drop `--yes`."
                    .to_string(),
            )));
        }
        // Skipped for a dry run, which lists and deletes nothing; that much a
        // redirected terminal may as well have.
        if !dry_run && !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
            return Err(anyhow::Error::new(crate::UsageError(
                "`--include-volumes` needs a terminal, because someone has to pick each \
                 volume off the list, and that is deliberate. From a script or an \
                 agent, add `--dry-run`: it lists the unused volumes by name and \
                 prints the command a person runs to do the picking themselves."
                    .to_string(),
            )));
        }
    }

    // The real pick list only arms within the window after a completed dry run for
    // this engine. Anyone who has not just read the list gets the list: the command
    // becomes the dry run — same output, and it writes the same stamp — so typing the
    // identical line again inside the window does the picking. Loudly, below, never
    // silently: this module refuses silent downgrades everywhere else too.
    let redirected = include_volumes && !dry_run && !volume_stamp_fresh(engine);
    let dry_run = dry_run || redirected;

    // Same reason as `caches clear`: a prompt nobody can answer is a hang, and the line
    // printed in its place would land in the middle of the JSON document.
    if json_output && !yes && !dry_run {
        return Err(anyhow::Error::new(crate::UsageError(
            "`--json` cannot ask for confirmation — pass `--yes` as well, or `--dry-run` \
             to see what would go."
                .to_string(),
        )));
    }

    if !adapters::binary_available(engine.binary) {
        return Err(anyhow::Error::new(crate::UsageError(format!(
            "{} is not installed on this machine, so there is nothing of its to clear.",
            engine.name
        ))));
    }

    let before = probe(engine);
    let rows = match &before.state {
        EngineState::Ready(rows) => rows,
        // Quoted, not paraphrased. A stopped daemon and a permission problem on the
        // socket read identically from here and are fixed completely differently.
        EngineState::Unavailable(why) => {
            return Err(anyhow::Error::new(crate::UsageError(format!(
                "{} did not answer, so dev-prune will not start deleting on a guess: {why}",
                engine.name
            ))));
        }
    };
    let before_bytes: u64 = rows.iter().filter_map(|r| r.bytes).sum();

    if redirected {
        let minutes = constants::VOLUME_PICK_WINDOW_SECS / 60;
        output::print_header("This run is the dry run");
        println!();
        output::print_wrapped(
            "  ",
            &format!(
                "No volume dry run for {} has finished in the last {minutes} minutes, \
                 so nothing below is deleted: the pick list only arms right after the \
                 list has been read. Run the exact same line again within {minutes} \
                 minutes to do the picking.",
                engine.name
            ),
        );
        println!();
    }
    if !json_output {
        print_clear_plan(engine, rows, include_volumes, dry_run);
    }
    if dry_run {
        if json_output {
            let planned = ClearOutcome {
                engine: engine.name,
                steps: planned_steps(engine),
                before: before_bytes,
                after: before_bytes,
            };
            return json::emit(&json::containers_clear_document(&planned, true));
        }
        if include_volumes && let Some(surface) = &engine.volume_candidates {
            print_volume_dry_run(engine, surface);
            write_volume_stamp(engine);
        }
        return Ok(());
    }
    if !json_output && !crate::commands::caches::confirm_clear(yes) {
        output::print_info("Nothing was cleared.");
        return Ok(());
    }

    let mut steps: Vec<StepOutcome> = engine.reclaim.iter().map(|s| run_step(engine, s)).collect();

    // After the reclaim steps on purpose: `container prune` is what turns a stopped
    // container's anonymous volumes dangling, so a list drawn first would be missing
    // the rows this very command just freed up.
    if include_volumes && let Some(surface) = &engine.volume_candidates {
        run_volume_phase(engine, surface, &mut steps);
    }

    // Asked again rather than subtracted from what each command claimed. `image prune`
    // reports the layers it deleted, and layers are shared — three images can each report
    // a gigabyte while the disk gets one back. `system df` is the only figure that
    // describes the disk instead of the bookkeeping.
    let after_bytes = probe(engine).total_bytes().unwrap_or(before_bytes);
    let outcome = ClearOutcome {
        engine: engine.name,
        steps,
        before: before_bytes,
        after: after_bytes,
    };
    record_container_clear(outcome.freed());

    if json_output {
        json::emit(&json::containers_clear_document(&outcome, false))?;
    } else {
        print_clear_result(&outcome);
    }

    // Reported first, then failed, for the same reason `caches clear` does it in that
    // order: the rows above are the useful part.
    let failed = outcome.steps.iter().filter(|s| s.problem.is_some()).count();
    if failed > 0 {
        anyhow::bail!(
            "{failed} of {}'s reclaim steps did not finish.",
            outcome.engine
        );
    }
    Ok(())
}

/// Every step as it would be reported had it run, for `--dry-run --json`.
fn planned_steps(engine: &Engine) -> Vec<StepOutcome> {
    engine
        .reclaim
        .iter()
        .map(|s| StepOutcome {
            command: step_command(engine, s),
            what: s.what,
            problem: None,
        })
        .collect()
}

/// The step as a human would type it, which is also the string that gets printed.
fn step_command(engine: &Engine, step: &ReclaimStep) -> String {
    format!("{} {}", engine.binary, step.args.join(" "))
}

/// Hand one step to the engine that owns it.
fn run_step(engine: &Engine, step: &ReclaimStep) -> StepOutcome {
    let captured = adapters::capture_allowing_failure(
        engine.binary,
        step.args,
        &query_dir(),
        std::time::Duration::from_secs(constants::CONTAINER_PRUNE_TIMEOUT_SECS),
    );
    let problem = match captured {
        Ok(out) if out.ok => None,
        Ok(out) => Some(first_line(&out.stderr).unwrap_or_else(|| {
            format!("`{}` failed without saying why", step_command(engine, step))
        })),
        Err(e) => Some(
            first_line(&e.to_string())
                .unwrap_or_else(|| format!("`{}` could not be run", step_command(engine, step))),
        ),
    };
    StepOutcome {
        command: step_command(engine, step),
        what: step.what,
        problem,
    }
}

/// The unused volumes an engine can name, one per line from its own `volume ls`.
fn unused_volumes(engine: &Engine, surface: &VolumeSurface) -> Result<Vec<String>, String> {
    let captured = adapters::capture_allowing_failure(
        engine.binary,
        surface.ls_args,
        &query_dir(),
        std::time::Duration::from_secs(constants::CONTAINER_QUERY_TIMEOUT_SECS),
    );
    match captured {
        Ok(out) if out.ok => Ok(out
            .stdout
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .map(str::to_string)
            .collect()),
        Ok(out) => Err(first_line(&out.stderr)
            .unwrap_or_else(|| format!("`{} volume ls` failed without saying why", engine.binary))),
        Err(e) => Err(first_line(&e.to_string())
            .unwrap_or_else(|| format!("`{} volume ls` could not be run", engine.binary))),
    }
}

/// Each volume's size, for the pick list. Best-effort: an empty map on any failure.
fn volume_sizes(
    engine: &Engine,
    surface: &VolumeSurface,
) -> std::collections::HashMap<String, String> {
    let Ok(out) = adapters::capture_allowing_failure(
        engine.binary,
        surface.df_args,
        &query_dir(),
        std::time::Duration::from_secs(constants::CONTAINER_QUERY_TIMEOUT_SECS),
    ) else {
        return std::collections::HashMap::new();
    };
    if !out.ok {
        return std::collections::HashMap::new();
    }
    parse_volume_sizes(&out.stdout)
}

/// Per-volume sizes out of a verbose `system df`, in whichever spelling this engine uses.
///
/// Docker's `{{json .}}` with `-v` is one object holding a `Volumes` array whose entries
/// carry `Name` and a formatted `Size`; Podman formats the same idea with its own field
/// names and sometimes raw byte counts. The sizes decorate the pick list rather than
/// gate it, so anything unrecognised degrades to "size unknown" on that row instead of
/// refusing the phase.
fn parse_volume_sizes(raw: &str) -> std::collections::HashMap<String, String> {
    let mut sizes = std::collections::HashMap::new();
    for candidate in std::iter::once(raw.trim()).chain(raw.lines().map(str::trim)) {
        let Ok(v) = serde_json::from_str::<Value>(candidate) else {
            continue;
        };
        let Some(volumes) = ["Volumes", "volumes"]
            .iter()
            .find_map(|k| v.get(k))
            .and_then(Value::as_array)
        else {
            continue;
        };
        for entry in volumes {
            let Some(name) = ["Name", "VolumeName", "Names"]
                .iter()
                .find_map(|k| entry.get(k))
                .and_then(Value::as_str)
            else {
                continue;
            };
            let size = match ["Size", "size"].iter().find_map(|k| entry.get(k)) {
                Some(Value::String(s)) => s.trim().to_string(),
                Some(Value::Number(n)) => n.as_u64().map(output::format_bytes).unwrap_or_default(),
                _ => String::new(),
            };
            if !size.is_empty() {
                sizes.insert(name.to_string(), size);
            }
        }
        if !sizes.is_empty() {
            break;
        }
    }
    sizes
}

/// The numbers typed at the pick list, as zero-based indexes in the order given.
///
/// An empty answer is a deliberate "none", `all` is every row, and anything else is
/// numbers and `3-5` ranges separated by commas or spaces, one-based to match the list,
/// duplicates dropped. Anything that does not read that way (a zero, a number past the
/// end, a word, a backwards range) is `None`, and `None` deletes nothing. One shot, no
/// retry loop: a mistyped answer costs re-running the command, not a volume.
fn parse_selection(input: &str, count: usize) -> Option<Vec<usize>> {
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Some(Vec::new());
    }
    if trimmed.eq_ignore_ascii_case("all") {
        return Some((0..count).collect());
    }
    let mut picked = Vec::new();
    let mut push = |index: usize| {
        if !picked.contains(&index) {
            picked.push(index);
        }
    };
    for token in trimmed.split([',', ' ']).filter(|t| !t.is_empty()) {
        if let Some((low, high)) = token.split_once('-') {
            let low: usize = low.trim().parse().ok()?;
            let high: usize = high.trim().parse().ok()?;
            if low == 0 || high < low || high > count {
                return None;
            }
            (low..=high).for_each(|n| push(n - 1));
        } else {
            let n: usize = token.parse().ok()?;
            if n == 0 || n > count {
                return None;
            }
            push(n - 1);
        }
    }
    Some(picked)
}

/// The `--include-volumes` phase: list what is unused, ask which, delete only those.
///
/// Everything it prints goes to stderr with the question, so a redirected stdout cannot
/// eat the list the answer is about. Each deletion lands in `steps` like any reclaim
/// step, so the result rows, the failure count and the exit code cover it too.
fn run_volume_phase(engine: &Engine, surface: &VolumeSurface, steps: &mut Vec<StepOutcome>) {
    use std::io::Write;
    let names = match unused_volumes(engine, surface) {
        Ok(names) => names,
        Err(why) => {
            output::print_info(&format!(
                "{} could not name its unused volumes, so none was offered: {why}",
                engine.name
            ));
            return;
        }
    };
    if names.is_empty() {
        output::print_info(&format!(
            "{} reports no unused volumes, so there is nothing to pick from.",
            engine.name
        ));
        return;
    }
    let sizes = volume_sizes(engine, surface);
    eprintln!();
    eprintln!("  Unused volumes. A volume holds the only copy of what is in it; anything");
    eprintln!("  picked here is gone for good.");
    eprintln!();
    for (i, name) in names.iter().enumerate() {
        let size = sizes.get(name).map_or("size unknown", String::as_str);
        eprintln!("  {:>3}. {:<44} {}", i + 1, name, size);
    }
    eprintln!();
    eprint!("Delete which? [numbers or ranges like `1 3-5`, `all`, Enter for none]: ");
    if std::io::stderr().flush().is_err() {
        return;
    }
    let mut input = String::new();
    if std::io::stdin().read_line(&mut input).is_err() {
        output::print_info("No answer could be read, so no volume was deleted.");
        return;
    }
    let Some(picked) = parse_selection(&input, names.len()) else {
        output::print_info(
            "That did not read as numbers from the list, so no volume was deleted. Run \
             the command again to see the list once more.",
        );
        return;
    };
    if picked.is_empty() {
        output::print_info("No volume picked; all of them stay.");
        return;
    }
    for index in picked {
        steps.push(remove_volume(engine, surface, &names[index]));
    }
}

/// One `volume rm <name>`, never forced.
///
/// Unforced on purpose: if the engine thinks something still uses this volume, its
/// refusal is the right answer and it lands in the result row, not overridden.
fn remove_volume(engine: &Engine, surface: &VolumeSurface, name: &str) -> StepOutcome {
    let mut args: Vec<&str> = surface.rm_args.to_vec();
    args.push(name);
    let command = format!("{} {}", engine.binary, args.join(" "));
    let captured = adapters::capture_allowing_failure(
        engine.binary,
        &args,
        &query_dir(),
        std::time::Duration::from_secs(constants::CONTAINER_PRUNE_TIMEOUT_SECS),
    );
    let problem = match captured {
        Ok(out) if out.ok => None,
        Ok(out) => Some(
            first_line(&out.stderr)
                .unwrap_or_else(|| format!("`{command}` failed without saying why")),
        ),
        Err(e) => Some(
            first_line(&e.to_string()).unwrap_or_else(|| format!("`{command}` could not be run")),
        ),
    };
    StepOutcome {
        command,
        what: "a volume picked by name",
        problem,
    }
}

/// What `--include-volumes --dry-run` shows: the list, the one devp command to paste,
/// and nothing run. It exists for the hand-off where an agent or script does everything
/// up to the deletion and a person runs that command at a terminal; the command is
/// devp's own rather than the engine's so the picks land on `devp stats`.
/// Where this engine's volume dry-run stamp lives, when the config dir is resolvable.
fn volume_stamp_path(engine: &Engine) -> Option<PathBuf> {
    crate::config::Registry::config_dir().ok().map(|dir| {
        dir.join(format!(
            "{}{}{}",
            constants::VOLUME_PICK_STAMP_PREFIX,
            engine.name.to_ascii_lowercase(),
            constants::VOLUME_PICK_STAMP_SUFFIX
        ))
    })
}

/// Seconds since the Unix epoch, or zero on a clock set before 1970 — which reads as
/// "no dry run is fresh", the safe direction.
fn unix_now() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Whether the stamp at `path` was written within the pick window before `now`.
///
/// A stamp from the future counts as stale, not fresh: a clock that jumped backwards
/// must not leave a permanently armed pick list behind it.
fn volume_stamp_fresh_at(path: &std::path::Path, now: u64) -> bool {
    let Ok(contents) = std::fs::read_to_string(path) else {
        return false;
    };
    let Ok(stamped) = contents.trim().parse::<u64>() else {
        return false;
    };
    stamped <= now && now - stamped <= constants::VOLUME_PICK_WINDOW_SECS
}

fn volume_stamp_fresh(engine: &Engine) -> bool {
    volume_stamp_path(engine).is_some_and(|path| volume_stamp_fresh_at(&path, unix_now()))
}

/// Record that a volume dry run for `engine` just finished, arming the real pick list.
///
/// Same pid-suffixed temp-then-rename dance as the registry save: a torn stamp would
/// parse as garbage and read as stale, which only costs one more dry run, but the
/// pattern is cheap and this file lives in the same directory.
fn write_volume_stamp_at(path: &std::path::Path, now: u64) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let tmp_path = path.with_extension(format!("stamp.{}.tmp", std::process::id()));
    std::fs::write(&tmp_path, now.to_string())?;
    std::fs::rename(&tmp_path, path)
}

fn write_volume_stamp(engine: &Engine) {
    let Some(path) = volume_stamp_path(engine) else {
        return;
    };
    // Surfaced rather than swallowed: if the stamp cannot land, the promise "run the
    // same line again within ten minutes" is not going to hold, and the person should
    // hear that now instead of meeting another dry run.
    if let Err(why) = write_volume_stamp_at(&path, unix_now()) {
        output::print_info(&format!(
            "Could not record this dry run at {}: {why}. The real `--include-volumes` \
             run will redirect here again until it can be recorded.",
            path.display()
        ));
    }
}

fn print_volume_dry_run(engine: &Engine, surface: &VolumeSurface) {
    match unused_volumes(engine, surface) {
        Err(why) => output::print_info(&format!(
            "{} could not name its unused volumes: {why}",
            engine.name
        )),
        Ok(names) if names.is_empty() => output::print_info(&format!(
            "{} reports no unused volumes right now.",
            engine.name
        )),
        Ok(names) => {
            let sizes = volume_sizes(engine, surface);
            output::print_wrapped(
                "  ",
                "These volumes are unused right now and would be offered on the pick \
                 list. The real list can be longer, because it is drawn after the \
                 containers are pruned and a stopped container keeps its anonymous \
                 volumes counted as in use until it is gone.",
            );
            println!();
            for (i, name) in names.iter().enumerate() {
                let size = sizes.get(name).map_or("size unknown", String::as_str);
                println!("  {:>3}. {:<44} {}", i + 1, name, size);
            }
            println!();
            output::print_wrapped(
                "  ",
                &format!(
                    "Nothing was deleted. To delete any of them, a person runs the \
                     line below at their own terminal within the next {} minutes and \
                     types the picks at the list; each pick is one unforced `volume \
                     rm`, and what it frees is measured and counted on `devp stats`, \
                     which a raw `{} volume rm` typed by hand would not be. After \
                     that the line shows this list again first.",
                    constants::VOLUME_PICK_WINDOW_SECS / 60,
                    engine.binary
                ),
            );
            println!();
            println!("    devp caches clear {} --include-volumes", engine.name);
            println!();
        }
    }
}

/// Credit what was reclaimed to the machine's running container total.
fn record_container_clear(bytes: u64) {
    if bytes == 0 {
        return;
    }
    if let Ok(mut registry) = crate::config::Registry::load() {
        registry.record_container_clear(bytes);
        let _ = registry.save();
    }
}

/// What is about to run, and what the engine says it is holding.
fn print_clear_plan(engine: &Engine, rows: &[Row], include_volumes: bool, dry_run: bool) {
    output::print_header(&format!("Clearing {}", engine.name));
    println!();
    for step in engine.reclaim {
        println!("  {:<40}  {}", step_command(engine, step).bold(), step.what);
    }
    println!();
    // The engine's reclaimable figure counts unused volumes, and not one of the commands
    // above touches one. Printing it whole would promise back space these steps cannot
    // give, so the volume row comes out of the estimate and is named as kept instead.
    let volumes: u64 = rows
        .iter()
        .filter(|r| r.kind.eq_ignore_ascii_case("Local Volumes"))
        .filter_map(|r| r.reclaimable)
        .sum();
    let reclaimable: u64 = rows.iter().filter_map(|r| r.reclaimable).sum();
    output::print_wrapped(
        "  ",
        &format!(
            "{} says about {} of this is reclaimable. None of the commands above touches \
             a volume, and dev-prune never runs `{} volume prune`: a volume holds the one \
             copy of what is in it, so a volume goes only when someone names it.",
            engine.name,
            output::format_bytes(reclaimable.saturating_sub(volumes)),
            engine.binary
        ),
    );
    if volumes > 0 {
        println!();
        if include_volumes {
            output::print_wrapped(
                "  ",
                &format!(
                    "{} of unused volumes will be offered after these steps run, listed \
                     by name for you to pick from. After, because pruning the stopped \
                     containers is what frees their anonymous volumes onto the list. \
                     Each pick is one `{} volume rm`, never forced.",
                    output::format_bytes(volumes),
                    engine.binary
                ),
            );
        } else if engine.volume_candidates.is_some() {
            output::print_wrapped(
                "  ",
                &format!(
                    "{} of unused volumes is being left alone. To pick which of them go, \
                     by name and one at a time, add `--include-volumes`.",
                    output::format_bytes(volumes)
                ),
            );
        } else {
            output::print_wrapped(
                "  ",
                &format!(
                    "{} of unused volumes is being left alone. If you have read what is \
                     in them and want it gone, that one is yours to run: `{} volume \
                     prune`.",
                    output::format_bytes(volumes),
                    engine.binary
                ),
            );
        }
    }
    if dry_run {
        println!();
        output::print_info("Dry run — nothing was deleted.");
    }
    println!();
}

/// What actually went, measured against the engine's own answer afterwards.
fn print_clear_result(outcome: &ClearOutcome) {
    println!();
    for step in &outcome.steps {
        match &step.problem {
            None => println!("  {:<40}  done", step.command),
            Some(why) => println!("  {:<40}  {why}", step.command),
        }
    }
    println!();
    output::print_success(&format!(
        "{} freed — {} is now holding {}, down from {}.",
        output::format_bytes(outcome.freed()),
        outcome.engine,
        output::format_bytes(outcome.after),
        output::format_bytes(outcome.before)
    ));
}

/// The engine names `devp caches containers <engine>` accepts.
pub fn known_engines() -> Vec<&'static str> {
    ENGINES.iter().map(|e| e.name).collect()
}

/// Whether a name is one of them, so `caches clear docker` can say where to go instead.
pub fn is_engine(name: &str) -> bool {
    ENGINES.iter().any(|e| e.name.eq_ignore_ascii_case(name))
}

fn print_report(reports: &[EngineReport], clusters: &[String], only: Option<&str>) {
    output::print_header("Container engines");

    if reports.is_empty() {
        println!();
        output::print_info(&match only {
            Some(name) => format!("{name} is not installed on this machine."),
            None => format!(
                "No container engine found. dev-prune looks for {}.",
                known_engines().join(", ")
            ),
        });
        return;
    }

    for report in reports {
        println!();
        match &report.state {
            EngineState::Unavailable(why) => print_unavailable(report.name, why),
            EngineState::Ready(rows) => print_engine(report.name, rows),
        }
    }

    if !clusters.is_empty() {
        print_clusters(clusters);
    }

    println!();
    output::print_wrapped(
        "  ",
        "Nothing above was deleted, and nothing dev-prune runs on a schedule will ever \
         delete it. To have dev-prune run the narrow ones for you — build cache, unused \
         images, stopped containers, and what that gave back counted on your stats — use \
         `devp caches clear <engine>`. It asks first, and it touches no volume on its \
         own: `--include-volumes` lists the unused ones by name for you to pick from, \
         one at a time, at a terminal.",
    );
}

/// An engine that is installed and did not answer.
///
/// Quoted rather than paraphrased. "Cannot connect to the Docker daemon" and "permission
/// denied on /var/run/docker.sock" are different problems with different fixes, and a
/// tidy dev-prune sentence in place of the engine's own would hide which one this is.
fn print_unavailable(name: &str, why: &str) {
    println!("  {name}");
    println!();
    output::print_wrapped("    ", why);
    println!();
    output::print_wrapped(
        "    ",
        &format!(
            "So dev-prune has no figures for {name} — a blank rather than a zero. Start \
             it and run this again."
        ),
    );
}

/// Column widths for the engine table, chosen so the longest real row — `Local
/// Volumes`, a ten-character size, a ten-character reclaimable figure and `41 items, 9
/// in use` — still lands inside the 90-column prose width the rest of the tool wraps to.
const KIND_WIDTH: usize = 16;
const SIZE_WIDTH: usize = 11;

/// One engine's rows, its total, and the commands that would reclaim each part.
fn print_engine(name: &str, rows: &[Row]) {
    println!("  {name}");
    println!();
    for row in rows {
        println!(
            "  {:<KIND_WIDTH$}{:>SIZE_WIDTH$}   {}   {}",
            row.kind,
            row.bytes.map_or("—".to_string(), output::format_bytes),
            reclaimable_cell(row.reclaimable),
            counts(row),
        );
    }

    let total: u64 = rows.iter().filter_map(|r| r.bytes).sum();
    let reclaimable: u64 = rows.iter().filter_map(|r| r.reclaimable).sum();
    println!();
    println!(
        "  {:<KIND_WIDTH$}{:>SIZE_WIDTH$}   {}",
        "Total",
        output::format_bytes(total),
        reclaimable_cell(Some(reclaimable)),
    );

    let Some(engine) = ENGINES.iter().find(|e| e.name == name) else {
        return;
    };
    println!();
    println!(
        "  {:<COMMAND_WIDTH$}what it takes with it",
        "Reclaim it yourself"
    );
    for (command, cost) in engine.prune {
        println!("  {command:<COMMAND_WIDTH$}{cost}");
    }
    if !engine.prompts {
        println!();
        // Worth one line, because the last command in that list deletes data and the
        // reader's expectation comes from the other engines: everywhere else a prune
        // stops and asks, and a `-f` in an example is the tell that it would have. This
        // one has no such flag because it has no such question.
        output::print_wrapped(
            "  ",
            &format!(
                "{} asks nothing first. Each of those runs the moment you press Return,                  including the last one.",
                engine.name
            ),
        );
    }
}

/// The `9.20 GiB reclaimable` cell, blank-padded when the engine did not say.
///
/// Padded rather than left empty so the counts column after it stays in one place down
/// the table; a row missing this figure otherwise pulls its neighbour eleven characters
/// left and the whole block stops reading as a table.
fn reclaimable_cell(bytes: Option<u64>) -> String {
    match bytes {
        Some(b) => format!("{:>SIZE_WIDTH$} reclaimable", output::format_bytes(b)),
        None => " ".repeat(SIZE_WIDTH + " reclaimable".len()),
    }
}

/// The "12 of them, 3 in use" half of a row.
fn counts(row: &Row) -> String {
    match (row.total, row.active) {
        (Some(total), Some(active)) => format!(
            "{total} {}, {active} in use",
            output::plural(total as usize, "item", "items")
        ),
        (Some(total), None) => format!(
            "{total} {}",
            output::plural(total as usize, "item", "items")
        ),
        _ => String::new(),
    }
}

/// The local Kubernetes clusters, named and deliberately unsized.
fn print_clusters(clusters: &[String]) {
    println!();
    println!("  kubernetes");
    println!();
    for name in clusters {
        println!("  {:<18} local cluster", name);
    }
    println!();
    output::print_wrapped(
        "  ",
        "Named and not sized on purpose: kind, k3d and minikube run their nodes as \
         containers or as a VM disk belonging to an engine above, so their disk is \
         already in that engine's total. A figure here would be the same gigabytes \
         counted twice. Delete a cluster with its own tool — `kind delete cluster`, \
         `minikube delete`, `k3d cluster delete` — which is also what releases the \
         space.",
    );
}

/// The one-line-per-engine block `devp caches` prints under its own table.
///
/// Short on purpose. `devp caches` is a report about package managers, and this is the
/// sentence that stops someone concluding they have reclaimed everything there is when
/// the largest thing on the disk was never in the table.
pub fn print_summary(reports: &[EngineReport]) {
    if reports.is_empty() {
        return;
    }
    println!();
    output::print_header("Container engines");
    println!();
    for report in reports {
        match &report.state {
            EngineState::Ready(_) => {
                let total = report.total_bytes().unwrap_or(0);
                let reclaimable = report.reclaimable_bytes().unwrap_or(0);
                println!(
                    "  {:<30} {:>10}  {} reclaimable · devp caches {}",
                    report.name,
                    output::format_bytes(total),
                    output::format_bytes(reclaimable),
                    report.name,
                );
            }
            EngineState::Unavailable(_) => {
                // The reason is a sentence from the engine and this is a
                // one-line-per-engine block, so it is shown by the command with room
                // for it.
                println!(
                    "  {:<30} {:>10}  did not answer · devp caches {}",
                    report.name, "—", report.name,
                );
            }
        }
    }
    println!();
    output::print_wrapped(
        "  ",
        "Container images, volumes and build cache are not package manager caches and are \
         not in the total above — dev-prune reports them, and deletes nothing of them \
         except through `devp caches clear <engine>`, which asks first.",
    );
}

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

    #[test]
    fn no_reclaim_step_can_touch_a_volume() {
        // The promise printed in the plan, checked against the argv rather than against
        // the prose. Every engine here has a `--volumes` spelling that would turn one of
        // these commands into the one that destroys data no registry can hand back, and
        // the only thing keeping it out is that nobody typed it into the table.
        for engine in ENGINES {
            for step in engine.reclaim {
                for arg in step.args {
                    assert!(
                        !arg.to_ascii_lowercase().contains("volume"),
                        "{} would run `{}`, which reaches a volume",
                        engine.name,
                        step_command(engine, step)
                    );
                }
            }
        }
    }

    #[test]
    fn the_volume_surface_deletes_one_named_volume_and_never_forces_it() {
        // The `--include-volumes` promise, checked against the argv like the one above:
        // the listing asks only for what nothing uses, the deletion takes exactly one
        // name, and no spelling of force or bulk prune appears anywhere on the surface.
        for engine in ENGINES {
            let Some(surface) = &engine.volume_candidates else {
                continue;
            };
            assert_eq!(
                surface.rm_args,
                ["volume", "rm"],
                "{} would delete with `{}`, not a single unforced rm",
                engine.name,
                surface.rm_args.join(" ")
            );
            assert!(
                surface.ls_args.contains(&"dangling=true") && surface.ls_args.contains(&"-q"),
                "{} would list volumes without narrowing to unused names",
                engine.name
            );
            for arg in surface
                .ls_args
                .iter()
                .chain(surface.df_args)
                .chain(surface.rm_args)
            {
                let lower = arg.to_ascii_lowercase();
                assert!(
                    lower != "-f"
                        && lower != "--force"
                        && !lower.contains("prune")
                        && lower != "--volumes",
                    "{} carries `{arg}` on its volume surface",
                    engine.name
                );
            }
        }
    }

    #[test]
    fn only_engines_that_can_name_unused_volumes_offer_them() {
        // nerdctl's `volume ls` filter knows label, name and size but not dangling
        // ("not supported yet" in its command reference), finch forwards nerdctl's
        // surface verbatim, and Apple's container exposes no per-volume usage. Offering
        // a pick list an engine cannot narrow to unused names would put in-use volumes
        // on it, so those three get a usage error instead.
        for engine in ENGINES {
            let can = matches!(engine.name, "docker" | "podman");
            assert_eq!(
                engine.volume_candidates.is_some(),
                can,
                "{} disagrees about offering volumes",
                engine.name
            );
        }
    }

    #[test]
    fn a_missing_stamp_never_arms_the_pick_list() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("volume-pick-docker.stamp");
        assert!(!volume_stamp_fresh_at(&path, 1_000_000));
    }

    #[test]
    fn a_fresh_stamp_arms_it_and_an_expired_one_does_not() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("volume-pick-docker.stamp");
        let now = 1_000_000;
        write_volume_stamp_at(&path, now).unwrap();
        assert!(volume_stamp_fresh_at(&path, now));
        assert!(volume_stamp_fresh_at(
            &path,
            now + constants::VOLUME_PICK_WINDOW_SECS
        ));
        assert!(!volume_stamp_fresh_at(
            &path,
            now + constants::VOLUME_PICK_WINDOW_SECS + 1
        ));
    }

    #[test]
    fn a_stamp_from_the_future_reads_as_stale() {
        // A clock that jumped backwards must not leave a permanently armed pick list.
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("volume-pick-docker.stamp");
        write_volume_stamp_at(&path, 2_000_000).unwrap();
        assert!(!volume_stamp_fresh_at(&path, 1_000_000));
    }

    #[test]
    fn a_garbled_stamp_reads_as_stale() {
        let tmp = tempfile::TempDir::new().unwrap();
        let path = tmp.path().join("volume-pick-docker.stamp");
        std::fs::write(&path, "not a number").unwrap();
        assert!(!volume_stamp_fresh_at(&path, 1_000_000));
    }

    #[test]
    fn each_engine_stamps_its_own_file() {
        // A dry run for podman must not arm docker's pick list.
        let docker = ENGINES.iter().find(|e| e.name == "docker").unwrap();
        let podman = ENGINES.iter().find(|e| e.name == "podman").unwrap();
        let (Some(a), Some(b)) = (volume_stamp_path(docker), volume_stamp_path(podman)) else {
            // No resolvable config dir on this machine; nothing to compare.
            return;
        };
        assert_ne!(a, b);
    }

    #[test]
    fn an_empty_answer_keeps_every_volume() {
        assert_eq!(parse_selection("", 5), Some(vec![]));
        assert_eq!(parse_selection("   \n", 5), Some(vec![]));
    }

    #[test]
    fn all_is_every_row_once() {
        assert_eq!(parse_selection("all", 3), Some(vec![0, 1, 2]));
        assert_eq!(parse_selection("ALL", 3), Some(vec![0, 1, 2]));
    }

    #[test]
    fn numbers_and_ranges_read_one_based_in_the_order_given() {
        assert_eq!(parse_selection("1 3-5", 5), Some(vec![0, 2, 3, 4]));
        assert_eq!(parse_selection("2,2,1", 3), Some(vec![1, 0]));
    }

    #[test]
    fn anything_that_is_not_a_row_number_deletes_nothing() {
        // `None` is the safe verdict, and it must catch every malformed shape: the list
        // is one-based so zero names nothing, a number past the end names nothing, a
        // backwards range is a typo, and words (including anything shell-shaped) are
        // not numbers.
        assert_eq!(parse_selection("0", 3), None);
        assert_eq!(parse_selection("4", 3), None);
        assert_eq!(parse_selection("2-1", 3), None);
        assert_eq!(parse_selection("yes please", 3), None);
        assert_eq!(parse_selection("1; rm -rf /", 3), None);
    }

    #[test]
    fn reads_dockers_volume_sizes_and_podmans() {
        // Docker's shape, from a run of `system df -v --format "{{json .}}"`: one
        // object, `Volumes` array, `Name` and a formatted `Size`.
        let docker = r#"{"Volumes":[
            {"Name":"chronos_cache_store","Size":"89B","Links":"0"},
            {"Name":"pgdata","Size":"1.2GB","Links":"0"}
        ]}"#;
        let sizes = parse_volume_sizes(docker);
        assert_eq!(
            sizes.get("chronos_cache_store").map(String::as_str),
            Some("89B")
        );
        assert_eq!(sizes.get("pgdata").map(String::as_str), Some("1.2GB"));
        // Podman spells the fields its own way and sometimes counts raw bytes; the
        // parser only has to find a name and render something, not match a format.
        let podman = r#"{"Volumes":[{"VolumeName":"data","Size":2048}]}"#;
        assert!(parse_volume_sizes(podman).contains_key("data"));
        // Garbage decorates nothing rather than failing anything.
        assert!(parse_volume_sizes("TYPE  TOTAL  ACTIVE").is_empty());
    }

    #[test]
    fn every_engine_that_can_be_reported_can_be_cleared() {
        // `caches clear <engine>` accepts any name `is_engine` knows, so an engine with an
        // empty reclaim table would confirm, run nothing, and report freeing zero bytes.
        for engine in ENGINES {
            assert!(
                !engine.reclaim.is_empty(),
                "{} can be named to clear and has no steps",
                engine.name
            );
        }
    }

    #[test]
    fn every_reclaim_step_answers_for_itself_without_a_prompt() {
        // These run without a terminal behind them — inside `devp caches clear --yes`, and
        // from a shell whose stdin the engine does not own. A step that stops to ask is a
        // hang, and dev-prune has already asked the only question that matters.
        //
        // The engines that ask take `-f` to say it has been answered. Apple's `container`
        // never asks and defines no such flag, so passing one there would not be caution:
        // it would be a usage error on every step, which is the same hang's worth of
        // nothing reclaimed by a different route.
        for engine in ENGINES {
            for step in engine.reclaim {
                let forced = step.args.contains(&"-f") || step.args.contains(&"--force");
                assert_eq!(
                    forced,
                    engine.prompts,
                    "`{}` disagrees with what {} does about prompting",
                    step_command(engine, step),
                    engine.name
                );
            }
        }
    }

    #[test]
    fn reads_apples_one_object_for_all_three() {
        // Apple's `container` is not installed on the machines this is developed on, so
        // the shape is pinned from `DiskUsageStats`/`ResourceUsage` in apple/container
        // rather than from a run. If those field names ever change, this fails here
        // instead of the report quietly showing an engine holding nothing.
        let raw = r#"{
          "images" : { "total" : 12, "active" : 3, "sizeInBytes" : 4210000000,
                       "reclaimable" : 3020000000 },
          "containers" : { "total" : 7, "active" : 1, "sizeInBytes" : 118400000,
                           "reclaimable" : 118400000 },
          "volumes" : { "total" : 2, "active" : 0, "sizeInBytes" : 2048,
                        "reclaimable" : 2048 }
        }"#;
        let rows = parse_rows(raw);
        assert_eq!(rows.len(), 3);
        assert_eq!(rows[0].kind, "Images");
        assert_eq!(rows[0].total, Some(12));
        assert_eq!(rows[0].active, Some(3));
        assert_eq!(rows[0].bytes, Some(4_210_000_000));
        assert_eq!(rows[0].reclaimable, Some(3_020_000_000));
        // The label is the engine's own, not the JSON key: `volumes` prints as
        // `Local Volumes`, which is also what the volume-keeping arithmetic matches on.
        assert_eq!(rows[2].kind, "Local Volumes");
        assert_eq!(rows[2].bytes, Some(2_048));
    }

    #[test]
    fn a_json_object_that_is_not_apples_is_not_read_as_apples() {
        // Docker printing a single row — one object, on one line — must still be read as
        // that row rather than swallowed by the branch above.
        let rows = parse_rows(
            r#"{"Active":"3","Reclaimable":"3.02GB (71%)","Size":"4.21GB","TotalCount":"12","Type":"Images"}"#,
        );
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].kind, "Images");
        // Two of the three keys is not the shape either, and half a report is worse than
        // the honest "could not read this" the caller prints for no rows.
        assert!(parse_rows(r#"{"images":{"total":1},"containers":{"total":1}}"#).is_empty());
    }

    #[test]
    fn parses_docker_si_sizes() {
        assert_eq!(parse_size("0B"), Some(0));
        assert_eq!(parse_size("1.093GB"), Some(1_093_000_000));
        assert_eq!(parse_size("987.4MB"), Some(987_400_000));
        assert_eq!(parse_size("1.5kB"), Some(1_500));
        assert_eq!(parse_size("2TB"), Some(2_000_000_000_000));
    }

    #[test]
    fn iec_suffix_is_base_1024() {
        assert_eq!(parse_size("1KiB"), Some(1_024));
        assert_eq!(parse_size("1GiB"), Some(1_073_741_824));
        // The distinction is the whole reason the suffix is inspected: the same number
        // with the other suffix is 7% smaller.
        assert_ne!(parse_size("1GiB"), parse_size("1GB"));
    }

    #[test]
    fn reclaimable_percentage_is_dropped() {
        assert_eq!(parse_size("1.093GB (100%)"), Some(1_093_000_000));
        assert_eq!(parse_size("0B (0%)"), Some(0));
    }

    #[test]
    fn rejects_what_is_not_a_size() {
        assert_eq!(parse_size(""), None);
        assert_eq!(parse_size("N/A"), None);
        assert_eq!(parse_size("GB"), None);
        assert_eq!(parse_size("12 apples"), None);
    }

    #[test]
    fn reads_dockers_one_object_per_line() {
        let raw = concat!(
            r#"{"Active":"3","Reclaimable":"3.02GB (71%)","Size":"4.21GB","TotalCount":"12","Type":"Images"}"#,
            "\n",
            r#"{"Active":"1","Reclaimable":"118.4MB (100%)","Size":"118.4MB","TotalCount":"7","Type":"Containers"}"#,
            "\n",
            r#"{"Active":"0","Reclaimable":"6.75GB","Size":"6.75GB","TotalCount":"41","Type":"Build Cache"}"#,
        );
        let rows = parse_rows(raw);
        assert_eq!(rows.len(), 3);
        assert_eq!(rows[0].kind, "Images");
        assert_eq!(rows[0].total, Some(12));
        assert_eq!(rows[0].active, Some(3));
        assert_eq!(rows[0].bytes, Some(4_210_000_000));
        assert_eq!(rows[0].reclaimable, Some(3_020_000_000));
        assert_eq!(rows[2].kind, "Build Cache");
        assert_eq!(rows[2].active, Some(0));
    }

    #[test]
    fn reads_podmans_single_array() {
        let raw = r#"[
            {"Type":"Images","Total":4,"Active":2,"Size":"1.5GB","Reclaimable":"500MB (33%)"},
            {"Type":"Local Volumes","Total":2,"Active":0,"RawSize":2048,"RawReclaimable":2048,
             "Size":"2.048kB","Reclaimable":"2.048kB (100%)"}
        ]"#;
        let rows = parse_rows(raw);
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0].total, Some(4));
        assert_eq!(rows[0].bytes, Some(1_500_000_000));
        // The raw byte count wins over the string rounded from it.
        assert_eq!(rows[1].bytes, Some(2_048));
        assert_eq!(rows[1].reclaimable, Some(2_048));
    }

    #[test]
    fn unparseable_output_is_no_rows_rather_than_zero_bytes() {
        assert!(parse_rows("").is_empty());
        assert!(parse_rows("Cannot connect to the Docker daemon").is_empty());
        // Valid JSON, but not a df row: no `Type` to name.
        assert!(parse_rows(r#"{"Size":"4GB"}"#).is_empty());
    }

    #[test]
    fn local_contexts_are_told_from_remote_ones() {
        assert!(is_local_context("kind-dev"));
        assert!(is_local_context("k3d-test"));
        assert!(is_local_context("minikube"));
        assert!(is_local_context("docker-desktop"));
        assert!(!is_local_context("arn:aws:eks:us-east-1:1234:cluster/prod"));
        assert!(!is_local_context("gke_project_us-central1_prod"));
        // A remote cluster somebody named after the tool is still remote, but this is
        // name-matching and the alternative is dialling it. Naming a production context
        // `minikube` is a problem that predates dev-prune.
        assert!(!is_local_context("kindly-prod"));
    }

    #[test]
    fn every_engine_prints_at_least_one_reclaim_command() {
        for engine in ENGINES {
            assert!(
                !engine.prune.is_empty(),
                "{} has no reclaim command to print",
                engine.name
            );
            for (command, _) in engine.prune {
                assert!(
                    command.starts_with(engine.binary),
                    "{command} is not a {} command",
                    engine.name
                );
            }
        }
    }

    #[test]
    fn no_reclaim_command_is_ever_run_by_dev_prune() {
        // The guard is that `prune` is only ever read into a `println!`. If a future
        // change hands one of these to a process spawner, this file is where the review
        // has to notice, so the strings are checked to be commands for a human to type
        // rather than argv this code could execute.
        for engine in ENGINES {
            for (command, _) in engine.prune {
                assert!(
                    command.contains(' '),
                    "{command} looks like a bare program name"
                );
            }
        }
    }
}