rs-rich-cli 0.0.26

The `rich` executable: a Rust port of Python `rich-cli` 1.8.1
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
//! `rich plugin`: find, install, update and check packages from the plugin
//! marketplace, on rs-rich-marketplace (docs/design/marketplace.md).
//!
//! A binary-boundary convenience (docs/PORTING.md): the crate verifies,
//! resolves and installs; this module prompts, prints and decides. Nothing
//! here changes how a render behaves, apart from what is installed and
//! enabled being used, each after its file is checked against the lockfile:
//! a WASM plugin loads on every run without `--plugin`
//! ([`installed_plugins`]), a micro pack loads into micro's user layer
//! ([`installed_micro_packs`]), and `--theme NAME` falls back to a theme
//! ([`installed_theme`]).
//!
//! - **The install directory** is `--plugin-dir DIR`, else `RICH_PLUGIN_DIR`,
//!   else `$XDG_DATA_HOME/rich/plugins` (`~/.local/share/rich/plugins`;
//!   `%LOCALAPPDATA%\rich\plugins` on Windows). The crate's lockfile
//!   (`marketplace.lock.json`) is there, and this module's own state
//!   (`marketplace.state.json`): the disabled packages, the last index each
//!   marketplace served (to refuse a rollback), the key generations
//!   verified from each trust root (re-verified from that root whenever
//!   they are read, so the file cannot add a key), and the yank reasons last
//!   seen for what is installed. On Unix the directory is created private
//!   (mode 700).
//! - **The marketplace** is `--marketplace LOCATION`, else
//!   `RICH_MARKETPLACE`, else [`DEFAULT_MARKETPLACE`]: an `https://` base
//!   URL, or a local directory (a path or `file://` URL) laid out as the
//!   marketplace repository is. A local marketplace serves artifacts from
//!   its `artifacts/HOST/PATH` mirror only, never from the network, which
//!   is how the tests and the CI compatibility job run offline.
//! - **The trust root** is `--marketplace-keys FILE` (a `keys-N.json`), else
//!   `RICH_MARKETPLACE_KEYS`, else the keys compiled into
//!   rs-rich-marketplace. Later generations are fetched from the
//!   marketplace's `keys/` and accepted one at a time. The generations a
//!   root has reached are kept per root, not per location, so a location
//!   that withholds a newer `keys-N.json` (a stale mirror, a
//!   `RICH_MARKETPLACE` someone else chose) cannot bring back a key
//!   another location's chain has revoked.
use super::*;

use std::collections::BTreeMap;
use std::io::IsTerminal;
use std::time::SystemTime;

use rich_ext::plugin_loading::{RuntimeKind, RuntimePlugin};
use rich_marketplace::{
    AcceptedIndex, AgentList, ArtifactChecker, CheckError, FetchError, Host, IndexError,
    InstallError, Installer, KeyChainError, KeySet, Kind, LOCKFILE_NAME, ListedVersion, Listing,
    ListingError, LockEntry, Lockfile, LockfileError, Request, Requires, ResolveError, Rotation,
    RotationKind, Tier, Transport, VerifiedIndex, WasmExpectation, resolve, verify_index,
};
use serde_json::{Value, json};

#[path = "marketplace_publish.rs"]
mod publish;

#[path = "marketplace_stats.rs"]
mod stats;

#[cfg(feature = "interact")]
#[path = "marketplace_browse.rs"]
mod browse;

/// The marketplace a build uses when nothing else is named.
pub(crate) const DEFAULT_MARKETPLACE: &str =
    "https://raw.githubusercontent.com/buchochelliq-labs/rs-rich-marketplace/main/";

/// This module's state file, beside the lockfile.
const STATE_NAME: &str = "marketplace.state.json";
const STATE_SCHEMA_VERSION: u64 = 1;

/// The most read of each marketplace file.
const MAX_INDEX_BYTES: u64 = 8 << 20;
const MAX_SIGNATURE_BYTES: u64 = 8 << 10;
const MAX_LISTING_BYTES: u64 = 1 << 20;
const MAX_KEYS_BYTES: u64 = 64 << 10;
/// Key generations walked in one refresh, so a hostile marketplace cannot
/// keep a client fetching.
const MAX_ROTATIONS: u64 = 64;

/// The exit code of an install or update the user declined.
const EXIT_DECLINED: u8 = 1;

/// The subcommands, in the order help lists them.
pub(super) const COMMANDS: &[&str] = &[
    "search", "info", "install", "update", "remove", "list", "enable", "disable", "verify",
    "browse", "publish",
];

/// Whether the command line is `rich plugin …` (not `rich -p plugin`).
pub(super) fn requested(args: &[String]) -> bool {
    subcommand_word(args) == Some("plugin")
}

/// `rich plugin`'s help, registered with the root spec in `cli_spec`.
pub(crate) fn spec() -> rich_ext::cli_doc::CommandSpec {
    use rich_ext::cli_doc::{ArgSpec, CommandSpec};
    let common = || {
        vec![
            ArgSpec::option("marketplace").value_name("LOCATION").help(
                "The marketplace: an https:// base URL, or a directory or file:// URL laid out as \
                 the marketplace repository is (artifacts from its artifacts/HOST/PATH mirror, \
                 never the network); else RICH_MARKETPLACE, else the official one",
            ),
            ArgSpec::option("marketplace-keys").value_name("FILE").help(
                "Trust this keys-N.json instead of the keys compiled in; else \
                 RICH_MARKETPLACE_KEYS",
            ),
            ArgSpec::option("plugin-dir").value_name("DIR").help(
                "Install into DIR; else RICH_PLUGIN_DIR, else $XDG_DATA_HOME/rich/plugins \
                 (~/.local/share/rich/plugins)",
            ),
            ArgSpec::option("report")
                .value_name("FORMAT")
                .help("json: the result or error envelope on stderr, nothing on stdout"),
        ]
    };
    let with_common = |mut command: CommandSpec| {
        for arg in common() {
            command = command.arg(arg);
        }
        command
    };
    let id = || ArgSpec::positional("id").help("The package's id, as `search` shows it");
    let ids = || ArgSpec::positional("id").multiple(true).help("Package ids");
    let yes = || {
        ArgSpec::flag("yes")
            .short('y')
            .help("Install without asking (for scripts); the summary is still shown")
    };
    let publish_option =
        |name: &str, value: &str, help: &str| ArgSpec::option(name).value_name(value).help(help);
    CommandSpec::new("plugin")
        .about(
            "Find, install, update and check plugins and asset packs from the plugin marketplace: \
             a signed index, every file checked by SHA-256; an installed, enabled WASM plugin \
             loads on every run without --plugin, after its file is checked against the lockfile",
        )
        .usage(
            "plugin COMMAND [ARGS] [--marketplace LOCATION] [--marketplace-keys FILE] \
             [--plugin-dir DIR] [--report json]",
        )
        .subcommand(with_common(
            CommandSpec::new("search")
                .about(
                    "List the marketplace's packages, or those with every word of QUERY in their \
                     id, name, description, keywords, authors or capabilities; the tier shows as \
                     `✓ official`, `approved` or `community`, a maintainers' pick as \
                     `★ recommended`, and who authored each",
                )
                .usage("search [QUERY] [--kind KIND] [--tier TIER] [--recommended] [--sort id|downloads]")
                .arg(ArgSpec::positional("query").help("Words to look for, in any case"))
                .arg(
                    ArgSpec::option("kind")
                        .value_name("KIND")
                        .help("Only this kind: crate, wasm-plugin, micro-pack, theme or agent"),
                )
                .arg(
                    ArgSpec::option("tier")
                        .value_name("TIER")
                        .help(
                            "Only this tier: official (rs-rich's own), reviewed (shown as \
                             approved) or community",
                        ),
                )
                .arg(ArgSpec::flag("recommended").help(
                    "Only the maintainers' picks, marked `★ recommended`",
                ))
                .arg(ArgSpec::option("sort").value_name("ORDER").help(
                    "id (the default), or downloads: most downloaded first, from the \
                     marketplace's unsigned stats.json, with a Downloads column",
                ))
                .example("rich plugin search rot13", "Packages with a rot13 capability, say")
                .example("rich plugin search --kind theme --tier official", "rs-rich's own themes"),
        ))
        .subcommand(with_common(
            CommandSpec::new("info")
                .about("One package: its tier, source, versions, what loads here, for a crate the `cargo add` line, and its downloads, 👍/👎 and reviews link when the marketplace's stats.json is there (not signed, shown only)")
                .usage("info ID")
                .arg(id()),
        ))
        .subcommand(with_common(
            CommandSpec::new("install")
                .about(
                    "Show the tier, permissions and capabilities, ask, then download, check \
                     (size, SHA-256, the WASM manifest in the sandbox) and install; a crate is \
                     refused with its `cargo add` line",
                )
                .usage("install ID[@VERSION]... [--yes]")
                .arg(ArgSpec::positional("id").multiple(true).help(
                    "Package ids, each optionally @VERSION (the only way to get a pre-release)",
                ))
                .arg(yes())
                .example("rich plugin install shout", "The newest version this host loads")
                .example("rich plugin install shout@0.2.0 --yes", "Exactly 0.2.0, without asking"),
        ))
        .subcommand(with_common(
            CommandSpec::new("update")
                .about("Move installed packages (or those named) to the newest version this host loads, asking first; a yanked version is replaced")
                .usage("update [ID...] [--yes]")
                .arg(ids())
                .arg(yes()),
        ))
        .subcommand(with_common(
            CommandSpec::new("remove")
                .about("Uninstall packages: the lockfile entry, then the file")
                .usage("remove ID...")
                .arg(ids()),
        ))
        .subcommand(with_common(
            CommandSpec::new("list")
                .about("What is installed: version, kind, tier, enabled, whether the file still matches the lockfile, and yank reasons last seen; no network")
                .usage("list"),
        ))
        .subcommand(with_common(
            CommandSpec::new("enable")
                .about("Load an installed package again on every run")
                .usage("enable ID...")
                .arg(ids()),
        ))
        .subcommand(with_common(
            CommandSpec::new("disable")
                .about("Keep a package installed but do not load it")
                .usage("disable ID...")
                .arg(ids()),
        ))
        .subcommand(with_common(
            CommandSpec::new("verify")
                .about(
                    "Check every installed file against the lockfile, and every installed \
                     version against the current index; yanked versions are reported with their \
                     reason; exits 4 when a file or listing does not match",
                )
                .usage("verify"),
        ))
        .subcommand(with_common(
            CommandSpec::new("browse")
                .about("The marketplace in a selector, with each package's provenance (tier, source, hash, permissions) beside the list; Enter installs, updates, removes, enables or disables")
                .usage("browse"),
        ))
        .subcommand(
            CommandSpec::new("publish")
                .about(
                    "Check a local package (a WASM plugin, a micro pack or a theme), compute its \
                     SHA-256 and size, and write its listing JSON for a pull request to the \
                     marketplace repository; no network",
                )
                .usage(
                    "publish FILE --url URL [--listing FILE | --license SPDX --repository URL \
                     [--description TEXT]] [--source-revision COMMIT] [--output FILE]",
                )
                .arg(ArgSpec::positional("file").help("The .wasm, .zip/.richmicro or .ini/.theme file"))
                .arg(publish_option("url", "URL", "Where the file will be downloaded from (https://, ending in its extension)"))
                .arg(publish_option("listing", "FILE", "An existing listing to add this version to (it is rewritten unless --output is given)"))
                .arg(publish_option("output", "FILE", "Where to write the listing (default packages/ID.json)"))
                .arg(publish_option("source-revision", "COMMIT", "The full Git commit the artifact was built from (required for a WASM plugin)"))
                .arg(publish_option("id", "ID", "A theme's id (default: the file name); for a plugin or pack, checked against its manifest"))
                .arg(publish_option("version", "VERSION", "A theme's version; for a plugin or pack, checked against its manifest"))
                .arg(publish_option("name", "TEXT", "The human-readable name (default: the id)"))
                .arg(publish_option("description", "TEXT", "One line on what it adds (default: a WASM plugin's or micro pack's own)"))
                .arg(publish_option("tier", "TIER", "community (the default), reviewed or official; raising it needs a maintainer"))
                .arg(publish_option("license", "SPDX", "The SPDX license expression (default: a micro pack's pack.json license)"))
                .arg(publish_option("repository", "URL", "The source repository, https://"))
                .arg(publish_option("homepage", "URL", "A homepage, https://"))
                .arg(publish_option("author", "NAME", "An author; repeatable"))
                .arg(publish_option("keyword", "WORD", "A search keyword; repeatable, at most 8"))
                .arg(publish_option("published", "DATE", "The listing date, YYYY-MM-DD (default: today, UTC)"))
                .example(
                    "rich plugin publish shout.wasm --url https://github.com/me/shout/releases/download/v0.2.0/shout.wasm --source-revision $(git rev-parse HEAD) --license MIT --repository https://github.com/me/shout",
                    "A new listing, packages/shout.json",
                )
                .example(
                    "rich plugin publish shout.wasm --url URL --source-revision COMMIT --listing packages/shout.json",
                    "Add a version to an existing listing",
                ),
        )
        .section(
            "On the web",
            format!(
                "The marketplace's own site, {MARKETPLACE_SITE}, searches and filters the same \
                 signed index in a browser; so does the docs site's Marketplace page, \
                 {MARKETPLACE_PAGE}. Both only show it: `rich plugin install` checks the \
                 signature."
            ),
        )
        .section(
            "Environment",
            "- RICH_MARKETPLACE: the marketplace, as --marketplace\n\
             - RICH_MARKETPLACE_KEYS: a keys-N.json to trust, as --marketplace-keys\n\
             - RICH_PLUGIN_DIR: the install directory, as --plugin-dir; also where every run \
             looks for installed plugins",
        )
}

// ---------------------------------------------------------------------------
// Failures and their exit classes.
// ---------------------------------------------------------------------------

/// A failure, with the exit class it reports.
#[derive(Debug)]
pub(crate) struct Failure {
    pub class: ExitClass,
    pub message: String,
}

pub(crate) type Outcome<T> = Result<T, Failure>;

pub(crate) fn usage(message: impl Into<String>) -> Failure {
    Failure {
        class: ExitClass::Usage,
        message: message.into(),
    }
}

pub(crate) fn input(message: impl Into<String>) -> Failure {
    Failure {
        class: ExitClass::Input,
        message: message.into(),
    }
}

pub(crate) fn data(message: impl Into<String>) -> Failure {
    Failure {
        class: ExitClass::Data,
        message: message.into(),
    }
}

fn index_failure(error: IndexError) -> Failure {
    data(format!("marketplace index refused: {error}"))
}

fn keys_failure(error: KeyChainError) -> Failure {
    match error {
        KeyChainError::NoTrustRoot => usage(
            "this build has no marketplace keys compiled in yet; pass --marketplace-keys FILE \
             (or set RICH_MARKETPLACE_KEYS) to a keys-N.json you trust",
        ),
        other => data(format!("marketplace keys refused: {other}")),
    }
}

fn listing_failure(error: ListingError) -> Failure {
    match error {
        ListingError::NotInIndex(id) => usage(format!(
            "no package {:?} in the marketplace",
            controls::shown(&id)
        )),
        other => data(other.to_string()),
    }
}

fn resolve_failure(error: ResolveError) -> Failure {
    match error {
        ResolveError::NoSuchVersion { .. } => usage(error.to_string()),
        other => data(other.to_string()),
    }
}

fn fetch_failure(error: FetchError) -> Failure {
    match error {
        FetchError::TooLarge { .. } | FetchError::NotHttps { .. } => data(error.to_string()),
        other => input(other.to_string()),
    }
}

fn lockfile_failure(error: LockfileError) -> Failure {
    match error {
        LockfileError::Io { .. } => input(error.to_string()),
        LockfileError::NotInstalled(_) => usage(error.to_string()),
        other => data(other.to_string()),
    }
}

fn install_failure(error: InstallError) -> Failure {
    match error {
        InstallError::NotInstallable { .. } => usage(error.to_string()),
        InstallError::Index(e) => index_failure(e),
        InstallError::Listing(e) => listing_failure(e),
        InstallError::Resolve(e) => resolve_failure(e),
        InstallError::Fetch(e) => fetch_failure(e),
        InstallError::Lockfile(e) => lockfile_failure(e),
        other => data(other.to_string()),
    }
}

// ---------------------------------------------------------------------------
// The command line.
// ---------------------------------------------------------------------------

/// What `rich plugin …` was asked.
#[derive(Debug, Default)]
pub(crate) struct Options {
    pub command: String,
    pub positionals: Vec<String>,
    pub json: bool,
    pub no_color: bool,
    pub yes: bool,
    pub marketplace: Option<String>,
    pub plugin_dir: Option<PathBuf>,
    pub keys: Option<PathBuf>,
    /// `search --sort`: `id` or `downloads`.
    pub sort: Option<String>,
    /// `search --kind KIND`.
    pub kind: Option<Kind>,
    /// `search --tier TIER`.
    pub tier: Option<Tier>,
    /// `search --recommended`.
    pub recommended: bool,
    /// `publish`'s options, by name without `--`; repeatable ones keep
    /// every value.
    pub publish: BTreeMap<&'static str, Vec<String>>,
}

/// `publish`'s options that take a value.
const PUBLISH_OPTIONS: &[&str] = &[
    "--url",
    "--listing",
    "--output",
    "--id",
    "--name",
    "--description",
    "--tier",
    "--license",
    "--repository",
    "--homepage",
    "--source-revision",
    "--version",
    "--published",
    "--author",
    "--keyword",
];

fn parse(args: &[String]) -> Outcome<Options> {
    let mut options = Options::default();
    let mut words = Vec::new();
    let mut iter = args.iter();
    let mut no_color = None;
    let mut kind = None;
    while let Some(arg) = iter.next() {
        let mut value = |name: &str| {
            iter.next()
                .cloned()
                .ok_or_else(|| usage(format!("{name} requires a value")))
        };
        match arg.as_str() {
            "--marketplace" => options.marketplace = Some(value(arg)?),
            "--plugin-dir" => options.plugin_dir = Some(fs_path(&value(arg)?)),
            "--marketplace-keys" => options.keys = Some(fs_path(&value(arg)?)),
            "--sort" => {
                let order = value(arg)?;
                if !matches!(order.as_str(), "id" | "downloads") {
                    return Err(usage(format!(
                        "unknown --sort {:?} (id, downloads)",
                        controls::shown(&order)
                    )));
                }
                options.sort = Some(order);
            }
            "--kind" => kind = Some(value(arg)?),
            "--recommended" => options.recommended = true,
            "--report" => {
                options.json = match value(arg)?.as_str() {
                    "json" => true,
                    "human" => false,
                    other => {
                        return Err(usage(format!(
                            "unknown report format {other:?} (human, json)"
                        )));
                    }
                }
            }
            "--machine-json" => options.json = true,
            "--yes" | "-y" => options.yes = true,
            "--no-color" => no_color = Some(true),
            "--color" => no_color = Some(false),
            "--" => words.extend(iter.by_ref().cloned()),
            other if other.starts_with("--") => {
                match PUBLISH_OPTIONS.iter().find(|known| **known == other) {
                    Some(known) => {
                        let v = value(other)?;
                        options.publish.entry(&known[2..]).or_default().push(v);
                    }
                    None => {
                        return Err(usage(format!(
                            "unexpected argument {:?}; see `rich plugin --help`",
                            controls::shown(other)
                        )));
                    }
                }
            }
            other if other.starts_with('-') && other != "-" => {
                return Err(usage(format!(
                    "unexpected argument {:?}; see `rich plugin --help`",
                    controls::shown(other)
                )));
            }
            _ => words.push(arg.clone()),
        }
    }
    // The first word is `plugin` itself.
    let mut words = words.into_iter().skip(1);
    options.command = words.next().unwrap_or_default();
    options.positionals = words.collect();
    if options.command.is_empty() {
        return Err(usage(format!(
            "rich plugin needs a command: {}",
            COMMANDS.join(", ")
        )));
    }
    if !COMMANDS.contains(&options.command.as_str()) {
        return Err(usage(format!(
            "unknown command {:?}; commands: {} (`rich plugins` lists what this run has loaded)",
            controls::shown(&options.command),
            COMMANDS.join(", ")
        )));
    }
    if options.sort.is_some() && options.command != "search" {
        return Err(usage("--sort only applies to `rich plugin search`"));
    }
    // `search` takes `--kind` and `--tier`; `--tier` is also publish's.
    if let Some(name) = kind {
        if options.command != "search" {
            return Err(usage("--kind only applies to `rich plugin search`"));
        }
        options.kind = Some(Kind::parse(&name).ok_or_else(|| {
            usage(format!(
                "unknown kind {:?} (crate, wasm-plugin, micro-pack, theme, agent)",
                controls::shown(&name)
            ))
        })?);
    }
    if options.recommended && options.command != "search" {
        return Err(usage("--recommended only applies to `rich plugin search`"));
    }
    if options.command == "search"
        && let Some(name) = options.publish.remove("tier").and_then(|mut v| v.pop())
    {
        options.tier = Some(Tier::parse(&name).ok_or_else(|| {
            usage(format!(
                "unknown tier {:?} (official, reviewed, community)",
                controls::shown(&name)
            ))
        })?);
    }
    if options.command != "publish" && !options.publish.is_empty() {
        let names: Vec<String> = options.publish.keys().map(|k| format!("--{k}")).collect();
        return Err(usage(format!(
            "{} only apply to `rich plugin publish`",
            names.join(", ")
        )));
    }
    let env_no_color = std::env::var_os("NO_COLOR").is_some_and(|v| !v.is_empty());
    options.no_color = no_color.unwrap_or(env_no_color);
    Ok(options)
}

pub(super) fn dispatch(args: &[String]) -> ExitCode {
    let json = wants_json_report(args);
    if args
        .iter()
        .take_while(|arg| *arg != "--")
        .any(|arg| arg == "--help" || arg == "-h")
    {
        let no_color = cli_spec::no_color_requested(args);
        let sub = args
            .iter()
            .find(|arg| COMMANDS.contains(&arg.as_str()))
            .map(String::as_str);
        let mut path = vec!["plugin"];
        path.extend(sub);
        if let Some(help) = cli_spec::subcommand_help(&path, no_color) {
            authoring::out(&format!("{help}\n"));
        }
        return ExitCode::SUCCESS;
    }
    let options = match parse(args) {
        Ok(options) => options,
        Err(failure) => return emit_error(json, failure.class, &failure.message),
    };
    let result = match options.command.as_str() {
        "search" => search(&options),
        "info" => info(&options),
        "install" => install(&options),
        "update" => update(&options),
        "remove" => remove(&options),
        "list" => list(&options),
        "enable" => set_enabled(&options, true),
        "disable" => set_enabled(&options, false),
        "verify" => verify(&options),
        "publish" => publish::run(&options),
        #[cfg(feature = "interact")]
        "browse" => browse::run(&options),
        #[cfg(not(feature = "interact"))]
        "browse" => Err(usage(
            "`rich plugin browse` needs a build with the interact feature; use `rich plugin \
             search` and `rich plugin info`",
        )),
        _ => unreachable!("checked by parse"),
    };
    finish(&options, result)
}

/// What a command did: the text for a person, and the `result` object of
/// the JSON envelope.
pub(crate) struct Done {
    pub text: String,
    pub result: Value,
    /// Set when the command ran but found problems (`verify`): reported
    /// with this class, `ok: false`, and the result still included.
    pub problem: Option<Failure>,
    /// The user declined: exit 1.
    pub declined: bool,
}

impl Done {
    pub(crate) fn new(text: String, result: Value) -> Self {
        Done {
            text,
            result,
            problem: None,
            declined: false,
        }
    }
}

fn finish(options: &Options, result: Outcome<Done>) -> ExitCode {
    match result {
        Err(failure) => emit_error(options.json, failure.class, &failure.message),
        Ok(done) => {
            if !options.json {
                authoring::out(&done.text);
            }
            if done.declined {
                let message = "cancelled; nothing was installed";
                if options.json {
                    eprintln!(
                        "{}",
                        json!({
                            "ok": false, "code": "cancelled", "exit_code": EXIT_DECLINED,
                            "message": message, "error": {"message": message},
                            "result": done.result,
                        })
                    );
                } else {
                    eprintln!("rich: {message}");
                }
                return ExitCode::from(EXIT_DECLINED);
            }
            match done.problem {
                Some(failure) => {
                    let message = controls::shown(&failure.message);
                    if options.json {
                        eprintln!(
                            "{}",
                            json!({
                                "ok": false, "code": failure.class.name(),
                                "exit_code": failure.class.code(), "message": message,
                                "error": {"message": message}, "result": done.result,
                            })
                        );
                    } else {
                        eprintln!("rich: {message}");
                    }
                    failure.class.exit_code()
                }
                None => {
                    if options.json {
                        eprintln!(
                            "{}",
                            json!({
                                "ok": true, "code": ExitClass::Success.name(),
                                "exit_code": ExitClass::Success.code(), "result": done.result,
                            })
                        );
                    }
                    ExitCode::SUCCESS
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// The install directory and this module's state.
// ---------------------------------------------------------------------------

/// The install directory: `explicit`, else `RICH_PLUGIN_DIR`, else the
/// platform's data directory.
pub(crate) fn plugin_dir(explicit: Option<&Path>) -> Option<PathBuf> {
    if let Some(dir) = explicit {
        return Some(dir.to_path_buf());
    }
    let env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty());
    if let Some(dir) = env("RICH_PLUGIN_DIR") {
        return Some(PathBuf::from(dir));
    }
    if cfg!(windows)
        && let Some(local) = env("LOCALAPPDATA")
    {
        return Some(PathBuf::from(local).join("rich").join("plugins"));
    }
    if let Some(data) = env("XDG_DATA_HOME").map(PathBuf::from)
        && data.is_absolute()
    {
        return Some(data.join("rich").join("plugins"));
    }
    env("HOME")
        .or_else(|| env("USERPROFILE"))
        .map(|home| PathBuf::from(home).join(".local/share/rich/plugins"))
}

fn require_dir(options: &Options) -> Outcome<PathBuf> {
    plugin_dir(options.plugin_dir.as_deref()).ok_or_else(|| {
        usage("no install directory: set HOME, RICH_PLUGIN_DIR or pass --plugin-dir DIR")
    })
}

/// What one marketplace served last.
#[derive(Clone, Debug, Default, PartialEq)]
struct MarketState {
    accepted: Option<AcceptedIndex>,
}

/// One key generation accepted after a trust root, as fetched: its
/// `keys-N.json` and its signatures, so it is verified again (from the
/// root, in order) each time it is read back.
#[derive(Clone, Debug, PartialEq)]
struct CachedRotation {
    keys_json: String,
    main_signature: Option<String>,
    backup_signature: String,
}

impl CachedRotation {
    fn rotation(&self) -> Rotation<'_> {
        Rotation {
            keys_json: self.keys_json.as_bytes(),
            main_signature: self.main_signature.as_deref(),
            backup_signature: &self.backup_signature,
        }
    }
}

/// `marketplace.state.json`.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct State {
    disabled: Vec<String>,
    markets: BTreeMap<String, MarketState>,
    /// The generations accepted after each trust root, by the root's main
    /// key id, whatever location served them.
    chains: BTreeMap<String, Vec<CachedRotation>>,
    /// The yank reason last seen for an installed version: `(version, reason)`.
    yanked: BTreeMap<String, (String, String)>,
}

impl State {
    fn path(dir: &Path) -> PathBuf {
        dir.join(STATE_NAME)
    }

    /// Read the state; a missing file is the empty state.
    pub(crate) fn load(dir: &Path) -> Outcome<State> {
        let path = State::path(dir);
        let bytes = match std::fs::read(&path) {
            Ok(bytes) => bytes,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(State::default()),
            Err(e) => return Err(input(format!("{}: {e}", path.display()))),
        };
        let bad = |why: &str| data(format!("{}: {why}", path.display()));
        let value: Value = serde_json::from_slice(&bytes).map_err(|e| bad(&e.to_string()))?;
        if value.get("schema_version").and_then(Value::as_u64) != Some(STATE_SCHEMA_VERSION) {
            return Err(bad("unsupported or missing schema_version"));
        }
        let strings = |v: Option<&Value>| -> Vec<String> {
            v.and_then(Value::as_array)
                .map(|a| {
                    a.iter()
                        .filter_map(Value::as_str)
                        .map(str::to_string)
                        .collect()
                })
                .unwrap_or_default()
        };
        let mut state = State {
            disabled: strings(value.get("disabled")),
            ..State::default()
        };
        if let Some(markets) = value.get("marketplaces").and_then(Value::as_object) {
            for (location, market) in markets {
                let accepted = match (
                    market.get("serial").and_then(Value::as_u64),
                    market.get("sha256").and_then(Value::as_str),
                ) {
                    (Some(serial), Some(sha256)) => Some(AcceptedIndex {
                        serial,
                        sha256: sha256.to_string(),
                    }),
                    _ => None,
                };
                // A `keys` value here (before 0.0.24) cannot be verified
                // again, so it is not read: the chain is fetched once more.
                state
                    .markets
                    .insert(location.clone(), MarketState { accepted });
            }
        }
        if let Some(chains) = value.get("key_chains").and_then(Value::as_object) {
            for (root, chain) in chains {
                let Some(chain) = chain.as_array() else {
                    continue;
                };
                // Read as written; `open` verifies it from the root.
                let chain: Option<Vec<CachedRotation>> = chain
                    .iter()
                    .map(|entry| {
                        Some(CachedRotation {
                            keys_json: entry.get("keys")?.as_str()?.to_string(),
                            main_signature: match entry.get("main_signature") {
                                None | Some(Value::Null) => None,
                                Some(v) => Some(v.as_str()?.to_string()),
                            },
                            backup_signature: entry.get("backup_signature")?.as_str()?.to_string(),
                        })
                    })
                    .collect();
                if let Some(chain) = chain {
                    state.chains.insert(root.clone(), chain);
                }
            }
        }
        if let Some(yanked) = value.get("yanked").and_then(Value::as_object) {
            for (id, entry) in yanked {
                if let (Some(version), Some(reason)) = (
                    entry.get("version").and_then(Value::as_str),
                    entry.get("reason").and_then(Value::as_str),
                ) {
                    state
                        .yanked
                        .insert(id.clone(), (version.to_string(), reason.to_string()));
                }
            }
        }
        Ok(state)
    }

    fn to_json(&self) -> String {
        let mut markets = serde_json::Map::new();
        for (location, market) in &self.markets {
            let mut entry = serde_json::Map::new();
            if let Some(accepted) = &market.accepted {
                entry.insert("serial".into(), json!(accepted.serial));
                entry.insert("sha256".into(), json!(accepted.sha256));
            }
            markets.insert(location.clone(), Value::Object(entry));
        }
        let chains: serde_json::Map<String, Value> = self
            .chains
            .iter()
            .map(|(root, chain)| {
                let entries = chain
                    .iter()
                    .map(|c| {
                        json!({
                            "keys": c.keys_json,
                            "main_signature": c.main_signature,
                            "backup_signature": c.backup_signature,
                        })
                    })
                    .collect();
                (root.clone(), Value::Array(entries))
            })
            .collect();
        let yanked: serde_json::Map<String, Value> = self
            .yanked
            .iter()
            .map(|(id, (version, reason))| {
                (id.clone(), json!({"version": version, "reason": reason}))
            })
            .collect();
        let value = json!({
            "schema_version": STATE_SCHEMA_VERSION,
            "disabled": self.disabled,
            "marketplaces": markets,
            "key_chains": chains,
            "yanked": yanked,
        });
        serde_json::to_string_pretty(&value).unwrap_or_default() + "\n"
    }

    pub(crate) fn save(&self, dir: &Path) -> Outcome<()> {
        write_atomically(&State::path(dir), self.to_json().as_bytes())
            .map_err(|e| input(format!("{}: {e}", State::path(dir).display())))
    }

    pub(crate) fn is_enabled(&self, id: &str) -> bool {
        !self.disabled.iter().any(|d| d == id)
    }

    fn set_enabled(&mut self, id: &str, enabled: bool) {
        self.disabled.retain(|d| d != id);
        if !enabled {
            self.disabled.push(id.to_string());
            self.disabled.sort();
        }
    }

    /// Remember whether the installed `version` of `id` is yanked.
    fn note_yank(&mut self, id: &str, version: &str, listed: Option<&ListedVersion>) {
        match listed.and_then(|v| v.yanked.as_ref()) {
            Some(reason) => {
                self.yanked
                    .insert(id.to_string(), (version.to_string(), reason.clone()));
            }
            None => {
                self.yanked.remove(id);
            }
        }
    }

    fn yank_reason(&self, entry: &LockEntry) -> Option<&str> {
        self.yanked
            .get(&entry.id)
            .filter(|(version, _)| *version == entry.version)
            .map(|(_, reason)| reason.as_str())
    }
}

/// Write `bytes` to `path` through a temporary file beside it. A directory
/// it creates is private on Unix (mode 700): the install directory holds
/// the lockfile and this state, which say what is trusted.
fn write_atomically(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    let dir = path.parent().unwrap_or(Path::new("."));
    rich_marketplace::create_private_dir_all(dir)?;
    let name = path
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_default();
    let temporary = dir.join(format!(".{name}.{}.partial", std::process::id()));
    let result = std::fs::write(&temporary, bytes).and_then(|()| std::fs::rename(&temporary, path));
    if result.is_err() {
        let _ = std::fs::remove_file(&temporary);
    }
    result
}

// ---------------------------------------------------------------------------
// The marketplace: where it is, its keys, its index and its listings.
// ---------------------------------------------------------------------------

/// Where the marketplace is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Location {
    /// A directory laid out as the marketplace repository is.
    Local(PathBuf),
    /// An `https://` base URL, ending in `/`.
    Remote(String),
}

impl Location {
    fn parse(text: &str) -> Outcome<Location> {
        if let Some(rest) = text.strip_prefix("file://") {
            // `file:///abs/path`, or `file://localhost/abs/path`.
            let path = rest.strip_prefix("localhost").unwrap_or(rest);
            if path.is_empty() {
                return Err(usage("--marketplace file:// needs a path"));
            }
            return Ok(Location::Local(PathBuf::from(percent_decode(path))));
        }
        if text.starts_with("https://") {
            let mut base = text.to_string();
            if !base.ends_with('/') {
                base.push('/');
            }
            return Ok(Location::Remote(base));
        }
        if text.contains("://") {
            return Err(usage(format!(
                "marketplace {:?}: only https:// URLs, file:// URLs and directories are allowed",
                controls::shown(text)
            )));
        }
        Ok(Location::Local(fs_path(text)))
    }

    /// The key it is remembered under.
    fn key(&self) -> String {
        match self {
            Location::Local(path) => {
                let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.clone());
                format!("file://{}", path.display())
            }
            Location::Remote(url) => url.clone(),
        }
    }

    fn shown(&self) -> String {
        match self {
            Location::Local(path) => path.display().to_string(),
            Location::Remote(url) => url.clone(),
        }
    }

    /// Read `relative` (`index.json`, `packages/ID.json`, …), at most
    /// `max` bytes. `None` when it is not there.
    fn fetch(&self, relative: &str, max: u64) -> Outcome<Option<Vec<u8>>> {
        match self {
            Location::Local(root) => {
                let path = relative
                    .split('/')
                    .fold(root.clone(), |path, part| path.join(part));
                read_bounded(&path, max).map_err(fetch_failure)
            }
            Location::Remote(base) => {
                #[cfg(feature = "fetch")]
                {
                    let url = format!("{base}{relative}");
                    match rich_marketplace::HttpsTransport::new().get(&url, max) {
                        Ok(bytes) => Ok(Some(bytes)),
                        Err(FetchError::Status { status: 404, .. }) => Ok(None),
                        Err(error) => Err(fetch_failure(error)),
                    }
                }
                #[cfg(not(feature = "fetch"))]
                {
                    let _ = (base, relative, max);
                    Err(usage(
                        "this build has no network access (the fetch feature); pass \
                         --marketplace DIR for a local marketplace",
                    ))
                }
            }
        }
    }

    /// Where artifacts come from: the network for a remote marketplace, the
    /// `artifacts/` mirror for a local one.
    fn transport(&self) -> Outcome<ArtifactTransport> {
        match self {
            Location::Local(root) => Ok(ArtifactTransport::Mirror(root.join("artifacts"))),
            #[cfg(feature = "fetch")]
            Location::Remote(_) => Ok(ArtifactTransport::Https(
                rich_marketplace::HttpsTransport::new(),
            )),
            #[cfg(not(feature = "fetch"))]
            Location::Remote(_) => Err(usage(
                "this build has no network access (the fetch feature); pass --marketplace DIR \
                 for a local marketplace",
            )),
        }
    }
}

/// `%XX` escapes in a `file://` URL's path.
fn percent_decode(text: &str) -> String {
    let bytes = text.as_bytes();
    let hex = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%'
            && i + 2 < bytes.len()
            && let (Some(high), Some(low)) = (hex(bytes[i + 1]), hex(bytes[i + 2]))
        {
            out.push(high << 4 | low);
            i += 3;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// Read a local file of at most `max` bytes; `None` when it is missing.
fn read_bounded(path: &Path, max: u64) -> Result<Option<Vec<u8>>, FetchError> {
    use std::io::Read;
    let url = path.display().to_string();
    let file = match std::fs::File::open(path) {
        Ok(file) => file,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(e) => {
            return Err(FetchError::Transport {
                url,
                message: e.to_string(),
            });
        }
    };
    let mut bytes = Vec::new();
    file.take(max.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|e| FetchError::Transport {
            url: url.clone(),
            message: e.to_string(),
        })?;
    if bytes.len() as u64 > max {
        return Err(FetchError::TooLarge { url, limit: max });
    }
    Ok(Some(bytes))
}

/// Downloads artifacts.
pub(crate) enum ArtifactTransport {
    /// `https://HOST/PATH` read from `DIR/HOST/PATH`: a local marketplace's
    /// mirror. Nothing outside it, and no network.
    Mirror(PathBuf),
    #[cfg(feature = "fetch")]
    Https(rich_marketplace::HttpsTransport),
}

impl Transport for ArtifactTransport {
    fn get(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>, FetchError> {
        rich_marketplace::require_https(url)?;
        match self {
            ArtifactTransport::Mirror(root) => {
                let not_found = || FetchError::NotFound {
                    url: url.to_string(),
                };
                let rest = &url["https://".len()..];
                let rest = rest.split(['?', '#']).next().unwrap_or(rest);
                let mut path = root.clone();
                for part in rest.split('/') {
                    if part.is_empty()
                        || part == "."
                        || part == ".."
                        || part.contains(['\\', ':', '\0'])
                    {
                        return Err(not_found());
                    }
                    path.push(part);
                }
                read_bounded(&path, max_bytes)
                    .map_err(|error| match error {
                        FetchError::TooLarge { limit, .. } => FetchError::TooLarge {
                            url: url.to_string(),
                            limit,
                        },
                        other => other,
                    })?
                    .ok_or_else(not_found)
            }
            #[cfg(feature = "fetch")]
            ArtifactTransport::Https(transport) => transport.get(url, max_bytes),
        }
    }
}

/// The marketplace named by `options`.
fn location(options: &Options) -> Outcome<Location> {
    let text = options
        .marketplace
        .clone()
        .or_else(|| {
            std::env::var("RICH_MARKETPLACE")
                .ok()
                .filter(|v| !v.is_empty())
        })
        .unwrap_or_else(|| DEFAULT_MARKETPLACE.to_string());
    Location::parse(&text)
}

/// The trust root: `--marketplace-keys`, `RICH_MARKETPLACE_KEYS`, or the
/// compiled-in keys.
fn trust_root(options: &Options) -> Outcome<KeySet> {
    let file = options.keys.clone().or_else(|| {
        std::env::var_os("RICH_MARKETPLACE_KEYS")
            .filter(|v| !v.is_empty())
            .map(PathBuf::from)
    });
    match file {
        Some(path) => {
            let bytes = std::fs::read(&path)
                .map_err(|e| input(format!("marketplace keys {}: {e}", path.display())))?;
            KeySet::from_json(&bytes)
                .map_err(|e| data(format!("marketplace keys {}: {e}", path.display())))
        }
        None => KeySet::official().map_err(keys_failure),
    }
}

/// An opened marketplace: its location and its verified index.
pub(crate) struct Market {
    pub location: Location,
    pub index: VerifiedIndex,
}

/// Open the marketplace: walk its key chain from the trust root (or the
/// newest generation already verified), then verify `index.json` against
/// the last index accepted from it, and remember both.
pub(crate) fn open(options: &Options, dir: &Path, state: &mut State) -> Outcome<Market> {
    let location = location(options)?;
    let key = location.key();
    let root = trust_root(options)?;
    let root_id = root.main().id().to_string();
    let market = state.markets.get(&key).cloned().unwrap_or_default();
    // The generations already accepted after this root, from any location,
    // verified again from the root: the state file can only take the walk
    // back to the root, never add a key.
    let (mut keys, mut chain) = match replay(&root, state.chains.get(&root_id)) {
        Ok(replayed) => replayed,
        Err(why) => {
            eprintln!(
                "rich: warning: the key chain cached in {} does not verify from the trust \
                 root ({why}); it is ignored and fetched again",
                State::path(dir).display()
            );
            // Dropped now, whatever the index below turns out to be.
            state.chains.remove(&root_id);
            let _ = state.save(dir);
            (root.clone(), Vec::new())
        }
    };
    let mut notices = Vec::new();
    for _ in 0..MAX_ROTATIONS {
        let next = keys.generation() + 1;
        let name = format!("keys/keys-{next}.json");
        let Some(keys_json) = location.fetch(&name, MAX_KEYS_BYTES)? else {
            break;
        };
        let backup = location
            .fetch(&format!("{name}.backup.minisig"), MAX_SIGNATURE_BYTES)?
            .ok_or_else(|| data(format!("{name} has no backup signature")))?;
        let main = location.fetch(&format!("{name}.main.minisig"), MAX_SIGNATURE_BYTES)?;
        let backup = String::from_utf8_lossy(&backup).into_owned();
        let main = main.map(|m| String::from_utf8_lossy(&m).into_owned());
        let (set, kind) = keys
            .rotate(Rotation {
                keys_json: &keys_json,
                main_signature: main.as_deref(),
                backup_signature: &backup,
            })
            .map_err(keys_failure)?;
        if let RotationKind::MainKeyReplaced { revoked } = kind {
            notices.push(format!(
                "the marketplace's main key {revoked} was revoked and replaced (keys generation \
                 {next})"
            ));
        }
        keys = set;
        // Kept only as the exact bytes verified; keys files are JSON, so
        // UTF-8.
        if let Ok(keys_json) = String::from_utf8(keys_json) {
            chain.push(CachedRotation {
                keys_json,
                main_signature: main,
                backup_signature: backup,
            });
        }
    }

    let index = location
        .fetch("index.json", MAX_INDEX_BYTES)?
        .ok_or_else(|| {
            input(format!(
                "no index.json in the marketplace at {}",
                location.shown()
            ))
        })?;
    let signature = location
        .fetch("index.json.minisig", MAX_SIGNATURE_BYTES)?
        .ok_or_else(|| {
            data(format!(
                "the marketplace at {} has no index.json.minisig",
                location.shown()
            ))
        })?;
    let signature = String::from_utf8_lossy(&signature);
    let verified = verify_index(
        &keys,
        &index,
        &signature,
        market.accepted.as_ref(),
        SystemTime::now(),
    )
    .map_err(|error| stale_keys_hint(error, &keys, &location))?;
    state.markets.insert(
        key,
        MarketState {
            accepted: Some(verified.accepted()),
        },
    );
    if chain.is_empty() {
        // Nothing past the root (or a cached chain that did not verify).
        state.chains.remove(&root_id);
    } else {
        state.chains.insert(root_id, chain);
    }
    // Without this, a rollback could not be noticed next time; a directory
    // that cannot be written is still searched.
    if let Err(failure) = state.save(dir) {
        eprintln!("rich: warning: {}", failure.message);
    }
    for notice in &notices {
        eprintln!("rich: warning: {notice}");
    }
    Ok(Market {
        location,
        index: verified,
    })
}

/// Walk `cached` from `root`, verifying each generation's signatures as a
/// fetched one is: the newest generation reached and the rotations kept.
/// Generations the root already includes (a newer root compiled in) are
/// skipped.
fn replay(
    root: &KeySet,
    cached: Option<&Vec<CachedRotation>>,
) -> Result<(KeySet, Vec<CachedRotation>), KeyChainError> {
    let mut keys = root.clone();
    let mut kept = Vec::new();
    for rotation in cached.into_iter().flatten() {
        let generation = KeySet::from_json(rotation.keys_json.as_bytes())?.generation();
        if generation <= keys.generation() {
            continue;
        }
        keys = keys.rotate(rotation.rotation())?.0;
        kept.push(rotation.clone());
    }
    Ok((keys, kept))
}

/// An index refused for its key: say when that key is one the chain
/// revoked, or when the location may be missing the next `keys-N.json`.
fn stale_keys_hint(error: IndexError, keys: &KeySet, location: &Location) -> Failure {
    let found = match &error {
        IndexError::Signature(rich_marketplace::SignatureError::WrongKeyId { found, .. }) => *found,
        _ => return index_failure(error),
    };
    let mut failure = index_failure(error);
    let generation = keys.generation();
    if keys.revoked().contains(&found) {
        failure.message.push_str(&format!(
            "; key {found} was revoked by keys generation {generation} or earlier, so the \
             marketplace at {} is stale or is withholding newer keys",
            location.shown()
        ));
    } else {
        failure.message.push_str(&format!(
            "; if the marketplace rotated its keys, {} may be missing keys/keys-{}.json",
            location.shown(),
            generation + 1
        ));
    }
    failure
}

impl Market {
    /// Read and check listing `id`.
    pub(crate) fn listing(&self, id: &str) -> Outcome<Listing> {
        self.read_listing(id)?.map_err(listing_failure)
    }

    /// A listing as read, its own fault kept apart from the marketplace's.
    fn read_listing(&self, id: &str) -> Outcome<Result<Listing, ListingError>> {
        let entry = self.index.entry(id).ok_or_else(|| {
            usage(format!(
                "no package {:?} in the marketplace at {}",
                controls::shown(id),
                self.location.shown()
            ))
        })?;
        let bytes = self
            .location
            .fetch(&entry.path, MAX_LISTING_BYTES)?
            .ok_or_else(|| data(format!("{} is missing from the marketplace", entry.path)))?;
        Ok(self.index.read_listing(id, &bytes))
    }

    /// Every listing, by id. A listing of a kind or a format this release
    /// does not know (a newer one's) is left out with a warning, so one new
    /// kind in the marketplace does not stop an older `rich` from searching
    /// the rest.
    pub(crate) fn listings(&self) -> Outcome<Vec<Listing>> {
        let mut out = Vec::new();
        let mut skipped = Vec::new();
        for id in self.index.listings().keys() {
            match self.read_listing(id)? {
                Ok(listing) => out.push(listing),
                Err(ListingError::UnknownKind(_) | ListingError::UnsupportedSchema(_)) => {
                    skipped.push(controls::shown(id).to_string());
                }
                Err(error) => return Err(listing_failure(error)),
            }
        }
        if !skipped.is_empty() {
            eprintln!(
                "rich: warning: left out {} listing(s) of a kind or format this rich does not \
                 know (update rich to see them): {}",
                skipped.len(),
                skipped.join(", ")
            );
        }
        Ok(out)
    }
}

// ---------------------------------------------------------------------------
// Checking a WASM module in the sandbox.
// ---------------------------------------------------------------------------

/// The CLI's [`ArtifactChecker`]: with `wasm-plugins`, a module is loaded in
/// the sandbox (`load_wasm_bytes`, the loader `--plugin` uses) and its
/// manifest compared with the listing; the other kinds use the built-in
/// checks.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct SandboxChecker;

impl ArtifactChecker for SandboxChecker {
    fn check_wasm(&self, bytes: &[u8], expected: &WasmExpectation<'_>) -> Result<(), CheckError> {
        rich_marketplace::check_wasm_header(bytes)?;
        #[cfg(feature = "wasm-plugins")]
        {
            let label = PathBuf::from(format!("{}-{}.wasm", expected.id, expected.version));
            let plugin = rich_ext::plugin_loading::load_wasm_bytes(
                bytes,
                &label,
                &rich_ext::plugin_loading::WasmLimits::default(),
            )
            .map_err(|e| CheckError::Host(format!("the module does not load: {e}")))?;
            rich_marketplace::compare_wasm_manifest(plugin.abi(), expected)
        }
        #[cfg(not(feature = "wasm-plugins"))]
        {
            let _ = expected;
            Err(CheckError::Host(
                "this build cannot load WASM plugins; it needs the wasm-plugins feature".into(),
            ))
        }
    }
}

// ---------------------------------------------------------------------------
// Loading what is installed, on every run.
// ---------------------------------------------------------------------------

/// Whether anything may be installed: the lockfile exists. One stat, so a
/// run with nothing installed does no more.
pub(crate) fn has_installed() -> bool {
    plugin_dir(None).is_some_and(|dir| dir.join(LOCKFILE_NAME).is_file())
}

/// The install directory and the installed, enabled entries of `kind`, or
/// nothing (with why, when the lockfile or state cannot be read). Nothing
/// installed costs one missing-file check.
fn installed_entries(kind: Kind, what: &str) -> (Option<(PathBuf, Vec<LockEntry>)>, Vec<String>) {
    let mut warnings = Vec::new();
    let Some(dir) = plugin_dir(None) else {
        return (None, warnings);
    };
    let lock_path = dir.join(LOCKFILE_NAME);
    if !lock_path.is_file() {
        return (None, warnings);
    }
    let lockfile = match Lockfile::load(&lock_path) {
        Ok(lockfile) => lockfile,
        Err(error) => {
            warnings.push(format!("installed {what} are not loaded: {error}"));
            return (None, warnings);
        }
    };
    let state = match State::load(&dir) {
        Ok(state) => state,
        Err(failure) => {
            warnings.push(format!(
                "installed {what} are not loaded: {}",
                failure.message
            ));
            return (None, warnings);
        }
    };
    let wanted: Vec<LockEntry> = lockfile
        .entries()
        .filter(|e| e.kind == kind && state.is_enabled(&e.id))
        .cloned()
        .collect();
    (Some((dir, wanted)), warnings)
}

/// The installed, enabled WASM plugins, each read once and checked against
/// the lockfile, then loaded from the bytes checked. `skip` names plugins
/// already loaded (`--plugin PATH` wins over an installed copy). Nothing
/// installed costs one missing-file check. A plugin that fails is not
/// loaded and is named in a warning: a changed file is refused.
pub(crate) fn installed_plugins(skip: &[String]) -> (Vec<RuntimePlugin>, Vec<String>) {
    let mut plugins = Vec::new();
    let (found, mut warnings) = installed_entries(Kind::WasmPlugin, "plugins");
    let Some((dir, wanted)) = found else {
        return (plugins, warnings);
    };
    let wanted: Vec<&LockEntry> = wanted.iter().filter(|e| !skip.contains(&e.id)).collect();
    if wanted.is_empty() {
        return (plugins, warnings);
    }
    if !RuntimeKind::Wasm.supported() {
        let ids: Vec<&str> = wanted.iter().map(|e| e.id.as_str()).collect();
        warnings.push(format!(
            "installed WASM plugins ({}) are not loaded: this build lacks the wasm-plugins \
             feature",
            ids.join(", ")
        ));
        return (plugins, warnings);
    }
    for entry in wanted {
        match load_entry(&dir, entry) {
            Ok(plugin) => plugins.push(plugin),
            Err(message) => warnings.push(format!(
                "plugin {} is not loaded: {message}; `rich plugin verify` checks every installed \
                 file",
                entry.id
            )),
        }
    }
    (plugins, warnings)
}

/// The installed, enabled micro packs, as `(id, file)`, for micro's
/// registry to load into the user layer. Each file is checked against the
/// lockfile first: one that changed on disk is left out and named in a
/// warning. micro reads an archive by path, and reads an asset's images
/// from it again when they are drawn, so the check is made when the
/// registry loads, not on every read.
#[cfg_attr(not(feature = "art"), allow(dead_code))]
pub(crate) fn installed_micro_packs() -> (Vec<(String, PathBuf)>, Vec<String>) {
    let mut packs = Vec::new();
    let (found, mut warnings) = installed_entries(Kind::MicroPack, "micro packs");
    let Some((dir, wanted)) = found else {
        return (packs, warnings);
    };
    for entry in wanted {
        match entry.verify(&dir) {
            Ok(_) => packs.push((entry.id.clone(), entry.file(&dir))),
            Err(error) => warnings.push(format!(
                "micro pack {} is not loaded: {error}; `rich plugin verify` checks every \
                 installed file",
                entry.id
            )),
        }
    }
    (packs, warnings)
}

/// The installed, enabled theme `id`, as `name -> style` bindings, for
/// `--theme NAME` when the config has no theme of that name. The file is
/// read once and checked against the lockfile, and the bytes checked are
/// parsed: one that changed on disk, or no longer parses, is not used and
/// is named in a warning. `None` when no such theme is installed and
/// enabled.
pub(crate) fn installed_theme(id: &str) -> (Option<BTreeMap<String, String>>, Vec<String>) {
    let (found, mut warnings) = installed_entries(Kind::Theme, "themes");
    let Some((dir, wanted)) = found else {
        return (None, warnings);
    };
    let Some(entry) = wanted.iter().find(|e| e.id == id) else {
        return (None, warnings);
    };
    let styles = entry
        .verify(&dir)
        .map_err(|error| error.to_string())
        .and_then(|bytes| theme_bindings(&bytes));
    match styles {
        Ok(styles) => (Some(styles), warnings),
        Err(error) => {
            warnings.push(format!(
                "theme {id} is not loaded: {error}; `rich plugin verify` checks every installed \
                 file"
            ));
            (None, warnings)
        }
    }
}

/// A `[styles]` theme file's bindings, each one `--theme-style` accepts.
fn theme_bindings(bytes: &[u8]) -> Result<BTreeMap<String, String>, String> {
    let text = std::str::from_utf8(bytes).map_err(|_| "not UTF-8".to_string())?;
    let theme = rich::Theme::from_file(text, false).map_err(|error| error.to_string())?;
    let mut styles = BTreeMap::new();
    for name in theme.names() {
        let Some(style) = theme.get(name) else {
            continue;
        };
        let definition = style.definition();
        super::config::validate_theme_binding(name, &definition)?;
        styles.insert(name.to_owned(), definition);
    }
    Ok(styles)
}

#[cfg(feature = "wasm-plugins")]
fn load_entry(dir: &Path, entry: &LockEntry) -> Result<RuntimePlugin, String> {
    let bytes = entry.verify(dir).map_err(|e| e.to_string())?;
    let plugin = rich_ext::plugin_loading::load_wasm_bytes(
        &bytes,
        &entry.file(dir),
        &rich_ext::plugin_loading::WasmLimits::default(),
    )
    .map_err(|e| e.to_string())?;
    if plugin.abi().name != entry.id {
        return Err(format!(
            "its manifest names {:?}, but it is installed as {}",
            plugin.abi().name,
            entry.id
        ));
    }
    Ok(plugin)
}

#[cfg(not(feature = "wasm-plugins"))]
fn load_entry(_: &Path, _: &LockEntry) -> Result<RuntimePlugin, String> {
    Err("this build lacks the wasm-plugins feature".into())
}

// ---------------------------------------------------------------------------
// Showing packages.
// ---------------------------------------------------------------------------

/// One line of listing text, safe to print.
pub(crate) fn line(text: &str) -> String {
    rich_ext::sanitize::sanitize_single_line(text)
}

fn escape(text: &str) -> String {
    rich::markup::escape(&line(text))
}

pub(crate) fn tier_meaning(tier: Tier) -> &'static str {
    match tier {
        Tier::Official => "rs-rich's own, built from its repository",
        Tier::Reviewed => "a maintainer reviewed the source and rebuilt the same artifact",
        _ => "checked by the marketplace's CI only, not reviewed",
    }
}

/// The tier as a marker that reads the same without colour: `✓ official`,
/// `approved` (the `reviewed` tier) or `community`. Only ever made from a
/// listing's `tier`.
pub(crate) fn tier_label(tier: Tier) -> &'static str {
    match tier {
        Tier::Official => "✓ official",
        Tier::Reviewed => "approved",
        _ => "community",
    }
}

/// The tier's name as people see it; a listing and the reports say
/// `reviewed`, shown as Approved.
pub(crate) fn tier_display(tier: Tier) -> &'static str {
    match tier {
        Tier::Official => "Official",
        Tier::Reviewed => "Approved",
        _ => "Community",
    }
}

/// The maintainers' pick, as a marker that reads the same without colour.
pub(crate) const RECOMMENDED_LABEL: &str = "★ recommended";

/// [`tier_marker`], and `★ recommended` under it for a recommended
/// listing. Only ever made from the listing's `tier` and `recommended`.
pub(crate) fn marks(listing: &Listing) -> String {
    let mut text = tier_marker(listing.tier);
    if listing.recommended.is_some() {
        text.push_str(&format!("\n[bold magenta]{RECOMMENDED_LABEL}[/]"));
    }
    text
}

/// The `Recommended` row: since when, and the maintainer's note.
pub(crate) fn recommended_text(recommended: &rich_marketplace::Recommended) -> String {
    format!(
        "{RECOMMENDED_LABEL} since {}: {}",
        recommended.since, recommended.note
    )
}

/// [`tier_label`] as markup: official in green, approved plain, community
/// in yellow.
pub(crate) fn tier_marker(tier: Tier) -> String {
    match tier {
        Tier::Official => format!("[bold green]{}[/]", tier_label(tier)),
        Tier::Reviewed => tier_label(tier).to_string(),
        _ => format!("[yellow]{}[/]", tier_label(tier)),
    }
}

/// A listing's repository as `host/owner/repo`, without the scheme.
pub(crate) fn repository_source(repository: &str) -> String {
    let rest = repository
        .strip_prefix("https://")
        .unwrap_or(repository)
        .trim_end_matches('/');
    line(rest.strip_suffix(".git").unwrap_or(rest))
}

/// Who publishes a listing's repository: the owner of a
/// `host/owner/...` repository, else its host.
pub(crate) fn repository_owner(repository: &str) -> String {
    let source = repository_source(repository);
    let mut parts = source.split('/');
    let host = parts.next().unwrap_or_default().to_string();
    parts
        .next()
        .filter(|owner| !owner.is_empty())
        .map_or(host, str::to_string)
}

/// The longest author name shown, and how many are named before "and N
/// more".
const MAX_AUTHOR_CHARS: usize = 40;
const MAX_AUTHORS: usize = 3;

/// "Authored by …": `rs-rich` for an official package; otherwise the
/// listing's own `authors` (its claim, in quotes when it names rs-rich, cut
/// short) or the repository's owner, then the repository it comes from.
pub(crate) fn authored_by(listing: &Listing) -> String {
    format!("Authored by {}", authors_text(listing))
}

/// [`authored_by`] without its first words, for a row named "Authored by".
pub(crate) fn authors_text(listing: &Listing) -> String {
    if listing.tier == Tier::Official {
        return "rs-rich".into();
    }
    let mut names: Vec<String> = listing
        .authors
        .iter()
        .take(MAX_AUTHORS)
        .map(|author| {
            let author = line(author);
            let mut short: String = author.chars().take(MAX_AUTHOR_CHARS).collect();
            if short.len() < author.len() {
                short.push('…');
            }
            if short.to_lowercase().contains("rs-rich") {
                format!("\"{short}\"")
            } else {
                short
            }
        })
        .collect();
    if listing.authors.len() > MAX_AUTHORS {
        names.push(format!("and {} more", listing.authors.len() - MAX_AUTHORS));
    }
    if names.is_empty() {
        names.push(repository_owner(&listing.repository));
    }
    format!(
        "{} from {}",
        names.join(", "),
        repository_source(&listing.repository)
    )
}

/// Who publishes a package, by its tier: rs-rich for an official one, the
/// repository's owner otherwise.
pub(crate) fn publisher(listing: &Listing) -> String {
    let owner = repository_owner(&listing.repository);
    match listing.tier {
        Tier::Official => "Official: built and published by rs-rich".into(),
        Tier::Reviewed => format!(
            "Approved: published by {owner}, not by rs-rich; a maintainer read its source and \
             rebuilt it"
        ),
        _ => format!(
            "Community: published by {owner}, not by rs-rich. Made by its author: check its \
             source and permissions"
        ),
    }
}

/// A grid or preview row's value as markup: escaped, with the `Tier` row's
/// leading [`tier_label`] coloured as [`tier_marker`].
pub(crate) fn row_markup(key: &str, value: &str) -> String {
    if key == "Recommended"
        && let Some(rest) = value.strip_prefix(RECOMMENDED_LABEL)
    {
        return format!("[bold magenta]{RECOMMENDED_LABEL}[/]{}", escape(rest));
    }
    if key == "Tier" {
        for tier in [Tier::Official, Tier::Reviewed, Tier::Community] {
            if let Some(rest) = value.strip_prefix(tier_label(tier)) {
                return format!("{}{}", tier_marker(tier), escape(rest));
            }
        }
    }
    escape(value)
}

pub(crate) fn requires_text(requires: Requires) -> String {
    match requires {
        Requires::Abi { major, minor } => format!("plugin ABI {major}.{minor}"),
        Requires::PluginApi(n) => format!("plugin API {n}"),
        Requires::MicroSchema(n) => format!("micro pack schema {n}"),
        Requires::ThemeFormat(n) => format!("theme format {n}"),
        _ => "unknown".into(),
    }
}

fn requires_json(requires: Requires) -> Value {
    match requires {
        Requires::Abi { major, minor } => json!({"abi": format!("{major}.{minor}")}),
        Requires::PluginApi(n) => json!({"plugin_api": n}),
        Requires::MicroSchema(n) => json!({"micro_schema": n}),
        Requires::ThemeFormat(n) => json!({"theme_format": n}),
        _ => Value::Null,
    }
}

pub(crate) fn capabilities_text(version: &ListedVersion) -> String {
    version
        .capabilities
        .iter()
        .map(|c| format!("{} {}", c.kind, c.name))
        .collect::<Vec<_>>()
        .join(", ")
}

pub(crate) fn permissions_text(kind: Kind, version: &ListedVersion) -> String {
    if version.permissions.is_empty() {
        return match kind {
            Kind::WasmPlugin => {
                "none (sandboxed: no files, network, clock or processes)".to_string()
            }
            Kind::Crate => "none declared".to_string(),
            _ => "none (data only)".to_string(),
        };
    }
    let mut text = version.permissions.join(", ");
    if kind == Kind::Crate {
        text.push_str(" (declared, not enforced: native code runs with your rights)");
    }
    text
}

fn version_json(listing: &Listing, version: &ListedVersion, host: &Host) -> Value {
    json!({
        "version": version.version.to_string(),
        "published": version.published,
        "requires": requires_json(version.requires),
        "compatible": host.check(listing.kind, version).is_ok(),
        "artifact": {
            "url": version.artifact.url,
            "sha256": version.artifact.sha256,
            "size": version.artifact.size,
        },
        "source_revision": version.source_revision,
        "capabilities": version.capabilities.iter()
            .map(|c| json!({"kind": c.kind, "name": c.name})).collect::<Vec<_>>(),
        "permissions": version.permissions,
        "yanked": version.yanked.is_some(),
        "yank_reason": version.yanked,
    })
}

fn listing_json(listing: &Listing, host: &Host, installed: Option<&LockEntry>) -> Value {
    let candidate = resolve(listing, host, &Request::Newest).ok();
    json!({
        "id": listing.id,
        "kind": listing.kind.as_str(),
        "name": listing.name,
        "description": listing.description,
        "tier": listing.tier.as_str(),
        "tier_label": tier_display(listing.tier),
        "recommended": listing.recommended.as_ref().map(|r| json!({"since": r.since, "note": r.note})),
        "license": listing.license,
        "authors": listing.authors,
        "repository": listing.repository,
        "homepage": listing.homepage,
        "keywords": listing.keywords,
        "crate": listing.crate_info.as_ref().map(|c| json!({"name": c.name, "features": c.features})),
        "installable": listing.kind.is_installable(),
        "candidate": candidate.map(|v| v.version.to_string()),
        "installed": installed.map(|e| e.version.clone()),
        "versions": listing.versions.iter().map(|v| version_json(listing, v, host)).collect::<Vec<_>>(),
    })
}

/// `cargo add` for a crate listing.
pub(crate) fn cargo_add(listing: &Listing, version: &ListedVersion) -> String {
    let name = listing
        .crate_info
        .as_ref()
        .map_or(listing.id.as_str(), |c| c.name.as_str());
    let mut command = format!("cargo add {name}@={}", version.version);
    if let Some(features) = listing.crate_info.as_ref().map(|c| &c.features)
        && !features.is_empty()
    {
        command.push_str(&format!(" --features {}", features.join(",")));
    }
    command
}

fn crate_refusal(listing: &Listing) -> Failure {
    let version = resolve(listing, &Host::current(), &Request::Newest)
        .ok()
        .or_else(|| listing.versions.first());
    let name = listing
        .crate_info
        .as_ref()
        .map_or(listing.id.as_str(), |c| c.name.as_str());
    match version {
        Some(version) => usage(format!(
            "{} is a Cargo crate ({name} {}); add it to your program:\n    {}",
            listing.id,
            version.version,
            cargo_add(listing, version)
        )),
        None => usage(format!(
            "{} is a Cargo crate ({name}), which is listed only and never installed",
            listing.id
        )),
    }
}

/// A key/value grid.
fn grid(rows: &[(&str, String)], no_color: bool) -> String {
    let mut table = rich::Table::grid().padding(0, 2, 0, 0);
    table.add_column("");
    table.add_column_with(
        Text::default(),
        rich::ColumnOptions {
            overflow: rich::Overflow::Fold,
            ..rich::ColumnOptions::default()
        },
    );
    for (key, value) in rows {
        let value: Vec<String> = value.lines().map(|l| row_markup(key, l)).collect();
        table.add_row(&[&format!("[bold]{key}[/]"), &value.join("\n")]);
    }
    cli_spec::render(&table, no_color) + "\n"
}

/// A table of markup cells: the caller escapes what it did not write.
fn table(columns: &[&str], rows: &[Vec<String>], no_color: bool) -> String {
    let mut table = rich::Table::new();
    for column in columns {
        table.add_column(*column);
    }
    for row in rows {
        let cells: Vec<&str> = row.iter().map(String::as_str).collect();
        table.add_row(&cells);
    }
    cli_spec::render(&table, no_color) + "\n"
}

/// What an install shows before it asks.
pub(crate) fn provenance(
    listing: &Listing,
    version: &ListedVersion,
) -> Vec<(&'static str, String)> {
    let mut rows = vec![
        (
            "Package",
            format!("{} {} ({})", listing.id, version.version, listing.kind),
        ),
        ("Name", listing.name.clone()),
        (
            "Tier",
            format!(
                "{}: {}",
                tier_label(listing.tier),
                tier_meaning(listing.tier)
            ),
        ),
        ("Publisher", publisher(listing)),
        ("Authored by", authors_text(listing)),
        ("Source", listing.repository.clone()),
    ];
    if let Some(recommended) = &listing.recommended {
        rows.push(("Recommended", recommended_text(recommended)));
    }
    if let Some(revision) = &version.source_revision {
        rows.push(("Revision", revision.clone()));
    }
    rows.push(("Artifact", version.artifact.url.clone()));
    rows.push(("SHA-256", version.artifact.sha256.clone()));
    rows.push(("Size", format!("{} bytes", version.artifact.size)));
    rows.push(("Requires", requires_text(version.requires)));
    rows.push(("Capabilities", capabilities_text(version)));
    rows.push(("Permissions", permissions_text(listing.kind, version)));
    rows.push(("License", listing.license.clone()));
    if let Some(reason) = &version.yanked {
        rows.push(("Yanked", reason.clone()));
    }
    rows
}

/// Ask `question` on the terminal; `--yes` answers yes. Without a terminal
/// and without `--yes`, nothing is asked and nothing is done.
pub(crate) fn confirm(question: &str, options: &Options) -> Outcome<bool> {
    if options.yes {
        return Ok(true);
    }
    if !std::io::stdin().is_terminal() {
        return Err(input(format!(
            "{question} needs an answer, and there is no terminal to ask on; pass --yes"
        )));
    }
    eprint!("{question} [y/N] ");
    let mut answer = String::new();
    std::io::stdin()
        .read_line(&mut answer)
        .map_err(|e| input(format!("cannot read the answer: {e}")))?;
    Ok(matches!(
        answer.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}

// ---------------------------------------------------------------------------
// The commands.
// ---------------------------------------------------------------------------

fn lockfile(dir: &Path) -> Outcome<Lockfile> {
    Lockfile::load(&dir.join(LOCKFILE_NAME)).map_err(lockfile_failure)
}

/// The marketplace's own web site: where `rich plugin search` points first
/// when nothing matches, and `rich plugin --help`'s "On the web".
pub(crate) const MARKETPLACE_SITE: &str =
    "https://buchochelliq-labs.github.io/rs-rich-marketplace/";

/// The docs site's Marketplace page, the second place on the web.
pub(crate) const MARKETPLACE_PAGE: &str =
    "https://buchochelliq-labs.github.io/rs-rich-cli/latest/marketplace/";

/// Whether `listing` is one `search` shows: of `--kind` and `--tier` when
/// given, recommended for `--recommended`, and with every word of `query` (lower-cased) in its id, name,
/// description, keywords, authors, crate, kind or any version's
/// capabilities.
pub(crate) fn search_matches(listing: &Listing, query: &str, options: &Options) -> bool {
    if options.kind.is_some_and(|k| k != listing.kind)
        || options.tier.is_some_and(|t| t != listing.tier)
        || (options.recommended && listing.recommended.is_none())
    {
        return false;
    }
    let mut fields = vec![
        listing.id.as_str(),
        listing.name.as_str(),
        listing.description.as_str(),
        listing.kind.as_str(),
    ];
    fields.extend(listing.keywords.iter().map(String::as_str));
    fields.extend(listing.authors.iter().map(String::as_str));
    if let Some(info) = &listing.crate_info {
        fields.push(info.name.as_str());
    }
    for version in &listing.versions {
        for capability in &version.capabilities {
            fields.push(capability.kind.as_str());
            fields.push(capability.name.as_str());
        }
    }
    let haystack = fields.join("\n").to_lowercase();
    query.split_whitespace().all(|word| haystack.contains(word))
}

/// `search [QUERY] [--kind KIND] [--tier TIER]`: every listing that
/// [`search_matches`].
fn search(options: &Options) -> Outcome<Done> {
    let dir = require_dir(options)?;
    let mut state = State::load(&dir)?;
    let market = open(options, &dir, &mut state)?;
    let lock = lockfile(&dir)?;
    let query = options.positionals.join(" ").to_lowercase();
    let host = Host::current();
    let by_downloads = options.sort.as_deref() == Some("downloads");
    let stats = if by_downloads {
        let stats = stats::load(&market.location);
        if stats.is_none() && !options.json {
            eprintln!(
                "rich: the marketplace's stats.json is not available; sorted by id ({})",
                stats::stats_source(&market.location)
            );
        }
        stats
    } else {
        None
    };
    let mut listings = market.listings()?;
    if let Some(stats) = &stats {
        // Most downloaded first; not counted last; then by id.
        listings.sort_by(|a, b| {
            let (x, y) = (stats.total(&a.id), stats.total(&b.id));
            y.cmp(&x).then_with(|| a.id.cmp(&b.id))
        });
    }
    let mut rows = Vec::new();
    let mut found = Vec::new();
    for listing in listings {
        if !search_matches(&listing, &query, options) {
            continue;
        }
        let installed = lock.get(&listing.id);
        let candidate = resolve(&listing, &host, &Request::Newest)
            .map(|v| v.version.to_string())
            .unwrap_or_else(|_| "none for this host".into());
        let mut row = vec![
            escape(&listing.id),
            escape(listing.kind.as_str()),
            marks(&listing),
            escape(&candidate),
            escape(&installed.map_or_else(String::new, |e| e.version.clone())),
        ];
        let mut value = listing_json(&listing, &host, installed);
        if let Some(stats) = &stats {
            row.push(
                stats
                    .total(&listing.id)
                    .map_or_else(|| "-".to_string(), |n| n.to_string()),
            );
            value["stats"] = stats.package_json(&listing.id);
        }
        row.push(format!(
            "{}\n[dim]{}[/]",
            escape(&listing.description),
            escape(&authored_by(&listing))
        ));
        rows.push(row);
        found.push(value);
    }
    let mut columns = vec!["Id", "Kind", "Tier", "Version", "Installed"];
    if stats.is_some() {
        columns.push("Downloads");
    }
    columns.push("Description");
    let text = if rows.is_empty() {
        format!(
            "No packages match. Try fewer words, or browse every package with `rich plugin \
             browse`, or on the web: {MARKETPLACE_SITE} (or the docs' {MARKETPLACE_PAGE})\n"
        )
    } else {
        table(&columns, &rows, options.no_color)
    };
    Ok(Done::new(
        text,
        json!({
            "marketplace": market.location.shown(),
            "index_serial": market.index.serial(),
            "packages": found,
        }),
    ))
}

fn one_id(options: &Options, what: &str) -> Outcome<String> {
    match options.positionals.as_slice() {
        [id] => Ok(id.clone()),
        [] => Err(usage(format!("rich plugin {what} needs a package ID"))),
        _ => Err(usage(format!("rich plugin {what} takes one package ID"))),
    }
}

/// `info ID`: a listing, its versions and what this host would install.
fn info(options: &Options) -> Outcome<Done> {
    let id = one_id(options, "info")?;
    let dir = require_dir(options)?;
    let mut state = State::load(&dir)?;
    let market = open(options, &dir, &mut state)?;
    let listing = market.listing(&id)?;
    let lock = lockfile(&dir)?;
    let installed = lock.get(&id);
    if let Some(entry) = installed {
        let listed = listing
            .versions
            .iter()
            .find(|v| v.version.to_string() == entry.version);
        state.note_yank(&id, &entry.version, listed);
        let _ = state.save(&dir);
    }
    let host = Host::current();
    let candidate = resolve(&listing, &host, &Request::Newest);
    let mut rows = vec![
        ("Name", listing.name.clone()),
        ("Kind", listing.kind.to_string()),
        (
            "Tier",
            format!(
                "{}: {}",
                tier_label(listing.tier),
                tier_meaning(listing.tier)
            ),
        ),
        ("Publisher", publisher(&listing)),
        ("Authored by", authors_text(&listing)),
    ];
    if let Some(recommended) = &listing.recommended {
        rows.push(("Recommended", recommended_text(recommended)));
    }
    rows.extend([
        ("Description", listing.description.clone()),
        ("License", listing.license.clone()),
        ("Repository", listing.repository.clone()),
    ]);
    if let Some(homepage) = &listing.homepage {
        rows.push(("Homepage", homepage.clone()));
    }
    match &candidate {
        Ok(version) => {
            rows.push(("Newest", format!("{} (suits this host)", version.version)));
            rows.push(("Capabilities", capabilities_text(version)));
            rows.push(("Permissions", permissions_text(listing.kind, version)));
            if listing.kind == Kind::Crate {
                rows.push(("Add with", cargo_add(&listing, version)));
            }
        }
        Err(error) => rows.push(("Newest", error.to_string())),
    }
    if let Some(entry) = installed {
        rows.push(("Installed", entry.version.clone()));
    }
    // Display-only: read after everything above is decided, and never
    // consulted by install, update or verify.
    let stats = stats::load(&market.location);
    if let Some(stats) = &stats {
        let versions: Vec<String> = listing
            .versions
            .iter()
            .map(|v| v.version.to_string())
            .collect();
        rows.extend(stats.rows(&listing.id, &versions));
    }
    let mut text = format!("{}\n\n", line(&listing.id));
    text.push_str(&grid(&rows, options.no_color));
    let versions: Vec<Vec<String>> = listing
        .versions
        .iter()
        .map(|v| {
            [
                v.version.to_string(),
                v.published.clone(),
                requires_text(v.requires),
                match host.check(listing.kind, v) {
                    Ok(()) => "yes".into(),
                    Err(reason) => reason.to_string(),
                },
                v.yanked.clone().unwrap_or_default(),
            ]
            .iter()
            .map(|cell| escape(cell))
            .collect()
        })
        .collect();
    text.push('\n');
    text.push_str(&table(
        &["Version", "Published", "Requires", "Loads here", "Yanked"],
        &versions,
        options.no_color,
    ));
    let mut result = listing_json(&listing, &host, installed);
    result["stats"] = stats.map_or(Value::Null, |s| s.package_json(&listing.id));
    Ok(Done::new(text, result))
}

/// `ID` or `ID@VERSION`.
fn requested_version(arg: &str) -> Outcome<(String, Request)> {
    match arg.split_once('@') {
        None => Ok((arg.to_string(), Request::Newest)),
        Some((id, version)) => {
            let version = rich_marketplace::semver::Version::parse(version).map_err(|e| {
                usage(format!(
                    "{:?}: not a version: {e}",
                    controls::shown(version)
                ))
            })?;
            Ok((id.to_string(), Request::Exact(version)))
        }
    }
}

fn entry_json(entry: &LockEntry) -> Value {
    json!({
        "id": entry.id,
        "kind": entry.kind.as_str(),
        "version": entry.version,
        "tier": entry.tier.as_str(),
        "tier_label": tier_display(entry.tier),
        "url": entry.url,
        "sha256": entry.sha256,
        "size": entry.size,
        "index_serial": entry.index_serial,
        "path": entry.path,
    })
}

/// Show what is about to be installed, ask, and install it. `None` when the
/// user declined.
fn install_version(
    options: &Options,
    dir: &Path,
    market: &Market,
    listing: &Listing,
    version: &ListedVersion,
    verb: &str,
) -> Outcome<Option<LockEntry>> {
    if listing.kind == Kind::WasmPlugin && !RuntimeKind::Wasm.supported() {
        return Err(usage(format!(
            "{} is a WASM plugin, and this build cannot load WASM plugins; install rs-rich-cli \
             with --features wasm-plugins",
            listing.id
        )));
    }
    if !options.json || !options.yes {
        eprint!("{}", grid(&provenance(listing, version), options.no_color));
    }
    let question = format!(
        "{verb} {} {} into {}?",
        listing.id,
        version.version,
        dir.display()
    );
    if !confirm(&question, options)? {
        return Ok(None);
    }
    let installer = Installer::new(dir, market.location.transport()?).with_checker(SandboxChecker);
    let entry = installer
        .install(&market.index, listing, version, SystemTime::now())
        .map_err(install_failure)?;
    Ok(Some(entry))
}

/// `install ID[@VERSION]...`.
fn install(options: &Options) -> Outcome<Done> {
    if options.positionals.is_empty() {
        return Err(usage("rich plugin install needs a package ID"));
    }
    let requests = options
        .positionals
        .iter()
        .map(|arg| requested_version(arg))
        .collect::<Outcome<Vec<_>>>()?;
    let dir = require_dir(options)?;
    let mut state = State::load(&dir)?;
    let market = open(options, &dir, &mut state)?;
    let host = Host::current();
    let mut text = String::new();
    let mut installed = Vec::new();
    for (id, request) in requests {
        let listing = market.listing(&id)?;
        if listing.kind == Kind::Agent {
            let version = resolve(&listing, &host, &request).map_err(resolve_failure)?;
            let (line, value) = record_agent(&dir, &listing, version)?;
            text.push_str(&line);
            installed.push(value);
            continue;
        }
        if !listing.kind.is_installable() {
            return Err(crate_refusal(&listing));
        }
        let version = resolve(&listing, &host, &request).map_err(resolve_failure)?;
        let current = lockfile(&dir)?;
        if let Some(entry) = current.get(&id)
            && entry.version == version.version.to_string()
            && entry.sha256 == version.artifact.sha256
            && entry.verify(&dir).is_ok()
        {
            text.push_str(&format!("{id} {} is already installed\n", entry.version));
            installed.push(entry_json(entry));
            continue;
        }
        match install_version(options, &dir, &market, &listing, version, "Install")? {
            Some(entry) => {
                state = State::load(&dir)?;
                state.note_yank(&id, &entry.version, None);
                state.save(&dir)?;
                text.push_str(&format!(
                    "Installed {} {} ({}, {})\n",
                    entry.id, entry.version, entry.kind, entry.tier
                ));
                installed.push(entry_json(&entry));
            }
            None => {
                let mut done = Done::new(text, json!({"installed": installed}));
                done.declined = true;
                return Ok(done);
            }
        }
    }
    Ok(Done::new(text, json!({"installed": installed})))
}

/// `install` of an agent: nothing is downloaded and nothing runs; the
/// verified launch command is recorded in `agents.json` for Cornacai, and
/// the install hint is printed for the user to follow.
fn record_agent(
    dir: &Path,
    listing: &Listing,
    version: &ListedVersion,
) -> Outcome<(String, Value)> {
    let mut agents = AgentList::load(dir).map_err(|e| agents_failure(dir, e))?;
    let Some(agent) = agents.add(listing, version).cloned() else {
        return Err(data(format!("{} lists no launch command", listing.id)));
    };
    agents.save(dir).map_err(|e| agents_failure(dir, e))?;
    let command = agent.argv().join(" ");
    let mut text = format!(
        "Recorded agent {} {} ({}): Cornacai offers it as `{}`\n",
        agent.id,
        agent.version,
        agent.tier.as_str(),
        line(&command)
    );
    text.push_str(&format!(
        "  Nothing was installed: install the program yourself with: {}\n",
        line(&agent.install)
    ));
    if !agent.env.is_empty() {
        text.push_str(&format!("  It reads: {}\n", line(&agent.env.join(", "))));
    }
    let value = json!({
        "id": agent.id,
        "version": agent.version,
        "kind": "agent",
        "tier": agent.tier.as_str(),
        "command": agent.argv(),
        "env": agent.env,
        "install": agent.install,
    });
    Ok((text, value))
}

fn agents_failure(dir: &Path, error: std::io::Error) -> Failure {
    data(format!("{}: {error}", AgentList::path(dir).display()))
}

/// `update [ID...]`: each installed package (or those named) to its newest
/// version for this host, asking first.
fn update(options: &Options) -> Outcome<Done> {
    let dir = require_dir(options)?;
    let lock = lockfile(&dir)?;
    let ids: Vec<String> = if options.positionals.is_empty() {
        lock.entries().map(|e| e.id.clone()).collect()
    } else {
        for id in &options.positionals {
            if lock.get(id).is_none() {
                return Err(usage(format!(
                    "{} is not installed; `rich plugin install {}` installs it",
                    controls::shown(id),
                    controls::shown(id)
                )));
            }
        }
        options.positionals.clone()
    };
    let mut state = State::load(&dir)?;
    let market = open(options, &dir, &mut state)?;
    let host = Host::current();
    let mut text = String::new();
    let (mut updated, mut current, mut skipped) = (Vec::new(), Vec::new(), Vec::new());
    for id in ids {
        let Some(entry) = lock.get(&id) else { continue };
        let listing = match market.listing(&id) {
            Ok(listing) => listing,
            Err(failure) if failure.class == ExitClass::Usage => {
                text.push_str(&format!(
                    "{id}: no longer listed; kept at {}\n",
                    entry.version
                ));
                skipped.push(json!({"id": id, "reason": "not listed"}));
                continue;
            }
            Err(failure) => return Err(failure),
        };
        let listed = listing
            .versions
            .iter()
            .find(|v| v.version.to_string() == entry.version);
        let yanked = listed.and_then(|v| v.yanked.clone());
        state.note_yank(&id, &entry.version, listed);
        state.save(&dir)?;
        let candidate = match resolve(&listing, &host, &Request::Newest) {
            Ok(candidate) => candidate,
            Err(error) => {
                text.push_str(&format!("{id}: {error}; kept at {}\n", entry.version));
                skipped.push(json!({"id": id, "reason": error.to_string()}));
                continue;
            }
        };
        let installed = rich_marketplace::semver::Version::parse(&entry.version).ok();
        let newer = installed.as_ref().is_none_or(|v| candidate.version > *v);
        let replace_yanked = yanked.is_some() && candidate.version.to_string() != entry.version;
        if !newer && !replace_yanked {
            text.push_str(&format!("{id} {} is up to date\n", entry.version));
            current.push(json!({"id": id, "version": entry.version}));
            continue;
        }
        match install_version(options, &dir, &market, &listing, candidate, "Update to")? {
            Some(new) => {
                state = State::load(&dir)?;
                state.note_yank(&id, &new.version, None);
                state.save(&dir)?;
                text.push_str(&format!(
                    "Updated {id} {} -> {}\n",
                    entry.version, new.version
                ));
                updated.push(json!({"id": id, "from": entry.version, "to": new.version}));
            }
            None => {
                let mut done = Done::new(
                    text,
                    json!({"updated": updated, "current": current, "skipped": skipped}),
                );
                done.declined = true;
                return Ok(done);
            }
        }
    }
    if text.is_empty() {
        text.push_str("Nothing is installed.\n");
    }
    Ok(Done::new(
        text,
        json!({"updated": updated, "current": current, "skipped": skipped}),
    ))
}

/// `remove ID...`.
fn remove(options: &Options) -> Outcome<Done> {
    if options.positionals.is_empty() {
        return Err(usage("rich plugin remove needs a package ID"));
    }
    let dir = require_dir(options)?;
    let installer = Installer::new(&dir, rich_marketplace::MemoryTransport::new());
    let mut state = State::load(&dir)?;
    let mut text = String::new();
    let mut removed = Vec::new();
    let mut agents = AgentList::load(&dir).map_err(|e| agents_failure(&dir, e))?;
    for id in &options.positionals {
        if agents.remove(id) {
            agents.save(&dir).map_err(|e| agents_failure(&dir, e))?;
            text.push_str(&format!("Forgot agent {}\n", line(id)));
            removed.push(json!({"id": id, "kind": "agent"}));
            continue;
        }
        let entry = installer.remove(id).map_err(lockfile_failure)?;
        state.set_enabled(id, true);
        state.yanked.remove(id);
        text.push_str(&format!("Removed {} {}\n", entry.id, entry.version));
        removed.push(entry_json(&entry));
    }
    state.save(&dir)?;
    Ok(Done::new(text, json!({"removed": removed})))
}

/// The state of one installed file, with no network.
fn file_status(dir: &Path, entry: &LockEntry) -> (&'static str, Option<String>) {
    match entry.verify(dir) {
        Ok(_) => ("ok", None),
        Err(LockfileError::Missing { .. }) => ("missing", Some("the file is missing".into())),
        Err(LockfileError::Mismatch { .. }) => (
            "changed",
            Some("the file changed on disk; it is not loaded".into()),
        ),
        Err(other) => ("error", Some(other.to_string())),
    }
}

/// `list`: what is installed, with no network.
fn list(options: &Options) -> Outcome<Done> {
    let dir = require_dir(options)?;
    let lock = lockfile(&dir)?;
    let state = State::load(&dir)?;
    let mut rows = Vec::new();
    let mut packages = Vec::new();
    for entry in lock.entries() {
        let enabled = state.is_enabled(&entry.id);
        let (status, problem) = file_status(&dir, entry);
        let yanked = state.yank_reason(entry);
        let mut note = problem.clone().unwrap_or_default();
        if let Some(reason) = yanked {
            if !note.is_empty() {
                note.push_str("; ");
            }
            note.push_str(&format!("yanked: {reason}"));
        }
        rows.push(vec![
            escape(&entry.id),
            escape(&entry.version),
            escape(entry.kind.as_str()),
            tier_marker(entry.tier),
            if enabled { "yes" } else { "no" }.into(),
            status.into(),
            escape(&note),
        ]);
        let mut value = entry_json(entry);
        value["enabled"] = json!(enabled);
        value["status"] = json!(status);
        value["yank_reason"] = json!(yanked);
        packages.push(value);
    }
    // Agents are recorded, not installed: no file, never disabled.
    let agents = AgentList::load(&dir).unwrap_or_default();
    for agent in agents.agents() {
        rows.push(vec![
            escape(&agent.id),
            escape(&agent.version),
            "agent".into(),
            tier_marker(agent.tier),
            "yes".into(),
            "-".into(),
            escape(&format!("runs `{}`", agent.argv().join(" "))),
        ]);
        packages.push(json!({
            "id": agent.id,
            "version": agent.version,
            "kind": "agent",
            "tier": agent.tier.as_str(),
            "command": agent.argv(),
        }));
    }
    let text = if rows.is_empty() {
        format!("Nothing is installed in {}.\n", dir.display())
    } else {
        table(
            &["Id", "Version", "Kind", "Tier", "Enabled", "File", "Notes"],
            &rows,
            options.no_color,
        )
    };
    Ok(Done::new(
        text,
        json!({"plugin_dir": dir.display().to_string(), "packages": packages}),
    ))
}

/// `enable ID...` and `disable ID...`.
fn set_enabled(options: &Options, enabled: bool) -> Outcome<Done> {
    let verb = if enabled { "enable" } else { "disable" };
    if options.positionals.is_empty() {
        return Err(usage(format!("rich plugin {verb} needs a package ID")));
    }
    let dir = require_dir(options)?;
    let lock = lockfile(&dir)?;
    let mut state = State::load(&dir)?;
    let mut text = String::new();
    let mut changed = Vec::new();
    for id in &options.positionals {
        if lock.get(id).is_none() {
            return Err(usage(format!("{} is not installed", controls::shown(id))));
        }
        state.set_enabled(id, enabled);
        text.push_str(&format!(
            "{} {id}\n",
            if enabled { "Enabled" } else { "Disabled" }
        ));
        changed.push(json!({"id": id, "enabled": enabled}));
    }
    state.save(&dir)?;
    Ok(Done::new(text, json!({"packages": changed})))
}

/// `verify`: every installed file against the lockfile, then every
/// installed version against the current index (still listed, the same
/// hash, and whether it is yanked since).
fn verify(options: &Options) -> Outcome<Done> {
    let dir = require_dir(options)?;
    let lock = lockfile(&dir)?;
    let mut problems = Vec::new();
    let mut yanked = Vec::new();
    let mut checked = 0;
    for entry in lock.entries() {
        checked += 1;
        if let (_, Some(problem)) = file_status(&dir, entry) {
            problems.push((entry.id.clone(), problem));
        }
    }
    let mut serial = None;
    let mut index_problem = None;
    if lock.entries().next().is_some() {
        let mut state = State::load(&dir)?;
        match open(options, &dir, &mut state) {
            Ok(market) => {
                serial = Some(market.index.serial());
                for entry in lock.entries() {
                    let listing = match market.listing(&entry.id) {
                        Ok(listing) => listing,
                        Err(failure) => {
                            problems.push((entry.id.clone(), failure.message));
                            continue;
                        }
                    };
                    let listed = listing
                        .versions
                        .iter()
                        .find(|v| v.version.to_string() == entry.version);
                    state.note_yank(&entry.id, &entry.version, listed);
                    match listed {
                        None => problems.push((
                            entry.id.clone(),
                            format!("version {} is no longer listed", entry.version),
                        )),
                        Some(v) if v.artifact.sha256 != entry.sha256 => problems.push((
                            entry.id.clone(),
                            format!(
                                "the listing's SHA-256 for {} is {}, the lockfile records {}",
                                entry.version, v.artifact.sha256, entry.sha256
                            ),
                        )),
                        Some(v) => {
                            if let Some(reason) = &v.yanked {
                                yanked.push((
                                    entry.id.clone(),
                                    entry.version.clone(),
                                    reason.clone(),
                                ));
                            }
                        }
                    }
                }
                state.save(&dir)?;
            }
            Err(failure) => index_problem = Some(failure),
        }
    }
    let mut text = String::new();
    if checked == 0 {
        text.push_str("Nothing is installed.\n");
    } else {
        text.push_str(&format!(
            "Checked {checked} installed package{}{}.\n",
            if checked == 1 { "" } else { "s" },
            serial.map_or_else(String::new, |s| format!(" against index serial {s}"))
        ));
    }
    for (id, version, reason) in &yanked {
        text.push_str(&format!(
            "{id} {version} is yanked: {}; `rich plugin update {id}` moves to the newest version\n",
            line(reason)
        ));
    }
    for (id, problem) in &problems {
        text.push_str(&format!("{id}: {}\n", line(problem)));
    }
    if let Some(failure) = &index_problem {
        text.push_str(&format!(
            "The marketplace index was not checked: {}\n",
            line(&failure.message)
        ));
    }
    let result = json!({
        "checked": checked,
        "index_serial": serial,
        "problems": problems.iter().map(|(id, p)| json!({"id": id, "problem": p})).collect::<Vec<_>>(),
        "yanked": yanked.iter().map(|(id, v, r)| json!({"id": id, "version": v, "reason": r})).collect::<Vec<_>>(),
        "index_error": index_problem.as_ref().map(|f| f.message.clone()),
    });
    let mut done = Done::new(text, result);
    if !problems.is_empty() {
        done.problem = Some(data(format!(
            "{} installed package{} failed verification",
            problems.len(),
            if problems.len() == 1 { "" } else { "s" }
        )));
    } else if let Some(failure) = index_problem {
        done.problem = Some(failure);
    }
    Ok(done)
}

// ---------------------------------------------------------------------------
// Shared with `browse`.
// ---------------------------------------------------------------------------

/// The commands `browse` runs on one package, with `id` as the only
/// positional.
#[cfg(feature = "interact")]
pub(crate) fn run_on(options: &Options, command: &str, id: &str) -> Outcome<Done> {
    let options = Options {
        command: command.to_string(),
        positionals: vec![id.to_string()],
        json: false,
        no_color: options.no_color,
        yes: options.yes,
        marketplace: options.marketplace.clone(),
        plugin_dir: options.plugin_dir.clone(),
        keys: options.keys.clone(),
        sort: None,
        kind: None,
        tier: None,
        recommended: false,
        publish: BTreeMap::new(),
    };
    match command {
        "install" => install(&options),
        "update" => update(&options),
        "remove" => remove(&options),
        "enable" => set_enabled(&options, true),
        "disable" => set_enabled(&options, false),
        _ => info(&options),
    }
}

#[cfg(feature = "interact")]
pub(crate) fn open_for_browse(options: &Options) -> Outcome<(PathBuf, Market, Lockfile, State)> {
    let dir = require_dir(options)?;
    let mut state = State::load(&dir)?;
    let market = open(options, &dir, &mut state)?;
    let lock = lockfile(&dir)?;
    Ok((dir, market, lock, state))
}

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

    fn args(words: &[&str]) -> Vec<String> {
        words.iter().map(|w| w.to_string()).collect()
    }

    #[test]
    fn locations() {
        assert_eq!(
            Location::parse("https://example.test/m").unwrap(),
            Location::Remote("https://example.test/m/".into())
        );
        assert_eq!(
            Location::parse("file:///tmp/a%20b").unwrap(),
            Location::Local(PathBuf::from("/tmp/a b"))
        );
        assert!(Location::parse("http://example.test/").is_err());
        assert!(matches!(
            Location::parse("some/dir").unwrap(),
            Location::Local(_)
        ));
    }

    #[test]
    fn the_mirror_stays_inside_its_directory() {
        let mirror = ArtifactTransport::Mirror(PathBuf::from("/nonexistent-mirror"));
        for url in [
            "https://example.test/../etc/passwd",
            "https://example.test//x",
            "https://example.test/a\\b",
        ] {
            assert!(
                matches!(mirror.get(url, 10), Err(FetchError::NotFound { .. })),
                "{url}"
            );
        }
        assert!(matches!(
            mirror.get("http://example.test/x", 10),
            Err(FetchError::NotHttps { .. })
        ));
    }

    #[test]
    fn options_parse() {
        let options = parse(&args(&[
            "plugin",
            "install",
            "shout@0.2.0",
            "--yes",
            "--marketplace",
            "m",
        ]))
        .unwrap();
        assert_eq!(options.command, "install");
        assert_eq!(options.positionals, ["shout@0.2.0"]);
        assert!(options.yes);
        assert!(parse(&args(&["plugin", "frob"])).is_err());
        assert!(parse(&args(&["plugin"])).is_err());
        assert!(parse(&args(&["plugin", "list", "--url", "x"])).is_err());
        let (id, request) = requested_version("shout@0.2.0").unwrap();
        assert_eq!(id, "shout");
        assert!(matches!(request, Request::Exact(_)));
        assert!(requested_version("shout@x").is_err());
    }

    #[test]
    fn tier_markers() {
        // Colour only marks what the plain words already say.
        assert_eq!(tier_marker(Tier::Official), "[bold green]✓ official[/]");
        assert_eq!(tier_marker(Tier::Reviewed), "approved");
        assert_eq!(tier_marker(Tier::Community), "[yellow]community[/]");
        assert_eq!(
            row_markup("Tier", "community: [b]x[/b]"),
            "[yellow]community[/]: \\[b]x\\[/b]"
        );
        // Only the Tier row is marked; any other value is escaped as is.
        assert_eq!(row_markup("Name", "✓ official"), "✓ official");
        assert_eq!(
            row_markup("Recommended", "★ recommended since x: [i]"),
            "[bold magenta]★ recommended[/] since x: \\[i]"
        );
        assert_eq!(repository_owner("https://github.com/ada/x.git"), "ada");
        assert_eq!(repository_owner("https://example.test"), "example.test");
        assert_eq!(
            repository_source("https://github.com/ada/x.git/"),
            "github.com/ada/x"
        );
        let options = parse(&args(&["plugin", "search", "--tier", "reviewed"])).unwrap();
        assert_eq!(options.tier, Some(Tier::Reviewed));
        assert!(options.publish.is_empty());
        assert!(parse(&args(&["plugin", "list", "--tier", "official"])).is_err());
    }

    #[test]
    fn state_round_trips() {
        let mut state = State::default();
        state.set_enabled("shout", false);
        state.markets.insert(
            "file:///m".into(),
            MarketState {
                accepted: Some(AcceptedIndex {
                    serial: 3,
                    sha256: "0".repeat(64),
                }),
            },
        );
        state
            .yanked
            .insert("shout".into(), ("0.2.1".into(), "bad".into()));
        state.chains.insert(
            "057D5BF5EBC4B734".into(),
            vec![CachedRotation {
                keys_json: "{\"generation\": 2}".into(),
                main_signature: None,
                backup_signature: "sig".into(),
            }],
        );
        let dir = tempfile::tempdir().unwrap();
        state.save(dir.path()).unwrap();
        assert_eq!(State::load(dir.path()).unwrap(), state);
        assert!(!state.is_enabled("shout"));
    }
}