vesper-player-cli 0.5.3

The vesper command-line tool for authoring, validating, and installing plugins.
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
#![deny(unsafe_code)]

mod android;
mod android_publish;
mod android_subtitle;
mod boundary;
mod cli_error;
mod contract;
mod desktop;
mod external_process;
mod ffi;
mod ffmpeg;
mod ffmpeg_android;
mod ffmpeg_apple;
mod ffmpeg_source;
mod flutter;
mod gradle;
mod ios;
mod ios_core_release;
mod ios_ffi;
mod ios_kit;
mod ios_native_frame;
mod ios_optional_device;
mod ios_optional_release;
mod ios_playback_device;
mod ios_plugin;
mod ios_plugin_release;
mod ios_release;
mod ios_spm_publish;
mod ios_subtitle;
mod media;
mod mobile;
mod plugin_build;
mod plugin_inspection;
mod plugin_scaffold;
mod plugin_scaffold_assets;
mod release;
mod release_notes;
mod source_archive;
mod subtitle;
mod worker_protocol;
mod worker_supervisor;

use std::ffi::OsString;
use std::fs::{self, File};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::Duration;

use clap::{Args, Parser, Subcommand, ValueEnum};
use cli_error::{CliError, CliResult};
use player_cli::{
    EmbeddedRegistryFragment, EmbeddedRegistryTarget, PluginArtifactTransport, PluginDescriptor,
    PluginProjectManifest, PluginSigningKey, PluginTrustStore, build_signed_plugin_package,
    install_verified_plugin_package, list_installed_plugins, uninstall_plugin,
    verify_signed_plugin_package,
};
use player_plugin_wasm_host::MAX_WASM_PLUGIN_COMPONENT_BYTES;

use plugin_build::{
    PluginArtifactSelector, PluginBuildError, PluginBuildProfile, PluginBuildRequest,
    build_plugin_artifact, select_plugin_artifact,
};
use plugin_inspection::{
    PluginInspectionOperation, PluginInspectionOutcome, PluginInspectionReport, inspect_manifest,
    inspect_project_catalog, inspect_wasm_plugin,
};
use plugin_scaffold::{PluginScaffoldCapability, PluginScaffoldRequest, create_plugin_scaffold};
use worker_protocol::{
    PLUGIN_WORKER_START_GATE, PluginWorkerRequest, PluginWorkerResponse, read_worker_request,
    write_worker_response,
};
use worker_supervisor::supervise_native_worker;

type PathIoHook<'a> = &'a mut dyn FnMut(&Path) -> io::Result<()>;
#[cfg(target_os = "macos")]
type PathHook<'a> = &'a mut dyn FnMut(&Path);
#[cfg(target_os = "macos")]
type TempDirIoHook<'a> = &'a mut dyn FnMut(tempfile::TempDir) -> io::Result<()>;

const MAX_PLUGIN_MANIFEST_BYTES: usize = 1024 * 1024;
const MAX_PLUGIN_KEY_FILE_BYTES: usize = 64 * 1024;
const MAX_PLUGIN_TRUST_STORE_BYTES: usize = 1024 * 1024;

#[cfg(test)]
fn source_checkout_root() -> Option<PathBuf> {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR")).canonicalize().ok()?;
    let root = manifest_dir.join("../../..");
    let workspace_member = root.join("crates/tools/player-cli").canonicalize().ok()?;
    (manifest_dir == workspace_member).then_some(root)
}

#[derive(Debug, Parser)]
#[command(
    name = "vesper",
    version,
    about = "Vesper Player SDK command-line tools"
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Debug, Subcommand)]
enum Command {
    Android(AndroidArgs),
    Ios(IosArgs),
    Ffmpeg(FfmpegArgs),
    Plugin(PluginArgs),
    Contract(ContractArgs),
    Ffi(FfiArgs),
    Desktop(DesktopArgs),
    Media(MediaArgs),
    Mobile(MobileArgs),
    Flutter(FlutterArgs),
    Release(ReleaseArgs),
    #[command(name = "__plugin-worker", hide = true)]
    PluginWorker(PluginWorkerArgs),
}

#[derive(Debug, Args)]
struct MediaArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: MediaCommand,
}

#[derive(Debug, Subcommand)]
enum MediaCommand {
    /// Generates the bounded local media fixtures used by SourceNormalizer smoke tests.
    #[command(name = "generate-source-normalizer-fixtures")]
    GenerateSourceNormalizerFixtures,
}

#[derive(Debug, Args)]
struct IosArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: IosCommand,
}

#[derive(Debug, Subcommand)]
enum IosCommand {
    /// Builds the Rust FFI archives and XCFramework consumed by the iOS host kit.
    Ffi(IosFfiArgs),
    /// Builds the FFmpeg-backed post-download remux plugin libraries.
    #[command(name = "remux-plugin")]
    RemuxPlugin(IosPluginBuildArgs),
    /// Builds the FFmpeg-backed source normalizer plugin libraries.
    #[command(name = "source-normalizer-plugin")]
    SourceNormalizerPlugin(IosPluginBuildArgs),
    /// Builds the diagnostic frame processor plugin libraries.
    #[command(name = "frame-processor-plugin")]
    FrameProcessorPlugin(IosPluginBuildArgs),
    /// Builds the performance diagnostics BenchmarkSink plugin libraries.
    #[command(name = "performance-diagnostics-plugin")]
    PerformanceDiagnosticsPlugin(IosPluginBuildArgs),
    /// Builds the internal VideoToolbox decoder plugin libraries.
    #[command(name = "decoder-videotoolbox-plugin", hide = true)]
    DecoderVideoToolboxPlugin(IosPluginBuildArgs),
    /// Builds and stages the FFmpeg-backed remux plugin XCFramework release.
    #[command(name = "stage-remux-plugin-release")]
    StageRemuxPluginRelease(IosPluginReleaseArgs),
    /// Builds and stages the FFmpeg-backed source normalizer XCFramework release.
    #[command(name = "stage-source-normalizer-plugin-release")]
    StageSourceNormalizerPluginRelease(IosPluginReleaseArgs),
    /// Builds and stages the diagnostic frame processor XCFramework release.
    #[command(name = "stage-frame-processor-plugin-release")]
    StageFrameProcessorPluginRelease(IosPluginReleaseArgs),
    /// Builds and stages the performance diagnostics XCFramework release.
    #[command(name = "stage-performance-diagnostics-plugin-release")]
    StagePerformanceDiagnosticsPluginRelease(IosPluginReleaseArgs),
    /// Builds and stages the internal VideoToolbox decoder XCFramework release.
    #[command(name = "stage-decoder-videotoolbox-plugin-release", hide = true)]
    StageDecoderVideoToolboxPluginRelease(IosPluginReleaseArgs),
    /// Builds the complete VesperPlayerKit device and Simulator XCFramework output.
    KitXcframework,
    /// Rebuilds manifest and C fragments from the checked-in bridge C/H sources.
    #[command(name = "bootstrap-bridge-shim")]
    BootstrapBridgeShim,
    /// Regenerates the checked-in Swift-to-Rust bridge shim as one transaction.
    SyncBridgeShim(IosSyncBridgeShimArgs),
    /// Verifies generated sources, C syntax, and available Rust archive exports.
    VerifyBridgeShim(IosVerifyBridgeShimArgs),
    /// Verifies the optional-plugin layout embedded in an App Store app bundle.
    VerifyAppStoreLayout(IosVerifyAppStoreLayoutArgs),
    /// Runs the experimental iOS native-frame Swift smoke verification.
    VerifyNativeFrame(IosVerifyNativeFrameArgs),
    /// Verifies optional plugin XCFramework and FFmpeg compliance release assets.
    VerifyOptionalPluginsRelease(IosVerifyOptionalPluginsReleaseArgs),
    /// Runs the Release optional-plugin acceptance suite on a physical iOS device.
    VerifyOptionalPluginsDevice(IosVerifyOptionalPluginsDeviceArgs),
    /// Runs the short Release playback lifecycle suite on a physical iOS device.
    VerifyPlaybackLifecycleDevice(IosVerifyPlaybackLifecycleDeviceArgs),
    /// Verifies core or complete iOS release archives.
    VerifyRelease(IosVerifyReleaseArgs),
    /// Builds and stages VesperPlayerKit release archives.
    StageRelease(IosStageReleaseArgs),
    /// Stages the iOS FFmpeg runtime release artifacts.
    #[command(name = "ffmpeg-runtime-release")]
    FfmpegRuntimeRelease(IosWorkerArgs),
    /// Stages the complete optional-plugin release bundle.
    #[command(name = "stage-optional-plugins-release")]
    StageOptionalPluginsRelease(IosWorkerArgs),
    /// Publishes the core XCFramework and SwiftUI sources through a remote Swift package.
    #[command(name = "publish-spm-index")]
    PublishSpmIndex(IosPublishSpmIndexArgs),
    /// Verifies iOS subtitle behavior.
    #[command(name = "verify-subtitles")]
    VerifySubtitles(IosVerifySubtitlesArgs),
}

#[derive(Debug, Args)]
struct IosFfiArgs {
    /// Cargo build profile for the Rust FFI archives.
    #[arg(value_enum, default_value = "release")]
    profile: IosFfiProfileArg,
    /// Builds one platform slice instead of the complete XCFramework.
    #[arg(long, value_enum)]
    platform: Option<IosFfiPlatformArg>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum IosFfiPlatformArg {
    Device,
    Simulator,
}

impl From<IosFfiPlatformArg> for ios_ffi::IosFfiPlatform {
    fn from(value: IosFfiPlatformArg) -> Self {
        match value {
            IosFfiPlatformArg::Device => Self::Device,
            IosFfiPlatformArg::Simulator => Self::Simulator,
        }
    }
}

#[derive(Debug, Args)]
struct IosPluginBuildArgs {
    /// Output directory for raw device and Simulator plugin libraries.
    output_directory: PathBuf,
    /// Legacy-compatible Cargo profile, FFmpeg options, and slice tokens.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    arguments: Vec<OsString>,
}

#[derive(Debug, Args)]
struct IosPluginReleaseArgs {
    /// Legacy-compatible output directory, profile options, dry-run flag, and slice tokens.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    arguments: Vec<OsString>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum IosFfiProfileArg {
    Debug,
    Release,
}

impl From<IosFfiProfileArg> for ios_ffi::IosFfiProfile {
    fn from(value: IosFfiProfileArg) -> Self {
        match value {
            IosFfiProfileArg::Debug => Self::Debug,
            IosFfiProfileArg::Release => Self::Release,
        }
    }
}

#[derive(Debug, Args)]
struct IosSyncBridgeShimArgs {
    /// Allows an intentional removal of public bridge functions from generated C/H.
    #[arg(long)]
    allow_public_api_removal: bool,
}

#[derive(Debug, Args)]
struct IosVerifyBridgeShimArgs {
    /// Rust FFI archive to verify instead of discovering checked-in iOS artifacts.
    #[arg(long)]
    archive: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct IosVerifyAppStoreLayoutArgs {
    /// Built iOS application bundle to verify.
    app_path: PathBuf,
    /// Verifies every optional framework and the containing application signature.
    #[arg(long)]
    verify_signatures: bool,
}

#[derive(Debug, Args)]
struct IosVerifyNativeFrameArgs {
    /// Legacy-compatible profile and smoke-mode tokens.
    #[arg(value_enum)]
    tokens: Vec<IosVerifyNativeFrameTokenArg>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum IosVerifyNativeFrameTokenArg {
    Debug,
    Release,
    SwiftSmoke,
}

impl IosVerifyNativeFrameTokenArg {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Debug => "debug",
            Self::Release => "release",
            Self::SwiftSmoke => "swift-smoke",
        }
    }
}

#[derive(Debug, Args)]
struct IosVerifyOptionalPluginsReleaseArgs {
    /// Release directory. Defaults to dist/release/ios under the repository root.
    release_directory: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct IosVerifyOptionalPluginsDeviceArgs {
    /// Release directory whose verified optional-plugin archives are tested.
    release_directory: PathBuf,
    /// Physical iOS device UDID used by xcodebuild.
    #[arg(long)]
    device: String,
    /// Apple Development Team identifier used for automatic code signing.
    #[arg(long)]
    development_team: String,
    /// New directory that receives DerivedData and the XCResult bundle.
    #[arg(long)]
    output_directory: PathBuf,
    /// Allows Xcode to update provisioning profiles for the connected device.
    #[arg(long)]
    allow_provisioning_updates: bool,
}

#[derive(Debug, Args)]
struct IosVerifyPlaybackLifecycleDeviceArgs {
    /// Physical iOS device UDID used by xcodebuild.
    #[arg(long)]
    device: String,
    /// Apple Development Team identifier used for automatic code signing.
    #[arg(long)]
    development_team: String,
    /// New directory that receives DerivedData and the XCResult bundle.
    #[arg(long)]
    output_directory: PathBuf,
    /// Allows Xcode to update provisioning profiles for the connected device.
    #[arg(long)]
    allow_provisioning_updates: bool,
}

#[derive(Debug, Args)]
struct IosVerifyReleaseArgs {
    /// Release directory. Defaults to dist/release/ios under the repository root.
    release_directory: Option<PathBuf>,
    /// Release artifact set to verify.
    #[arg(long, value_enum, default_value = "core")]
    scope: IosReleaseScopeArg,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum IosReleaseScopeArg {
    Core,
    Complete,
}

#[derive(Debug, Args)]
struct IosStageReleaseArgs {
    /// Release output directory. Defaults to dist/release/ios under the repository root.
    output_directory: Option<PathBuf>,
    /// Includes optional plugin XCFrameworks and FFmpeg compliance assets.
    #[arg(
        long,
        num_args = 0..=1,
        default_missing_value = "true",
        value_name = "BOOL"
    )]
    include_optional_plugins: Option<bool>,
    /// Local Swift package Artifacts directory for optional XCFrameworks.
    #[arg(long)]
    package_artifacts_directory: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct IosPublishSpmIndexArgs {
    /// Release tag in vMAJOR.MINOR.PATCH[-PRERELEASE] form.
    tag: String,
    /// Released VesperPlayerKit XCFramework archive.
    archive: PathBuf,
    /// GitHub repository that owns the release asset, for example umbrella22/Vesper.
    #[arg(long)]
    source_repository: Option<String>,
    /// GitHub repository used as the Swift package index.
    #[arg(long)]
    repository: Option<String>,
    /// Generates and validates the package in a local directory without network writes.
    #[arg(long)]
    dry_run: bool,
    /// Output directory used by --dry-run.
    #[arg(long, requires = "dry_run")]
    output_directory: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct IosWorkerArgs {
    /// Arguments forwarded to the platform worker.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    arguments: Vec<OsString>,
}

#[derive(Debug, Args)]
struct IosVerifySubtitlesArgs {
    /// Verification scope. Device and complete scopes require --device.
    #[arg(long, value_enum, default_value = "regression")]
    scope: IosSubtitleScopeArg,
    /// Physical iOS device identifier used by device and complete scopes.
    #[arg(long)]
    device: Option<String>,
    /// iOS Simulator identifier. Regression scopes auto-select when omitted.
    #[arg(long)]
    simulator: Option<String>,
    /// New evidence directory. Defaults under devnotes/evidence/subtitle/ios.
    #[arg(long)]
    evidence_dir: Option<PathBuf>,
    /// Apple development Team ID. Overrides VESPER_IOS_DEVELOPMENT_TEAM.
    #[arg(long)]
    development_team: Option<String>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum IosSubtitleScopeArg {
    Regression,
    Device,
    Complete,
}

impl From<IosSubtitleScopeArg> for subtitle::SubtitleScope {
    fn from(value: IosSubtitleScopeArg) -> Self {
        match value {
            IosSubtitleScopeArg::Regression => Self::Regression,
            IosSubtitleScopeArg::Device => Self::Device,
            IosSubtitleScopeArg::Complete => Self::Complete,
        }
    }
}

#[derive(Debug, Args)]
struct AndroidArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: AndroidCommand,
}

#[derive(Debug, Subcommand)]
enum AndroidCommand {
    /// Builds Rust JNI libraries for the Android host kit.
    Jni(AndroidJniArgs),
    /// Builds Android host-kit AAR modules with cached Gradle.
    Aar(AndroidAarArgs),
    /// Builds the Android FFmpeg-backed post-download remux plugin.
    #[command(name = "remux-plugin")]
    RemuxPlugin(AndroidWorkerArgs),
    /// Builds the Android FFmpeg-backed SourceNormalizer plugin.
    #[command(name = "source-normalizer-plugin")]
    SourceNormalizerPlugin(AndroidWorkerArgs),
    /// Builds the Android MediaCodec decoder plugin.
    #[command(name = "decoder-mediacodec-plugin")]
    DecoderMediacodecPlugin(AndroidWorkerArgs),
    /// Builds the Android diagnostic FrameProcessor plugin.
    #[command(name = "frame-processor-plugin")]
    FrameProcessorPlugin(AndroidWorkerArgs),
    /// Builds the Android performance diagnostics BenchmarkSink plugin.
    #[command(name = "performance-diagnostics-plugin")]
    PerformanceDiagnosticsPlugin(AndroidWorkerArgs),
    /// Stages Android host-kit release artifacts.
    #[command(name = "stage-release")]
    StageRelease(AndroidStageReleaseArgs),
    /// Stages Android sample APKs.
    #[command(name = "sample-apks")]
    SampleApks(AndroidSampleApksArgs),
    /// Publishes Android host-kit coordinates to Maven Central.
    #[command(name = "publish-maven-central")]
    PublishMavenCentral(AndroidPublishMavenCentralArgs),
    /// Provisions the Android instrumentation JNI fixture through Rust.
    #[command(name = "provision-test-jni", hide = true)]
    ProvisionTestJni(AndroidProvisionTestJniArgs),
    /// Builds the optional external-playback relay JNI library through Rust.
    #[command(name = "external-playback-jni", hide = true)]
    ExternalPlaybackJni(AndroidExternalPlaybackJniArgs),
    /// Verifies Android subtitle behavior.
    #[command(name = "verify-subtitles")]
    VerifySubtitles(AndroidVerifySubtitlesArgs),
    /// Internal Rust worker used by the temporary Android shell compatibility shims.
    #[command(name = "__runtime-free-plugin", hide = true)]
    RuntimeFreePlugin(AndroidRuntimeFreePluginArgs),
    /// Internal Rust worker used by the temporary Android FFmpeg plugin shims.
    #[command(name = "__ffmpeg-plugin", hide = true)]
    FfmpegPlugin(AndroidFfmpegPluginArgs),
}

#[derive(Debug, Args)]
struct AndroidJniArgs {
    /// Build profile. The legacy contract treats values other than `release` as debug.
    profile: Option<String>,
    /// Android ABIs. Defaults to RUST_ANDROID_ABIS, then arm64-v8a.
    abis: Vec<String>,
}

#[derive(Debug, Args)]
struct AndroidAarArgs {
    /// AAR-producing Gradle module task. Defaults to assembleRelease.
    #[arg(value_parser = parse_android_aar_task)]
    module_task: Option<String>,
    /// Includes optional Android plugin modules. The environment is used when omitted.
    #[arg(
        long,
        num_args = 0..=1,
        default_missing_value = "true",
        value_name = "BOOL"
    )]
    include_optional_plugins: Option<bool>,
}

#[derive(Debug, Args)]
struct AndroidStageReleaseArgs {
    /// Output directory. Defaults to dist/release/android.
    output_directory: Option<PathBuf>,
    /// Android ABIs. Defaults to RUST_ANDROID_ABIS, then arm64-v8a.
    abis: Vec<String>,
    /// Includes optional Android plugin AARs. The environment is used when omitted.
    #[arg(
        long,
        num_args = 0..=1,
        default_missing_value = "true",
        value_name = "BOOL"
    )]
    include_optional_plugins: Option<bool>,
}

#[derive(Debug, Args)]
struct AndroidSampleApksArgs {
    /// Output directory. Defaults to dist/release/android-samples.
    output_directory: Option<PathBuf>,
    /// Android ABIs. Defaults to RUST_ANDROID_ABIS, then arm64-v8a.
    abis: Vec<String>,
}

#[derive(Debug, Args)]
struct AndroidPublishMavenCentralArgs {
    /// Release tag in vMAJOR.MINOR.PATCH[-PRERELEASE] form.
    tag: String,
    /// Approved Central Portal namespace that authorizes io.github.umbrella22.vesper.
    #[arg(long, default_value = "io.github.umbrella22")]
    namespace: String,
    /// Stages and verifies the signed repository without uploading it.
    #[arg(long)]
    dry_run: bool,
}

#[derive(Debug, Args)]
struct AndroidProvisionTestJniArgs {
    /// Android instrumentation JNI output directory.
    output_directory: PathBuf,
    /// Native build profile. Defaults to debug.
    #[arg(long, default_value = "debug")]
    profile: String,
    /// FFmpeg profile used by the SourceNormalizer fixture.
    #[arg(long, default_value = "default")]
    ffmpeg_profile: String,
}

#[derive(Debug, Args)]
struct AndroidExternalPlaybackJniArgs {
    /// Relay JNI output directory.
    output_directory: PathBuf,
    /// Relay metadata asset root.
    #[arg(long)]
    assets_directory: PathBuf,
    /// Native build profile. Defaults to debug.
    #[arg(long, default_value = "debug")]
    profile: String,
    /// FFmpeg profile used by the relay.
    #[arg(long, default_value = "default")]
    ffmpeg_profile: String,
    /// Reuse existing shared FFmpeg runtime artifacts instead of rebuilding them.
    #[arg(long)]
    skip_ffmpeg_runtime: bool,
}

#[derive(Debug, Args)]
struct AndroidVerifySubtitlesArgs {
    /// Verification scope. Device and complete scopes require --device.
    #[arg(long, value_enum, default_value = "regression")]
    scope: AndroidSubtitleScopeArg,
    /// Physical Android device serial used by device and complete scopes.
    #[arg(long)]
    device: Option<String>,
    /// New evidence directory. Defaults under devnotes/evidence/subtitle/android.
    #[arg(long)]
    evidence_dir: Option<PathBuf>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum AndroidSubtitleScopeArg {
    Regression,
    Device,
    Complete,
}

impl From<AndroidSubtitleScopeArg> for subtitle::SubtitleScope {
    fn from(value: AndroidSubtitleScopeArg) -> Self {
        match value {
            AndroidSubtitleScopeArg::Regression => Self::Regression,
            AndroidSubtitleScopeArg::Device => Self::Device,
            AndroidSubtitleScopeArg::Complete => Self::Complete,
        }
    }
}

#[derive(Debug, Args)]
struct AndroidWorkerArgs {
    /// Arguments forwarded to the platform worker.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    arguments: Vec<OsString>,
}

#[derive(Debug, Args)]
struct AndroidRuntimeFreePluginArgs {
    /// Internal plugin identifier.
    plugin: String,
    /// Legacy-compatible output directory and build profile.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    arguments: Vec<OsString>,
}

#[derive(Debug, Args)]
struct AndroidFfmpegPluginArgs {
    /// Internal plugin identifier.
    plugin: String,
    /// Legacy-compatible output directory, profile, and metadata options.
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    arguments: Vec<OsString>,
}

#[derive(Debug, Args)]
struct FfmpegArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    /// Declared FFmpeg profile. Defaults to platform environment, then `default`.
    #[arg(long)]
    profile: Option<String>,
    /// Build platform. Required unless --list-profiles is used.
    #[arg(long, value_enum, required_unless_present = "list_profiles")]
    platform: Option<FfmpegPlatformArg>,
    /// Lists declared profiles without resolving or building them.
    #[arg(long)]
    list_profiles: bool,
    /// Prints the resolved profile and worker arguments without building.
    #[arg(long)]
    dry_run: bool,
    /// Validates existing artifacts without building.
    #[arg(long)]
    verify_only: bool,
    /// Overrides the FFmpeg prebuilt output directory.
    #[arg(long)]
    output_dir: Option<PathBuf>,
    /// Android artifact to build.
    #[arg(long, value_enum, default_value = "runtime-aar")]
    android_artifact: FfmpegAndroidArtifactArg,
    /// Android ABI, repeatable or comma-separated.
    #[arg(long, action = clap::ArgAction::Append)]
    abi: Vec<String>,
    /// iOS slice, repeatable or comma-separated.
    #[arg(long, action = clap::ArgAction::Append)]
    slice: Vec<String>,
    /// Adds FFmpeg libraries to the resolved profile.
    #[arg(long, alias = "enable-libraries", action = clap::ArgAction::Append)]
    extra_libraries: Vec<String>,
    /// Adds FFmpeg demuxers to the resolved profile.
    #[arg(long, alias = "enable-demuxers", action = clap::ArgAction::Append)]
    extra_demuxers: Vec<String>,
    /// Adds FFmpeg muxers to the resolved profile.
    #[arg(long, alias = "enable-muxers", action = clap::ArgAction::Append)]
    extra_muxers: Vec<String>,
    /// Adds FFmpeg protocols to the resolved profile.
    #[arg(long, alias = "enable-protocols", action = clap::ArgAction::Append)]
    extra_protocols: Vec<String>,
    /// Adds FFmpeg decoders to the resolved profile.
    #[arg(long, alias = "enable-decoders", action = clap::ArgAction::Append)]
    extra_decoders: Vec<String>,
    /// Adds FFmpeg parsers to the resolved profile.
    #[arg(long, alias = "enable-parsers", action = clap::ArgAction::Append)]
    extra_parsers: Vec<String>,
    /// Adds FFmpeg bitstream filters to the resolved profile.
    #[arg(long, alias = "enable-bsfs", action = clap::ArgAction::Append)]
    extra_bsfs: Vec<String>,
    /// Adds a raw FFmpeg configure argument.
    #[arg(
        long,
        action = clap::ArgAction::Append,
        allow_hyphen_values = true
    )]
    extra_configure_arg: Vec<String>,
    /// Overrides the resolved TLS backend.
    #[arg(long)]
    tls_backend: Option<String>,
    /// Rebuilds even when metadata matches.
    #[arg(long)]
    force: bool,
    /// Acknowledges GPL or nonfree FFmpeg configure flags.
    #[arg(long)]
    acknowledge_gpl_nonfree: bool,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum FfmpegPlatformArg {
    Android,
    Ios,
    All,
}

impl From<FfmpegPlatformArg> for ffmpeg::FfmpegPlatform {
    fn from(value: FfmpegPlatformArg) -> Self {
        match value {
            FfmpegPlatformArg::Android => Self::Android,
            FfmpegPlatformArg::Ios => Self::Ios,
            FfmpegPlatformArg::All => Self::All,
        }
    }
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum FfmpegAndroidArtifactArg {
    RuntimeAar,
    Prebuilts,
}

impl From<FfmpegAndroidArtifactArg> for ffmpeg::AndroidArtifact {
    fn from(value: FfmpegAndroidArtifactArg) -> Self {
        match value {
            FfmpegAndroidArtifactArg::RuntimeAar => Self::RuntimeAar,
            FfmpegAndroidArtifactArg::Prebuilts => Self::Prebuilts,
        }
    }
}

fn parse_android_aar_task(value: &str) -> Result<String, String> {
    let is_test_variant = |variant: &str| {
        ["AndroidTest", "UnitTest", "TestFixtures"]
            .iter()
            .any(|suffix| variant.ends_with(suffix))
    };
    let is_assemble = value
        .strip_prefix("assemble")
        .is_some_and(|variant| !is_test_variant(variant));
    let is_bundle_aar = value
        .strip_prefix("bundle")
        .and_then(|value| value.strip_suffix("Aar"))
        .is_some_and(|variant| !variant.is_empty() && !is_test_variant(variant));
    if is_assemble || is_bundle_aar {
        Ok(value.to_owned())
    } else {
        Err(format!(
            "'{value}' is not an AAR-producing Gradle task; expected assemble*, or bundle*Aar"
        ))
    }
}

#[derive(Debug, Args)]
struct DesktopArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: DesktopCommand,
}

#[derive(Debug, Subcommand)]
enum DesktopCommand {
    /// Installs the repository-local desktop FFmpeg fallback when needed.
    #[command(name = "ensure-ffmpeg")]
    EnsureFfmpeg,
    /// Verifies the FFmpeg-backed post-download remux plugin.
    #[command(name = "verify-remux")]
    VerifyRemux(DesktopVerifyRemuxArgs),
    /// Verifies the decoder fixture plugin and macOS runtime diagnostics.
    #[command(name = "verify-decoder-diagnostics")]
    VerifyDecoderDiagnostics(DesktopVerifyRemuxArgs),
    /// Verifies the Windows D3D11 decoder plugin.
    #[command(name = "verify-decoder-d3d11")]
    VerifyDecoderD3d11(DesktopVerifyRemuxArgs),
    /// Verifies the macOS VideoToolbox decoder and native-frame playback path.
    #[command(name = "verify-decoder-videotoolbox")]
    VerifyDecoderVideoToolbox(DesktopVerifyRemuxArgs),
}

#[derive(Debug, Args)]
struct DesktopVerifyRemuxArgs {
    /// Positional profile and mode tokens accepted by the selected verification command.
    #[arg(value_name = "PROFILE_OR_MODE")]
    tokens: Vec<String>,
}

#[derive(Debug, Args)]
struct MobileArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: MobileCommand,
}

#[derive(Debug, Subcommand)]
enum MobileCommand {
    /// Verifies that default Android and iOS host artifacts exclude FFmpeg payloads.
    #[command(name = "verify-no-remux")]
    VerifyNoRemux(MobileVerifyNoRemuxArgs),
    /// Verifies Rust and mobile distribution binary library naming contracts.
    #[command(name = "verify-binary-names")]
    VerifyBinaryNames,
}

#[derive(Debug, Args)]
struct MobileVerifyNoRemuxArgs {
    /// Host artifact set to build and inspect.
    #[arg(value_enum, default_value = "all")]
    mode: MobileVerifyNoRemuxMode,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum MobileVerifyNoRemuxMode {
    Android,
    Ios,
    All,
}

impl From<MobileVerifyNoRemuxMode> for mobile::NoRemuxMode {
    fn from(value: MobileVerifyNoRemuxMode) -> Self {
        match value {
            MobileVerifyNoRemuxMode::Android => Self::Android,
            MobileVerifyNoRemuxMode::Ios => Self::Ios,
            MobileVerifyNoRemuxMode::All => Self::All,
        }
    }
}

#[derive(Debug, Args)]
struct FlutterArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: FlutterCommand,
}

#[derive(Debug, Subcommand)]
enum FlutterCommand {
    /// Stages publishable Flutter packages with release dependency metadata.
    #[command(name = "stage-pub")]
    StagePub(FlutterPubArgs),
    /// Runs `flutter pub publish --dry-run` for staged packages.
    #[command(name = "pub-dry-run")]
    PubDryRun(FlutterPubArgs),
    /// Publishes staged packages to pub.dev.
    #[command(name = "pub-publish")]
    PubPublish(FlutterPubArgs),
    /// Writes local path dependency overrides for the Flutter workspace.
    #[command(name = "local-overrides")]
    LocalOverrides(FlutterLocalOverridesArgs),
    /// Compiles the Android implementations of the Flutter plugins.
    #[command(name = "verify-android-plugin")]
    VerifyAndroidPlugin(FlutterLocalOverridesArgs),
    /// Verifies that a release APK contains arm64 Flutter AOT code and no test fixtures.
    #[command(name = "verify-android-release")]
    VerifyAndroidRelease(FlutterVerifyAndroidReleaseArgs),
}

#[derive(Debug, Args)]
struct FlutterVerifyAndroidReleaseArgs {
    /// Flutter Android release APK to inspect without extracting it.
    apk: PathBuf,
}

#[derive(Debug, Args)]
struct FlutterLocalOverridesArgs {
    /// Includes optional Flutter plugin packages. The environment is used when omitted.
    #[arg(
        long,
        num_args = 0..=1,
        default_missing_value = "true",
        value_name = "BOOL"
    )]
    include_optional_plugins: Option<bool>,
}

#[derive(Debug, Args)]
struct FlutterPubArgs {
    /// Staging directory. Defaults to dist/release/flutter-pub under the repository root.
    output_directory: Option<PathBuf>,
    /// Package version. Defaults to the vesper_player pubspec version.
    version: Option<String>,
    /// Includes optional Flutter plugin packages. The environment is used when omitted.
    #[arg(
        long,
        num_args = 0..=1,
        default_missing_value = "true",
        value_name = "BOOL"
    )]
    include_optional_plugins: Option<bool>,
}

#[derive(Debug, Args)]
struct FfiArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: FfiCommand,
}

#[derive(Debug, Subcommand)]
enum FfiCommand {
    /// Generates and atomically replaces the checked-in C header.
    Generate,
    /// Updates the checked-in C header only when generated content differs.
    Sync,
    /// Verifies that the checked-in C header matches cbindgen output.
    Verify,
    /// Builds and optionally runs the plain C host smoke example.
    #[command(name = "c-host-smoke")]
    CHostSmoke(FfiCHostSmokeArgs),
}

#[derive(Debug, Args)]
struct FfiCHostSmokeArgs {
    /// Media source passed to the C host. Defaults to the bundled smoke fixture.
    source: Option<PathBuf>,
    /// Builds the C host without running it.
    #[arg(long)]
    build_only: bool,
}

#[derive(Debug, Args)]
struct ReleaseArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: ReleaseCommand,
}

#[derive(Debug, Subcommand)]
enum ReleaseCommand {
    /// Generates bilingual GitHub release notes from a verified Git tag.
    Notes(ReleaseNotesArgs),
    /// Atomically updates product version metadata and changelog headings.
    SetVersion(ReleaseSetVersionArgs),
    /// Resolves a tag, updates metadata, verifies it, and emits CI values.
    PrepareFromTag(ReleaseTagArgs),
    /// Resolves a tag and emits CI values without changing repository files.
    MetadataFromTag(ReleaseTagArgs),
    /// Classifies a v-prefixed SemVer tag for CI release routing.
    TagChannel(ReleaseChannelArgs),
    /// Verifies all product metadata against one numeric version.
    VerifyVersion(ReleaseVerifyVersionArgs),
    /// Verifies product metadata against the current workspace version.
    VerifyCurrent,
}

#[derive(Debug, Args)]
struct ReleaseNotesArgs {
    /// Git tag. Defaults to GITHUB_REF_NAME.
    tag: Option<String>,
    /// Release notes output path. Defaults to dist/release/RELEASE_NOTES.md.
    output: Option<PathBuf>,
}

#[derive(Debug, Args)]
struct ReleaseSetVersionArgs {
    /// Numeric major.minor.patch product version.
    version: String,
    #[command(flatten)]
    metadata: ReleaseMetadataArgs,
}

#[derive(Debug, Args)]
struct ReleaseTagArgs {
    /// Release tag, including an optional v prefix and prerelease suffix.
    tag: String,
    #[command(flatten)]
    metadata: ReleaseMetadataArgs,
}

#[derive(Debug, Args)]
struct ReleaseChannelArgs {
    /// Release tag in vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-PRERELEASE form.
    tag: String,
}

#[derive(Debug, Args)]
struct ReleaseMetadataArgs {
    /// Numeric iOS CFBundleVersion. Defaults to release environment or versionCode.
    #[arg(long)]
    ios_build: Option<String>,
    /// Numeric Android versionCode. Defaults to release environment or the version tuple.
    #[arg(long)]
    android_version_code: Option<String>,
    /// Release date in YYYY-MM-DD form.
    #[arg(long)]
    date: Option<String>,
}

impl From<ReleaseMetadataArgs> for release::ReleaseMetadataOptions {
    fn from(value: ReleaseMetadataArgs) -> Self {
        Self {
            ios_build: value.ios_build,
            android_version_code: value.android_version_code,
            release_date: value.date,
        }
    }
}

#[derive(Debug, Args)]
struct ReleaseVerifyVersionArgs {
    /// Numeric major.minor.patch product version.
    version: String,
    /// Expected numeric iOS CFBundleVersion; defaults to the current value.
    #[arg(long)]
    ios_build: Option<String>,
    /// Expected numeric Android versionCode; defaults to the current value.
    #[arg(long)]
    android_version_code: Option<String>,
}

#[derive(Debug, Args)]
struct ContractArgs {
    /// Repository root. Defaults to VESPER_REPO_ROOT or the current directory.
    #[arg(long, global = true)]
    root: Option<PathBuf>,
    #[command(subcommand)]
    command: ContractCommand,
}

#[derive(Debug, Subcommand)]
enum ContractCommand {
    /// Verifies cross-language DTO fixtures and binary naming contracts.
    Verify,
    /// Scans boundary lifecycle and forward-compatibility invariants.
    Boundary(ContractBoundaryArgs),
}

#[derive(Debug, Args)]
struct ContractBoundaryArgs {
    /// Emits focused warning candidates in addition to failures.
    #[arg(long)]
    warnings: bool,
    /// Emits the broad warning candidate set in addition to failures.
    #[arg(long)]
    all_warnings: bool,
}

#[derive(Debug, Args)]
struct PluginArgs {
    #[command(subcommand)]
    command: PluginCommand,
}

#[derive(Debug, Subcommand)]
enum PluginCommand {
    /// Creates a safe Rust Native or WASM plugin project.
    New(PluginNewArgs),
    /// Builds and stages one manifest-declared Rust plugin artifact.
    Build(PluginBuildArgs),
    /// Inspects manifest metadata or one concrete plugin artifact.
    Inspect(PluginInspectArgs),
    /// Runs bounded conformance checks against one concrete plugin artifact.
    Check(PluginCheckArgs),
    /// Reports canonical catalog metadata without opening plugin artifacts.
    Catalog(PluginCatalogArgs),
    /// Emits the artifact-independent canonical descriptor as JSON.
    Descriptor(PluginDescriptorArgs),
    /// Emits one validated mobile registry fragment as JSON.
    RegistryFragment(PluginRegistryFragmentArgs),
    /// Builds a deterministic signed Vesper plugin package.
    Package(PluginPackageArgs),
    /// Verifies package integrity and publisher trust without loading code.
    Verify(PluginVerifyArgs),
    /// Verifies and atomically installs a signed plugin package.
    Install(PluginInstallArgs),
    /// Removes one installed plugin version.
    Uninstall(PluginUninstallArgs),
    /// Lists verified plugin versions installed under a root.
    List(PluginListArgs),
    /// Manages publisher signing keys.
    Key(PluginKeyArgs),
}

#[derive(Debug, Args)]
struct PluginBuildArgs {
    /// Path to vesper-plugin.toml.
    manifest: PathBuf,
    /// Path to Cargo.toml; relative paths are resolved from the current directory.
    #[arg(long)]
    cargo_manifest: Option<PathBuf>,
    /// Artifact transport selector.
    #[arg(long, value_enum)]
    transport: Option<PluginTransportArg>,
    /// Exact manifest artifact target selector.
    #[arg(long)]
    target: Option<String>,
    /// Exact manifest artifact architecture selector.
    #[arg(long)]
    architecture: Option<String>,
    /// Cargo profile used for the build.
    #[arg(long, value_enum, default_value_t = PluginBuildProfile::Dev)]
    profile: PluginBuildProfile,
    /// Optional Cargo package selector for workspace projects.
    #[arg(long, value_parser = clap::builder::NonEmptyStringValueParser::new())]
    package: Option<String>,
    /// Cargo build deadline in milliseconds.
    #[arg(
        long,
        default_value_t = 900_000,
        value_parser = clap::value_parser!(u64).range(1..=3_600_000)
    )]
    timeout_ms: u64,
}

#[derive(Debug, Args)]
struct PluginNewArgs {
    /// New plugin project directory; it must not already exist.
    directory: PathBuf,
    /// Valid reverse-DNS plugin identity.
    #[arg(long)]
    plugin_id: String,
    /// Valid reverse-DNS publisher identity.
    #[arg(long)]
    publisher: String,
    /// SPDX license expression for the plugin project.
    #[arg(long)]
    license: String,
    /// Rust plugin transport.
    #[arg(long, value_enum)]
    transport: PluginTransportArg,
    /// Capability to scaffold; pass the option more than once for multiple capabilities.
    #[arg(long, value_enum, required = true)]
    capability: Vec<PluginScaffoldCapability>,
    /// Human-readable plugin name.
    #[arg(long)]
    name: Option<String>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum PluginTransportArg {
    Native,
    Wasm,
}

impl From<PluginTransportArg> for PluginArtifactTransport {
    fn from(value: PluginTransportArg) -> Self {
        match value {
            PluginTransportArg::Native => Self::Native,
            PluginTransportArg::Wasm => Self::Wasm,
        }
    }
}

#[derive(Debug, Args)]
struct PluginInspectArgs {
    /// Path to vesper-plugin.toml.
    manifest: PathBuf,
    /// Validates and reports manifest metadata without accessing an artifact.
    #[arg(long, conflicts_with_all = ["artifact", "transport"])]
    manifest_only: bool,
    /// Native library or WASM component to inspect.
    #[arg(
        long,
        required_unless_present = "manifest_only",
        requires = "transport"
    )]
    artifact: Option<PathBuf>,
    /// Artifact transport; selection is never automatic.
    #[arg(
        long,
        value_enum,
        required_unless_present = "manifest_only",
        requires = "artifact"
    )]
    transport: Option<PluginTransportArg>,
    /// Worker deadline in milliseconds for native artifact inspection.
    #[arg(
        long,
        default_value_t = 10_000,
        value_parser = clap::value_parser!(u64).range(1..=300_000),
        conflicts_with = "manifest_only"
    )]
    timeout_ms: u64,
}

#[derive(Debug, Args)]
struct PluginCheckArgs {
    /// Path to vesper-plugin.toml.
    manifest: PathBuf,
    /// Native library or WASM component to check.
    #[arg(long)]
    artifact: PathBuf,
    /// Artifact transport; selection is never automatic.
    #[arg(long, value_enum)]
    transport: PluginTransportArg,
    /// Worker deadline in milliseconds for native artifact checks.
    #[arg(
        long,
        default_value_t = 30_000,
        value_parser = clap::value_parser!(u64).range(1..=300_000)
    )]
    timeout_ms: u64,
}

#[derive(Debug, Args)]
struct PluginCatalogArgs {
    /// Path to vesper-plugin.toml.
    manifest: PathBuf,
}

#[derive(Debug, Args)]
struct PluginWorkerArgs {
    #[arg(long, hide = true)]
    request: PathBuf,
    #[arg(long, hide = true)]
    response: PathBuf,
}

#[derive(Debug, Args)]
struct PluginPackageArgs {
    /// Path to vesper-plugin.toml.
    manifest: PathBuf,
    /// Publisher signing key generated by vesper.
    #[arg(long)]
    signing_key: PathBuf,
    /// Destination with the .vesper-plugin extension.
    #[arg(long)]
    output: PathBuf,
}

#[derive(Debug, Args)]
struct PluginVerifyArgs {
    /// Signed .vesper-plugin package.
    package: PathBuf,
    /// Host-configured publisher trust store.
    #[arg(long)]
    trust_store: PathBuf,
}

#[derive(Debug, Args)]
struct PluginInstallArgs {
    /// Signed .vesper-plugin package.
    package: PathBuf,
    /// Host-configured publisher trust store.
    #[arg(long)]
    trust_store: PathBuf,
    /// Root directory for verified plugin installations.
    #[arg(long)]
    root: PathBuf,
}

#[derive(Debug, Args)]
struct PluginUninstallArgs {
    /// Reverse-DNS plugin identity.
    #[arg(long)]
    plugin_id: String,
    /// Exact semantic version to remove.
    #[arg(long)]
    version: String,
    /// Root directory for verified plugin installations.
    #[arg(long)]
    root: PathBuf,
}

#[derive(Debug, Args)]
struct PluginListArgs {
    /// Root directory for verified plugin installations.
    #[arg(long)]
    root: PathBuf,
}

#[derive(Debug, Args)]
struct PluginKeyArgs {
    #[command(subcommand)]
    command: PluginKeyCommand,
}

#[derive(Debug, Subcommand)]
enum PluginKeyCommand {
    /// Generates a signing key and adds its public key to a trust store.
    Generate(PluginKeyGenerateArgs),
}

#[derive(Debug, Args)]
struct PluginKeyGenerateArgs {
    #[arg(long)]
    publisher: String,
    #[arg(long)]
    signing_key_output: PathBuf,
    #[arg(long)]
    trust_store_output: PathBuf,
}

#[derive(Debug, Args)]
struct PluginDescriptorArgs {
    /// Path to vesper-plugin.toml.
    manifest: PathBuf,
    /// Emit only the canonical descriptor SHA-256.
    #[arg(long)]
    hash_only: bool,
    /// Atomically write the result instead of emitting it to stdout.
    #[arg(long)]
    output: Option<PathBuf>,
}

#[derive(Debug, Clone, Copy, ValueEnum)]
enum RegistryPlatform {
    Android,
    Ios,
}

#[derive(Debug, Args)]
struct PluginRegistryFragmentArgs {
    /// Path to vesper-plugin.toml.
    manifest: PathBuf,
    #[arg(long, value_enum)]
    platform: RegistryPlatform,
    #[arg(long)]
    target: String,
    #[arg(long)]
    architecture: String,
    #[arg(long)]
    minimum_os: String,
    #[arg(long)]
    locator_name: String,
    /// Android runtime shared library to hash.
    #[arg(long, required_if_eq("platform", "android"))]
    artifact: Option<PathBuf>,
    /// Apple framework bundle identifier.
    #[arg(long, required_if_eq("platform", "ios"))]
    bundle_identifier: Option<String>,
    /// Atomically write the fragment instead of emitting it to stdout.
    #[arg(long)]
    output: Option<PathBuf>,
}

fn main() -> ExitCode {
    match run(Cli::parse()) {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            let _ = writeln!(io::stderr().lock(), "{error}");
            ExitCode::from(error.kind().exit_code())
        }
    }
}

fn run(cli: Cli) -> CliResult<()> {
    match cli.command {
        Command::Android(arguments) => run_android(arguments),
        Command::Ios(arguments) => run_ios(arguments),
        Command::Ffmpeg(arguments) => run_ffmpeg(arguments),
        Command::Plugin(plugin) => match plugin.command {
            PluginCommand::New(arguments) => new_plugin(arguments),
            PluginCommand::Build(arguments) => build_plugin(arguments),
            PluginCommand::Inspect(arguments) => inspect_plugin(arguments),
            PluginCommand::Check(arguments) => check_plugin(arguments),
            PluginCommand::Catalog(arguments) => report_plugin_catalog(arguments),
            PluginCommand::Descriptor(arguments) => emit_descriptor(arguments),
            PluginCommand::RegistryFragment(arguments) => emit_registry_fragment(arguments),
            PluginCommand::Package(arguments) => package_plugin(arguments),
            PluginCommand::Verify(arguments) => verify_plugin(arguments),
            PluginCommand::Install(arguments) => install_plugin(arguments),
            PluginCommand::Uninstall(arguments) => uninstall_installed_plugin(arguments),
            PluginCommand::List(arguments) => list_plugins(arguments),
            PluginCommand::Key(arguments) => match arguments.command {
                PluginKeyCommand::Generate(arguments) => generate_plugin_key(arguments),
            },
        },
        Command::Contract(arguments) => run_contract(arguments),
        Command::Ffi(arguments) => run_ffi(arguments),
        Command::Desktop(arguments) => run_desktop(arguments),
        Command::Media(arguments) => run_media(arguments),
        Command::Mobile(arguments) => run_mobile(arguments),
        Command::Flutter(arguments) => run_flutter(arguments),
        Command::Release(arguments) => run_release(arguments),
        Command::PluginWorker(arguments) => run_plugin_worker(arguments),
    }
}

fn run_media(arguments: MediaArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    match arguments.command {
        MediaCommand::GenerateSourceNormalizerFixtures => {
            let stdout = io::stdout();
            let stderr = io::stderr();
            let mut output = stdout.lock();
            let mut diagnostics = stderr.lock();
            media::generate_source_normalizer_fixtures(&root, &mut output, &mut diagnostics)
                .map_err(|error| match error.kind() {
                    media::MediaErrorKind::Storage => {
                        CliError::manifest_or_package(error.to_string())
                    }
                    media::MediaErrorKind::Compatibility => {
                        CliError::compatibility(error.to_string())
                    }
                    media::MediaErrorKind::Conformance => CliError::conformance(error.to_string()),
                    media::MediaErrorKind::Worker => CliError::worker(error.to_string()),
                })
        }
    }
}

fn run_ffmpeg(arguments: FfmpegArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    let stdout = io::stdout();
    let mut output = stdout.lock();
    ffmpeg::run(
        &root,
        &ffmpeg::FfmpegRequest {
            profile: arguments.profile,
            platform: arguments.platform.map(Into::into),
            list_profiles: arguments.list_profiles,
            dry_run: arguments.dry_run,
            verify_only: arguments.verify_only,
            output_directory: arguments.output_dir,
            android_artifact: arguments.android_artifact.into(),
            android_abis: arguments.abi,
            ios_slices: arguments.slice,
            extra_libraries: arguments.extra_libraries,
            extra_demuxers: arguments.extra_demuxers,
            extra_muxers: arguments.extra_muxers,
            extra_protocols: arguments.extra_protocols,
            extra_decoders: arguments.extra_decoders,
            extra_parsers: arguments.extra_parsers,
            extra_bsfs: arguments.extra_bsfs,
            extra_configure_args: arguments.extra_configure_arg,
            tls_backend: arguments.tls_backend,
            force: arguments.force,
            acknowledge_gpl_nonfree: arguments.acknowledge_gpl_nonfree,
        },
        &mut output,
    )
    .map_err(map_ffmpeg_error)
}

fn map_ffmpeg_error(error: ffmpeg::FfmpegError) -> CliError {
    match error.kind() {
        ffmpeg::FfmpegErrorKind::Storage => CliError::manifest_or_package(error.to_string()),
        ffmpeg::FfmpegErrorKind::Compatibility => CliError::compatibility(error.to_string()),
        ffmpeg::FfmpegErrorKind::Conformance => CliError::conformance(error.to_string()),
        ffmpeg::FfmpegErrorKind::Worker => CliError::worker(error.to_string()),
    }
}

fn run_ios(arguments: IosArgs) -> CliResult<()> {
    let stdout = io::stdout();
    let mut output = stdout.lock();
    let requested_root = arguments.root;
    match arguments.command {
        IosCommand::Ffi(arguments) => {
            ios_ffi::ensure_supported_host().map_err(map_ios_error)?;
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            match arguments.platform {
                Some(platform) => ios_ffi::build_platform(
                    &root,
                    platform.into(),
                    arguments.profile.into(),
                    &mut output,
                    &mut diagnostics,
                ),
                None => ios_ffi::build(
                    &root,
                    arguments.profile.into(),
                    &mut output,
                    &mut diagnostics,
                ),
            }
            .map_err(map_ios_error)
        }
        IosCommand::RemuxPlugin(arguments) => run_ios_plugin_build(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::RemuxFfmpeg,
            arguments,
            &mut output,
        ),
        IosCommand::SourceNormalizerPlugin(arguments) => run_ios_plugin_build(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::SourceNormalizerFfmpeg,
            arguments,
            &mut output,
        ),
        IosCommand::FrameProcessorPlugin(arguments) => run_ios_plugin_build(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::FrameProcessorDiagnostic,
            arguments,
            &mut output,
        ),
        IosCommand::PerformanceDiagnosticsPlugin(arguments) => run_ios_plugin_build(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::PerformanceDiagnostics,
            arguments,
            &mut output,
        ),
        IosCommand::DecoderVideoToolboxPlugin(arguments) => run_ios_plugin_build(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::DecoderVideoToolbox,
            arguments,
            &mut output,
        ),
        IosCommand::StageRemuxPluginRelease(arguments) => run_ios_plugin_release(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::RemuxFfmpeg,
            arguments,
            &mut output,
        ),
        IosCommand::StageSourceNormalizerPluginRelease(arguments) => run_ios_plugin_release(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::SourceNormalizerFfmpeg,
            arguments,
            &mut output,
        ),
        IosCommand::StageFrameProcessorPluginRelease(arguments) => run_ios_plugin_release(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::FrameProcessorDiagnostic,
            arguments,
            &mut output,
        ),
        IosCommand::StagePerformanceDiagnosticsPluginRelease(arguments) => run_ios_plugin_release(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::PerformanceDiagnostics,
            arguments,
            &mut output,
        ),
        IosCommand::StageDecoderVideoToolboxPluginRelease(arguments) => run_ios_plugin_release(
            requested_root.as_deref(),
            ios_plugin::IosPluginId::DecoderVideoToolbox,
            arguments,
            &mut output,
        ),
        IosCommand::KitXcframework => {
            ios_kit::ensure_supported_host().map_err(map_ios_error)?;
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_kit::build(&root, &mut output, &mut diagnostics).map_err(map_ios_error)
        }
        IosCommand::BootstrapBridgeShim => {
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            ios::bootstrap_bridge_shim(&root, &mut output).map_err(map_ios_error)
        }
        IosCommand::SyncBridgeShim(arguments) => {
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            ios::sync_bridge_shim(&root, arguments.allow_public_api_removal, &mut output)
                .map_err(map_ios_error)
        }
        IosCommand::VerifyBridgeShim(arguments) => {
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            ios::verify_bridge_shim(&root, arguments.archive.as_deref(), &mut output)
                .map_err(map_ios_error)
        }
        IosCommand::VerifyAppStoreLayout(arguments) => ios::verify_app_store_layout(
            &arguments.app_path,
            arguments.verify_signatures,
            &mut output,
        )
        .map_err(map_ios_error),
        IosCommand::VerifyNativeFrame(arguments) => {
            ios_native_frame::ensure_supported_host().map_err(map_ios_error)?;
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let tokens = arguments
                .tokens
                .into_iter()
                .map(IosVerifyNativeFrameTokenArg::as_str)
                .collect::<Vec<_>>();
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_native_frame::verify(&root, &tokens, &mut output, &mut diagnostics)
                .map_err(map_ios_error)
        }
        IosCommand::VerifyOptionalPluginsRelease(arguments) => {
            ios_optional_release::ensure_supported_host().map_err(map_ios_error)?;
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_optional_release::verify_optional_plugins_release(
                &root,
                arguments.release_directory.as_deref(),
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_ios_error)
        }
        IosCommand::VerifyOptionalPluginsDevice(arguments) => {
            ios_optional_device::ensure_supported_host().map_err(map_ios_error)?;
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_optional_device::verify(
                &root,
                ios_optional_device::IosOptionalPluginDeviceRequest {
                    release_directory: arguments.release_directory,
                    device: arguments.device,
                    development_team: arguments.development_team,
                    output_directory: arguments.output_directory,
                    allow_provisioning_updates: arguments.allow_provisioning_updates,
                },
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_ios_error)
        }
        IosCommand::VerifyPlaybackLifecycleDevice(arguments) => {
            ios_playback_device::ensure_supported_host().map_err(map_ios_error)?;
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_playback_device::verify(
                &root,
                ios_playback_device::IosPlaybackDeviceRequest {
                    device: arguments.device,
                    development_team: arguments.development_team,
                    output_directory: arguments.output_directory,
                    allow_provisioning_updates: arguments.allow_provisioning_updates,
                },
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_ios_error)
        }
        IosCommand::VerifyRelease(arguments) => {
            ios_optional_release::ensure_release_supported_host().map_err(map_ios_error)?;
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_optional_release::verify_release(
                &root,
                arguments.release_directory.as_deref(),
                matches!(arguments.scope, IosReleaseScopeArg::Complete),
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_ios_error)
        }
        IosCommand::StageRelease(arguments) => {
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let include_optional_plugins =
                arguments.include_optional_plugins.unwrap_or_else(|| {
                    matches!(
                        std::env::var("VESPER_IOS_INCLUDE_OPTIONAL_PLUGINS").as_deref(),
                        Ok("1" | "true" | "TRUE" | "yes" | "YES")
                    )
                });
            let package_artifacts_explicit = arguments.package_artifacts_directory.is_some();
            let package_artifacts_directory = arguments.package_artifacts_directory.or_else(|| {
                std::env::var_os("VESPER_IOS_OPTIONAL_PACKAGE_ARTIFACTS_DIR").map(Into::into)
            });
            ios_release::stage_release(
                &root,
                arguments.output_directory.as_deref(),
                include_optional_plugins,
                package_artifacts_directory.as_deref(),
                package_artifacts_explicit,
                &mut output,
            )
            .map_err(map_ios_error)
        }
        IosCommand::FfmpegRuntimeRelease(arguments) => {
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_plugin_release::stage_ffmpeg_runtime(
                &root,
                arguments.arguments,
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_ios_error)
        }
        IosCommand::StageOptionalPluginsRelease(arguments) => {
            let root = root_for_worker(requested_root.as_deref())?;
            let stdout = io::stdout();
            let mut output = stdout.lock();
            ios_release::stage_optional_plugins_release(&root, arguments.arguments, &mut output)
                .map_err(map_ios_error)
        }
        IosCommand::PublishSpmIndex(arguments) => {
            let root = contract::resolve_repository_root(requested_root.as_deref())
                .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
            ios_spm_publish::publish(
                &root,
                ios_spm_publish::SpmPublishRequest {
                    tag: &arguments.tag,
                    archive: &arguments.archive,
                    source_repository: arguments.source_repository.as_deref(),
                    repository: arguments.repository.as_deref(),
                    dry_run: arguments.dry_run,
                    output_directory: arguments.output_directory.as_deref(),
                },
                &mut output,
            )
            .map_err(map_ios_error)
        }
        IosCommand::VerifySubtitles(arguments) => {
            let root = root_for_worker(requested_root.as_deref())?;
            let development_team = match arguments.development_team {
                Some(team) => Some(team),
                None => std::env::var_os("VESPER_IOS_DEVELOPMENT_TEAM")
                    .map(|value| {
                        value.into_string().map_err(|_| {
                            CliError::usage("VESPER_IOS_DEVELOPMENT_TEAM must contain valid UTF-8")
                        })
                    })
                    .transpose()?,
            };
            let stderr = io::stderr();
            let mut diagnostics = stderr.lock();
            ios_subtitle::verify(
                &root,
                ios_subtitle::IosSubtitleRequest {
                    scope: arguments.scope.into(),
                    device_id: arguments.device,
                    simulator_id: arguments.simulator,
                    evidence_directory: arguments.evidence_dir,
                    development_team,
                },
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_subtitle_error)
        }
    }
}

fn root_for_worker(requested_root: Option<&Path>) -> CliResult<PathBuf> {
    contract::resolve_repository_root(requested_root)
        .map_err(|error| CliError::manifest_or_package(error.to_string()))
}

fn run_ios_plugin_build(
    requested_root: Option<&Path>,
    plugin_id: ios_plugin::IosPluginId,
    arguments: IosPluginBuildArgs,
    output: &mut dyn Write,
) -> CliResult<()> {
    ios_plugin::ensure_supported_host().map_err(map_ios_error)?;
    let root = contract::resolve_repository_root(requested_root)
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    let stderr = io::stderr();
    let mut diagnostics = stderr.lock();
    ios_plugin::build(
        &root,
        ios_plugin::IosPluginBuildRequest {
            plugin_id,
            output_directory: arguments.output_directory,
            arguments: arguments.arguments,
            environment: ios_plugin::IosPluginBuildEnvironment::default(),
        },
        output,
        &mut diagnostics,
    )
    .map_err(map_ios_error)
}

fn run_ios_plugin_release(
    requested_root: Option<&Path>,
    plugin_id: ios_plugin::IosPluginId,
    arguments: IosPluginReleaseArgs,
    output: &mut dyn Write,
) -> CliResult<()> {
    ios_plugin_release::ensure_supported_host().map_err(map_ios_error)?;
    let root = contract::resolve_repository_root(requested_root)
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    let stderr = io::stderr();
    let mut diagnostics = stderr.lock();
    ios_plugin_release::stage(
        &root,
        plugin_id,
        arguments.arguments,
        output,
        &mut diagnostics,
    )
    .map_err(map_ios_error)
}

fn map_ios_error(error: ios::IosError) -> CliError {
    match error.kind() {
        ios::IosErrorKind::Storage => CliError::manifest_or_package(error.to_string()),
        ios::IosErrorKind::Compatibility => CliError::compatibility(error.to_string()),
        ios::IosErrorKind::Conformance => CliError::conformance(error.to_string()),
        ios::IosErrorKind::Worker => CliError::worker(error.to_string()),
    }
}

fn run_android(arguments: AndroidArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    match arguments.command {
        AndroidCommand::Jni(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_jni(
                &root,
                arguments.profile.as_deref().unwrap_or("debug"),
                &arguments.abis,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::Aar(arguments) => android::build_aar(
            &root,
            arguments
                .module_task
                .as_deref()
                .unwrap_or("assembleRelease"),
            android::include_optional_plugins(arguments.include_optional_plugins),
        )
        .map_err(map_android_error),
        AndroidCommand::RemuxPlugin(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_ffmpeg_plugin(&root, "remux", &arguments.arguments, &mut output)
                .map_err(map_android_error)
        }
        AndroidCommand::SourceNormalizerPlugin(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_ffmpeg_plugin(
                &root,
                "source-normalizer",
                &arguments.arguments,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::DecoderMediacodecPlugin(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_runtime_free_plugin(
                &root,
                "decoder-mediacodec",
                &arguments.arguments,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::FrameProcessorPlugin(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_runtime_free_plugin(
                &root,
                "frame-processor-diagnostic",
                &arguments.arguments,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::PerformanceDiagnosticsPlugin(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_runtime_free_plugin(
                &root,
                "performance-diagnostics",
                &arguments.arguments,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::StageRelease(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::stage_release(
                &root,
                arguments.output_directory.as_deref(),
                &arguments.abis,
                android::include_optional_plugins(arguments.include_optional_plugins),
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::SampleApks(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::sample_apks(
                &root,
                arguments.output_directory.as_deref(),
                &arguments.abis,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::PublishMavenCentral(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android_publish::publish(
                &root,
                android_publish::MavenPublishRequest {
                    tag: &arguments.tag,
                    portal_namespace: &arguments.namespace,
                    dry_run: arguments.dry_run,
                },
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::ProvisionTestJni(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::provision_test_jni(
                &root,
                &arguments.output_directory,
                &arguments.profile,
                &arguments.ffmpeg_profile,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::ExternalPlaybackJni(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_external_playback_jni(
                &root,
                &arguments.output_directory,
                &arguments.assets_directory,
                &arguments.profile,
                &arguments.ffmpeg_profile,
                arguments.skip_ffmpeg_runtime,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::VerifySubtitles(arguments) => {
            let stdout = io::stdout();
            let stderr = io::stderr();
            let mut output = stdout.lock();
            let mut diagnostics = stderr.lock();
            android_subtitle::verify(
                &root,
                android_subtitle::SubtitleRequest {
                    scope: arguments.scope.into(),
                    device_id: arguments.device,
                    evidence_directory: arguments.evidence_dir,
                },
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_subtitle_error)
        }
        AndroidCommand::RuntimeFreePlugin(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_runtime_free_plugin(
                &root,
                &arguments.plugin,
                &arguments.arguments,
                &mut output,
            )
            .map_err(map_android_error)
        }
        AndroidCommand::FfmpegPlugin(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            android::build_ffmpeg_plugin(
                &root,
                &arguments.plugin,
                &arguments.arguments,
                &mut output,
            )
            .map_err(map_android_error)
        }
    }
}

fn map_android_error(error: android::AndroidError) -> CliError {
    match error.kind() {
        android::AndroidErrorKind::Usage => CliError::usage(error.to_string()),
        android::AndroidErrorKind::Storage => CliError::manifest_or_package(error.to_string()),
        android::AndroidErrorKind::Compatibility => CliError::compatibility(error.to_string()),
        android::AndroidErrorKind::Conformance => CliError::conformance(error.to_string()),
        android::AndroidErrorKind::Worker => CliError::worker(error.to_string()),
    }
}

fn map_subtitle_error(error: subtitle::SubtitleError) -> CliError {
    match error.kind() {
        subtitle::SubtitleErrorKind::Usage => CliError::usage(error.to_string()),
        subtitle::SubtitleErrorKind::Storage => CliError::manifest_or_package(error.to_string()),
        subtitle::SubtitleErrorKind::Compatibility => CliError::compatibility(error.to_string()),
        subtitle::SubtitleErrorKind::Conformance => CliError::conformance(error.to_string()),
        subtitle::SubtitleErrorKind::Worker => CliError::worker(error.to_string()),
    }
}

fn run_desktop(arguments: DesktopArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    match arguments.command {
        DesktopCommand::EnsureFfmpeg => desktop::ensure_ffmpeg(&root).map_err(|error| match error
            .kind()
        {
            desktop::DesktopErrorKind::Storage => CliError::manifest_or_package(error.to_string()),
            desktop::DesktopErrorKind::Compatibility => CliError::compatibility(error.to_string()),
            desktop::DesktopErrorKind::Conformance => CliError::conformance(error.to_string()),
            desktop::DesktopErrorKind::Worker => CliError::worker(error.to_string()),
        }),
        DesktopCommand::VerifyRemux(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            desktop::verify_remux(&root, &arguments.tokens, &mut output).map_err(
                |error| match error.kind() {
                    desktop::DesktopErrorKind::Storage => {
                        CliError::manifest_or_package(error.to_string())
                    }
                    desktop::DesktopErrorKind::Compatibility => {
                        CliError::compatibility(error.to_string())
                    }
                    desktop::DesktopErrorKind::Conformance => {
                        CliError::conformance(error.to_string())
                    }
                    desktop::DesktopErrorKind::Worker => CliError::worker(error.to_string()),
                },
            )
        }
        DesktopCommand::VerifyDecoderDiagnostics(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            desktop::verify_decoder_diagnostics(&root, &arguments.tokens, &mut output).map_err(
                |error| match error.kind() {
                    desktop::DesktopErrorKind::Storage => {
                        CliError::manifest_or_package(error.to_string())
                    }
                    desktop::DesktopErrorKind::Compatibility => {
                        CliError::compatibility(error.to_string())
                    }
                    desktop::DesktopErrorKind::Conformance => {
                        CliError::conformance(error.to_string())
                    }
                    desktop::DesktopErrorKind::Worker => CliError::worker(error.to_string()),
                },
            )
        }
        DesktopCommand::VerifyDecoderD3d11(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            desktop::verify_decoder_d3d11(&root, &arguments.tokens, &mut output).map_err(|error| {
                match error.kind() {
                    desktop::DesktopErrorKind::Storage => {
                        CliError::manifest_or_package(error.to_string())
                    }
                    desktop::DesktopErrorKind::Compatibility => {
                        CliError::compatibility(error.to_string())
                    }
                    desktop::DesktopErrorKind::Conformance => {
                        CliError::conformance(error.to_string())
                    }
                    desktop::DesktopErrorKind::Worker => CliError::worker(error.to_string()),
                }
            })
        }
        DesktopCommand::VerifyDecoderVideoToolbox(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            desktop::verify_decoder_videotoolbox(&root, &arguments.tokens, &mut output).map_err(
                |error| match error.kind() {
                    desktop::DesktopErrorKind::Storage => {
                        CliError::manifest_or_package(error.to_string())
                    }
                    desktop::DesktopErrorKind::Compatibility => {
                        CliError::compatibility(error.to_string())
                    }
                    desktop::DesktopErrorKind::Conformance => {
                        CliError::conformance(error.to_string())
                    }
                    desktop::DesktopErrorKind::Worker => CliError::worker(error.to_string()),
                },
            )
        }
    }
}

fn run_mobile(arguments: MobileArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    match arguments.command {
        MobileCommand::VerifyNoRemux(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            mobile::verify_no_remux(&root, arguments.mode.into(), &mut output).map_err(|error| {
                match error.kind() {
                    mobile::MobileErrorKind::Storage => {
                        CliError::manifest_or_package(error.to_string())
                    }
                    mobile::MobileErrorKind::Compatibility => {
                        CliError::compatibility(error.to_string())
                    }
                    mobile::MobileErrorKind::Conformance => {
                        CliError::conformance(error.to_string())
                    }
                    mobile::MobileErrorKind::Worker => CliError::worker(error.to_string()),
                }
            })
        }
        MobileCommand::VerifyBinaryNames => contract::verify_binary_library_names(&root)
            .map_err(|error| match error {
                contract::ContractError::Drift(message) => CliError::conformance(message),
                contract::ContractError::Storage(message) => CliError::manifest_or_package(message),
            })
            .and_then(|()| {
                emit_bytes(
                    b"Verified Rust and mobile distribution binary names use libvesper_* outputs.\n",
                    None,
                )
            }),
    }
}

fn run_flutter(arguments: FlutterArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    match arguments.command {
        FlutterCommand::StagePub(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            let include_optional =
                flutter::include_optional_plugins(arguments.include_optional_plugins);
            flutter::stage_pub_packages(
                &root,
                arguments.output_directory.as_deref(),
                arguments.version.as_deref(),
                include_optional,
                &mut output,
            )
            .map_err(map_flutter_error)
        }
        FlutterCommand::PubDryRun(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            let include_optional =
                flutter::include_optional_plugins(arguments.include_optional_plugins);
            flutter::dry_run_pub_packages(
                &root,
                arguments.output_directory.as_deref(),
                arguments.version.as_deref(),
                include_optional,
                &mut output,
            )
            .map_err(map_flutter_error)
        }
        FlutterCommand::PubPublish(arguments) => {
            let stdout = io::stdout();
            let stderr = io::stderr();
            let mut output = stdout.lock();
            let mut diagnostics = stderr.lock();
            let include_optional =
                flutter::include_optional_plugins(arguments.include_optional_plugins);
            flutter::publish_pub_packages(
                &root,
                arguments.output_directory.as_deref(),
                arguments.version.as_deref(),
                include_optional,
                &mut output,
                &mut diagnostics,
            )
            .map_err(map_flutter_error)
        }
        FlutterCommand::LocalOverrides(arguments) => {
            let stdout = io::stdout();
            let mut output = stdout.lock();
            let include_optional =
                flutter::include_optional_plugins(arguments.include_optional_plugins);
            flutter::write_local_overrides(&root, include_optional, &mut output)
                .map_err(map_flutter_error)
        }
        FlutterCommand::VerifyAndroidPlugin(arguments) => {
            let include_optional =
                flutter::include_optional_plugins(arguments.include_optional_plugins);
            flutter::verify_android_plugin(&root, include_optional).map_err(map_flutter_error)
        }
        FlutterCommand::VerifyAndroidRelease(arguments) => {
            android::validate_android_sample_apk(&arguments.apk, "arm64-v8a", true)
                .map_err(map_android_error)?;
            emit_bytes(
                format!(
                    "Verified Flutter Android release APK excludes test fixtures: {}\n",
                    arguments.apk.display()
                )
                .as_bytes(),
                None,
            )
        }
    }
}

fn map_flutter_error(error: flutter::FlutterError) -> CliError {
    match error.kind() {
        flutter::FlutterErrorKind::Storage => CliError::manifest_or_package(error.to_string()),
        flutter::FlutterErrorKind::Compatibility => CliError::compatibility(error.to_string()),
        flutter::FlutterErrorKind::Conformance => CliError::conformance(error.to_string()),
        flutter::FlutterErrorKind::Worker => CliError::worker(error.to_string()),
    }
}

fn run_ffi(arguments: FfiArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    let stdout = io::stdout();
    let mut output = stdout.lock();
    match arguments.command {
        FfiCommand::Generate => ffi::run_header(&root, ffi::FfiHeaderMode::Generate, &mut output),
        FfiCommand::Sync => ffi::run_header(&root, ffi::FfiHeaderMode::Sync, &mut output),
        FfiCommand::Verify => ffi::run_header(&root, ffi::FfiHeaderMode::Verify, &mut output),
        FfiCommand::CHostSmoke(arguments) => ffi::run_c_host_smoke(
            &root,
            arguments.build_only,
            arguments.source.as_deref(),
            &mut output,
        ),
    }
    .map_err(map_ffi_error)
}

fn map_ffi_error(error: ffi::FfiError) -> CliError {
    match error.kind() {
        ffi::FfiErrorKind::Storage => CliError::manifest_or_package(error.to_string()),
        ffi::FfiErrorKind::Conformance => CliError::conformance(error.to_string()),
        ffi::FfiErrorKind::Worker => CliError::worker(error.to_string()),
    }
}

fn run_release(arguments: ReleaseArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::manifest_or_package(error.to_string()))?;
    let context = release::ReleaseContext::new(root, release::ReleaseEnvironment::from_process());
    match arguments.command {
        ReleaseCommand::Notes(arguments) => {
            let tag = arguments
                .tag
                .or_else(|| context.default_notes_tag().map(str::to_owned))
                .ok_or_else(|| {
                    CliError::manifest_or_package("release notes requires a tag or GITHUB_REF_NAME")
                })?;
            let output = context
                .generate_notes(&tag, arguments.output.as_deref())
                .map_err(map_release_error)?;
            emit_bytes(
                format!(
                    "Generated VesperPlayerKit release notes at:\n  {}\n",
                    output.display()
                )
                .as_bytes(),
                None,
            )
        }
        ReleaseCommand::SetVersion(arguments) => {
            let metadata = context
                .metadata_for_version(&arguments.version, arguments.metadata.into())
                .map_err(map_release_error)?;
            context.set_version(&metadata).map_err(map_release_error)?;
            emit_bytes(
                format!(
                    "Updated Vesper product version to {}.\n",
                    metadata.version()
                )
                .as_bytes(),
                None,
            )
        }
        ReleaseCommand::PrepareFromTag(arguments) => {
            let metadata = context
                .metadata_from_tag(&arguments.tag, arguments.metadata.into())
                .map_err(map_release_error)?;
            context.set_version(&metadata).map_err(map_release_error)?;
            context
                .verify_metadata(&metadata)
                .map_err(map_release_error)?;
            context
                .append_ci_metadata(&metadata)
                .map_err(map_release_error)?;
            let output = format!(
                "Updated Vesper product version to {}.\nVerified Vesper product version {}.\n{}",
                metadata.version(),
                metadata.version(),
                metadata.output()
            );
            emit_bytes(output.as_bytes(), None)
        }
        ReleaseCommand::MetadataFromTag(arguments) => {
            let metadata = context
                .metadata_from_tag(&arguments.tag, arguments.metadata.into())
                .map_err(map_release_error)?;
            context
                .append_ci_metadata(&metadata)
                .map_err(map_release_error)?;
            emit_bytes(metadata.output().as_bytes(), None)
        }
        ReleaseCommand::TagChannel(arguments) => {
            let channel = release::ReleaseContext::channel_from_tag(&arguments.tag)
                .map_err(map_release_error)?;
            emit_bytes(channel.output().as_bytes(), None)
        }
        ReleaseCommand::VerifyVersion(arguments) => {
            context
                .verify_version(
                    &arguments.version,
                    arguments.ios_build,
                    arguments.android_version_code,
                )
                .map_err(map_release_error)?;
            emit_bytes(
                format!("Verified Vesper product version {}.\n", arguments.version).as_bytes(),
                None,
            )
        }
        ReleaseCommand::VerifyCurrent => {
            let version = context.verify_current().map_err(map_release_error)?;
            emit_bytes(
                format!("Verified Vesper product version {version}.\n").as_bytes(),
                None,
            )
        }
    }
}

fn map_release_error(error: release::ReleaseError) -> CliError {
    match error.kind() {
        release::ReleaseErrorKind::Verification => CliError::conformance(error.to_string()),
        release::ReleaseErrorKind::Input | release::ReleaseErrorKind::Storage => {
            CliError::manifest_or_package(error.to_string())
        }
    }
}

fn run_contract(arguments: ContractArgs) -> CliResult<()> {
    let root = contract::resolve_repository_root(arguments.root.as_deref())
        .map_err(|error| CliError::conformance(error.to_string()))?;
    match arguments.command {
        ContractCommand::Verify => {
            let verification = contract::verify(&root)
                .map_err(|error| CliError::conformance(error.to_string()))?;
            emit_bytes(verification.output().as_bytes(), None)
        }
        ContractCommand::Boundary(arguments) => {
            let report = boundary::scan(
                &root,
                boundary::BoundaryScanOptions {
                    show_warnings: arguments.warnings,
                    show_all_warnings: arguments.all_warnings,
                },
            )
            .map_err(CliError::conformance)?;
            emit_bytes(report.output().as_bytes(), None)?;
            if let Some(failure) = report.failure() {
                return Err(CliError::conformance(failure));
            }
            Ok(())
        }
    }
}

fn build_plugin(arguments: PluginBuildArgs) -> CliResult<()> {
    let project = read_project_manifest(&arguments.manifest)?;
    let artifact = select_plugin_artifact(
        &project,
        &PluginArtifactSelector {
            transport: arguments.transport.map(Into::into),
            target: arguments.target,
            architecture: arguments.architecture,
        },
    )
    .map_err(map_plugin_build_error)?;
    let base_directory = arguments
        .manifest
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let cargo_manifest = arguments
        .cargo_manifest
        .unwrap_or_else(|| base_directory.join("Cargo.toml"));
    validate_regular_file_for_json(&cargo_manifest, "Cargo manifest")?;
    let cargo_manifest = if cargo_manifest.is_absolute() {
        cargo_manifest
    } else {
        std::env::current_dir()
            .map_err(|error| {
                CliError::worker(format!(
                    "failed to resolve Cargo manifest '{}': {error}",
                    cargo_manifest.display()
                ))
            })?
            .join(cargo_manifest)
    };
    let cargo_directory = cargo_manifest
        .parent()
        .ok_or_else(|| {
            CliError::manifest_or_package(format!(
                "Cargo manifest '{}' has no parent directory",
                cargo_manifest.display()
            ))
        })?
        .to_path_buf();
    let destination = if artifact.source.is_absolute() {
        artifact.source.clone()
    } else {
        base_directory.join(&artifact.source)
    };
    validate_path_for_json_report(&destination, "built plugin artifact")?;
    let report = build_plugin_artifact(PluginBuildRequest {
        plugin_id: project.descriptor().plugin.id.clone(),
        cargo_manifest,
        working_directory: cargo_directory,
        artifact,
        destination,
        profile: arguments.profile,
        package: arguments.package,
        timeout: Duration::from_millis(arguments.timeout_ms),
    })
    .map_err(map_plugin_build_error)?;
    emit_json_result(&report)
}

fn map_plugin_build_error(error: PluginBuildError) -> CliError {
    match error {
        PluginBuildError::Storage(message) => CliError::manifest_or_package(message),
        PluginBuildError::Compatibility(message) => CliError::compatibility(message),
        PluginBuildError::Conformance(message) => CliError::conformance(message),
        PluginBuildError::Worker(message) => CliError::worker(message),
    }
}

fn new_plugin(arguments: PluginNewArgs) -> CliResult<()> {
    validate_path_for_json_report(&arguments.directory, "plugin scaffold directory")?;
    let result = create_plugin_scaffold(PluginScaffoldRequest {
        directory: arguments.directory,
        plugin_id: arguments.plugin_id,
        plugin_name: arguments.name,
        publisher: arguments.publisher,
        license: arguments.license,
        transport: arguments.transport.into(),
        capabilities: arguments.capability,
    });
    let report = result.map_err(|error| {
        if error.is_compatibility() {
            CliError::compatibility(error.to_string())
        } else {
            CliError::manifest_or_package(error.to_string())
        }
    })?;
    emit_json_result(&report)
}

fn inspect_plugin(arguments: PluginInspectArgs) -> CliResult<()> {
    let project = read_project_manifest(&arguments.manifest)?;
    let descriptor = project.descriptor().clone();
    if arguments.manifest_only {
        let report = inspect_manifest(&descriptor, PluginInspectionOperation::Inspect, None);
        return emit_inspection_report(report);
    }
    let artifact = arguments.artifact.ok_or_else(|| {
        CliError::manifest_or_package("--artifact is required unless --manifest-only is used")
    })?;
    let transport = arguments.transport.ok_or_else(|| {
        CliError::manifest_or_package("--transport is required unless --manifest-only is used")
    })?;
    inspect_or_check_artifact(
        descriptor,
        &artifact,
        transport.into(),
        PluginInspectionOperation::Inspect,
        Duration::from_millis(arguments.timeout_ms),
    )
}

fn check_plugin(arguments: PluginCheckArgs) -> CliResult<()> {
    let project = read_project_manifest(&arguments.manifest)?;
    inspect_or_check_artifact(
        project.descriptor().clone(),
        &arguments.artifact,
        arguments.transport.into(),
        PluginInspectionOperation::Check,
        Duration::from_millis(arguments.timeout_ms),
    )
}

fn report_plugin_catalog(arguments: PluginCatalogArgs) -> CliResult<()> {
    let project = read_project_manifest(&arguments.manifest)?;
    let report = inspect_project_catalog(&project).map_err(CliError::manifest_or_package)?;
    emit_json_result(&report)
}

fn inspect_or_check_artifact(
    descriptor: PluginDescriptor,
    artifact: &Path,
    transport: PluginArtifactTransport,
    operation: PluginInspectionOperation,
    native_worker_timeout: Duration,
) -> CliResult<()> {
    let preflight = inspect_manifest(&descriptor, operation, Some(transport));
    if preflight.outcome() != PluginInspectionOutcome::Passed {
        return emit_inspection_report(preflight);
    }
    validate_regular_file_for_json(artifact, "plugin artifact")?;

    let report = match transport {
        PluginArtifactTransport::Native => {
            let artifact_utf8 = artifact.to_str().ok_or_else(|| {
                CliError::manifest_or_package(
                    "plugin artifact path must be valid UTF-8 because it crosses the worker JSON boundary",
                )
            })?;
            let request =
                PluginWorkerRequest::new(1, operation, artifact_utf8.to_owned(), descriptor);
            supervise_native_worker(request, native_worker_timeout)?
        }
        PluginArtifactTransport::Wasm => {
            let bytes = read_bounded_regular_file(
                artifact,
                MAX_WASM_PLUGIN_COMPONENT_BYTES,
                "WASM plugin component",
            )?;
            inspect_wasm_plugin(&descriptor, &bytes, operation).map_err(|error| {
                CliError::worker(format!(
                    "failed to initialize the WASM plugin host: {error}"
                ))
            })?
        }
    };
    emit_inspection_report(report)
}

fn emit_inspection_report(report: PluginInspectionReport) -> CliResult<()> {
    let operation = report.operation.as_str();
    let outcome = report.outcome();
    emit_json_result(&report)?;
    match outcome {
        PluginInspectionOutcome::Passed => Ok(()),
        PluginInspectionOutcome::CompatibilityFailure => Err(CliError::compatibility(format!(
            "plugin {operation} found compatibility failures"
        ))),
        PluginInspectionOutcome::ConformanceFailure => Err(CliError::conformance(format!(
            "plugin {operation} found conformance failures"
        ))),
    }
}

fn run_plugin_worker(arguments: PluginWorkerArgs) -> CliResult<()> {
    let mut gate = [0_u8; PLUGIN_WORKER_START_GATE.len()];
    io::stdin().lock().read_exact(&mut gate).map_err(|error| {
        CliError::worker(format!("failed to read plugin worker start gate: {error}"))
    })?;
    if &gate != PLUGIN_WORKER_START_GATE {
        return Err(CliError::worker("invalid plugin worker start gate"));
    }
    let request = read_worker_request(&arguments.request).map_err(CliError::worker)?;
    request.validate().map_err(CliError::worker)?;
    let report = plugin_inspection::inspect_native_plugin(
        &request.descriptor,
        Path::new(&request.library_path_utf8),
        request.operation,
    );
    let response = PluginWorkerResponse::new(request.request_id, report);
    write_worker_response(&arguments.response, &response).map_err(CliError::worker)
}

fn emit_descriptor(arguments: PluginDescriptorArgs) -> CliResult<()> {
    let descriptor = read_descriptor(&arguments.manifest)?;
    let canonical = descriptor
        .canonicalize()
        .map_err(|error| error.to_string())?;
    let bytes = if arguments.hash_only {
        format!("{}\n", canonical.sha256()).into_bytes()
    } else {
        let mut bytes = canonical.json().to_vec();
        bytes.push(b'\n');
        bytes
    };
    emit_bytes(&bytes, arguments.output.as_deref())
}

fn emit_registry_fragment(arguments: PluginRegistryFragmentArgs) -> CliResult<()> {
    let descriptor = read_descriptor(&arguments.manifest)?;
    let canonical = descriptor
        .canonicalize()
        .map_err(|error| error.to_string())?;
    let target = match arguments.platform {
        RegistryPlatform::Android => EmbeddedRegistryTarget::AndroidNativeLibrary {
            target: arguments.target,
            architecture: arguments.architecture,
            minimum_os: arguments.minimum_os,
            library_name: arguments.locator_name,
            artifact_path: arguments
                .artifact
                .ok_or_else(|| "--artifact is required for Android".to_owned())?,
        },
        RegistryPlatform::Ios => EmbeddedRegistryTarget::AppleFramework {
            target: arguments.target,
            architecture: arguments.architecture,
            minimum_os: arguments.minimum_os,
            framework_name: arguments.locator_name,
            bundle_identifier: arguments
                .bundle_identifier
                .ok_or_else(|| "--bundle-identifier is required for iOS".to_owned())?,
        },
    };
    let fragment = EmbeddedRegistryFragment::generate(&canonical, &target)
        .map_err(|error| error.to_string())?;
    emit_bytes(fragment.canonical_json(), arguments.output.as_deref())
}

fn package_plugin(arguments: PluginPackageArgs) -> CliResult<()> {
    validate_path_for_json_report(&arguments.output, "plugin package output path")?;
    let project = read_project_manifest(&arguments.manifest)?;
    let key_bytes = read_bounded_regular_file(
        &arguments.signing_key,
        MAX_PLUGIN_KEY_FILE_BYTES,
        "plugin signing key",
    )?;
    let signing_key = PluginSigningKey::from_json(&key_bytes).map_err(|error| error.to_string())?;
    let base_directory = arguments
        .manifest
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    let report =
        build_signed_plugin_package(&project, base_directory, &signing_key, &arguments.output)
            .map_err(|error| error.to_string())?;
    emit_json_result(&report)
}

fn verify_plugin(arguments: PluginVerifyArgs) -> CliResult<()> {
    validate_path_for_json_report(&arguments.package, "plugin package path")?;
    let trust_store = read_trust_store(&arguments.trust_store)?;
    let verified = verify_signed_plugin_package(&arguments.package, &trust_store)
        .map_err(|error| error.to_string())?;
    emit_json_result(verified.verification())
}

fn install_plugin(arguments: PluginInstallArgs) -> CliResult<()> {
    validate_path_for_json_report(&arguments.root, "plugin install root")?;
    let trust_store = read_trust_store(&arguments.trust_store)?;
    let verified = verify_signed_plugin_package(&arguments.package, &trust_store)
        .map_err(|error| error.to_string())?;
    let report = install_verified_plugin_package(&verified, &arguments.root)
        .map_err(|error| error.to_string())?;
    emit_json_result(&report)
}

fn uninstall_installed_plugin(arguments: PluginUninstallArgs) -> CliResult<()> {
    let removed = uninstall_plugin(&arguments.root, &arguments.plugin_id, &arguments.version)
        .map_err(|error| error.to_string())?;
    emit_json_result(&serde_json::json!({
        "plugin_id": arguments.plugin_id,
        "version": arguments.version,
        "removed": removed,
    }))
}

fn list_plugins(arguments: PluginListArgs) -> CliResult<()> {
    validate_path_for_json_report(&arguments.root, "plugin install root")?;
    let plugins = list_installed_plugins(&arguments.root).map_err(|error| error.to_string())?;
    emit_json_result(&plugins)
}

fn generate_plugin_key(arguments: PluginKeyGenerateArgs) -> CliResult<()> {
    validate_path_for_json_report(&arguments.signing_key_output, "signing key output path")?;
    validate_path_for_json_report(&arguments.trust_store_output, "trust store output path")?;
    if arguments.signing_key_output == arguments.trust_store_output {
        return Err(CliError::manifest_or_package(
            "signing key and trust store outputs must be different paths",
        ));
    }
    let key = PluginSigningKey::generate(arguments.publisher).map_err(|error| error.to_string())?;
    let mut trust_store = if arguments.trust_store_output.exists() {
        let bytes = read_bounded_regular_file(
            &arguments.trust_store_output,
            MAX_PLUGIN_TRUST_STORE_BYTES,
            "plugin trust store",
        )?;
        PluginTrustStore::from_json(&bytes).map_err(|error| error.to_string())?
    } else {
        PluginTrustStore::empty()
    };
    trust_store
        .insert(key.public_key())
        .map_err(|error| error.to_string())?;
    let mut key_bytes = key.to_json().map_err(|error| error.to_string())?;
    key_bytes.push(b'\n');
    write_new_sensitive_file(&arguments.signing_key_output, &key_bytes)?;
    let mut trust_bytes = trust_store.to_json().map_err(|error| error.to_string())?;
    trust_bytes.push(b'\n');
    emit_bytes(&trust_bytes, Some(&arguments.trust_store_output))?;
    emit_json_result(&serde_json::json!({
        "publisher": key.publisher(),
        "keyId": key.key_id(),
        "signingKey": arguments.signing_key_output,
        "trustStore": arguments.trust_store_output,
    }))
}

fn validate_path_for_json_report(path: &Path, label: &str) -> CliResult<()> {
    path.to_str().map(|_| ()).ok_or_else(|| {
        CliError::manifest_or_package(format!(
            "{label} must be valid UTF-8 because it is included in JSON output"
        ))
    })
}

fn validate_regular_file_for_json(path: &Path, label: &str) -> CliResult<()> {
    validate_path_for_json_report(path, label)?;
    let metadata = fs::symlink_metadata(path).map_err(|error| {
        CliError::manifest_or_package(format!(
            "failed to inspect {label} '{}': {error}",
            path.display()
        ))
    })?;
    if !metadata.file_type().is_file() {
        return Err(CliError::manifest_or_package(format!(
            "{label} '{}' is not a regular non-symlink file",
            path.display()
        )));
    }
    Ok(())
}

fn emit_json_result<T: serde::Serialize>(value: &T) -> CliResult<()> {
    let mut bytes = serde_json::to_vec(value).map_err(|error| error.to_string())?;
    bytes.push(b'\n');
    emit_bytes(&bytes, None)
}

fn emit_bytes(bytes: &[u8], output: Option<&Path>) -> CliResult<()> {
    let Some(output) = output else {
        return io::stdout()
            .lock()
            .write_all(bytes)
            .map_err(|error| CliError::manifest_or_package(error.to_string()));
    };
    let parent = output
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    if !parent.is_dir() {
        return Err(CliError::manifest_or_package(format!(
            "output directory `{}` is not a directory",
            parent.display()
        )));
    }
    let mut temporary = tempfile::NamedTempFile::new_in(parent)
        .map_err(|error| format!("failed to create output staging file: {error}"))?;
    temporary
        .write_all(bytes)
        .and_then(|()| temporary.as_file().sync_all())
        .map_err(|error| format!("failed to write output staging file: {error}"))?;
    temporary.persist(output).map_err(|error| {
        format!(
            "failed to atomically replace output `{}`: {}",
            output.display(),
            error.error
        )
    })?;
    Ok(())
}

fn write_new_sensitive_file(path: &Path, bytes: &[u8]) -> CliResult<()> {
    let parent = path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."));
    if !parent.is_dir() {
        return Err(CliError::manifest_or_package(format!(
            "signing key output directory '{}' is not a directory",
            parent.display()
        )));
    }
    let mut temporary = tempfile::NamedTempFile::new_in(parent)
        .map_err(|error| format!("failed to create signing key staging file: {error}"))?;
    temporary
        .write_all(bytes)
        .and_then(|()| temporary.as_file().sync_all())
        .map_err(|error| format!("failed to write signing key staging file: {error}"))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        temporary
            .as_file()
            .set_permissions(fs::Permissions::from_mode(0o600))
            .map_err(|error| format!("failed to restrict signing key permissions: {error}"))?;
    }
    temporary.persist_noclobber(path).map_err(|error| {
        format!(
            "refusing to replace signing key '{}': {}",
            path.display(),
            error.error
        )
    })?;
    Ok(())
}

fn read_project_manifest(path: &Path) -> CliResult<PluginProjectManifest> {
    let bytes = read_bounded_regular_file(path, MAX_PLUGIN_MANIFEST_BYTES, "plugin manifest")?;
    let source = String::from_utf8(bytes)
        .map_err(|error| format!("plugin manifest '{}' is not UTF-8: {error}", path.display()))?;
    PluginProjectManifest::from_toml(&source)
        .map_err(|error| CliError::manifest_or_package(error.to_string()))
}

fn read_trust_store(path: &Path) -> CliResult<PluginTrustStore> {
    let bytes =
        read_bounded_regular_file(path, MAX_PLUGIN_TRUST_STORE_BYTES, "plugin trust store")?;
    PluginTrustStore::from_json(&bytes)
        .map_err(|error| CliError::manifest_or_package(error.to_string()))
}

fn read_bounded_regular_file(path: &Path, maximum_bytes: usize, label: &str) -> CliResult<Vec<u8>> {
    let metadata = fs::symlink_metadata(path)
        .map_err(|error| format!("failed to inspect {label} '{}': {error}", path.display()))?;
    if !metadata.file_type().is_file() {
        return Err(CliError::manifest_or_package(format!(
            "{label} '{}' is not a regular non-symlink file",
            path.display()
        )));
    }
    if metadata.len() > maximum_bytes as u64 {
        return Err(CliError::manifest_or_package(format!(
            "{label} '{}' exceeds {maximum_bytes} bytes",
            path.display()
        )));
    }
    let file = File::open(path)
        .map_err(|error| format!("failed to open {label} '{}': {error}", path.display()))?;
    let mut bytes = Vec::with_capacity(metadata.len() as usize);
    file.take((maximum_bytes + 1) as u64)
        .read_to_end(&mut bytes)
        .map_err(|error| format!("failed to read {label} '{}': {error}", path.display()))?;
    if bytes.len() > maximum_bytes {
        return Err(CliError::manifest_or_package(format!(
            "{label} '{}' exceeds {maximum_bytes} bytes",
            path.display()
        )));
    }
    Ok(bytes)
}

fn read_descriptor(path: &Path) -> CliResult<PluginDescriptor> {
    let project = read_project_manifest(path)?;
    Ok(project.descriptor().clone())
}