gunnar-common 3.0.0

Shared command line, logging, and build identity for the gunnar binaries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
//! The `gunnar` command line, in clap derive.
//!
//! Both halves live in one enum with `#[cfg]` on the variants, so
//! `--no-default-features --features server` produces a binary whose `--help`
//! genuinely has no `clone` in it, rather than one that offers a verb and then
//! fails at runtime.

// Every use is behind a half's feature: with none on, nothing names it (OX-GUNBR 2026-10-28).
#[cfg(any(
    feature = "server",
    feature = "client",
    feature = "control",
    feature = "systemd"
))]
use std::path::PathBuf;

#[cfg(feature = "server")]
use clap::ArgGroup;
#[cfg(any(feature = "server", feature = "control"))]
use clap::ValueEnum;
use clap::{Parser, Subcommand};

/// gunnar — a git server and a git client, in Rust, over SSH and smart HTTP.
#[derive(Debug, Parser)]
#[command(
    name = "gunnar",
    // Not the bare crate version. `gunnar 0.1.0` names a manifest field, not a
    // build — and on 2026-08-04/05 several benchmark runs had to identify the
    // binary under test by file size and mtime because nothing on it said which
    // commit it was; one silently measured a ten-hour-old build. The git
    // description and build date come from `build.rs`, which degrades to
    // `unknown` rather than failing when there is no `.git`.
    version = concat!(
        env!("CARGO_PKG_VERSION"),
        " (",
        env!("GUNNAR_BUILD_REF"),
        ", built ",
        env!("GUNNAR_BUILD_DATE"),
        ")"
    ),
    about = "a git server and a git client, in Rust, over SSH and smart HTTP",
    long_about = "gunnar serves git over SSH (publickey auth, no shell) and, when built with \
                  `--features http` and started with `--http-bind`, over smart HTTP. It \
                  controls itself over gRPC. The client half is a normal git client.\n\n\
                  Two git transports, one implementation: smart HTTP carries the same \
                  pkt-line conversation SSH carries, through the same authorisation check \
                  against the same key table and the same ACL, and an access token is the \
                  HTTP credential where a public key is the SSH one. What is refused is \
                  refused on both.\n\n\
                  What gunnar does NOT serve: git:// ever, being unauthenticated by \
                  construction; the dumb HTTP protocol, which is refused by name; and no \
                  git or ssh subprocess anywhere in the server, on any transport."
)]
pub struct Cli {
    /// Log at `debug` rather than `info`. `RUST_LOG` still wins.
    #[arg(long, short = 'v', global = true)]
    pub verbose: bool,

    /// Where the server keeps its control repository and its repositories.
    #[cfg(feature = "server")]
    #[arg(
        long,
        global = true,
        env = "GUNNAR_DATA_ROOT",
        default_value_os_t = default_data_root(),
        value_name = "DIR"
    )]
    pub data_root: PathBuf,

    #[command(subcommand)]
    pub command: Command,
}

/// `$GUNNAR_DATA_ROOT`, else `$HOME/.local/share/gunnar`, else `./gunnar-data`.
#[cfg(feature = "server")]
pub fn default_data_root() -> PathBuf {
    match std::env::var_os("HOME") {
        Some(home) if !home.is_empty() => PathBuf::from(home).join(".local/share/gunnar"),
        _ => PathBuf::from("gunnar-data"),
    }
}

#[derive(Debug, Subcommand)]
pub enum Command {
    // ── server ─────────────────────────────────────────────────────────────
    /// Start the listeners: SSH for git, gRPC for the control plane, and smart
    /// HTTP for git as well when `--http-bind` asks for it.
    // Boxed: `ServeArgs` is several times the size of every other verb.
    #[cfg(feature = "server")]
    Serve(Box<ServeArgs>),

    /// Namespaces: the `<ns>` in `git@host:<ns>/<repo>.git`.
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Namespace(NamespaceCommand),

    /// Repositories.
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Repo(RepoCommand),

    /// Principals. Keys and grants hang off these.
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Principal(PrincipalCommand),

    /// **The server's own certificate issuer** — identity from a certificate.
    ///
    /// With one of these, creating a user *is* issuing their certificate:
    /// there is no external PKI to run and no second system to keep in step.
    ///
    /// Present in a CONTROL-only build too, where it carries exactly one verb:
    /// `issuer show --at <addr>`. That is not a convenience. `Pki::read_only`
    /// exists so this read "works on a client-shaped binary", and the box
    /// whose CA anyone actually needs to check is the appliance — which has no
    /// shell, so the asking is always done from somewhere else.
    #[cfg(any(feature = "server", feature = "control"))]
    #[command(subcommand)]
    Issuer(IssuerCommand),

    /// Public keys.
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Key(KeyCommand),

    /// Mint and revoke the access tokens smart HTTP authenticates with.
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Token(TokenCommand),

    /// **The transparency log** over the push attestations.
    ///
    /// The attestation log is append-only by discipline; these verbs are what
    /// make it append-only by evidence. `head` signs what the log currently
    /// holds, `audit` checks every signed head against the records on disk, and
    /// `prove` hands out the inclusion proof a client checks offline.
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Attest(AttestCommand),

    /// **Walk the chain backwards from a line of source.**
    ///
    /// Which commit wrote the line, whether that commit is signed by a key this
    /// server knows, which push landed it, and whether that push sits in the
    /// transparency log under a signed tree head.
    ///
    /// Every link is reported as proven, broken or **unproven**, and the three
    /// are different: an unsigned commit is not a failed signature, and a push
    /// with no attestation is not a push that was refused. A chain with an
    /// unproven link is INCOMPLETE, never green.
    #[cfg(feature = "server")]
    Verify(VerifyArgs),

    /// **Who wrote each line of a file** (`verify --line` for the whole file).
    ///
    /// For every line of `<path>` at a revision, the commit that last touched
    /// it and that commit's author — the same line→commit attribution `verify`
    /// closes as link 1, done once per line instead of once for a single line.
    #[cfg(feature = "server")]
    Blame(BlameArgs),

    /// **Find a literal string** across the latest revision of a repository.
    ///
    /// Walks the tree at a ref and scans each text file, returning `path:line`
    /// matches. Bounded by a file-size and a match ceiling; it is a live walk,
    /// not a persistent index.
    #[cfg(feature = "server")]
    Search(SearchArgs),

    /// **Build provenance**: record what was built and from what (roadmap
    /// phase 3, links 5–6).
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Build(BuildCommand),

    /// **The forge**: issues, reviews and merges as signed events (roadmap
    /// phase 1).
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Forge(ForgeCommand),

    /// **The artifact registry** (roadmap phase 4).
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Registry(RegistryCommand),

    /// Give a principal access.
    #[cfg(feature = "server")]
    Grant(GrantArgs),

    /// Take a principal's access away.
    #[cfg(feature = "server")]
    Revoke(RevokeArgs),

    /// Repack a repository's objects.
    #[cfg(feature = "server")]
    Gc(GcArgs),

    /// Read a repository's reference history, and optionally seal it.
    #[cfg(feature = "server")]
    Reflog(ReflogArgs),

    /// WireGuard identity: mint the keypair an appliance is seeded with.
    #[cfg(feature = "server")]
    #[command(subcommand)]
    Wg(WgCommand),

    // ── client ─────────────────────────────────────────────────────────────
    /// Clone a repository over SSH into a working tree.
    #[cfg(feature = "client")]
    Clone(CloneArgs),

    /// Fetch from an SSH remote into an existing repository.
    #[cfg(feature = "client")]
    Fetch(FetchArgs),

    /// List the references an SSH remote advertises, without cloning it.
    ///
    /// The cheapest way to ask whether a remote is reachable, whether the key
    /// authenticates, and whether the repository holds what you expect. Prints
    /// `git ls-remote`'s lines — `<oid>\t<ref>`, `HEAD` first, an annotated tag
    /// followed by its peeled `^{}` line — because scripts parse them.
    #[cfg(feature = "client")]
    #[command(name = "ls-remote")]
    LsRemote(LsRemoteArgs),

    /// Push to an SSH remote (send-pack, implemented here; gix has none).
    #[cfg(feature = "client")]
    Push(PushArgs),

    /// Pull-mirror a remote repository.
    #[cfg(feature = "client")]
    #[command(subcommand)]
    Mirror(MirrorCommand),

    /// Encrypted repositories: the server holds ciphertext only, and only the
    /// members' SSH keys open it.
    ///
    /// Each repository has one key ring, wrapped to every member's SSH PUBLIC
    /// key (`ssh-ed25519`, `ssh-rsa`) in `.gunnar-crypt/keys`. git's clean and
    /// smudge filter seal and open file content on this machine; the server
    /// never sees a key. File names, commit messages, sizes and the shape of
    /// history stay visible (Level 1). See `.nornir/encrypted-repos.md`.
    #[cfg(feature = "client")]
    #[command(subcommand)]
    Crypt(CryptCommand),

    /// **A repository's settings on a forge** (owner, 2026-10-14): show it,
    /// make it public or private, or change its default branch — over the
    /// forge's SSH door, signed in with your SSH key, the way git and `crypt`
    /// reach an installed Gunnar. The server decides who may (its own rules:
    /// the account admin for visibility, a repository admin for the branch).
    ///
    /// `gunnar settings nordisk/knut`,
    /// `gunnar settings nordisk/knut --visibility public`,
    /// `gunnar settings nordisk/knut --default-branch main`.
    #[cfg(feature = "client")]
    Settings(SettingsArgs),

    /// **Create an empty repository on a forge** in the object format you
    /// choose (sha256 unless `--sha1`), over the forge's SSH door: a repository
    /// made by a first push can only be sha1. `gunnar push` does this by itself
    /// for a sha256 repository whose remote does not exist yet.
    #[cfg(feature = "client")]
    Create(CreateArgs),

    /// Show the commit log.
    #[cfg(feature = "client")]
    Log(LogArgs),

    /// Show the working tree status.
    #[cfg(feature = "client")]
    Status(RepoArgs),

    /// Commit everything in the working tree.
    #[cfg(feature = "client")]
    Commit(CommitArgs),

    /// Branches.
    #[cfg(feature = "client")]
    Branch(BranchArgs),

    /// Tags.
    #[cfg(feature = "client")]
    Tag(TagArgs),

    // ── the control plane, over the wire ───────────────────────────────────
    /// Configure a RUNNING gunnar over its gRPC control plane.
    ///
    /// The first call needs no credential at all; every one after it is
    /// authenticated with an ssh key. `gunnar control status` says which of
    /// those a server is in.
    ///
    /// These are the ONLINE verbs. `gunnar principal`, `gunnar key` and
    /// `gunnar grant` write the control repository directly and therefore need
    /// the server to be DOWN; these do the same work against one that is up.
    #[cfg(feature = "control")]
    #[command(subcommand)]
    Control(ControlCommand),

    /// **Log this terminal in with your passkey, through a console.**
    ///
    /// Mints a fresh ed25519 key here, shows a code, and waits: open the
    /// console's `/login/device` page, type the code and touch your passkey.
    /// Gunnar enrols THIS key on you, expiring (at most a day); its private
    /// half never leaves this machine. Use it with `-i <path>` (printed).
    /// The other CLI way in is a FIDO2 `sk-ssh-ed25519` key in ssh-agent.
    #[cfg(feature = "control")]
    Login(LoginArgs),

    // ── systemd ────────────────────────────────────────────────────────────
    /// Manage gunnar as a systemd service. Off unless built with `--features systemd`.
    #[cfg(feature = "systemd")]
    #[command(subcommand)]
    Service(ServiceCommand),
}

/// `gunnar login`, see [`Command::Login`].
#[cfg(feature = "control")]
#[derive(Debug, clap::Args)]
pub struct LoginArgs {
    /// The console's address, e.g. `https://console.example.com`.
    pub console: String,
    /// How long the key lives, in hours (the console allows at most 24).
    #[arg(long, default_value_t = 12)]
    pub ttl: u64,
    /// What the approval page calls this terminal (default: `user@host`).
    #[arg(long)]
    pub label: Option<String>,
    /// Where the key is written (default: `~/.config/gunnar/login`).
    #[arg(long)]
    pub dir: Option<PathBuf>,
}

// ───────────────────────────────────────────────────────────────────────────
// server
// ───────────────────────────────────────────────────────────────────────────

/// `--anonymous`, see [`ServeArgs::anonymous`].
#[cfg(feature = "server")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum AnonymousArg {
    /// Serve anonymous reads of public repositories on this box.
    Allow,
    /// Refuse them, naming `--browse-host` when given.
    Refuse,
}

/// `gunnar serve --role`.
#[cfg(feature = "server")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ServeRole {
    /// Serves git; frames every transaction for its twin.
    Primary,
    /// Serves no git; holds the primary's log.
    Twin,
}

/// `gunnar serve`.
#[cfg(feature = "server")]
#[derive(Debug, clap::Args, Clone)]
pub struct ServeArgs {
    /// Where the SSH listener binds. Publickey auth, so binding publicly is the
    /// intended configuration.
    #[arg(long, default_value = "0.0.0.0:2222", value_name = "ADDR")]
    pub ssh_bind: std::net::SocketAddr,

    /// Where the gRPC control plane binds — `<addr>:<port>`, or
    /// `<interface>:<port>` for an address learned at boot.
    ///
    /// **Loopback by default and it should stay there.** gRPC now requires an
    /// `sshsig` credential from a key in gunnar's identity table and a grant from
    /// the same ACL as SSH (the allow-all hole was closed 2026-08-03), but the
    /// loopback default is defence in depth and costs nothing: every real
    /// deployment reaches this port over an SSH tunnel or from the same host
    /// anyway.
    ///
    /// **`0.0.0.0` is not the way to reach it from another host.** A cloud
    /// appliance has a PUBLIC interface and a private one, and a wildcard
    /// binds both — which is how this control plane ended up answering
    /// `repo list` and `repo create` to an uncredentialled caller on the open
    /// internet (measured 2026-08-31). Name the private interface instead:
    /// `--grpc-bind eth1:50051`. Its address is not knowable when the medium
    /// is mastered — DHCP decides it, per box, per lease — and the interface
    /// is. See [`gunnar_common::bindspec::BindSpec`].
    #[arg(
        long,
        default_value = "127.0.0.1:50051",
        value_name = "ADDR|IFACE:PORT"
    )]
    pub grpc_bind: crate::bindspec::BindSpec,

    /// An OpenSSH public key line, or `@<path>` to read one from a file, to
    /// install as the bootstrap admin when the identity table is empty.
    ///
    /// Without it, an empty table makes gunnar **refuse to serve** rather than
    /// start unreachable.
    #[arg(long, value_name = "KEY|@FILE")]
    pub admin_key: Option<String>,

    /// **A key this box may take a `Bootstrap.Restore` from**: an OpenSSH
    /// public key line, or `@<path>` to read one. Repeat the flag for more;
    /// `GUNNAR_RESTORE_PUBKEY` takes several separated by `,`.
    ///
    /// A restore stream decides a fresh box's KEK, its admin, its host key and
    /// its issuer, and a fresh box has no identity table to check its sender
    /// against, so it takes one only under a credential signed by a key it was
    /// FED: this flag, or — on an installer-fed box — the fed `admin_pubkey`
    /// and admin principals. A box with neither refuses every restore by name
    /// (`restore-no-key`).
    #[arg(
        long = "restore-pubkey",
        value_name = "KEY|@FILE",
        env = "GUNNAR_RESTORE_PUBKEY",
        value_delimiter = ','
    )]
    pub restore_pubkeys: Vec<String>,

    /// Do not start the gRPC listener. The SSH listener still runs.
    #[arg(long)]
    pub no_grpc: bool,

    /// **WireGuard-only** (owner, 2026-10-04): every box-to-box connection
    /// runs over the estate's overlay. The control plane's bound address (the
    /// utility network, `eth1:50051`) serves nothing; the control plane and the
    /// replication listener answer only on the tunnel's address, and SSH drops
    /// a connection that arrives at the utility address. A plain-IP connection
    /// between two boxes is refused.
    #[arg(long = "wg-only", env = "GUNNAR_WG_ONLY")]
    pub wg_only: bool,

    /// **What this box is.** `primary` (the default) serves git and frames
    /// every transaction. `twin` serves NO git from its first boot (the forge
    /// listener is bound to loopback only), waits for `Bootstrap.BecomeTwin`,
    /// and then follows its primary's log (`.nornir/twin-transaction-log.md`).
    /// **A twin is not a different medium.** Until 2026-09-17 a `gunnar-twin`
    /// ISO welded `--role twin` into its `korp.args=`, which made the role part
    /// of a medium's identity and — because that medium was cloned from the
    /// KEYLESS row — made gunnar.rs's twin an UNMETERED binary that would have
    /// served every suspended tenant the moment it was promoted. Since 2026-09-22
    /// the medium does not say what a box is at all (no `role` install parameter,
    /// no `GUNNAR_ROLE` env read): every box installs as a fresh appliance and a
    /// twin is made one over the wire by `Bootstrap.BecomeTwin`, which writes
    /// `twin.json` — the durable role `stores.is_twin()` reads. This argv flag
    /// stays for a directly started server (tests, benches); an installed box
    /// never passes it.
    #[arg(long, value_enum, default_value_t = ServeRole::Primary)]
    pub role: ServeRole,

    /// Refuse unauthenticated callers entirely, even for repositories marked
    /// `--public`.
    ///
    /// By default a public repository can be cloned with no key at all, over
    /// `ssh://anonymous@host/ns/repo.git`. This closes that door at the
    /// listener, before any repository is resolved, for an appliance that has
    /// to be able to state it has never served a stranger. It is **not** what
    /// protects private repositories: those are protected by the ACL and are
    /// unreachable anonymously either way.
    #[arg(long)]
    pub no_anonymous: bool,

    /// **Where anonymous reads are served** — the browse replica. `allow`
    /// (the default) serves a stranger's clone of a public repository here.
    /// `refuse` sends every anonymous request away with a line that names the
    /// browse replica (`--browse-host`) it is served by: strangers cost CPU and
    /// bandwidth on the box that also takes the authenticated writes, and the
    /// browse replica is where that cost belongs. Unlike `--no-anonymous`, which
    /// merely fails the stranger's authentication, `refuse` tells them where
    /// to go. A box whose role is BROWSE serves anonymous reads whatever this
    /// says — it is the box the knob points at.
    #[arg(long, value_enum, default_value_t = AnonymousArg::Allow, env = "GUNNAR_ANONYMOUS")]
    pub anonymous: AnonymousArg,

    /// The browse replica's `host[:port]`, named in the `--anonymous refuse`
    /// line (`clone <repo> from <host>`). Optional: without it the refusal
    /// says only that anonymous reads are not served here.
    #[arg(long, value_name = "HOST[:PORT]", env = "GUNNAR_BROWSE_HOST")]
    pub browse_host: Option<String>,

    /// **How much of the store root's disk must stay free** before a push or
    /// a `Repos.Create` is refused — the community plan gate, the "free lunch"
    /// (ruled 2026-09-04). Terms separated by commas: a percentage (`5%`)
    /// and/or a byte count (`2GiB`, `500M`, `4096`); the LARGER of the two is
    /// the floor. The default keeps 5 % or 2 GiB, whichever is more: 5 % is the
    /// reserve the box needs to keep operating (gc scratch, control-store
    /// commits, `replication.json` rewrites) and mirrors ext4's own reserved
    /// blocks; 2 GiB is the absolute floor for a small disk where 5 % is less
    /// than one pack. A push under the floor is refused BEFORE any pack byte,
    /// naming the free bytes and the floor; reads are never refused. Measured
    /// with `statvfs`, no `df`. `0%,0` is refused by name: a gate that can never
    /// refuse is not a gate.
    #[arg(
        long,
        value_name = "SPEC",
        default_value = "5%,2GiB",
        env = "GUNNAR_DISK_FLOOR"
    )]
    pub disk_floor: String,
    /// **Do not enumerate a push's object ids for the attestation.**
    ///
    /// Enumeration waits for the indexer to absorb the pack, which is a drain
    /// on the push path, so an operator who does not need the ids in the record
    /// can decline them. Declining does NOT restore silence: the attestation
    /// then carries the reason the set is absent
    /// (`PushAttestation.new_object_oids_unknown`), because an absence that
    /// renders as an empty list is the defect this flag exists beside, not the
    /// behaviour it restores.
    ///
    /// Named in the negative on purpose: the complete attestation is what you
    /// get by forgetting, and the cheap one is what you opt into. A push that a
    /// policy gate reads is enumerated either way — the gate needs the set.
    #[arg(long)]
    pub no_attest_objects: bool,

    /// How many git transfers may be in flight across the whole server (the
    /// admission gate). Default: DERIVED from the box — cores x 16, capped by
    /// the descriptors the handle cache has not spoken for, floor 8, ceiling
    /// 256.
    ///
    /// The server says what it derived, and what from, in one INFO row at
    /// start: `transfers 64 · open repos 204 · git memory 3.9G (cores 4,
    /// fds 1048576, MemAvailable 7.8G)`. Setting this replaces the derivation
    /// exactly — the number is never raised and never lowered.
    #[arg(long, value_name = "N", env = "GUNNAR_MAX_TRANSFERS")]
    pub max_concurrent_transfers: Option<usize>,
    /// The memory budget for git operations in flight, in bytes — the
    /// admission gate's second budget. Default: half of `MemAvailable` at
    /// start.
    ///
    /// The ledger charges each transfer a small entry cost and then what its
    /// pack actually moves, so this is a budget rather than a second
    /// concurrency cap. It used to be a compiled-in 8 GiB against a flat
    /// 320 MiB per push, which made "25 concurrent pushes" the real ceiling on
    /// every box regardless of its RAM.
    #[arg(long, value_name = "BYTES", env = "GUNNAR_GIT_MEMORY_BYTES")]
    pub git_memory_bytes: Option<u64>,

    /// How long a transfer may WAIT for a slot before it is refused, in
    /// milliseconds. Default 2000; `0` refuses on the spot.
    ///
    /// A refused client reconnects, and a reconnect is a whole SSH handshake —
    /// more than the wait costs. The wait is bounded, counted, and is what the
    /// delay governor is driven by.
    #[arg(long, value_name = "MS", env = "GUNNAR_ADMISSION_WAIT_MS")]
    pub admission_wait_ms: Option<u64>,

    /// What one identity is **guaranteed** at once, and its share of a
    /// contended server. Default 32.
    ///
    /// A floor, not a wall: on a server that is not near saturation a single
    /// identity may use every slot `--max-concurrent-transfers` allows. Once
    /// the server is contended each active identity gets an equal share of it,
    /// never below this number.
    #[arg(long, value_name = "N")]
    pub max_transfers_per_principal: Option<usize>,

    /// How many git reads are served **without a key** at once.
    /// Default 5.
    ///
    /// The companion to `--anonymous`: that decides whether the door is open,
    /// this decides how wide. Unlike `--max-transfers-per-principal` it is a
    /// wall and not a floor — it binds on an idle server, because the caller it
    /// bounds cannot be named, revoked or telephoned, and "the box was quiet so
    /// I let a stranger have all of it" is not a trade an operator would make
    /// deliberately.
    ///
    /// Raise it on a box whose *purpose* is public serving (a browse replica);
    /// `0` refuses every anonymous read while leaving the door itself open,
    /// which is the arm to use when you want the refusal to say so rather than
    /// have `--anonymous refuse` deny the repository exists.
    #[arg(long, value_name = "N", env = "GUNNAR_MAX_ANONYMOUS_TRANSFERS")]
    pub max_anonymous_transfers: Option<usize>,

    /// **The usage share's budget**: bytes (in + out) a namespace may move per
    /// window at the ordinary per-principal share. Past it the namespace is
    /// served at the ANONYMOUS ceiling (`--max-anonymous-transfers`) and
    /// refused fast with its own reason — never queued. `none` turns the
    /// share off (PassThrough: admission decides as a build without it).
    /// SI or IEC sizes: `100 GB`, `5 GiB`, or bytes. Default 100 GB.
    ///
    /// Only in a build with the `admit-share` feature.
    #[cfg(feature = "admit-share")]
    #[arg(long, value_name = "SIZE|none", env = "GUNNAR_ADMIT_LIMIT")]
    pub admit_limit: Option<String>,

    /// The usage share's rolling window, in UTC days, today included.
    /// Default 30.
    ///
    /// Only in a build with the `admit-share` feature.
    #[cfg(feature = "admit-share")]
    #[arg(long, value_name = "DAYS", env = "GUNNAR_ADMIT_WINDOW_DAYS")]
    pub admit_window_days: Option<u32>,

    /// The largest object `Refs.ReadObject` will read, in bytes.
    /// Default 67108864 (64 MiB); `0` means no ceiling.
    ///
    /// Reading any part of an object costs the WHOLE object in memory — a
    /// prefix of a delta-encoded object needs its entire base chain — so
    /// `max_bytes` bounds the answer and not the work. This bounds the work.
    /// The default is a 512 MiB budget divided by the 8 control-plane workers
    /// that can be inflating at once; raise it on a box whose repositories hold
    /// large blobs and whose control port is trusted, and note that the git
    /// clone path is untouched by this and streams either way.
    #[arg(long, value_name = "BYTES")]
    pub max_object_bytes: Option<u64>,

    /// **The metered appliance's key**: monetize-server's Ed25519 public key,
    /// either spelled inline as its 64 hexadecimal characters or as the path of
    /// a file holding it (32 raw bytes, 64 hex characters, or
    /// `ed25519:<base64>`). Every `Entitlement.Set` is verified against it
    /// before a plan moves. Only a `metered` build honours it; any other build
    /// REFUSES to start when it is set, by name — an operator who configured a
    /// metered appliance on a binary that cannot meter must find out at boot,
    /// not from a tenant who was never suspended.
    ///
    /// **This flag is NOT compiled out of the open build, and that is the
    /// point.** It is the one piece of the monetize seam an open gunnar must
    /// still RECOGNISE, because a flag clap has never heard of is refused as
    /// "unexpected argument" — a parser complaint that says nothing about why
    /// this binary cannot do what was asked. Kept, the open build answers with
    /// the sentence in `gunnar_server::dispatch` instead: this build contains
    /// no entitlement code at all and would serve every namespace Free.
    ///
    /// **Which of the two it is, is decided by SHAPE — there is no second
    /// flag.** A value with no `/` in it that is either all hexadecimal or
    /// exactly 64 characters long is the KEY; anything else is a PATH. So
    /// `/data/monetize.pub` and `monetize.pub` are files, as they always were,
    /// and `43cb…8428` is the key itself. A near-miss (63 characters, or a
    /// typo that is not a hex digit) is refused as a malformed key naming what
    /// was wrong, rather than silently becoming a filename nothing will find.
    ///
    /// Inline is what an appliance actually needs. The installer only stages
    /// files onto `/data` under `korp.reinstall=wipe`, the ESP is read-only at
    /// runtime, and so on a keep-upgrade the kernel command line is the only
    /// writable channel into a booting gunnar — a path there names a file
    /// nothing was allowed to create. An Ed25519 *public* key is safe to carry
    /// that way; a private key never would be.
    #[arg(long, value_name = "HEX_OR_PATH", env = "GUNNAR_MONETIZE_PUBKEY")]
    pub monetize_pubkey: Option<crate::monetize_key::MonetizePubkey>,

    // ── WHY THIS ONE IS COMPILED OUT AND `--monetize-pubkey` IS NOT ────────
    //
    // Kept as a plain comment rather than a doc comment ON PURPOSE: clap turns
    // `///` into `--help`, and the explanation below is for whoever reads this
    // file, not for an operator of the open build — writing it as documentation
    // would reintroduce, in prose, exactly the vocabulary this gate removes.
    //
    // gunnar is the OPEN half of the split: it reports `Usage`, it receives a
    // signed `Entitlement`, and it takes no money ever. The private monetize
    // half is the only thing that knows what a byte is worth. So an open
    // `gunnar-server --help` must not advertise a flag whose whole noun is a
    // payment page — and until this `cfg`, it did, for a field the open binary
    // has no code to honour.
    //
    // `--monetize-pubkey` three declarations up is deliberately NOT gated, and
    // the asymmetry is the argument, not an oversight. That flag's PRESENCE
    // changes what the box would do — meter, or silently serve every namespace
    // Free — so an open build has to recognise it in order to refuse it by
    // name at boot. This flag cannot even be given without it: `requires`
    // sees to that, so an open build handed both stops on the pubkey's
    // sentence either way, and one handed this alone was already going to be
    // refused. Compiling it out therefore costs no refusal that the pubkey's
    // own does not already carry, and buys a `--help` with no money in it.
    //
    // And there is NO DEFAULT, here or at the use site. The fallback used to
    // live in `gunnar_server::dispatch` as Vetra's own commercial URL, which
    // meant anybody building a metered gunnar and forgetting this flag pointed
    // their tenants at somebody else's payment page. A metered build given
    // `--monetize-pubkey` without this now refuses at boot; see
    // `gunnar_server::entitlement::MeteredConfig::load`.
    /// **Where a lapsed tenant goes to restore its plan**, as a template with
    /// `{tenant}` for the namespace (without the placeholder, `/{tenant}` is
    /// appended, so the link always names the tenant). Printed in every
    /// refusal and Grace warning. Requires `--monetize-pubkey`, and a
    /// `metered` build that is given that flag without this one refuses to
    /// start: a page belonging to whoever built the binary is not a default
    /// anybody else's tenants should be sent to.
    #[cfg(feature = "metered")]
    //
    // No clap `requires = "monetize_pubkey"` (2026-09-24): the key may come from the
    // installer's door (`gunnar_server::feed`) instead of this argv, so a one-medium
    // metered box carries the pay page and no key. The same refusal — this flag with
    // no key from EITHER source — is made in `gunnar_server::dispatch`.
    #[arg(long, value_name = "URL", env = "GUNNAR_BILLING_URL")]
    pub billing_url: Option<String>,

    /// **Is monetize VITAL to this box?** Owner ruling 2026-09-22. `true`, the default: stored
    /// entitlement facts that do not verify at boot (a main restored under another monetize key)
    /// raise the `Admin.Health` alarm `entitlement.key_mismatch`, naming the namespaces, and the
    /// box reports status `maintenance` until monetize pushes a fact that verifies. The box
    /// still starts and serves either way, and gunnar never dials monetize. `false`: the same
    /// refusal is only logged.
    #[cfg(feature = "metered")]
    #[arg(long, value_name = "BOOL", env = "GUNNAR_MONETIZE_VITAL", default_value_t = true, action = clap::ArgAction::Set)]
    pub monetize_vital: bool,

    /// Make `--max-transfers-per-principal` an unconditional ceiling.
    ///
    /// For a host where an identity is a *tenant* and the cap is how the
    /// box is shared out. On an appliance — one team, a handful of keys — this only
    /// throttles the owner, which is why it is off by default.
    #[arg(long)]
    pub hard_per_principal_limit: bool,

    /// Serve the **counters** on this address, as Prometheus text.
    ///
    /// Off unless asked for, and there is no default address: nothing binds
    /// until you name one. `curl http://<addr>/metrics` then returns the same
    /// nineteen numbers the `gunnar::metrics` heartbeat writes to the log —
    /// but on demand, at whatever rate you ask, which is the only way
    /// `gunnar_transfers_in_flight` tells a slow transfer from a stuck one
    /// while it is still running.
    ///
    /// **It has no authentication.** The body is nineteen integers about this
    /// process — no repository names, no principals, no references — so it is
    /// not worth a credential, but anyone who can reach the port learns how
    /// busy this server is. Bind it to `127.0.0.1` and let the scraper come
    /// over a tunnel unless you mean otherwise; a non-loopback address is
    /// accepted and logged as a `warn` at start-up.
    #[arg(long, value_name = "ADDR")]
    pub metrics_bind: Option<std::net::SocketAddr>,

    /// **Watch this primary and TAKE OVER if it stops answering** — I11's
    /// passive heartbeat, the standby half of failover.
    ///
    /// Off unless you name an address, and that is the design rather than
    /// caution: naming a new primary is a decision, so a box never makes it
    /// because nobody configured it not to. Give the PRIMARY's control-plane
    /// address; this box probes it every `--watch-probe-ms` and, after
    /// `--watch-promote-after` **consecutive** failures, does to itself exactly
    /// what `gunnar control replication promote` does — persists `role:
    /// primary` and thaws the write freeze. One reachable probe resets the run,
    /// so a flapping link cannot add up to a takeover.
    ///
    /// It does nothing on a box whose role is `primary`: the watch re-reads the
    /// role every tick and stops when this box is not a standby, so putting the
    /// flag on BOTH boxes of a pair is safe and is what one unit file wants.
    ///
    /// **What the probe proves:** a TCP connect to that address, i.e. *"is
    /// something listening"* — not *"is it serving git"*. A primary that is
    /// wedged but still listening reads as alive and this box will NOT promote.
    /// That is the safe direction to be wrong in: the cost is a manual
    /// `replication promote`, where the other way round is two writable boxes.
    ///
    /// **The address still has to move.** Taking over makes this box writable;
    /// it does not repoint the front (DNS / the UpCloud DNAT). That is the one
    /// infrastructure step failover has always had.
    #[arg(long, value_name = "ADDR")]
    pub watch_primary: Option<std::net::SocketAddr>,

    /// Milliseconds between probes of `--watch-primary`. Ignored without it.
    #[arg(long, value_name = "MS", default_value_t = 5_000)]
    pub watch_probe_ms: u64,

    /// Consecutive failed probes before this box promotes itself. Ignored
    /// without `--watch-primary`; a zero is read as one.
    ///
    /// The default is six, which at the default interval is **thirty seconds of
    /// continuous unreachability** — longer than a restart of the primary, and
    /// shorter than a coffee break.
    #[arg(long, value_name = "N", default_value_t = 6)]
    pub watch_promote_after: u32,

    /// Milliseconds one connect attempt may take before it counts as a failure.
    /// Ignored without `--watch-primary`.
    ///
    /// Kept below `--watch-probe-ms` deliberately: a connect that outlives the
    /// interval lets probes overlap, and one dead primary becomes a growing
    /// pile of pending sockets.
    #[arg(long, value_name = "MS", default_value_t = 2_000)]
    pub watch_connect_ms: u64,

    /// **Auto-fix** (5.4 resilience): when this box comes up with its data set
    /// dead or empty while a healthy twin exists, recharge it from the twin by
    /// itself. OFF by default: without it the box only SAYS `data lost; recharge
    /// from twin available`, and an admin's [Recharge from twin] or a signed
    /// guardian order does it. The estate's opt-in, like `--watch-primary`.
    #[arg(long, env = "GUNNAR_REPAIR_AUTO")]
    pub repair_auto: bool,

    /// The OpenSSH private key this box signs repair calls with (reading the
    /// twin's log, `Bootstrap.Restore` into a fresh main, fencing a primary).
    /// Default: this box's twin key, when it has one. A fresh main takes a
    /// restore only from a key it was fed (`--restore-pubkey`).
    #[arg(long, value_name = "PATH", env = "GUNNAR_REPAIR_KEY")]
    pub repair_key: Option<std::path::PathBuf>,

    /// The twin the boot check reviews and recharges from (`host:port` of its
    /// control plane). Default: the twin the installer's re-admit named; a main
    /// that grows also asks the twin in the door's peer list.
    #[arg(long, value_name = "ADDR", env = "GUNNAR_REPAIR_TWIN")]
    pub repair_twin: Option<String>,

    /// **The pull channel**: monetize's `Fleet` endpoint this box reports to and
    /// pulls signed repair orders from (`https://…`). Off when absent. Monetize
    /// never calls into the box; every order is verified under the monetize key.
    #[arg(long, value_name = "URL", env = "GUNNAR_FLEET")]
    pub fleet: Option<String>,

    /// PEM of the CA monetize's `Fleet` certificate is signed by.
    #[arg(long, value_name = "PATH", env = "GUNNAR_FLEET_CA")]
    pub fleet_ca: Option<std::path::PathBuf>,

    /// The estate (monetize instance) this box belongs to. Required with `--fleet`.
    #[arg(long, value_name = "NAME", env = "GUNNAR_FLEET_INSTANCE")]
    pub fleet_instance: Option<String>,

    /// The role this box pulls as (`main` / `twin`). Default: what the box is.
    #[arg(long, value_name = "ROLE", env = "GUNNAR_FLEET_ROLE")]
    pub fleet_role: Option<String>,

    /// The longest pause between two reports, in seconds.
    #[arg(long, value_name = "S", default_value_t = 60)]
    pub fleet_every_s: u64,

    /// Also serve **smart HTTP** on this address.
    ///
    /// Off unless asked for. `git clone http://host/ns/repo.git` then works,
    /// and so does `push`, with an access token as the HTTP Basic password
    /// (`gunnar token add`). The same repositories, the same grants and the
    /// same `--no-anonymous` switch as SSH: this is a second transport, not a
    /// second server.
    #[cfg(feature = "http")]
    #[arg(long, value_name = "ADDR")]
    pub http_bind: Option<std::net::SocketAddr>,

    /// Accept an access token over a **plain** HTTP connection.
    ///
    /// gunnar terminates no TLS. By default it therefore refuses to read a
    /// credential unless a terminator in front of it says the client spoke TLS
    /// (`X-Forwarded-Proto: https`), because a token in an `Authorization`
    /// header on a cleartext connection is a password on the wire. This turns
    /// that off, for loopback, a test, or a link you vouch for.
    ///
    /// **Anonymous read is unaffected either way**: it presents no credential.
    #[cfg(feature = "http")]
    #[arg(long)]
    pub http_allow_cleartext_credentials: bool,

    /// Terminate **TLS on the smart-HTTP listener itself**, with a certificate
    /// gunnar mints from its own issuer at start — the single-executable
    /// deployment: no proxy, no PEM files, `git clone https://host/ns/repo.git`
    /// against one binary. Clients pin the issuer (`gunnar issuer show --pem`)
    /// exactly as they do for the client certificates it already mints.
    ///
    /// ALPN offers HTTP/2 then HTTP/1.1, so a client that multiplexes gets to.
    /// Mutually exclusive with `--http-tls-cert`/`--http-tls-key`, which is the
    /// bring-your-own-certificate form of the same listener.
    #[cfg(feature = "http")]
    #[arg(long, conflicts_with_all = ["http_tls_cert", "http_tls_key"])]
    pub http_tls_self: bool,

    /// Terminate TLS on the smart-HTTP listener with this certificate chain
    /// (PEM, leaf first). Needs `--http-tls-key`.
    #[cfg(feature = "http")]
    #[arg(long, value_name = "PEM", requires = "http_tls_key")]
    pub http_tls_cert: Option<std::path::PathBuf>,

    /// The private key for `--http-tls-cert` (PEM).
    #[cfg(feature = "http")]
    #[arg(long, value_name = "PEM", requires = "http_tls_cert")]
    pub http_tls_key: Option<std::path::PathBuf>,

    /// Require a **client certificate** on the gRPC control plane, and mint the
    /// listener's own identity from this server's issuer at start.
    ///
    /// This is what makes the control plane safe to bind off loopback. Two
    /// things change together: a peer whose certificate this issuer did not
    /// sign never finishes a handshake, and a certificate that does get through
    /// is looked up in the identity key table — so one the issuer signed and nobody
    /// registered is still refused, by the gate, with an audit record.
    ///
    /// Clients get their certificate from `gunnar control bootstrap` (which
    /// writes `<name>.cert.pem`, `<name>.key.pem` and `gunnar-issuer.pem` to
    /// `~/.config/gunnar/<server>/`, or `--out`) and
    /// present it with `--client-cert`/`--client-key`/`--ca`.
    ///
    /// Off by default: turning it on rewrites how every existing client
    /// connects, and a default that breaks a working deployment gets turned
    /// back off everywhere.
    ///
    /// **It cannot be the first thing a server does.** A mutual listener
    /// refuses every peer with no certificate, and on a server that has never
    /// been enrolled there is no certificate anywhere — including for
    /// `Bootstrap.Enroll`, the one RPC served without a credential, which is
    /// behind the same handshake. `gunnar serve` REFUSES to start in that
    /// state and names the enrolment steps. Every other unhappy state is a
    /// warning naming the principals that lose access; run
    /// `gunnar issuer readiness` first to see them before the restart, and
    /// `gunnar control health` afterwards to confirm the flip took.
    #[arg(long)]
    pub grpc_tls_self: bool,

    /// **The mutual replication listener a twin follows this box through.**
    ///
    /// Mutual TLS 1.3 only: a peer must present a certificate this server's
    /// issuer signed (`gunnar control twin certify` gets a twin one). Unset, it is
    /// DERIVED — the `--grpc-bind` address, port + 1, whenever that address is
    /// off loopback — so the appliance serves it with no flag on its medium, and
    /// a loopback control plane serves none.
    #[arg(long, value_name = "ADDR")]
    pub grpc_replication_bind: Option<std::net::SocketAddr>,
    /// **Accepted and ignored since 5.3.3.** The method-blind
    /// `gunnar-sshsig-v1` credential is refused on every listener, always
    /// (GUN-001; OWNER 2026-10-10), so there is nothing left for this to turn
    /// on — and nothing that turns it off. Kept, hidden, only so a unit file
    /// that still passes it starts instead of failing to parse.
    #[arg(long, hide = true)]
    pub grpc_require_bound_credentials: bool,

    /// **A WebAuthn relying party this server answers for**:
    /// `<rp_id>=<origin>[,<origin>…]`, repeatable (stinky row 13, 2026-10-10).
    ///
    /// Without one, a passkey ceremony's `rp_id` and `origin` are the relay's
    /// word, as before. With any, a ceremony for another relying party, or from
    /// an origin not listed, is refused — so a relay cannot run one for a
    /// relying party it merely names.
    #[arg(long = "web-relying-party", value_name = "RP_ID=ORIGIN[,ORIGIN]")]
    pub web_relying_party: Vec<String>,

    /// **Every passkey ceremony must verify the user** (a PIN or a biometric,
    /// not a touch): web logins and the passkey after a company sign-in alike.
    /// The server decides; a relay may ask for more, never for less (A34-12).
    /// Off: a touch is enough unless the relay asks.
    #[arg(long = "web-require-user-verification")]
    pub web_require_user_verification: bool,
    /// **Anybody may sign up on this site** (IDENTITY-HOST): the identity core's Root
    /// site, where anybody may sign up; without it the site is Private (invite
    /// only), the default.
    #[arg(long = "identity-root-site")]
    pub identity_root_site: bool,

    /// **Build every push, in this process, hermetically** (roadmap phase 3).
    ///
    /// The runner subscribes to the same event bus a push publishes on, so the
    /// build happens *because* the push landed and not some time after it. This
    /// is the golden path's fourth step, the one that is nothing at all.
    ///
    /// Needs `--runner-workspace` and `--runner-builder`.
    #[arg(long, requires_all = ["runner_workspace", "runner_builder"])]
    pub runner: bool,

    /// Where the runner puts checkouts and build output.
    #[arg(long, value_name = "PATH")]
    pub runner_workspace: Option<std::path::PathBuf>,

    /// The identity-table principal the runner attributes every build record to.
    #[arg(long, value_name = "PRINCIPAL")]
    pub runner_builder: Option<String>,

    /// Let the runner's builds reach the network.
    ///
    /// Off by default, and the server **refuses to start** with the runner on
    /// and no sandbox available rather than building non-hermetically and
    /// signing records that say otherwise. Turning this on is recorded in every
    /// record the runner produces.
    #[arg(long)]
    pub runner_allow_network: bool,

    /// Do not offer `filter`, so this server serves no partial clones.
    ///
    /// Removes `filter` from the advertisement **and** makes the parser refuse
    /// the argument, in both protocol versions, so a client cannot get a
    /// filtered pack by asking for one anyway. `git clone --filter=blob:none`
    /// then fails with *"this server does not offer the filter capability"*
    /// rather than quietly serving the whole thing.
    ///
    /// For an appliance that has to be able to state it never serves arbitrary
    /// blob subsets. Everything else about a clone is unchanged.
    #[arg(long)]
    pub no_filter: bool,

    /// Which object ids a client may `want`. Default `reachable`.
    ///
    /// `advertised-tips` is the strictest and **breaks partial clone**: a
    /// `blob:none` clone's lazy fetch asks for bare blob ids that were never
    /// advertised, so every `git checkout` in one becomes "the remote end hung
    /// up unexpectedly". Pair it with `--no-filter` or not at all. `any` makes
    /// every object ever pushed fetchable by whoever can name it, including on
    /// deleted branches.
    #[arg(long, value_name = "POLICY", value_enum)]
    pub want_policy: Option<WantPolicyArg>,

    /// Ceiling on **objects emitted** while answering one fetch.
    ///
    /// An operator's explicit cap on the size of a clone. It is no longer what
    /// bounds gunnar's memory — `--max-fetch-walk-bytes` is, in the unit a
    /// machine is actually sized in — and the reason is that an object count
    /// does not convert to bytes at a fixed rate: MEASURED across gunnar's
    /// corpus on 2026-08-05 the same walk cost between 393.8 and 1 572.9 bytes
    /// per emitted object, a 4x spread set by the repository's shape.
    ///
    /// There is no "off" value. `0` would refuse every fetch rather than allow
    /// every fetch — the walk stops when it reaches the budget — so it is
    /// rejected at startup instead of being accepted as an unbounded server
    /// that in fact serves nothing.
    #[arg(long, value_name = "N")]
    pub fetch_budget: Option<usize>,

    /// Bytes of object bookkeeping **one fetch** may hold. `0` removes the
    /// ceiling. Default 8589934592 (8 GiB).
    ///
    /// Charged at a measured 384 bytes per object the walk is holding, so the
    /// default admits about 22.4 million objects. That is deliberately past the
    /// linux kernel's 13 816 503: MEASURED 2026-08-05, a 14 042 000-object
    /// repository with no `.bitmap` clones in 5 460 816 kB of peak RSS and 64
    /// seconds, and the object-counted ceiling it shipped with refused it.
    ///
    /// This is a **per-request** number and on its own it is not a bound on the
    /// server: multiply it by `--max-concurrent-transfers`. See
    /// `--max-walk-bytes-total`.
    #[arg(long, value_name = "BYTES")]
    pub max_fetch_walk_bytes: Option<usize>,

    /// Bytes of object bookkeeping **the whole server** may hold at once,
    /// shared by every transfer in flight. `0` removes the ceiling. Defaults to
    /// half of this machine's `MemTotal`.
    ///
    /// The ceiling that actually bounds the box. `--max-concurrent-transfers`
    /// counts transfers, which says nothing about memory: 256 concurrent clones
    /// of a kernel-sized repository need well over a terabyte between them, and
    /// what the shipped server did about that was let the OOM killer choose.
    /// A transfer that cannot get its reservation is refused with a sentence
    /// naming both numbers, and the client can retry.
    ///
    /// A walk holding under 8 MiB never touches the pool, so ordinary clones
    /// neither queue nor draw on it.
    #[arg(long, value_name = "BYTES")]
    pub max_walk_bytes_total: Option<usize>,

    /// Bytes of pkt-line payload held for one peer-supplied request. `0`
    /// removes the ceiling. Default 8388608 (8 MiB).
    ///
    /// The size is the **peer's** to choose and costs it about what it costs
    /// the server, which is why this is an absolute number.
    #[arg(long, value_name = "BYTES")]
    pub max_fetch_request_bytes: Option<usize>,

    /// Bytes of a single object gunnar will put in a pack. `0` removes the
    /// ceiling. Default 1073741824 (1 GiB), the same number `gunnar-pack`
    /// applies on the way in.
    #[arg(long, value_name = "BYTES")]
    pub max_fetch_object_bytes: Option<usize>,

    /// Largest LFS object this server will store, in bytes. Default
    /// 8589934592 (8 GiB).
    ///
    /// **There is no "off" value**, and `0` is refused at startup. Unlike the
    /// two fetch ceilings above, `gunnar_lfs::Limits` holds a plain `u64` and
    /// not an `Option`, so `0` means "refuse every upload" rather than "accept
    /// any size". A finite default is deliberate: "no limit" means one client
    /// decides how much disk the server has.
    #[arg(long, value_name = "BYTES")]
    pub max_lfs_object_bytes: Option<u64>,

    /// Most objects one LFS `batch` request may name. Default 10000. `0` is
    /// refused, for the same reason as above.
    #[arg(long, value_name = "N")]
    pub max_lfs_batch_objects: Option<usize>,

    /// Bytes of a refused LFS upload that will be read and discarded to keep
    /// the channel in sync before the session is dropped. Default 131056
    /// (two pkt-line payloads). `0` is refused.
    ///
    /// A refusal cannot simply stop reading: the client is already writing the
    /// object into the channel and the framing only ends at its flush-pkt, so a
    /// server that answered 413 and then read the next *command* would read
    /// object bytes instead.
    #[arg(long, value_name = "BYTES")]
    pub max_lfs_drain_bytes: Option<u64>,

    /// Bind, report, and exit rather than serving. For smoke tests and for
    /// checking a configuration without holding the ports.
    #[arg(long)]
    pub check: bool,
}

/// `--want-policy`, one arm per [`gunnar_wire::WantPolicy`].
#[cfg(feature = "server")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum WantPolicyArg {
    /// Only ids that appeared in the advertisement. Breaks partial clone.
    AdvertisedTips,
    /// Anything reachable from a reference. The default.
    Reachable,
    /// Anything in the store, reachable or not.
    Any,
}

#[cfg(feature = "server")]
impl WantPolicyArg {
    /// The wire's own enum. One translation, in one place, so the flag and the
    /// behaviour cannot drift (one implementation).
    pub fn to_wire(self) -> gunnar_wire::WantPolicy {
        match self {
            WantPolicyArg::AdvertisedTips => gunnar_wire::WantPolicy::AdvertisedTips,
            WantPolicyArg::Reachable => gunnar_wire::WantPolicy::ReachableFromRefs,
            WantPolicyArg::Any => gunnar_wire::WantPolicy::Any,
        }
    }
}

/// Namespace verbs.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum NamespaceCommand {
    /// Create a namespace. Nested names (`team/sub`) are legal; grants do NOT
    /// inherit between them.
    Create {
        /// The namespace name.
        name: String,
    },
    /// List namespaces.
    List,
    /// Delete a namespace.
    Delete {
        /// The namespace name.
        name: String,
        /// Also delete every repository in it. Never implicit.
        #[arg(long)]
        delete_repos: bool,
    },
    /// Set this account's read-cache budget.
    #[command(alias = "set-quota")]
    SetBudget {
        /// The namespace name.
        name: String,
        /// **The exploded read cache each of this account's repositories may
        /// hold**: `8G`, `512M`, `unlimited`, or `default` to go back to the
        /// server's own (10 % of /data, capped at 8 GiB).
        ///
        /// A bigger cache means more objects are already inflated and reads
        /// are fast; a smaller one means more reads re-inflate their own delta
        /// chain out of the pack, ~0.5–2 ms an object. It is never a refusal
        /// and never an error: an account at its budget serves everything it
        /// has, correctly, more slowly. Nothing it bounds can be lost — every
        /// byte of it is re-derivable from the packs, which it does not bound.
        #[arg(long, value_name = "BYTES")]
        explode_budget: Option<String>,
    },
}

/// Repository verbs.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum RepoCommand {
    /// Create a repository. Its namespace must already exist.
    Create {
        /// `<namespace>/<name>`, with or without a `.git` suffix.
        path: String,
        /// sha256 is the default for new repositories.
        #[arg(long, value_enum, default_value_t = HashArg::Sha256)]
        hash: HashArg,
        /// The default branch, as a short name or a full ref.
        #[arg(long, value_name = "BRANCH")]
        default_branch: Option<String>,
        /// **Readable by anyone, with no key**: `git clone
        /// ssh://anonymous@host/ns/repo.git` works for a stranger. Writing
        /// still needs a grant. Private is the default.
        #[arg(long)]
        public: bool,
        /// A one-line description.
        #[arg(long, default_value = "")]
        description: String,
        /// **Take over a store already on disk at this name** instead of
        /// refusing it. Only for a matching hash (the store's `OBJECT_FORMAT`
        /// marker). Without this a create never adopts a directory it did not
        /// make: that is how a deleted repository came back (2026-08-30).
        #[arg(long)]
        adopt: bool,
    },
    /// List repositories.
    List {
        /// Only this namespace.
        #[arg(long, value_name = "NS")]
        namespace: Option<String>,
    },
    /// **Delete a repository. Without `--purge` this is a DATED TOMBSTONE, not
    /// a reclaim.**
    ///
    /// The catalog row goes, so the name stops working and nothing can be
    /// pushed to it — but the bytes stay, for `--retention-days` (30 by
    /// default), and `repo undelete <path>` puts it back exactly as it was.
    /// A background sweep reclaims them when the window closes.
    ///
    /// Why the window exists: `--purge` returns the bytes in about two seconds
    /// — 181 GiB to 33 MiB, measured — and a live mirror does not help,
    /// because the delete replicates to the standby too. Deleting the wrong
    /// repository is the mistake that will actually happen.
    ///
    /// **A tombstone still costs storage.** Its bytes are on the account until
    /// the window closes; `repo list-deleted` and `Admin.StorageInfo` report
    /// them, so the space a tombstone holds is never a surprise.
    Delete {
        /// `<namespace>/<name>`.
        path: String,
        /// **Reclaim the bytes NOW**, with no window and no undo.
        #[arg(long)]
        purge: bool,
        /// How long the bytes are kept. `0` means at the next sweep — an
        /// operator freeing space meant it.
        #[arg(long, value_name = "DAYS")]
        retention_days: Option<u32>,
    },
    /// **Put a soft-deleted repository back**, inside its retention window.
    ///
    /// It comes back as it was — the recorded hash kind above all. A
    /// repository recreated as sha256 over a sha1 store serves refs no client
    /// can read, which is why this is a verb and not `repo create --adopt`.
    Undelete {
        /// `<namespace>/<name>`.
        path: String,
    },
    /// **End a retention window early**: reclaim a soft-deleted repository's
    /// bytes now. There is no undo after it.
    Purge {
        /// `<namespace>/<name>`.
        path: String,
    },
    /// What is deleted and not yet purged, when the window closes, and the
    /// bytes each is still costing.
    ListDeleted {},
    /// **Store directories with no catalog row and no soft-delete tombstone —
    /// bytes nothing else on this box can see.**
    ///
    /// `repo list` reads the catalog and an orphan is not in it. `repo
    /// list-deleted`, `repo undelete`, `repo purge` and the retention sweep
    /// all key off a tombstone and an orphan has none. So a directory with
    /// neither was reachable by nothing at all — while `repo create` refused
    /// its name *because the directory was there*.
    ///
    /// MEASURED on the appliance 2026-08-30: ~25-39 GB standing at
    /// `alice/linux`, the wreckage of a failed kernel mirror, with the name
    /// permanently unusable and no verb able to touch the bytes.
    ///
    /// With `repo list` and `repo list-deleted` this closes the set: every
    /// `<name>.git` directory is in exactly one of the three.
    ListOrphans {
        /// Only this namespace.
        #[arg(long, value_name = "NS")]
        namespace: Option<String>,
    },
    /// **Reclaim an orphan's bytes.** There is no undo.
    ///
    /// Refuses anything that is not an orphan by name: a catalogued repository
    /// is `repo delete --purge`'s and a soft-deleted one is `repo undelete`'s
    /// or `repo purge`'s. To KEEP an orphan's objects instead, run `repo
    /// create <path> --adopt --hash <the OBJECT_FORMAT that list-orphans
    /// reports>`.
    Reclaim {
        /// `<namespace>/<name>`.
        path: String,
    },
    /// **One repository's stored bytes, out to ONE FILE.**
    ///
    /// The file is self-describing and copyable anywhere — another appliance,
    /// object storage, a laptop. It carries the verbatim pack bytes, the
    /// durable extent journal and the ref log; **no index travels**, because an
    /// index is a derivation and the receiver builds its own.
    ///
    /// `--from-generation` is a WATERMARK, not a diff: the pack is append-only,
    /// so everything above a byte offset is new and nothing below it changed.
    /// Pass a previous run's `to_generation` for an incremental archive.
    ///
    /// Safe while the server is running: the cut is taken at one length, and
    /// every byte below it is already fsynced.
    ArchiveOut {
        /// `<namespace>/<name>`.
        path: String,
        /// Where to write the archive.
        #[arg(long, value_name = "FILE")]
        to: std::path::PathBuf,
        /// Start above this `objects.pack` offset. 0 = a full archive.
        #[arg(long, default_value_t = 0, value_name = "N")]
        from_generation: u64,
    },
    /// **Put an archive back**, into a repository this server does not have.
    ///
    /// Restores the bytes and then puts the catalog row back (adopting the
    /// store it just wrote), so a restored repository is servable without a
    /// second command. An incremental archive is applied on top of its base and
    /// refuses by name if the base is not exactly what it was cut against.
    ArchiveIn {
        /// The archive file.
        file: std::path::PathBuf,
        /// `<namespace>/<name>` to restore it as. Its namespace must exist.
        #[arg(long = "as", value_name = "NS/NAME")]
        as_path: String,
        /// Restore the bytes only; do not touch the catalog.
        #[arg(long)]
        no_catalog: bool,
    },
}

/// `gunnar issuer …` — the server's certificate authority.
///
/// **Exactly one issuer.** Not a list, not a default among several. A second
/// issuer is a second answer to *who may mint a user*, and the failure mode of
/// two is that nobody can say which one signed a given client. `create` on a
/// server that has one is refused; replacing it invalidates every certificate
/// in the field and is therefore a different verb.
///
/// The trusted-CA **list** is a separate thing and stays a list: a rotation
/// needs the old CA and the new one trusted at the same instant, or every
/// client is locked out at the swap. `trust`/`untrust` are that list.
/// `gunnar registry …` — the artifact registry (roadmap phase 4).
///
/// One rule, enforced where bytes become pullable: **no artifact without valid,
/// logged provenance**. Everything else here is plumbing around it.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum RegistryCommand {
    /// **Land a manifest under a tag** — if the image it names was built and
    /// attested, and a signed tree head covers the record.
    ///
    /// Refuses in four distinguishable ways, because the operator's next action
    /// differs for each. The commonest is the fourth: run
    /// `gunnar attest head --builds` first.
    Push {
        /// The image reference's name, e.g. `team/app`.
        #[arg(long, value_name = "NAME")]
        name: String,
        /// The tag to point at it.
        #[arg(long, value_name = "TAG", default_value = "latest")]
        tag: String,
        /// The manifest's digest, as `gunnar build image` printed it.
        #[arg(long, value_name = "DIGEST")]
        digest: String,
    },
    /// What a tag points at.
    Resolve {
        #[arg(long, value_name = "NAME")]
        name: String,
        #[arg(long, value_name = "TAG", default_value = "latest")]
        tag: String,
    },
    /// **Pull a manifest and verify the whole chain behind it.**
    ///
    /// The registry's acceptance test in one command: resolve the tag, read the
    /// manifest back out of content-addressed storage, and walk the chain from
    /// its digest down to the source.
    Pull {
        #[arg(long, value_name = "NAME")]
        name: String,
        #[arg(long, value_name = "TAG", default_value = "latest")]
        tag: String,
        /// `<path>:<line>` — check the chain reaches this line of source.
        #[arg(long, value_name = "PATH:LINE")]
        line: Option<String>,
    },
}

/// `gunnar forge …` — issues, reviews and merges, as signed events (roadmap
/// phase 1).
///
/// Every verb that changes anything **signs** with the actor's own key, and the
/// event goes into an append-only log the same transparency machinery covers.
/// An approval is therefore evidence anybody can check later, without trusting
/// the server that stored it — which a row in a table saying `approved_by` is
/// not.
///
/// **This is the review half only.** The pull request itself — its number, its
/// refs, its state — is `PullRequests`' record under the control store's CAS,
/// and there is no CLI for it yet: open and merge one over gRPC.
///
/// The same events are reachable over gRPC as `Forge.*` — `Append` takes an
/// event the CALLER signed, verifies it against the identity key table and appends it,
/// because a server that could sign an approval could manufacture one. What is
/// deliberately not here yet is the console views, which live in the separate
/// `gunnar-UI` repository.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum ForgeCommand {
    /// Comment on a pull request.
    Comment {
        #[arg(long, value_name = "REPO")]
        repo: String,
        /// The pull request number, as `PullRequests.Create` assigned it.
        #[arg(long, value_name = "N")]
        pull: u64,
        #[arg(long, value_name = "TEXT")]
        body: String,
        /// The identity-table principal the event is attributed to.
        #[arg(long, value_name = "PRINCIPAL")]
        actor: String,
        /// The private key to sign with.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: std::path::PathBuf,
    },
    /// **Approve a specific commit.**
    ///
    /// The commit is part of what is signed, so a force-push after the review
    /// leaves an approval that visibly names the commit that was reviewed — and
    /// not the one that is there now. `PullRequests.Merge` refuses on exactly
    /// that, so this is a gate and not a display.
    Approve {
        #[arg(long, value_name = "REPO")]
        repo: String,
        #[arg(long, value_name = "N")]
        pull: u64,
        #[arg(long, value_name = "OID")]
        commit: String,
        #[arg(long, value_name = "PRINCIPAL")]
        actor: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: std::path::PathBuf,
    },
    /// **Withdraw an approval**, naming the commit it covered and why.
    ///
    /// Appended, never deleted: the log is append-only, so what the fold shows
    /// is that this actor no longer approves — and the withdrawal itself stays
    /// readable, which is the fact an auditor wants.
    Reject {
        #[arg(long, value_name = "REPO")]
        repo: String,
        #[arg(long, value_name = "N")]
        pull: u64,
        #[arg(long, value_name = "OID")]
        commit: String,
        #[arg(long, value_name = "TEXT")]
        reason: String,
        #[arg(long, value_name = "PRINCIPAL")]
        actor: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: std::path::PathBuf,
    },
    /// Show a pull request's review: its comments, and who approves what.
    ///
    /// The review only. The pull request itself — its title, its refs, whether
    /// it is open — belongs to `PullRequests`, and a second copy printed here
    /// would be a second answer that can disagree.
    Show {
        #[arg(long, value_name = "REPO")]
        repo: String,
        #[arg(long, value_name = "N")]
        pull: u64,
    },
    /// **Issues**: open, comment, close, list and show — as signed events.
    ///
    /// An issue is not a pull request and has no record behind it: it IS the
    /// fold of its own signed events, so opening one and closing one are events
    /// here (a review has neither — those are the pull request record's). A
    /// signed opening is the property GitHub, GitLab and Gitea have no
    /// equivalent for: who filed it is the author's own key.
    #[command(subcommand)]
    Issue(IssueCommand),
}

/// `gunnar forge issue …` — issues as signed events.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum IssueCommand {
    /// **Open an issue.** Signs the title and body with the author's own key
    /// and appends it; the number is assigned by the fold and printed back.
    Open {
        #[arg(long, value_name = "REPO")]
        repo: String,
        #[arg(long, value_name = "TEXT")]
        title: String,
        #[arg(long, value_name = "TEXT", default_value = "")]
        body: String,
        /// The identity-table principal the issue is attributed to.
        #[arg(long, value_name = "PRINCIPAL")]
        actor: String,
        /// The private key to sign with.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: std::path::PathBuf,
    },
    /// Comment on an issue.
    Comment {
        #[arg(long, value_name = "REPO")]
        repo: String,
        /// The issue number, as `issue open` (or the fold) assigned it.
        #[arg(long, value_name = "N")]
        number: u64,
        #[arg(long, value_name = "TEXT")]
        body: String,
        #[arg(long, value_name = "PRINCIPAL")]
        actor: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: std::path::PathBuf,
    },
    /// **Close an issue**, naming why. Appended, never deleted — the close
    /// stays readable.
    Close {
        #[arg(long, value_name = "REPO")]
        repo: String,
        #[arg(long, value_name = "N")]
        number: u64,
        #[arg(long, value_name = "TEXT", default_value = "")]
        reason: String,
        #[arg(long, value_name = "PRINCIPAL")]
        actor: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: std::path::PathBuf,
    },
    /// List every issue in a repository, folded.
    List {
        #[arg(long, value_name = "REPO")]
        repo: String,
    },
    /// Show one issue: its state and its whole thread.
    Show {
        #[arg(long, value_name = "REPO")]
        repo: String,
        #[arg(long, value_name = "N")]
        number: u64,
    },
}

/// `gunnar build …` — recording what was built, and from what.
///
/// The verbs a runner calls. There is no `run` here yet: executing a build
/// hermetically is roadmap phase 3's sandbox, and this is the half that makes
/// its output *evidence* — a signed record, in a log, joinable to the push that
/// landed the source.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum BuildCommand {
    /// **Record a build**: sign what was made, from what, by whom, and append
    /// it to the build log.
    ///
    /// Every artifact is named by the SHA-256 of its bytes, computed here from
    /// the file — never taken on trust from an argument, because a digest a
    /// caller supplies is a digest a caller can choose.
    Attest {
        /// `<namespace>/<repo>` the source came from.
        #[arg(long, value_name = "REPO")]
        repo: String,
        /// The commit that was built, hex.
        #[arg(long, value_name = "OID")]
        commit: String,
        /// What the build was asked to make: a recipe, an atom, a variant.
        #[arg(long, value_name = "NAME")]
        recipe: String,
        /// The toolchain, as the builder resolved it.
        #[arg(long, value_name = "TEXT", default_value = "")]
        toolchain: String,
        /// The identity-table principal that ran the build.
        #[arg(long, value_name = "PRINCIPAL")]
        builder: String,
        /// Say that the build **had** network access.
        ///
        /// Off by default and named in the positive, so a hermetic build is the
        /// one nobody has to remember a flag for — and a build that reached the
        /// network has to say so out loud.
        #[arg(long)]
        network: bool,
        /// A file the build consumed. Repeatable.
        #[arg(long = "material", value_name = "PATH")]
        materials: Vec<std::path::PathBuf>,
        /// A file the build produced. Repeatable, and at least one is required:
        /// a build record with no subject attests to nothing.
        #[arg(long = "artifact", value_name = "PATH", required = true)]
        artifacts: Vec<std::path::PathBuf>,
    },
    /// **A CycloneDX SBOM for an artifact**, out of the `Cargo.lock` that was
    /// locked when it was built.
    ///
    /// The lockfile and not `cargo metadata`: the lock is what the build
    /// resolved and is in the commit, so the document is a function of the
    /// source and can be reproduced from it. `cargo metadata` re-resolves
    /// against the index as it stands now, which describes a build that may
    /// never have happened.
    Sbom {
        /// The `Cargo.lock` the build used.
        #[arg(long, value_name = "PATH")]
        lock: std::path::PathBuf,
        /// The artifact the document is about.
        #[arg(long, value_name = "PATH")]
        artifact: std::path::PathBuf,
    },
    /// **Ask the registry's one question**: may these bytes land?
    ///
    /// No artifact without valid, logged provenance. Exits zero only when a
    /// build record names the artifact, verifies, sits in the build log, and is
    /// covered by a signed tree head — and names which of the four is missing
    /// when it refuses.
    Admit {
        /// The artifact to ask about.
        #[arg(long, value_name = "PATH")]
        artifact: std::path::PathBuf,
    },
    /// **Build a commit and attest to what came out.**
    ///
    /// Materialises exactly that commit from the store, builds it in a network
    /// namespace of its own, hashes the artifacts and signs a record naming the
    /// commit — which is the join `gunnar verify --artifact` walks.
    ///
    /// Refuses rather than building when the sandbox cannot be entered: a
    /// record that says `network: false` has to mean it on every machine.
    Run {
        /// `<namespace>/<repo>`.
        #[arg(long, value_name = "REPO")]
        repo: String,
        /// The commit to build. A ref name or a hex oid; defaults to the
        /// repository's HEAD.
        #[arg(long, default_value = "HEAD", value_name = "REV")]
        at: String,
        /// Where checkouts and build output go.
        #[arg(long, value_name = "PATH")]
        workspace: std::path::PathBuf,
        /// The identity-table principal the record is attributed to.
        #[arg(long, value_name = "PRINCIPAL")]
        builder: String,
        /// **Build with the network up.** Off by default, and recorded in the
        /// signed record when it is on, so a non-hermetic build is never
        /// mistaken for a hermetic one.
        #[arg(long)]
        allow_network: bool,
    },
    /// **Watch for pushes and build them.**
    ///
    /// The step the golden path calls "nothing at all": a push lands, this
    /// builds it hermetically and signs a record, and nobody types anything.
    ///
    /// Runs in the serving process — `gunnar serve --runner` is the same thing
    /// wired to the same bus. One build at a time, on purpose.
    Watch {
        /// Where checkouts and build output go.
        #[arg(long, value_name = "PATH")]
        workspace: std::path::PathBuf,
        /// The identity-table principal every record is attributed to.
        #[arg(long, value_name = "PRINCIPAL")]
        builder: String,
        /// Only build these refs. Repeatable; empty means every branch.
        #[arg(long = "ref", value_name = "REF")]
        refs: Vec<String>,
        /// Build with the network up. Recorded in every record it produces.
        #[arg(long)]
        allow_network: bool,
        /// Stop after this many builds, instead of watching for ever.
        #[arg(long, value_name = "N")]
        max_builds: Option<usize>,
    },
    /// **Build an OCI image around an attested artifact.**
    ///
    /// `FROM scratch`, one layer, one file — so "zero CVEs" is a statement
    /// about surface area rather than about diligence, and the file count is
    /// printed so it stays a number.
    ///
    /// The artifact must already be admitted: an image built from a binary
    /// nobody attested to would be an image whose chain stops one link short.
    /// The image's own manifest digest is then attested in turn, which is what
    /// lets the registry take it.
    Image {
        /// The binary to put in the image.
        #[arg(long, value_name = "PATH")]
        artifact: std::path::PathBuf,
        /// Where it lands inside the image, and what it is run as.
        #[arg(long, value_name = "PATH", default_value = "/gunnar")]
        entrypoint: String,
        /// The identity-table principal the image's record is attributed to.
        #[arg(long, value_name = "PRINCIPAL")]
        builder: String,
    },
    /// List what this server has attested to building.
    List,
    /// The public key a verifier pins to check build records.
    Key,
}

/// `gunnar verify` — the chain, walked backwards (roadmap phase 2).
#[cfg(feature = "server")]
#[derive(Debug, clap::Args)]
pub struct VerifyArgs {
    /// `<namespace>/<repo>`. Omit it when `--artifact` is given: the build
    /// record names the repository the artifact was built from, and taking it
    /// from the command line instead would let a caller ask about a different
    /// one than the record claims.
    #[arg(value_name = "REPO", required_unless_present = "artifact")]
    pub repo: Option<String>,
    /// **Start at an artifact**, by its lowercase-hex SHA-256.
    ///
    /// The direction a verifier actually stands in: it holds a binary and wants
    /// the source. The build record that claims to have produced it supplies
    /// the repository and the commit, and the walk continues from there.
    #[arg(long, value_name = "SHA256", conflicts_with = "at")]
    pub artifact: Option<String>,
    /// The revision to start from: a branch, a tag, `HEAD`, or a hex oid.
    #[arg(long, default_value = "HEAD", value_name = "REV")]
    pub at: String,
    /// `<path>:<line>`, one-based — the way an editor and `git blame` count.
    ///
    /// Without it the chain starts at the revision's own commit and link 1 is
    /// reported as unchecked rather than as passed.
    #[arg(long, value_name = "PATH:LINE")]
    pub line: Option<String>,
}

/// `gunnar blame <ns>/<repo> <path> [--rev REV]`.
#[cfg(feature = "server")]
#[derive(Debug, clap::Args)]
pub struct BlameArgs {
    /// `<namespace>/<repo>`.
    #[arg(value_name = "REPO")]
    pub repo: String,
    /// The file to blame, as a path within the repository's tree.
    #[arg(value_name = "PATH")]
    pub path: String,
    /// The revision to blame at: a branch, a tag, `HEAD`, or a hex oid.
    #[arg(long, default_value = "HEAD", value_name = "REV")]
    pub rev: String,
}

/// `gunnar search <ns>/<repo> <pattern> [--rev REV] [--max-*]`.
#[cfg(feature = "server")]
#[derive(Debug, clap::Args)]
pub struct SearchArgs {
    /// `<namespace>/<repo>`.
    #[arg(value_name = "REPO")]
    pub repo: String,
    /// The literal string to look for. Not a regular expression — see the verb's
    /// help for why the appliance does not link one yet.
    #[arg(value_name = "PATTERN")]
    pub pattern: String,
    /// The revision to search: a branch, a tag, `HEAD`, or a hex oid. Only this
    /// one revision is searched, not the history behind it.
    #[arg(long, default_value = "HEAD", value_name = "REV")]
    pub rev: String,
    /// Skip files larger than this many bytes (they are never read).
    #[arg(long, default_value_t = 1 << 20, value_name = "BYTES")]
    pub max_file_bytes: u64,
    /// Stop after this many matches.
    #[arg(long, default_value_t = 1000, value_name = "N")]
    pub max_matches: usize,
}

/// The transparency log's verbs, over the push attestations.
///
/// The log itself is `attestations.jsonl` and is written by every push. These
/// verbs do not write records; they sign, check and prove over the records that
/// are already there — which is why none of them can change what the log says.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum AttestCommand {
    /// **Sign what the log holds right now**, and append the head.
    ///
    /// Issue one whenever a claim about the log needs to be checkable later —
    /// after a release, on a timer, before an audit. Each head pins every
    /// record beneath it, so a rewrite of an old line is caught by every head
    /// issued since, including by somebody who never saw the original line.
    Head {
        /// Head the **build** log instead of the push-attestation log.
        ///
        /// Two logs, two heads: a head over one says nothing about the other,
        /// and signing both under one root would make a build record's proof
        /// depend on a push it has nothing to do with.
        #[arg(long)]
        builds: bool,
    },
    /// **Check every signed head against the records on disk.**
    ///
    /// The one verb that can say the log was tampered with. It keeps three
    /// failures apart on purpose: a head that does not verify (somebody wrote a
    /// head they could not sign, or the key rotated), a head that verifies over
    /// a root the records no longer produce (the records were changed), and a
    /// head covering more records than exist (lines were removed).
    Audit {
        /// Audit the **build** log instead of the push-attestation log.
        #[arg(long)]
        builds: bool,
    },
    /// The public key a verifier pins to check this server's tree heads.
    ///
    /// An OpenSSH public-key line, so `ssh-keygen -Y verify` can check a head
    /// with no gunnar involved.
    Key,
    /// **The inclusion proof for one push**, by the pack it landed.
    ///
    /// What a client checks offline: the record's position, the tree size and
    /// the sibling hashes. With a signed head it proves the push is in the log
    /// without trusting the server that served the proof.
    Prove {
        /// The `pack_hash` the attestation carries.
        #[arg(value_name = "PACK-HASH")]
        pack_hash: String,
    },
}

/// **The certificate issuer.** Every verb but `show` writes, and writing needs
/// the storage half; `show` is a read and is here in either build.
#[cfg(any(feature = "server", feature = "control"))]
#[derive(Debug, Subcommand)]
pub enum IssuerCommand {
    /// Mint this server's issuer. **Refused if it already has one.**
    #[cfg(feature = "server")]
    Create {
        /// The subject common name the CA certificate carries.
        #[arg(long, default_value = "gunnar issuer")]
        subject: String,
        /// How long it is good for.
        #[arg(long, value_name = "DAYS", default_value_t = gunnar_core::DEFAULT_ISSUER_DAYS)]
        days: u32,
    },
    /// Adopt an issuer that already exists. **Refused if this server has one.**
    ///
    /// Both halves are checked against each other before anything is stored: a
    /// certificate that is not this key's is refused, rather than accepted and
    /// discovered on the first `principal add`.
    #[cfg(feature = "server")]
    Import {
        /// The CA certificate, PEM.
        #[arg(long, value_name = "PATH")]
        cert: std::path::PathBuf,
        /// Its private key, PEM. It goes straight into the sealed secret store
        /// and never into the control database.
        #[arg(long, value_name = "PATH")]
        key: std::path::PathBuf,
    },
    /// What is live: the issuer, and every CA this server trusts.
    ///
    /// **One verb, two places to stand.** With no `--at` it reads the data
    /// root under your feet, as it always has. With `--at <addr>` it asks a
    /// RUNNING server the same question over the control plane
    /// (`Admin.IssuerInfo`, server-wide `Read`) and prints the same lines.
    ///
    /// There is no second verb for the remote read, and that is a decision.
    /// `gunnar namespace` and `gunnar control namespace` are split because
    /// they are WRITES with different preconditions — the offline one needs
    /// the server stopped. This is a read of one document with no
    /// precondition at all: the answer is identical from either side, out of
    /// the same `pki_readonly` seam, and two spellings of one question would
    /// be two renderings to keep in step.
    ///
    /// # Why the wire half exists
    ///
    /// The appliance has no shell, so `--data-root` is unreachable on the box
    /// where it matters. The issuer certificate was otherwise handed out by
    /// exactly one RPC, `Bootstrap.Enroll`, whose window shuts for good on the
    /// first enrol — so a RESTORED appliance could never again tell anyone
    /// which CA it mints with, which is precisely when "is this still the CA
    /// my clients pinned?" needs an answer.
    Show {
        /// Print the issuer certificate itself, so it can be piped to a client.
        #[arg(long)]
        pem: bool,
        /// Ask a running server instead of this host's data root.
        ///
        /// No default and no environment variable on purpose: `issuer show`
        /// must not quietly start answering about a different machine because
        /// `GUNNAR_CONTROL_ADDR` was exported in the shell.
        #[arg(long, value_name = "ADDR", long_help = CONTROL_ADDR_HELP)]
        at: Option<String>,
        /// The private key to sign the call with. Only with `--at`.
        #[arg(long, short = 'i', value_name = "PATH", requires = "at")]
        identity: Option<PathBuf>,
    },
    /// Trust a CA this server does not mint with — the other half of a rotation.
    #[cfg(feature = "server")]
    Trust {
        /// A label. Never part of the credential.
        #[arg(long, default_value = "")]
        label: String,
        /// The CA certificate, PEM.
        #[arg(long, value_name = "PATH")]
        cert: std::path::PathBuf,
    },
    /// Stop trusting a CA. Refuses to remove the live issuer's own entry.
    #[cfg(feature = "server")]
    Untrust {
        /// The `SHA256:` fingerprint `issuer show` prints.
        fingerprint: String,
    },
    /// **Can this server be moved to `serve --grpc-tls-self`, and who does it
    /// cost?**
    ///
    /// Mutual TLS on the control plane refuses every peer that cannot present
    /// a certificate this server's issuer signed. That is the point of it, and
    /// it is also a cliff: a principal that holds only an SSH key can
    /// authenticate today and cannot complete a handshake afterwards. This
    /// prints, per principal, which side of the cliff they are on, and ends
    /// with the verdict `gunnar serve` itself will reach — it is the same
    /// function, asked in advance, so the two cannot disagree.
    ///
    /// Offline and local: it reads this host's identity table, because
    /// `--grpc-tls-self` is a serve flag and whoever flips it is already here.
    /// It changes nothing.
    #[cfg(feature = "server")]
    Readiness,
}

/// Principal verbs.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum PrincipalCommand {
    /// Add a principal, and optionally issue its certificate.
    Add {
        /// A stable identifier. Grants name it, and it is the `CN` the
        /// certificate carries.
        id: String,
        /// A display name. Defaults to the id.
        #[arg(long)]
        name: Option<String>,
        /// What sort of actor this is.
        #[arg(long, value_enum, default_value_t = PrincipalKindArg::User)]
        kind: PrincipalKindArg,
        /// **Issue from a certificate signing request. This is the strong
        /// form.**
        ///
        /// The private key is generated on the machine that will use it and
        /// never leaves it, so this server is structurally incapable of
        /// impersonating the principal. Whatever subject the request claims is
        /// discarded: the certificate is issued under `id`.
        #[arg(long, value_name = "PATH", conflicts_with = "server_generated_key")]
        csr: Option<std::path::PathBuf>,
        /// **Generate the private key here and hand it back.** The convenient
        /// form, and the weaker one.
        ///
        /// The key existed on this server and travelled over the wire, so the
        /// server could have kept a copy and nothing in the protocol proves it
        /// did not — *"only alice could have signed this"* stops being true. It
        /// is spelled out rather than being what you get by not thinking about
        /// it, because a machine account being bootstrapped genuinely needs it.
        #[arg(long)]
        server_generated_key: bool,
        /// Where the issued `<id>_cert.pem` (and, for
        /// `--server-generated-key`, `<id>_key.pem`) are written.
        #[arg(long, value_name = "DIR", default_value = ".")]
        out: std::path::PathBuf,
        /// How long the issued certificate is good for.
        #[arg(long, value_name = "DAYS", default_value_t = gunnar_core::DEFAULT_LEAF_DAYS)]
        days: u32,
    },
    /// List principals.
    List,
    /// Remove a principal, with its keys and grants.
    Remove {
        /// The principal id.
        id: String,
    },
}

/// Key verbs.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum TokenCommand {
    /// Mint an access token for a principal, and **print it once**.
    ///
    /// The secret is not stored: only its sha-256 is. Nothing in gunnar can
    /// print it again, which is why this is the only place it appears.
    Add {
        /// The principal the token authenticates as. It gets exactly that
        /// principal's grants and nothing else.
        principal: String,
        /// A label — which laptop, which CI job. Never part of the credential.
        #[arg(long, default_value = "")]
        label: String,
        /// Stop accepting it after this many days.
        #[arg(long, value_name = "DAYS")]
        expires_in: Option<u64>,
    },
    /// List tokens by their hash, which is what `revoke` takes.
    List {
        /// Only this principal's.
        #[arg(long)]
        principal: Option<String>,
    },
    /// Revoke a token by the hash `list` prints.
    Revoke {
        /// The token hash.
        hash: String,
    },
}

/// WireGuard verbs.
///
/// One verb, and it exists because provisioning an OS-less fleet needs a key
/// and `wg genkey` is a SHELL — a thing this product does not have, on the
/// appliance or in its build. The curve is already linked into this binary for
/// the tunnel itself, so minting a key costs nothing that was not already
/// there.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum WgCommand {
    /// Mint a fresh x25519 keypair — what `wg genkey | wg pubkey` prints,
    /// without a shell.
    Keygen {
        /// Write the PRIVATE key here (one base64 line, mode 0600) instead of
        /// printing it, and print only the public half.
        ///
        /// This is the `wg0.key` an appliance is seeded with. An existing file
        /// is REFUSED rather than overwritten: a regenerated identity is a
        /// silent fleet-wide outage — every hub still allowlists the old public
        /// key, and a peer whose key is unknown gets silence, not an error.
        #[arg(long, value_name = "PATH")]
        private: Option<std::path::PathBuf>,
    },
}

/// Public-key verbs.
#[cfg(feature = "server")]
#[derive(Debug, Subcommand)]
pub enum KeyCommand {
    /// Register an OpenSSH public key line to a principal.
    Add {
        /// The principal id.
        principal: String,
        /// An OpenSSH public key line, or `@<path>` to read one from a file.
        ///
        /// Omit when registering a certificate with `--cert`.
        #[arg(required_unless_present = "cert")]
        key: Option<String>,
        /// Register an X.509 certificate instead, from a PEM or DER file.
        ///
        /// The mTLS credential. It lands in the same table as an SSH key and
        /// under the same principal, because a fingerprint is all gunnar knows
        /// about a credential — only how it is presented differs.
        #[arg(long, conflicts_with = "key", value_name = "PATH")]
        cert: Option<std::path::PathBuf>,
    },
    /// List registered keys.
    List {
        /// Only this principal's keys.
        #[arg(long)]
        principal: Option<String>,
    },
    /// Revoke a key by its `SHA256:` fingerprint.
    Revoke {
        /// The fingerprint, exactly as `ssh-keygen -lf` prints it.
        fingerprint: String,
    },
}

/// `gunnar grant`.
#[cfg(feature = "server")]
#[derive(Debug, clap::Args)]
#[command(group(ArgGroup::new("scope").required(true).args(["server", "namespace", "repo"])))]
pub struct GrantArgs {
    /// The principal id.
    pub principal: String,
    /// How much access.
    #[arg(value_enum)]
    pub level: LevelArg,
    /// Scope the grant to the whole server (the bootstrap admin's scope).
    #[arg(long)]
    pub server: bool,
    /// Scope the grant to one namespace, matched EXACTLY: `team` does not reach
    /// `team/sub`.
    #[arg(long, value_name = "NS")]
    pub namespace: Option<String>,
    /// Scope the grant to one repository, `<namespace>/<name>`.
    #[arg(long, value_name = "NS/NAME")]
    pub repo: Option<String>,
}

/// `gunnar revoke`.
#[cfg(feature = "server")]
#[derive(Debug, clap::Args)]
#[command(group(ArgGroup::new("scope").required(true).args(["server", "namespace", "repo"])))]
pub struct RevokeArgs {
    /// The principal id.
    pub principal: String,
    /// The server-wide grant.
    #[arg(long)]
    pub server: bool,
    /// A namespace grant.
    #[arg(long, value_name = "NS")]
    pub namespace: Option<String>,
    /// A repository grant.
    #[arg(long, value_name = "NS/NAME")]
    pub repo: Option<String>,
}

/// `gunnar reflog`.
///
/// Reads the archive `gunnar-store`'s compaction has always written and until
/// now nothing read. It opens **no store**, so it works against a repository a
/// running server holds the exclusive lock on — which is the only kind of
/// repository anyone wants the history of.
#[cfg(feature = "server")]
#[derive(Debug, clap::Args)]
pub struct ReflogArgs {
    /// The repository, `<namespace>/<name>`. Omit for every one.
    pub path: Option<String>,

    /// Write the sealed history to this path instead of listing it.
    ///
    /// One Arrow IPC stream, one batch, the push boundary carried as a
    /// `push_seq` column rather than as a frame boundary — measured at 6.68x
    /// smaller per push than the live log it seals. With more than one
    /// repository this is treated as a **directory** and one artifact is
    /// written per repository, because a single file would silently keep only
    /// the last.
    #[arg(long, value_name = "PATH")]
    pub seal: Option<std::path::PathBuf>,

    /// Print at most this many of the most recent transactions per repository.
    #[arg(long, default_value_t = 20, value_name = "N")]
    pub limit: usize,

    /// Print every transaction, ignoring `--limit`.
    #[arg(long, conflicts_with = "limit")]
    pub all: bool,
}

/// `gunnar gc`.
///
/// `Default` exists so that a caller — the tests, and any future programmatic
/// `gc` — can name the one field it cares about and inherit the verb's real
/// defaults for the rest. Spelling every flag out at each call site is how a
/// test ends up pinned to `Preserve` because that was the easiest literal to
/// write, and then guards nothing.
///
/// **It is hand-written, and it has to be.** A derive gives `0` for every
/// integer, and `--window 0`/`--depth 0` is a delta search that can never find
/// a base: every `GcArgs { .. , ..Default::default() }` in the tests would
/// silently stop deltifying and every one of them would still pass, because a
/// pack of whole objects is a valid pack. `gc_default_matches_the_command_line`
/// asserts the two agree, field by field.
#[cfg(feature = "server")]
#[derive(Debug, clap::Args)]
pub struct GcArgs {
    /// The repository to maintain, `<namespace>/<name>`. Omit for every one.
    pub path: Option<String>,

    /// Also drop objects nothing reaches.
    ///
    /// Off unless asked, because reachability is computed from the refs as they
    /// are at this instant and a push landing mid-run is a race the grace
    /// window below exists to cover.
    #[arg(long)]
    pub prune: bool,

    /// How long an unreachable object is kept before `--prune` may drop it.
    #[arg(long, value_name = "DURATION", default_value = "2w", value_parser = parse_prune_grace)]
    pub prune_grace: std::time::Duration,
}

/// `now`, `<N>`, or `<N>` with a `s`/`m`/`h`/`d`/`w` suffix.
///
/// Hand-written rather than pulling in a date parser: the dependency budget is
/// a guarded number (`xtask guard`) and this is eleven lines. It deliberately
/// does **not** accept git's full `approxidate` grammar (`2.weeks.ago`), because
/// half-supporting a grammar is how `--prune=yesterday` ends up silently
/// meaning zero.
#[cfg(feature = "server")]
fn parse_prune_grace(raw: &str) -> std::result::Result<std::time::Duration, String> {
    parse_duration_words(raw, "grace period", "2w")
}

/// `--max-silence` on `control twin replay`: the same grammar as [`parse_prune_grace`].
#[cfg(feature = "control")]
fn parse_max_silence(raw: &str) -> std::result::Result<std::time::Duration, String> {
    parse_duration_words(raw, "silence", "24h")
}

/// The grammar of [`parse_prune_grace`], naming `what` and an `example` in its refusals.
#[cfg(any(feature = "server", feature = "control"))]
fn parse_duration_words(
    raw: &str,
    what: &str,
    example: &str,
) -> std::result::Result<std::time::Duration, String> {
    let raw = raw.trim();
    if raw.eq_ignore_ascii_case("now") {
        return Ok(std::time::Duration::ZERO);
    }
    let (digits, unit) = match raw.as_bytes().last() {
        Some(b) if b.is_ascii_digit() => (raw, 1u64),
        Some(b's') => (&raw[..raw.len() - 1], 1),
        Some(b'm') => (&raw[..raw.len() - 1], 60),
        Some(b'h') => (&raw[..raw.len() - 1], 60 * 60),
        Some(b'd') => (&raw[..raw.len() - 1], 24 * 60 * 60),
        Some(b'w') => (&raw[..raw.len() - 1], 7 * 24 * 60 * 60),
        _ => {
            return Err(format!(
                "{raw:?} is not a {what}; write `now`, a number of seconds, or a number \
                 with a s/m/h/d/w suffix such as `{example}`"
            ))
        }
    };
    let n: u64 = digits.parse().map_err(|_| {
        format!(
            "{raw:?} is not a {what}: {digits:?} is not a number. Write `now`, a number \
             of seconds, or a number with a s/m/h/d/w suffix such as `{example}`"
        )
    })?;
    n.checked_mul(unit)
        .map(std::time::Duration::from_secs)
        .ok_or_else(|| format!("{raw:?} is not a {what}: it does not fit in a duration"))
}

#[cfg(feature = "server")]
impl Default for GcArgs {
    fn default() -> Self {
        GcArgs {
            path: None,
            prune: false,
            // The same value as `default_value = "2w"` above;
            // `gc_default_matches_the_command_line` fails if they drift.
            prune_grace: std::time::Duration::from_secs(14 * 24 * 60 * 60),
        }
    }
}

#[cfg(feature = "server")]
impl GcArgs {}

/// The hash kinds gunnar knows.
#[cfg(any(feature = "server", feature = "control"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum HashArg {
    /// Git's original hash.
    Sha1,
    /// The default for new repositories.
    Sha256,
}

#[cfg(feature = "server")]
impl From<HashArg> for gunnar_core::HashKind {
    fn from(arg: HashArg) -> Self {
        match arg {
            HashArg::Sha1 => gunnar_core::HashKind::Sha1,
            HashArg::Sha256 => gunnar_core::HashKind::Sha256,
        }
    }
}

/// Grant levels, ordered `read < write < admin`.
///
/// Shared by the offline `gunnar grant` and the online `gunnar control grant`,
/// so `--level admin` means one thing whichever side of the wire it is spelled
/// on (one implementation).
#[cfg(any(feature = "server", feature = "control"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum LevelArg {
    /// `git-upload-pack`: clone and fetch.
    Read,
    /// `git-receive-pack`: push. Implies read.
    Write,
    /// Administer. Implies write.
    Admin,
}

#[cfg(feature = "control")]
impl LevelArg {
    /// The proto enum this level is on the wire.
    pub fn to_proto(self) -> gunnar_proto::GrantLevel {
        match self {
            LevelArg::Read => gunnar_proto::GrantLevel::Read,
            LevelArg::Write => gunnar_proto::GrantLevel::Write,
            LevelArg::Admin => gunnar_proto::GrantLevel::Admin,
        }
    }
}

#[cfg(feature = "server")]
impl From<LevelArg> for gunnar_core::Level {
    fn from(arg: LevelArg) -> Self {
        match arg {
            LevelArg::Read => gunnar_core::Level::Read,
            LevelArg::Write => gunnar_core::Level::Write,
            LevelArg::Admin => gunnar_core::Level::Admin,
        }
    }
}

/// The three kinds of principal in the identity table.
#[cfg(any(feature = "server", feature = "control"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum PrincipalKindArg {
    /// A human.
    User,
    /// CI, a mirror, a robot with its own identity.
    Machine,
    /// A key scoped to one repository.
    Deploy,
    /// A group of principals (punkt 9): holds no key, is granted access like
    /// any principal, and its members inherit those grants. Prefer
    /// `gunnar control group add`, which is this with a name for it.
    Group,
}

#[cfg(feature = "server")]
impl From<PrincipalKindArg> for gunnar_core::PrincipalKind {
    fn from(arg: PrincipalKindArg) -> Self {
        match arg {
            PrincipalKindArg::User => gunnar_core::PrincipalKind::User,
            PrincipalKindArg::Machine => gunnar_core::PrincipalKind::Machine,
            PrincipalKindArg::Deploy => gunnar_core::PrincipalKind::Deploy,
            PrincipalKindArg::Group => gunnar_core::PrincipalKind::Group,
        }
    }
}

// ───────────────────────────────────────────────────────────────────────────
// the control plane, over the wire
// ───────────────────────────────────────────────────────────────────────────

/// Where a `gunnar control` verb sends its call.
///
/// Its own arg rather than a global one, because it must appear in the
/// `--help` of each verb that uses it: a first-time user reading
/// `gunnar control bootstrap --help` has to see where it is about to send an
/// unauthenticated credential-granting call.
///
/// Declared in the SERVER build too, because `gunnar issuer show --at` is:
/// that binary must still parse the flag in order to refuse it BY NAME —
/// telling an operator "this binary carries no control client" rather than
/// "unexpected argument" — which is the same asymmetry `--monetize-pubkey`
/// has in the open build. It is a `&str`; it pulls in nothing.
#[cfg(any(feature = "control", feature = "server"))]
pub const CONTROL_ADDR_HELP: &str =
    "Where the control plane is. gunnar binds it to LOOPBACK by default, so the default here is \
     this host's server. To reach another host, tunnel to its loopback \
     (`ssh -L 50051:127.0.0.1:50051 <host>`) rather than binding it publicly. An estate is \
     reached through its site, `--at https://<site>`: its front carries the call, signed with \
     your key, to the main (GUNNAR_SITE_CA names the site's own CA, if a public one did not \
     issue its certificate).";

/// `gunnar control admit …`
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum AdmitCommand {
    /// How each kind of transfer for one namespace would be admitted
    /// (`Usage.AdmitPlan`).
    Show {
        #[arg(value_name = "NAMESPACE")]
        namespace: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control …`
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlCommand {
    /// Ask a server whether it has been enrolled. **Needs no credential.**
    ///
    /// It is the one question a server that nobody holds a key for can answer,
    /// and an unenrolled server is exactly that.
    Status {
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Step 1: claim a fresh server.** Creates the first user, who is
    /// gunnar-admin. Needs NO credential — and works exactly once, ever.
    ///
    /// The window is open only while no identity has ever been enrolled. It
    /// closes permanently on the first success, and deleting every user does
    /// not reopen it.
    Bootstrap {
        /// Your name. It is also your ACCOUNT: you are always admin of
        /// `<host>/<name>/<repo>`, and that is not a grant anybody can revoke.
        name: String,
        /// An OpenSSH public key line, or `@<path>`. Defaults to the public
        /// half of the key `-i` names, so neither flag is usually needed.
        #[arg(long, value_name = "KEY")]
        key: Option<String>,
        /// The private key whose public half to enrol, and to authenticate
        /// with afterwards.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        /// Where the client certificate the server issues (`<name>.cert.pem`,
        /// `<name>.key.pem`, `gunnar-issuer.pem`) is written. Defaults to a
        /// directory of your own, `~/.config/gunnar/<server>/`, created 0700 —
        /// never the current directory, which is a git checkout more often
        /// than not, and a private key in a checkout is one `git add` from a
        /// remote.
        #[arg(long, value_name = "DIR")]
        out: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Step 3: log in** with your ssh key, and see what you are.
    ///
    /// Writes nothing. gunnar keeps no session on either side: every call signs
    /// a fresh single-use credential, so there is no state for `bootstrap` to
    /// have left behind and none for this to create.
    Login {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Step 4: users.** Authenticated, and creating one needs gunnar-admin.
    #[command(subcommand)]
    User(ControlUserCommand),

    /// **Groups: grant access to a team, not one person at a time** (punkt 9).
    ///
    /// A group is a principal that holds no key. Grant it access with the
    /// ordinary `gunnar control grant <group> …`, add people to it, and they
    /// inherit the grant; remove them and they lose it. Managing a group needs
    /// gunnar-admin, exactly like a grant.
    #[command(subcommand)]
    Group(ControlGroupCommand),

    /// Repositories, against a running server.
    ///
    /// You may always create one in your OWN account with no grant at all;
    /// somebody else's needs a grant on their namespace.
    #[command(subcommand)]
    Repo(ControlRepoCommand),

    /// **Is the record of what happened on this box still complete?**
    /// (`Admin.AuditTrail`, server-wide `Read`.)
    ///
    /// The control plane has written a tamper-evident hash chain of its
    /// decisions since GUN-044, and until 2026-09-21 there was no way to read
    /// it except as root on the box — which an appliance does not have. This
    /// prints the chain's shape: how many entries, the tip hash, whether the
    /// chain still verifies, and whether it is replicated to the twin.
    ///
    /// It prints no entry. Who did what is a read of the file; this verb
    /// answers completeness.
    ///
    /// # After a restore
    ///
    /// A restored box keeps appending, so its TIP has moved by the time you
    /// ask. Give `--at-seq <N>` the last sequence the old primary reported and
    /// compare the `hash at seq` line: because every entry's hash commits to
    /// its `prev`, one matching hash proves the whole prefix came back
    /// unaltered.
    Audit {
        /// Ask for the hash this chain carried at this sequence number — the
        /// prefix proof a restore is checked with.
        #[arg(long, value_name = "N")]
        at_seq: Option<u64>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// Namespaces, against a running server.
    ///
    /// The offline `gunnar namespace` writes the control repository directly
    /// and therefore needs the server **stopped**. These do not.
    #[command(subcommand)]
    Namespace(ControlNamespaceCommand),

    /// **Accounts: lock a user out, and empty their account for good.**
    ///
    /// The per-USER half of what `repo` does per repository. `repo delete
    /// --purge` reaches one repository at a time; an account can hold hundreds
    /// of them plus soft-delete tombstones and orphan stores that no other
    /// listing shows, and there was no verb whose unit was a *user*.
    ///
    /// Every one of these needs **gunnar-admin** — Admin at server scope, not
    /// on the namespace. A namespace check would be self-granting: you are
    /// unconditionally admin of your own account, so it would let any user
    /// hard-purge themselves with one call and no undo.
    #[command(subcommand)]
    Account(ControlAccountCommand),

    /// **Clans: ordinary accounts grouped, each giving part of its own room.**
    ///
    /// A clan has a namespace of its own (private, like every account's) and
    /// an admin — its creator — who invites accounts and administers what is
    /// made in it: visibility, who else may reach it, deletion. Its members
    /// read, write and create private repositories there. Its room is the sum
    /// of what its members give out of their own; a contribution goes down
    /// only as far as what the clan stores, and leaving gives it back.
    /// Every verb is YOURS: gunnar decides from the clan who may.
    #[command(subcommand)]
    Clan(ControlClanCommand),

    /// **Pull mirroring: where this server's copy comes FROM.**
    ///
    /// The pull direction, and the exact mirror of `replication` below: that one
    /// says where a second copy of gunnar's repositories is pushed TO, this one
    /// says which other forge a repository here is pulled from. One service on
    /// the wire, because "where does this repository's history also live" is one
    /// question asked from two sides.
    ///
    /// `import` is the door: it lists a whole GitHub/Codeberg/GitLab/Forgejo
    /// account over that forge's REST API and mirrors what you choose, which is
    /// how a person moves in without a migration project.
    ///
    /// Not to be confused with `gunnar mirror` (no `control`), which keeps a
    /// copy in a data root on the machine you typed it on. This one talks to a
    /// server.
    #[command(subcommand)]
    Mirror(ControlMirrorCommand),

    /// **Replication: where a second copy of everything lives.**
    ///
    /// The appliance has no shell. `<data-root>/replication.json` is the truth
    /// and it survives a reboot, but on an OS-less image running as PID 1 there
    /// is no editor to write it with — so these are how a standby is named, and
    /// they are the only way.
    ///
    /// A target is configurable BEFORE any repository exists: replication is
    /// scoped to the server, a namespace or a repository, and nothing is
    /// looked up when you set one.
    #[command(subcommand)]
    Replication(ControlReplicationCommand),

    /// **The twin: the box that holds every transaction, and the restore
    /// from it.**
    ///
    /// A twin follows a primary's transaction log — every pack, ref edit,
    /// control-database write, secret and LFS object, in the order the
    /// primary was told — into a data root of its own, and never serves. On
    /// a gap it fetches the missing range first; when the primary no longer
    /// retains what it needs it stops and says `snapshot-needed`. `restore`
    /// replays a twin's log into a fresh data root.
    #[command(subcommand)]
    Twin(ControlTwinCommand),

    /// **The WireGuard tunnel address: handed over at bootstrap, never baked
    /// into the medium.** `enrol` allocates the next free address of the
    /// site's pool (keyed by the box's minted public key), hands it to the box
    /// over `Bootstrap.AssignTunnelAddress`, and registers the box's `[Peer]`
    /// in the hub's WireGuard config.
    #[command(subcommand)]
    Tunnel(ControlTunnelCommand),

    /// **Outbound events: send them to an external URL (webhooks).**
    ///
    /// A webhook is a subscriber to gunnar's event stream that POSTs each
    /// matching event to a URL — the way a CI/CD pipeline is triggered when a
    /// ref moves, without a process camped on `Events.Watch`. Every delivery is
    /// SIGNED with the server's key (an `sshsig`, no shared secret), so the
    /// receiver verifies it came from this gunnar with `ssh-keygen -Y verify`.
    ///
    /// Configured over the control plane and durable in
    /// `<data-root>/webhooks.json`, for the same reason replication is: the
    /// appliance has no shell.
    #[command(subcommand)]
    Webhook(ControlWebhookCommand),

    /// **The pre-receive gate: branch protection and ref-name policy.**
    ///
    /// A merge already needs a verified signed approval naming the exact
    /// commit. Nothing stopped a DIRECT push to the same branch, because the
    /// only surface that could was reachable from neither this CLI nor the
    /// console — while the server had been serving `Policy.*` out of
    /// `refs/gunnar/policy` the whole time. These are that surface.
    #[command(subcommand)]
    Policy(ControlPolicyCommand),

    /// Give a principal access, against a running server — or `grant list`
    /// to see who holds what.
    ///
    /// `gunnar control grant <principal> <level> --repo <ns>/<r>` gives;
    /// `gunnar control grant list` reads the whole table back. The one name
    /// this shadows is a principal literally called `list`, which `user add`
    /// will let you create and this verb can then not grant to.
    #[command(args_conflicts_with_subcommands = true)]
    Grant {
        #[command(subcommand)]
        command: Option<ControlGrantCommand>,
        /// The principal id.
        principal: Option<String>,
        /// How much access.
        #[arg(value_enum)]
        level: Option<LevelArg>,
        /// Scope it to the whole server. This IS gunnar-admin at `admin`.
        #[arg(long)]
        server: bool,
        /// Scope it to one namespace.
        #[arg(long, value_name = "NAME")]
        namespace: Option<String>,
        /// Scope it to one repository, `<namespace>/<repo>`.
        #[arg(long, value_name = "NS/REPO")]
        repo: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Take a grant back**, against a running server.
    ///
    /// The mirror of `grant`, minus the level: a scope holds at most ONE
    /// grant per principal — granting on the same scope replaces — so the
    /// principal and the scope name the grant, and there is no level to
    /// choose. Revoking a grant that is not there is an ERROR, not a quiet
    /// success: "revoked" about a grant that never existed reads identically
    /// to "revoked" about the one you meant, and the difference is whether
    /// somebody still has access.
    ///
    /// A principal's OWN account is not a grant and cannot be revoked here;
    /// `user remove` takes the whole principal.
    Revoke {
        /// The principal id.
        principal: String,
        /// The server-wide grant. This is how gunnar-admin is taken back.
        #[arg(long)]
        server: bool,
        /// The grant on one namespace.
        #[arg(long, value_name = "NAME")]
        namespace: Option<String>,
        /// The grant on one repository, `<namespace>/<repo>`.
        #[arg(long, value_name = "NS/REPO")]
        repo: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// The server's own health, authenticated: version, uptime and both
    /// listener binds.
    ///
    /// `status` is the unauthenticated question ("is this box enrolled, does
    /// it gate callers"); this is the authenticated one — what a headless
    /// appliance would tell you on a console you cannot see.
    Health {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **The public key this appliance signs actor tickets with**, as 64 hex
    /// characters — the string a monetize needs in `[products.<id>]
    /// appliance_key` before a tenant can renew their own subscription.
    ///
    /// `Billing.ApplianceIdentity` has served this since it was written, "so an
    /// operator can configure their monetize with it", and until 2026-09-19
    /// nothing but a test ever asked: there was no verb. MEASURED on gunnar.rs
    /// that day — every tenant's own renewal answered `501 unimplemented`,
    /// because the plugin had no key to check a ticket with and correctly
    /// refuses rather than trusting one it cannot verify.
    ///
    /// It is a PUBLIC key. Admin at server scope because it is operator
    /// configuration, not because the string is a secret — it VERIFIES tickets,
    /// it does not mint them.
    ///
    /// `metered` only, like the service it calls: `billing.proto` is not in
    /// codegen without the feature, and the community build "never mentions
    /// money at all" — an appliance that cannot sell a period carries no
    /// service that mints the permission to buy one, so a verb asking for one
    /// would be a promise the binary cannot keep.
    #[cfg(feature = "metered")]
    ApplianceIdentity {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **A namespace's plan, as this box ENFORCES it** — and the one door that
    /// hands the box a fact monetize signed.
    ///
    /// `Entitlement.Get/List/Set` had no verb: the only caller of `Set` was
    /// monetize's own poller, so a bench, a restore drill or an operator after
    /// a rescue could not put a fact on a box or ask what it was enforcing
    /// without writing a gRPC client. The reads answer out of the snapshot the
    /// front door reads, so a fact refused at boot — the wrong
    /// `--monetize-pubkey` after a restore — reads as Free here too.
    ///
    /// `metered` only, like `appliance-identity`: `entitlement.proto` is not in
    /// codegen without it.
    #[cfg(feature = "metered")]
    #[command(subcommand)]
    Entitlement(ControlEntitlementCommand),

    /// The server's counters: principals, keys, grants, repositories, the
    /// event bus, tombstones, replication and index work in flight.
    Stats {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **"If a tenant's cap rose to N bytes, could you serve it?"** — the
    /// question to ask BEFORE adding a disk.
    ///
    /// Not "how much is free". The answer is a verdict measured off the same
    /// `statvfs` the push door refuses under, AND — separately — whether this
    /// data set can ever grow at all. On the appliance it cannot: `/data` is an
    /// md set laid once at install, gunnar has no runtime growth path, and
    /// gunnar is PID 1 with no shell, so a disk attached to it would be added for nothing
    /// and stay invisible. Both halves are printed, on the yes arm as well as
    /// the no arm.
    Capacity {
        /// The cap being contemplated, in bytes: `--bytes 107374182400` asks
        /// "could you serve a tenant capped at 100 GiB?".
        #[arg(long, value_name = "BYTES")]
        bytes: u64,
        /// Whose cap is rising. Bytes it ALREADY holds are already spent out
        /// of free space, so only the difference needs new room. Without it
        /// the harder question is asked: could you serve `--bytes` that are
        /// not here yet.
        #[arg(long, value_name = "NAMESPACE")]
        namespace: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Grow the data set WITHOUT a restart** (`DATA-SET-GROWTH-FLOW.md`
    /// §3): drain, unmount, wait for every member volume to come back
    /// larger, grow in place, mount, reopen. `status` needs no credential.
    #[command(subcommand)]
    Grow(ControlGrowCommand),

    /// What is on disk: which backends are behind the two traits, hot and
    /// cold bytes, and one row per repository.
    Storage {
        /// Only this repository, `<namespace>/<repo>`. Without it, the
        /// server-wide totals and no per-repository rows.
        #[arg(long, value_name = "NS/REPO")]
        repo: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **The estate's boxes, as this gunnar knows them** (`Admin.Topology`):
    /// this box first (primary or twin), then its twins and standbys with their
    /// live state, the consoles that call it and the monetize it registers
    /// with — one row per box, each with the sentence that says how gunnar
    /// knows. The same rows the console's Machine card draws.
    Topology {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **The meters, per namespace: what is held and what moved.**
    ///
    /// `pack_bytes` (the packs and their indexes — the stored bytes),
    /// `cache_bytes` (the exploded read cache, re-derivable), `lfs_bytes`,
    /// `tombstoned_bytes` (soft-deleted, still held, still counted), `repos`,
    /// and `objects` (the indexed objects of stores open right now — the RAM in
    /// use).
    ///
    /// Since the flow ledger it also prints what MOVED today — `in`, `out`,
    /// `pushes`, `fetches`, `refused` — and when the namespace was last seen.
    /// Those are counts of events and not readings of a disk; `gunnar control
    /// activity <namespace>` is the same numbers day by day.
    ///
    /// Open source and always on: a self-hoster reads exactly the numbers a
    /// service provider meters from. Needs `read` on the namespace, or a
    /// server-wide `read` for every namespace.
    Usage {
        /// One namespace. Without it, every namespace the catalog holds.
        #[arg(value_name = "NAMESPACE")]
        namespace: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **What MOVED through a namespace, day by day.**
    ///
    /// Every number `gunnar control usage` prints is a STOCK meter: it answers
    /// *how much is on the disk*, and it reads exactly the same for a namespace
    /// that was pushed to this morning and one that was last touched in March.
    /// This is the other kind — bytes in and out, pushes, fetches, refusals
    /// (with the reason), the keys that were seen, and when the namespace was
    /// last used. One row per UTC day that moved something; a day with no
    /// traffic has no row.
    ///
    /// Open source and always on, as `usage` is. Needs `read` on the namespace
    /// — a tenant's own traffic is a tenant's own business, so this takes the
    /// same grant `usage <namespace>` does and never a server-wide one.
    Activity {
        /// The namespace. Required: activity is per tenant, and there is no
        /// server-wide answer that would mean anything.
        #[arg(value_name = "NAMESPACE")]
        namespace: String,
        /// How many days back, ending today. The server keeps 400.
        #[arg(long, default_value_t = 30, value_name = "N")]
        days: u32,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Admission: what a namespace's next transfer would get, and why.**
    ///
    /// `gunnar control admit show <namespace>` prints the usage over the
    /// rolling window, the budget and what is left of it, and per kind of work
    /// (clone, fetch, push, request) the class the gate would give it, the
    /// learnt estimate and the gate's own sentence. Needs `read` on the
    /// namespace — a tenant may read their own budget.
    Admit {
        #[command(subcommand)]
        command: AdmitCommand,
    },

    /// **Who wrote each line of a file, against a RUNNING server.**
    ///
    /// The offline `gunnar blame` opens the data root directly and takes an
    /// exclusive lock, so it cannot run while a `gunnar serve` holds the same
    /// root — which on a sealed appliance with no shell means it cannot run at
    /// all. This asks the running server to walk its own open store and answer
    /// over the control plane, so a headless box can finally be blamed. Needs
    /// `read` on the repository.
    Blame {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        repo: String,
        /// The file to blame, as a path within the repository's tree.
        #[arg(value_name = "PATH")]
        path: String,
        /// The revision to blame at: a branch, a tag, `HEAD`, or a hex oid.
        #[arg(long, default_value = "HEAD", value_name = "REV")]
        rev: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **A literal string across one revision's files, against a RUNNING
    /// server.** The up-server twin of `gunnar search`, reachable on a
    /// no-shell appliance for the same reason `control blame` is. Needs `read`
    /// on the repository.
    Search {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        repo: String,
        /// The literal string to look for. Not a regular expression.
        #[arg(value_name = "PATTERN")]
        pattern: String,
        /// The revision to search: a branch, a tag, `HEAD`, or a hex oid. Only
        /// this one revision, not the history behind it.
        #[arg(long, default_value = "HEAD", value_name = "REV")]
        rev: String,
        /// Skip files larger than this many bytes (they are never read). 0
        /// means the server default.
        #[arg(long, default_value_t = 0, value_name = "BYTES")]
        max_file_bytes: u64,
        /// Stop after this many matches. 0 means the server default.
        #[arg(long, default_value_t = 0, value_name = "N")]
        max_matches: u32,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Show a pull request's review, against a RUNNING server.**
    ///
    /// The comments and the approvals, with every approval re-checked against
    /// the identity key table right now — the same fold `gunnar forge show` prints,
    /// but reached over the control plane. The offline `gunnar forge show`
    /// opens the data root under an exclusive lock and so cannot run while a
    /// `gunnar serve` holds it, which on a sealed appliance with no shell means
    /// an operator has no other door to the review at all. Whether the pull
    /// request is open and what it merged at are `gunnar control pull`'s
    /// answers, deliberately not duplicated here. Needs `read` on the
    /// repository.
    Show {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        repo: String,
        /// The pull request number, as `PullRequests.Create` assigned it.
        #[arg(value_name = "N")]
        pull: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Merge a reviewed pull request, against a RUNNING server.**
    ///
    /// Fast-forward only, and gated: the server refuses unless a verified
    /// approval names the exact commit the target ref is about to move to, so a
    /// force-push after the review does not inherit it. This is the merge an
    /// operator on a sealed appliance runs — there is no other door to
    /// `PullRequests.Merge` from a shell-less box — and the gate's rules (the
    /// approval names the commit, forbid-self-approval, required-approvals) are
    /// the server's, applied unchanged; this is only the verb that reaches
    /// them. Needs `write` on the repository.
    Merge {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        repo: String,
        /// The pull request number to merge.
        #[arg(value_name = "N")]
        pull: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Who am I on this server?** (`Access.WhoAmI`.) The principal your key
    /// belongs to and the highest server-wide level it holds. Needs no grant.
    Whoami {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Pull requests, against a RUNNING server** (`PullRequests.*`): open,
    /// list, show and close one. Merging is `gunnar control merge`.
    #[command(subcommand)]
    Pr(ControlPrCommand),

    /// **Issues, against a RUNNING server**, signed with YOUR key and appended
    /// with `Forge.Append` — the online twin of the offline `gunnar forge issue`.
    #[command(subcommand)]
    Issue(ControlIssueCommand),

    /// **A pull request's review, against a RUNNING server**: read it, comment
    /// on it, approve a commit — the events signed with YOUR key.
    #[command(subcommand)]
    Review(ControlReviewCommand),

    /// **The live event feed** (`Events.Watch`).
    #[command(subcommand)]
    Events(ControlEventsCommand),

    /// **A first-login link onto an existing person** (`Access.EnrolmentLink`,
    /// IDENTITY-HOST): minted by the identity core, a server admin's.
    #[command(subcommand)]
    Invite(ControlInviteCommand),
}

/// `gunnar control invite …`
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlInviteCommand {
    /// Create one; prints its id and its SECRET — shown here once, never again.
    Create {
        /// The person whose passkey it enrols.
        #[arg(value_name = "PRINCIPAL")]
        principal: String,
        /// Days until it expires (at most 30).
        #[arg(long, value_name = "DAYS", default_value_t = 7)]
        expires_in_days: u32,
        /// Refuse a person who already holds a passkey (their FIRST one only).
        #[arg(long)]
        first_only: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control pr …` — pull requests over the control plane.
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlPrCommand {
    /// Open a pull request from `--source` into `--target`. Needs `write`.
    Create {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        repo: String,
        /// The full ref proposed, e.g. `refs/heads/topic`.
        #[arg(long, value_name = "REF")]
        source: String,
        /// The full ref it would merge into, e.g. `refs/heads/main`.
        #[arg(long, value_name = "REF")]
        target: String,
        #[arg(long, value_name = "TEXT")]
        title: String,
        #[arg(long, value_name = "TEXT", default_value = "")]
        body: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// List a repository's pull requests. Needs `read`.
    List {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        /// `open`, `merged`, `closed` or `all`.
        #[arg(long, value_name = "STATE", default_value = "all")]
        state: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Show one pull request. Needs `read`.
    Get {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        number: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Close a pull request without merging it. Needs `write`.
    Close {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        number: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control issue …` — issues over the control plane, signed with the
/// caller's own key. The actor is who gunnar says the key is (`WhoAmI`).
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlIssueCommand {
    /// Open an issue; prints the number the fold assigned. Needs `write`.
    Open {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(long, value_name = "TEXT")]
        title: String,
        #[arg(long, value_name = "TEXT", default_value = "")]
        body: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Comment on an issue. Needs `write`.
    Comment {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        number: u64,
        #[arg(long, value_name = "TEXT")]
        body: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Close an issue, naming why. Needs `write`.
    Close {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        number: u64,
        #[arg(long, value_name = "TEXT", default_value = "")]
        reason: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// List a repository's issues. Needs `read`.
    List {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Show one issue and its whole thread. Needs `read`.
    Get {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        number: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control review …` — a pull request's review over the control
/// plane, the events signed with the caller's own key.
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlReviewCommand {
    /// The review: comments and who approves what, each approval re-checked by
    /// gunnar. The same as `gunnar control show`. Needs `read`.
    Get {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        pull: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Comment on a pull request — on one line of one file with `--path`,
    /// `--line` and `--blob`, or on the whole pull request without. Needs
    /// `write`.
    Comment {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        pull: u64,
        #[arg(long, value_name = "TEXT")]
        body: String,
        /// The file the comment anchors to.
        #[arg(long, value_name = "PATH", requires_all = ["line", "blob"])]
        path: Option<String>,
        /// The line in that file (1-based).
        #[arg(long, value_name = "N")]
        line: Option<u32>,
        /// The blob the line is in, so the comment follows the code.
        #[arg(long, value_name = "OID")]
        blob: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Approve a specific commit — the one `gunnar control merge` will move
    /// the target to. Needs `write`.
    Approve {
        #[arg(value_name = "NS/REPO")]
        repo: String,
        #[arg(value_name = "N")]
        pull: u64,
        #[arg(long, value_name = "OID")]
        commit: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control events …`
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlEventsCommand {
    /// **Print the live feed**, one line per event, until interrupted (or
    /// `--count` events). With a server-wide `read`: everything, narrowed by
    /// the flags. Without one: naming no `--namespace` watches your own
    /// accounts (and accounts whose events are public); naming some asks for
    /// exactly those, and gunnar refuses an account you may not watch.
    Watch {
        /// An account to watch. Repeatable.
        #[arg(long, value_name = "NS")]
        namespace: Vec<String>,
        /// One repository, `<namespace>/<repo>`. Repeatable.
        #[arg(long, value_name = "NS/REPO")]
        repo: Vec<String>,
        /// Only these kinds, e.g. `ref-updated`, `repo-created`,
        /// `pull-request-opened`. Repeatable.
        #[arg(long, value_name = "KIND")]
        kind: Vec<String>,
        /// Stop after this many events (the stream's own prologue not counted).
        #[arg(long, value_name = "N")]
        count: Option<u64>,
        /// Resume after this sequence number, as far as the server still holds.
        #[arg(long, value_name = "SEQ", default_value_t = 0)]
        from_seq: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control grant list` — who holds what.
#[cfg(feature = "control")]
#[derive(Debug, Clone, Subcommand)]
pub enum ControlGrantCommand {
    /// **Every grant on the server, per principal** — the answer to "what can
    /// this principal see?".
    ///
    /// One line per grant under the principal that holds it: the scope
    /// (`server`, `namespace:<name>`, `repo:<namespace>/<repo>`) and the
    /// level. A principal's OWN account does not appear: everyone is admin of
    /// `<their-name>/…` by construction, and that is not a grant anybody gave
    /// or can revoke.
    List {
        /// Only this principal's grants.
        #[arg(long, value_name = "ID")]
        principal: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control tunnel …` — a box's WireGuard tunnel address.
#[cfg(feature = "control")]
#[derive(Debug, Clone, Subcommand)]
pub enum ControlTunnelCommand {
    /// What the box holds: its WireGuard public key, its tunnel address, and
    /// whether `wg0` is up (`Bootstrap.AssignTunnelAddress` with no address).
    Show {
        /// The box's control plane.
        #[arg(
            long,
            value_name = "HOST:PORT",
            conflicts_with = "ssh",
            required_unless_present = "ssh"
        )]
        at: Option<String>,
        /// A SEALED box's SSH door instead (`serve --no-grpc`): the
        /// `gunnar-tunnel-address` verb, as a gunnar-admin (`-i`).
        #[arg(long, value_name = "HOST:PORT")]
        ssh: Option<String>,
        /// The gunnar-admin key for `--ssh`.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
    /// **Give a fresh box its tunnel address and register it on the hub.**
    /// Idempotent: the same box gets the same address back.
    Enrol {
        /// The box's control plane (gRPC). A fresh box takes the address on
        /// `Bootstrap.AssignTunnelAddress`, an enrolled one on
        /// `Admin.SetTunnelAddress` (needs `-i`).
        #[arg(
            long,
            value_name = "HOST:PORT",
            conflicts_with = "ssh",
            required_unless_present = "ssh"
        )]
        at: Option<String>,
        /// A SEALED box instead (`serve --no-grpc --admin-key …`, no control
        /// plane): its SSH door, `gunnar-tunnel-address`, as the gunnar-admin
        /// whose key `-i` names.
        #[arg(long, value_name = "HOST:PORT")]
        ssh: Option<String>,
        /// The site's tunnel subnet, `a.b.c.d/prefix`. Its first host is the
        /// hub's and is never handed out.
        #[arg(long, value_name = "CIDR")]
        pool: String,
        /// The site's ledger of which box holds which address (created if absent).
        #[arg(long, value_name = "PATH")]
        ledger: PathBuf,
        /// The hub's WireGuard config; the box's `[Peer]` is appended once.
        #[arg(long, value_name = "PATH")]
        hub_peers: PathBuf,
        /// A name for the box in the ledger and the hub's comment (default: `--at`).
        #[arg(long)]
        label: Option<String>,
        /// A gunnar-admin key: for `--ssh`, and for a gRPC box PAST its
        /// bootstrap window (then the address goes over `Admin.SetTunnelAddress`).
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
}

/// `gunnar control twin …` — the twin, and the restore from it.
#[cfg(feature = "control")]
#[derive(Debug, Clone, Subcommand)]
pub enum ControlTwinCommand {
    /// **Make a FRESH box a twin** (`Bootstrap.BecomeTwin` — refused once
    /// anything is enrolled, and taken only under a credential from a key the
    /// box was FED: the installer's admin, an admin principal of its feed, or
    /// `--restore-pubkey`; h-bootstrap-open). Prints the twin's public key:
    /// enrol it on the primary as a machine in group `twin`.
    Join {
        /// The fresh box's control plane.
        #[arg(long, value_name = "HOST:PORT")]
        at: String,
        /// The primary's control plane, as the TWIN reaches it.
        #[arg(long, value_name = "HOST:PORT")]
        primary: String,
        /// A key the fresh box was fed (it signs the call).
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
    /// **Give a twin its mutual-TLS credential** — the pairing step the one
    /// medium cannot carry. Asks the TWIN for a signing request (its key is
    /// minted there and never leaves), has the PRIMARY's issuer sign it for
    /// `--principal` (Admin; the principal must be in group `twin`), and hands
    /// the certificate and the issuer to pin back to the twin. Run it after the
    /// twin's key is enrolled on the primary. Run it again under the same
    /// issuer to RE-ISSUE it, without a shell on either box.
    Certify {
        /// The twin's control plane.
        #[arg(long, value_name = "HOST:PORT")]
        at: String,
        /// The primary's control plane, as THIS machine reaches it.
        #[arg(long, value_name = "HOST:PORT")]
        primary_at: String,
        /// The twin's principal on the primary.
        #[arg(long, default_value = "twin-box")]
        principal: String,
        /// An admin key on the primary.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
    /// **Restore a fresh primary from its twin, over the wire**: the twin's
    /// `Mirror.LogFetch` piped into the fresh box's `Bootstrap.Restore`
    /// (no credential there — it is fresh). Restart the box afterwards.
    Replay {
        /// The twin's control plane.
        #[arg(long, value_name = "HOST:PORT")]
        twin: String,
        /// The fresh box's control plane.
        #[arg(long, value_name = "HOST:PORT")]
        into: String,
        /// The key to read the twin's log with (an admin of the set).
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        /// **Do not tell the box how much is coming, so it cannot refuse for room.**
        ///
        /// By default the replay announces the twin's log size and the box checks its own
        /// data set against it before the first byte lands, refusing by name when it is
        /// short — the restore-onto-smaller-hardware case. That check is deliberately
        /// conservative: it asks for twice the LOG, and a long-lived box's log is larger
        /// than the stores it builds (superseded documents, deleted packs — what
        /// `twin retain` exists to trim). So a legitimate restore of an old, busy box onto
        /// the same hardware can be refused.
        ///
        /// This says "I have looked at the numbers in the refusal and this set holds it".
        /// The restore then behaves as it always did: if the volume really does fill, the
        /// apply fails mid-stream, the box stays `restoring`, and the replay is resumable
        /// onto a bigger set. It is never a silent short restore either way.
        #[arg(long)]
        ignore_room: bool,
        /// **Restore from this twin even though it is not a current copy.**
        ///
        /// By default the replay asks the twin how current it is and REFUSES
        /// when the answer is not "level with its primary, as of moments ago":
        /// a twin that is behind, that is not following, or whose primary last
        /// answered longer ago than the heartbeat's silent bound. The refusal
        /// carries both numbers (applied / the primary's head) and the AGE, so
        /// the operator is refusing or overriding on facts.
        ///
        /// The twin exists for the worst case, and the worst case is exactly
        /// when nobody has time to notice that the copy stopped following a
        /// week ago. Restoring from a stale twin is sometimes still the right
        /// call — it is the only copy there is — so this says "I have read the
        /// numbers in the refusal and I want this copy anyway". It is never a
        /// silent stale restore either way.
        #[arg(long)]
        stale_ok: bool,
        /// **Take the replay although the twin no longer holds its oldest entries.** A twin
        /// that trimmed its log (`twin retain`) and keeps no snapshot of what it trimmed
        /// cannot give those entries back; by default the replay refuses by name, saying how
        /// many and what goes with them (DATA-SET-GROWTH-FLOW §2.1), before a byte streams.
        #[arg(long)]
        accept_lost: bool,
        /// **How long a twin that was LEVEL at its last answer may have heard nothing from its
        /// primary before plain replay refuses it** (`--stale-ok` then required). Default 24 h.
        ///
        /// From the twin, a primary that died and a network cut to a primary still alive and
        /// taking writes look the same: level, then silence. Minutes of that is main dying; a
        /// day of it is not something to assume. `now` refuses any silence; `<N>` seconds, or
        /// `<N>` with a `s`/`m`/`h`/`d`/`w` suffix.
        #[arg(long, value_name = "DURATION", default_value = "24h", value_parser = parse_max_silence)]
        max_silence: std::time::Duration,
        /// **The twin's old primary is fenced (or its machine stopped): replay beside it.**
        ///
        /// A twin that heard its primary within the last minute is following a box that is
        /// ALIVE; filling a fresh box from it would make two writable primaries, so plain
        /// replay refuses `not_fenced`. Fence the old primary first (`Mirror.SetRole` standby
        /// and `DemoteReplication`, or stop it) and say so here: a fenced primary still
        /// answers its twin, so the twin cannot tell. A primary re-laid at the same address
        /// reads `diverged` and needs no fence.
        #[arg(long)]
        primary_fenced: bool,
    },
    /// **Follow a primary.** Fetch every transaction it has that this data
    /// root has not, in order, apply it, keep polling. Needs server Admin on
    /// the primary: the log carries every sealed secret.
    Follow {
        /// The primary's control plane.
        #[arg(long, value_name = "HOST:PORT")]
        at: String,
        /// This twin's data root — its own copy of everything, plus the log.
        #[arg(long, value_name = "DIR")]
        data_root: PathBuf,
        /// The private key to authenticate with.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        /// Seconds between polls.
        #[arg(long, default_value_t = 5, value_name = "SECS")]
        poll_secs: u64,
        /// One poll, then exit — a cron, a bench, a hand check.
        #[arg(long)]
        once: bool,
    },
    /// **Restore: replay a twin's log into a fresh data root.** The restored
    /// primary continues the same sequence.
    Restore {
        /// The twin's data root (its `txlog/` is what is replayed).
        #[arg(long, value_name = "DIR")]
        from: PathBuf,
        /// The fresh data root to rebuild into.
        #[arg(long, value_name = "DIR")]
        into: PathBuf,
    },
    /// **What a box's log says**: head, oldest retained, and on a twin what
    /// it has applied and whether it is caught up.
    Status {
        /// The box's control plane.
        #[arg(long, value_name = "HOST:PORT")]
        at: String,
        /// The private key to authenticate with.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
    /// **Retention** (`Mirror.LogRetain`, server Admin): drop every whole
    /// segment of the PRIMARY's log below `--from` (default: everything up to
    /// the head). A twin that has not applied up to there takes a snapshot.
    Retain {
        /// The primary's control plane.
        #[arg(long, value_name = "HOST:PORT")]
        at: String,
        /// The oldest sequence to keep; 0 = keep nothing older than the next append.
        #[arg(long, default_value_t = 0, value_name = "SEQ")]
        from: u64,
        /// **Retain past what a twin has applied** (`LogRetainRequest.allow_past_twin`). By
        /// default the primary refuses to drop a frame the lowest-reporting twin has not applied,
        /// naming both numbers. This says the twin is gone or the hole is the point (a drill);
        /// the audit trail records who said it.
        #[arg(long)]
        allow_past_twin: bool,
        /// The private key to authenticate with.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
    /// **CATCH A TWIN UP THROUGH A RETENTION HOLE** — the one verb that drives
    /// `Mirror.SnapshotFetch` on purpose (`.nornir/twin-transaction-log.md`
    /// §Snapshot; the KVM row R8 in the same file).
    ///
    /// A twin that was away longer than the primary's retention window meets a
    /// HOLE: the next sequence it needs, `applied + 1`, is below the primary's
    /// `first_seq`, and no `LogFetch` can ever answer for it again
    /// (`mirror.proto`'s `LogFetch`: "`from` below `first_seq` is
    /// FAILED_PRECONDITION naming `first_seq`: the twin needs a snapshot, not a
    /// range"). The only way across is a full copy of the primary's state at one
    /// sequence, and this is the verb that takes one.
    ///
    /// **It freezes the primary, and that is why it is its own verb.** The
    /// producer holds `Log::freeze()` for the whole of `SnapshotFetch`
    /// (`crates/gunnar-grpc/src/service/mirror.rs:117`), so while the snapshot
    /// streams EVERY framed write on the primary is stopped — every push, every
    /// ref update, every control-plane mutation. A 44 GiB snapshot legitimately
    /// takes a long time and the freeze is the cost of a consistent `at`; it is
    /// never a cost to incur by accident. So:
    ///
    ///   * it REFUSES BY NAME when there is no hole (`no-hole`), because a twin
    ///     that is merely behind catches up with `twin follow`, which freezes
    ///     nothing;
    ///
    ///   * it reports how long the primary's writes were frozen, as a number;
    ///
    ///   * it bounds the wait: no piece for `--stall-secs` fails by name
    ///     (`stalled`) and drops the stream, which is what releases the freeze.
    ///
    /// Run it WHERE THE TWIN'S DISK IS, like `twin follow`: `--at` is the
    /// PRIMARY's control plane, `--data-root` is this box's own data root. The
    /// twin's own follower must not be running against that root at the same
    /// time.
    ///
    /// ```text
    /// gunnar control twin catch-up --at primary:50051 --data-root /data
    /// ```
    ///
    /// `--dry-run` establishes the hole and stops, so the decision to stop the
    /// primary's write path is made before it happens.
    CatchUp {
        /// **The PRIMARY's control plane** — the box the snapshot is taken
        /// from, and the box whose writes freeze while it streams.
        #[arg(long, value_name = "HOST:PORT")]
        at: String,
        /// **This twin's data root**, on this machine. The snapshot is staged
        /// in it (`txlog-snapshot-staging/`) and installed over it.
        #[arg(long, value_name = "DIR")]
        data_root: PathBuf,
        /// The private key to authenticate with: server Admin on the primary,
        /// or the twin's own machine key in group `twin` — a snapshot carries
        /// every sealed secret and every object.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        /// **Give up when NO snapshot piece has arrived for this long.** The
        /// deadline is on no progress, never on the transfer: a slow primary
        /// that keeps sending pieces is never cut off. The default is the
        /// primary's own mirror-image guard
        /// (`gunnar_grpc::service::mirror::SNAPSHOT_STALL_TIMEOUT`, 120 s),
        /// which is what cuts a twin off that stops READING.
        #[arg(long, default_value_t = 120, value_name = "SECS")]
        stall_secs: u64,
        /// **How many times the whole stream may be restarted.**
        ///
        /// `SnapshotFetchRequest` has no fields (`mirror.proto:165`), so there
        /// is no cursor on the wire and a broken stream can only be taken
        /// again FROM THE BEGINNING — which re-freezes the primary from
        /// scratch. Each restart is announced. A stall is never retried.
        #[arg(long, default_value_t = 3, value_name = "N")]
        attempts: u32,
        /// Establish whether there is a hole and say so, then stop. Nothing is
        /// streamed and the primary is never frozen.
        #[arg(long)]
        dry_run: bool,
    },
}

/// `gunnar control replication …` — replication's standbys.
#[cfg(feature = "control")]
#[derive(Debug, Clone, Subcommand)]
pub enum ControlReplicationCommand {
    /// **Add or replace a standby, by name.** Takes effect immediately and
    /// survives a reboot.
    ///
    /// Idempotent: the same `<name>` twice replaces rather than duplicates, so
    /// a retry over a flaky link cannot leave two standbys behind.
    Add {
        /// Your name for this standby. Every event, log line and status row
        /// identifies it by this rather than by its URL.
        name: String,
        /// Where it is: an SSH base — `ssh://git@standby:2222` — onto which
        /// `/<namespace>/<repo>.git` is appended, or a complete URL ending in
        /// `.git` for a `--repo`-scoped target.
        ///
        /// SSH only, and anything else is refused by name: the push half is a
        /// send-pack over the server's russh transport, which has no HTTP
        /// transport to dial with.
        remote: String,
        /// Scope it to one namespace instead of the whole server.
        #[arg(long, value_name = "NAME", conflicts_with = "repo")]
        namespace: Option<String>,
        /// Scope it to one repository, `<namespace>/<repo>`.
        #[arg(long, value_name = "NS/REPO")]
        repo: Option<String>,
        /// **The deploy key the SERVER authenticates to the standby with**, as
        /// a path ON THE SERVER.
        ///
        /// A server has no ssh-agent and no interactive user. Without this the
        /// push falls back to the client key ladder, which on a server is
        /// almost never what was meant — and the server warns about it at
        /// every start-up.
        #[arg(long, value_name = "PATH")]
        identity_path: Option<String>,
        /// Override the `known_hosts` file for this target, as a path on the
        /// server.
        #[arg(long, value_name = "PATH")]
        known_hosts_path: Option<String>,
        /// Refuse an unknown host key instead of trusting it on first use.
        /// Off by default so a standby can be brought up without a
        /// provisioning step; on is right for anything that outlives an
        /// afternoon.
        #[arg(long)]
        strict_host_key: bool,
        /// **Which repositories, by visibility.** `all` (the default) is a
        /// standby: everything the scope covers. `public-only` is a browse
        /// replica's feed: a private repository is
        /// never pushed there, and one that goes private is DELETED there —
        /// which is why `public-only` also needs `--control`.
        #[arg(long, value_enum, default_value_t = ReplicationScopeArg::All)]
        scope: ReplicationScopeArg,
        /// The replica's control plane, `host:port`, REQUIRED with
        /// `--scope public-only`: the delete on a public → private flip is
        /// `Repos.Delete` over this address, signed with `--identity-path`.
        #[arg(long, value_name = "HOST:PORT", required_if_eq("scope", "public-only"))]
        control: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Remove a standby by name and stop replicating to it now.
    ///
    /// A name that is not configured is an error and not a quiet success:
    /// "removed" about a standby that was never there reads identically to
    /// "removed" about the one you meant, and the difference is whether your
    /// data is still going somewhere.
    Remove {
        name: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **DEMOTE this box: drop EVERY standby at once — "I am no longer a
    /// primary".**
    ///
    /// The failover primitive. When a primary dies and its standby is promoted
    /// (promotion is operational — a gunnar standby is already a full gunnar
    /// that serves reads and takes writes, so nothing on it flips), the
    /// recovered old box comes back up and serving but its
    /// `replication.json` still lists the box that is now the NEW primary. Its
    /// replicator then resumes pushing its now-stale state and
    /// **force-clobbers the new primary's post-failover writes** — MEASURED in
    /// `deploy/checks/failover-drill.sh`, where a client commit made against the
    /// promoted standby was overwritten back to the old primary's ref.
    ///
    /// Run this on the recovered box before re-attaching it: it clears the whole
    /// target roster in one write, so the box stops being a primary. Then point
    /// the NEW primary at it with `replication add` and `replication resync`, and
    /// the pair is whole again — replicating the other way.
    ///
    /// It does not touch the box's repositories or its own control plane: a
    /// demoted box still serves git and still takes writes. It has only stopped
    /// shipping a second copy anywhere. Idempotent — a box with no targets
    /// demotes to the same place, so it is safe to run again.
    Demote {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Make this box a BROWSE replica**: a
    /// read-only standby that also serves anonymous reads of public
    /// repositories, refuses every control-plane mutator, and CANNOT be
    /// promoted — not by `promote`, not by `abdicate --promote`, not by the
    /// passive heartbeat. Feed it from the primary with
    /// `replication add <name> <remote> --scope public-only --control <this
    /// box>:50051`. The way back is `standby`, which only narrows what it
    /// serves.
    Browse {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **ABDICATE: this master steps down cleanly, then hands off.**
    ///
    /// The voluntary counterpart to a crash. `demote` is what you run on a box
    /// that already died; `abdicate` is how a healthy master leaves without
    /// losing a write, in order:
    ///
    ///   1. **freeze** — this box stops taking client writes (role → standby),
    ///      so nothing lands here after the hand-off begins;
    ///   2. **flush** — every standby is resynced and this waits for the queues
    ///      to drain, so the standby has everything that was pending. The wait
    ///      is a poll that returns the instant every queue is empty, bounded by
    ///      a ceiling (default 30 s) so a dead standby cannot wedge the hand-off.
    ///      On a heavily loaded box a *healthy* standby's backlog can take longer
    ///      than 30 s; raise the ceiling with `GUNNAR_ABDICATE_FLUSH_SECS=<secs>`
    ///      in the serving box's environment (a blank/zero/garbage value keeps
    ///      the 30 s default);
    ///   3. **demote** — the roster is cleared, so this box can never later
    ///      clobber the new primary.
    ///
    /// Then, as abdication's LAST act, it promotes the new primary — IF you name
    /// where its control plane is with `--promote`. That is the takeover: the
    /// standby is told `SetRole(PRIMARY)` and begins taking writes. Without
    /// `--promote` the three local steps still run and the command prints the
    /// one `replication promote` line to run against the standby yourself —
    /// naming a new primary is a decision, so it is never silently assumed.
    ///
    /// **The traffic switch is separate and is infrastructure.** The front
    /// (DNS / the UpCloud DNAT) still has to point at the new primary; abdication
    /// makes the hand-off safe, it does not move the address.
    Abdicate {
        /// The NEW primary's control plane, `host:port` — the standby to promote
        /// as abdication's last act. Omit to run only the local freeze/flush/
        /// demote and be told the `promote` command to run yourself.
        #[arg(long, value_name = "ADDR")]
        promote: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **PROMOTE this box to a writable primary — the takeover flip.**
    ///
    /// A standby serves reads and, once promoted, takes writes. Run it on the
    /// standby after the old master abdicated or died: the box records that it
    /// is a primary (persisted, so it survives a reboot) and thaws the write
    /// freeze. Idempotent — promoting a box that is already a primary is a
    /// no-op that prints the same "primary" status.
    ///
    /// The old master's `abdicate --promote <this box>` runs exactly this for
    /// you; this verb is the manual half, and the one a passive-heartbeat
    /// standby would call for itself when it decides the master is gone.
    Promote {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **STANDBY: make this box read-only to clients.**
    ///
    /// A standby serves reads and accepts only its primary's replication push (a
    /// `Machine` identity); a direct `git push` from a person or a deploy key is
    /// refused with "push to the primary". This is how a second box is
    /// deliberately made a standby up front, so a client that is mis-pointed at
    /// it cannot leave a write the primary never sees. `promote` is the inverse.
    Standby {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// What is configured, and what each standby has actually done — including
    /// **"last successful replication: never"**.
    ///
    /// Cheap by default: it reports the roster, each standby's
    /// synced/failed/pending, the verdict word and each repository's copy state
    /// without opening a single repository store. The one expensive number —
    /// **how many refs live on this box alone** — is behind `--refs`, because
    /// counting it opens every repository's reference database.
    List {
        /// **Also count the refs a mirror does not carry**, per repository and
        /// server-wide. This opens every repository's reference database — one
        /// refold each on a cold box — so it is off unless you ask: reach for it
        /// when you want the durability shortfall, not on every status glance.
        #[arg(long)]
        refs: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **BACKFILL a standby with what it never got.**
    ///
    /// Adding a standby copies NOTHING. Replication rides the push bus, so a
    /// standby holds what was pushed after it existed — a repository's whole
    /// history arrives on its next push, and a repository nobody pushes to
    /// again never arrives at all. MEASURED on the reference appliance 2026-08-31: a
    /// standby configured against 22 existing repositories held **0** of them,
    /// and `alice/linux-mirror` had 3818 refs on the primary and none on the
    /// standby.
    ///
    /// This queues them. It does not copy anything itself: every byte still
    /// moves on the standby's own background worker, through the same bounded
    /// queue and the same backoff a push uses, so a backfill never blocks a
    /// push and never waits for one. Watch it with `replication list` — the
    /// `pending` count falls, and the row names the repository in flight.
    ///
    /// **It is safe to run again.** A repository already outstanding coalesces;
    /// one the standby already has costs one ref advertisement and an empty
    /// command list. Interrupted half way — a reboot, a dead standby, a network
    /// that went away — the answer is to run it again.
    ///
    /// **The hash.** A standby PUSH-CREATES sha1 — the first-push prospect since
    /// 2026-09-20, because git advertises the object format before the client
    /// says anything and sha1 is what an un-negotiated client assumes. A
    /// repository of any OTHER hash replicates to nothing until it is
    /// pre-created on the standby with
    /// `control repo create <ns>/<repo> --hash sha256`. Those repositories are
    /// listed by name rather than left to fail quietly.
    Resync {
        /// The standby, by name, exactly as `list` prints it. A name that is
        /// not configured is an error: "resynced" about a standby that was
        /// never there reads identically to "resynced" about the one you meant.
        name: String,
        /// Only this repository, `<namespace>/<repo>`.
        ///
        /// Without it, every repository the standby's scope covers. With it,
        /// one — which is how a repository too large to ship in this maintenance
        /// window stays a separate decision from all the others.
        #[arg(long, value_name = "NS/REPO")]
        repo: Option<String>,
        /// Everything the standby covers **except** these. Repeatable.
        ///
        /// The other half of `--repo`, and the one you actually reach for. On
        /// the reference appliance 24 of the 25 repositories are a few hundred
        /// megabytes together and one is ~8.7 GB and 13.9 M objects that
        /// projects **182–235 GiB** against a standby whose `/data` is
        /// **224.9 GiB**. Without this the only way to ship the safe
        /// twenty-four is one call each, and a box with no shell is exactly
        /// what this control plane is for.
        ///
        /// Ignored when `--repo` names one. An exclusion that matched nothing
        /// is reported rather than passed over: a typo and a real exclusion are
        /// the same command with very different outcomes.
        #[arg(long, value_name = "NS/REPO")]
        except: Vec<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Flush — the replication watermark.** Push everything pending to
    /// every standby, wait (bounded), and report whether the twin is caught
    /// up: the proof step 0 of a data-set growth needs before `/data` is
    /// unmounted. Changes no role and no roster.
    ///
    /// What it proves: every push the replicator saw is on the twin. What
    /// it does NOT prove: refs outside heads/tags, LFS objects, the control
    /// database, visibility, tombstones — and repositories nobody pushed
    /// since the twin existed, unless `--resync` enqueues them all.
    Flush {
        /// How long to wait for the queues to drain; 0 = the abdicate ceiling.
        #[arg(long, default_value_t = 0, value_name = "SECS")]
        timeout_secs: u32,
        /// Enqueue EVERY repository first (a full backfill).
        #[arg(long)]
        resync: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control grow …` — the runtime data-set growth
/// (`DATA-SET-GROWTH-FLOW.md` §3, ruling 1: the appliance never goes down).
#[cfg(feature = "control")]
#[derive(Subcommand, Debug, Clone)]
pub enum ControlGrowCommand {
    /// **Begin a growth.** gunnar-admin. Drains the box (new pushes are
    /// refused with "gunnar.rs is growing its storage…"), unmounts `/data`,
    /// then WAITS for the outside actor to detach, enlarge and re-attach
    /// every member volume; when all are back and larger it grows in place,
    /// mounts and serves again. `grow status` follows it; `grow resume` says
    /// "look again".
    ///
    /// Mints an OPERATOR go-ahead (the signed fact D3 asks for): the
    /// gunnar-admin credential on this call is the approval. `--go-ahead`
    /// sends one minted elsewhere (monetize's, on a metered box) instead.
    Start {
        /// The per-member size to grow to, GiB; without it, whatever every
        /// member comes back larger at.
        #[arg(long, value_name = "GIB")]
        target_gib: Option<u64>,
        /// How long in-flight transfers may take to finish before the growth
        /// aborts with nothing changed (never kills a transfer).
        #[arg(long, default_value_t = 600, value_name = "SECS")]
        drain_timeout_secs: u32,
        /// How long `/data` may stay unmounted waiting for the members. Past it,
        /// with every member present, the set is mounted back at the size the
        /// members carry and the growth fails as `grow.unmounted_too_long`
        /// (alarmed on `Admin.Health`); with a member missing it keeps waiting,
        /// alarmed.
        #[arg(long, default_value_t = 3600, value_name = "SECS")]
        wait_members_timeout_secs: u32,
        /// A go-ahead file to send verbatim instead of minting an operator one.
        #[arg(long, value_name = "PATH")]
        go_ahead: Option<PathBuf>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// The growth's phase, the members and the journal. **Needs no
    /// credential** — the actor outside the box that owns the volumes reads
    /// this while the identity table is off the stripe.
    Status {
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Look again**: the members are back and larger. gunnar-admin.
    /// `--give-up` stops waiting, assembles what is there at whatever size it
    /// is, and serves.
    Resume {
        #[arg(long)]
        give_up: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control webhook …` — the event stream's outbound delivery, over the control
/// plane.
///
/// Each verb returns the endpoint roster AND the server's webhook signing
/// public key — the OpenSSH line a receiver pins to verify a delivery with
/// `ssh-keygen -Y verify`. The private half never leaves the box.
#[cfg(feature = "control")]
#[derive(Debug, Clone, Subcommand)]
pub enum ControlWebhookCommand {
    /// **Add or replace an endpoint, by name.** Takes effect immediately and
    /// survives a reboot.
    ///
    /// Idempotent: the same `<name>` twice replaces rather than duplicates.
    Add {
        /// Your name for this endpoint. Every log line and status row names it
        /// by this rather than by its URL.
        name: String,
        /// Where deliveries are POSTed: `http://…` or `https://…`.
        url: String,
        /// Only deliver these event kinds (repeatable, or comma-separated),
        /// e.g. `ref.updated`. Omit for every kind. A name that matches no kind
        /// is refused — a filter that names nothing delivers nothing.
        #[arg(long, value_name = "KIND", value_delimiter = ',')]
        kinds: Vec<String>,
        /// Only deliver events about this namespace.
        #[arg(long, value_name = "NAME", conflicts_with = "repo")]
        namespace: Option<String>,
        /// Only deliver events about this repository, `<namespace>/<repo>`.
        #[arg(long, value_name = "NS/REPO")]
        repo: Option<String>,
        /// An HMAC shared secret, for a receiver written against GitHub's
        /// `X-Hub-Signature-256`. The `sshsig` is always sent and is the one to
        /// prefer; this is only for compatibility. Stored on the server, never
        /// shown again.
        #[arg(long, value_name = "SECRET")]
        secret: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// What is configured, plus the signing public key a receiver verifies
    /// deliveries with, and per-endpoint delivered/failed/dropped counters.
    List {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Remove an endpoint by name and stop delivering to it now.
    ///
    /// A name that is not configured is an error, not a quiet success:
    /// "removed" about an endpoint that was never there reads identically to
    /// removing the one you meant.
    Remove {
        name: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control policy …` — the pre-receive gate, over the control plane.
///
/// **The asymmetry these close.** Since a merge started requiring a verified
/// signed approval naming the exact commit, the review gate has been real —
/// and a direct push to `main` walked straight past it, because the surface
/// that would have stopped it was reachable from nothing. `Policy.*` has been
/// served since `gunnar_core::PolicyStore` gave the document a home at
/// `refs/gunnar/policy`; these verbs are the half that lets anyone say so.
///
/// A rule is stored **per repository, keyed by ref pattern**, and the pattern
/// is a git-style glob over full ref names — `refs/heads/main`,
/// `refs/heads/release/*`. It is not a branch name: `main` matches no ref and
/// protects nothing, which is why `protect` refuses it by name.
#[cfg(feature = "control")]
#[derive(Debug, Clone, Subcommand)]
pub enum ControlPolicyCommand {
    /// **Protect refs matching a pattern.** Upserted on the pattern, so the
    /// same pattern twice replaces rather than accumulates.
    ///
    /// The defaults are the strict ones: with no flags at all a matching ref
    /// cannot be force-pushed and cannot be deleted. Each `--allow-*` gives one
    /// of those back, which makes the permissive choice the one that had to be
    /// typed.
    Protect {
        /// `<account>/<name>`.
        path: String,
        /// A git-style glob over FULL ref names — `refs/heads/main`,
        /// `refs/heads/release/*`. Not a branch name.
        pattern: String,
        /// Permit a non-fast-forward update. Off by default.
        #[arg(long)]
        allow_force_push: bool,
        /// Permit deleting a matching ref. Off by default.
        #[arg(long)]
        allow_delete: bool,
        /// Every new commit must carry a valid ssh-sig from a key registered
        /// to its pusher.
        #[arg(long)]
        require_signature: bool,
        /// Only these principals may push here. Repeatable. Empty — the
        /// default — means "any principal with WRITE".
        #[arg(long, value_name = "ID")]
        principal: Vec<String>,
        /// Reject an object larger than this BEFORE it lands. 0 is no limit.
        #[arg(long, value_name = "BYTES", default_value_t = 0)]
        max_object_bytes: u64,
        /// Reject a push carrying more objects than this. 0 is no limit.
        #[arg(long, value_name = "N", default_value_t = 0)]
        max_objects_per_push: u64,
        /// A merge into a matching ref does not count the pull request
        /// AUTHOR's own approval. Off by default: a solo operator must stay
        /// able to merge.
        #[arg(long)]
        forbid_self_approval: bool,
        /// A merge into a matching ref needs this many DISTINCT verified
        /// approvers of the exact tip. Approvals by the same principal count
        /// once. 0 keeps the baseline: one verified approval.
        #[arg(long, value_name = "N", default_value_t = 0)]
        required_approvals: u32,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Remove the rule on a pattern**, exactly as `list` prints it.
    ///
    /// A pattern that has no rule is an error and not a quiet success:
    /// "unprotected" about a rule that was never there reads identically to
    /// "unprotected" about the one you meant, and the difference is whether
    /// `main` is still guarded.
    Unprotect {
        /// `<account>/<name>`.
        path: String,
        /// The pattern, byte for byte as `list` prints it.
        pattern: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// What is protected here — and **"nothing"** said as the word.
    ///
    /// An unprotected repository and a repository whose rules failed to load
    /// are the same empty list and very different facts, so the empty case
    /// says which one it is.
    List {
        /// `<account>/<name>`.
        path: String,
        /// Only the rule on this pattern. Without it, every rule.
        #[arg(long, value_name = "GLOB")]
        pattern: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// The ref-name allowlist/denylist. **Deny wins.**
    RefNames {
        /// `<account>/<name>`.
        path: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Replace** the ref-name allowlist/denylist. Deny wins.
    ///
    /// Replace and not merge: the document is written whole, so passing
    /// neither flag CLEARS the policy rather than leaving the old one in
    /// place. That is the only version of this verb whose result can be
    /// predicted from the command line alone, and it says so before it writes.
    SetRefNames {
        /// `<account>/<name>`.
        path: String,
        /// A ref name may match one of these. Repeatable. Empty means "any
        /// name that is not denied".
        #[arg(long, value_name = "GLOB")]
        allow: Vec<String>,
        /// A ref name matching one of these is refused, even if it is also
        /// allowed. Repeatable.
        #[arg(long, value_name = "GLOB")]
        deny: Vec<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// The gates that run on this repository's push path, and **which of them
    /// this repository has configuration for**.
    ///
    /// `enabled` is not "compiled in": a gate with nothing configured cannot
    /// reject anything, and a list that claimed otherwise would be a UI
    /// rendering a guard that does not exist.
    Gates {
        /// `<account>/<name>`.
        path: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control repo …`
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlRepoCommand {
    /// Create a repository at `<account>/<name>`.
    ///
    /// New repositories are **sha256**, so a stock `git init` working
    /// tree cannot push to one — `git init --object-format=sha256`, or
    /// `--hash sha1` here.
    Create {
        /// `<account>/<name>`.
        path: String,
        /// The object hash. sha256 unless you have a sha1 client you cannot
        /// change.
        #[arg(long, value_enum, default_value_t = HashArg::Sha256)]
        hash: HashArg,
        /// Readable by anyone, with no key at all.
        #[arg(long)]
        public: bool,
        /// **Take over a store already on disk at this name** (a catalog
        /// restored over a surviving data disk). Refused unless the store's
        /// hash marker matches `--hash`. Without it a create refuses the name
        /// BY NAME: "a store already exists at …; delete reclaims it".
        #[arg(long)]
        adopt: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// List repositories.
    List {
        /// Only this account's.
        #[arg(long, value_name = "ACCOUNT")]
        namespace: Option<String>,
        /// Only repositories whose `<account>/<name>` contains this,
        /// case-insensitively — gunnar filters, over everything you may see.
        #[arg(long, value_name = "TEXT")]
        query: Option<String>,
        /// Only repositories that are mirrors of an upstream.
        #[arg(long)]
        mirrors: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Show one repository: its hash, default branch and visibility.
    Get {
        /// `<account>/<name>`.
        path: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Delete a repository. Without `--purge` the bytes are KEPT for a
    /// retention window and `repo undelete` puts it back.**
    ///
    /// The catalog row goes either way, so the name stops working immediately.
    /// What differs is the bytes: a tombstone holds them for
    /// `--retention-days` (30 by default) and a sweep reclaims them when it
    /// closes; `--purge` returns them now, in about two seconds, with no undo.
    ///
    /// A tombstone is still storage on the account until it expires —
    /// `repo list-deleted` shows what is held and what it costs.
    Delete {
        /// `<account>/<name>`.
        path: String,
        /// Required. Deleting a repository takes its name out of the catalog
        /// immediately, and a typo in a path is not distinguishable from an
        /// intention.
        #[arg(long)]
        yes: bool,
        /// **Reclaim the bytes NOW.** No window, no undelete.
        #[arg(long)]
        purge: bool,
        /// How long the bytes are kept. `0` means at the next sweep.
        #[arg(long, value_name = "DAYS")]
        retention_days: Option<u32>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Put a soft-deleted repository back**, inside its retention window.
    Undelete {
        /// `<account>/<name>`.
        path: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **End a retention window early.** There is no undo after it.
    Purge {
        /// `<account>/<name>`.
        path: String,
        /// Required, for the same reason `delete --yes` is.
        #[arg(long)]
        yes: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Maintain a live repository: seal, compact, drop the read cache.**
    ///
    /// The same maintenance `gunnar gc <path>` runs on the box, reachable from
    /// wherever the control plane is. It reclaims only what the server can
    /// re-derive — the lazily-exploded read cache goes, the commit-and-tree
    /// pool stays because that is the graph — so there is nothing to confirm
    /// and no `--yes`: the worst outcome is a slower next read.
    ///
    /// Needs `Write` on the repository, not `Admin`. A principal who may push
    /// to a repository may reclaim its cache.
    ///
    /// The server runs **one gc at a time for the whole box** and queues the
    /// rest, so this enqueues and then waits for its turn, printing what it
    /// freed. Asking twice for a repository already queued joins the job that
    /// is there rather than running a second one.
    Gc {
        /// `<account>/<name>`.
        path: String,
        /// Enqueue and return, printing the job instead of waiting for it.
        ///
        /// For a script that wants the gc started and is not going to sit
        /// through it. `repo gc-status <path>` reads the outcome afterwards.
        #[arg(long)]
        no_wait: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **How a repository's gc is going, or how the last one went.**
    ///
    /// Needs only `Read`: seeing that maintenance ran is not asking for it.
    /// Says so plainly when the server is holding no job at all, which is a
    /// different answer from a gc that reclaimed nothing.
    GcStatus {
        /// `<account>/<name>`.
        path: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// What is deleted and not yet purged, with the bytes it is still costing.
    ListDeleted {
        /// Only this account's.
        #[arg(long, value_name = "ACCOUNT")]
        namespace: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Store directories with no catalog row and no tombstone — bytes
    /// nothing else can see, and names nothing else can free.**
    ///
    /// Every other reclaim path keys off a record: `repo delete` off the
    /// catalog row, `undelete`/`purge`/`list-deleted`/the sweep off a
    /// tombstone. A directory with neither is invisible to all of them, and
    /// `repo create` still refuses its name because the bytes are there.
    /// MEASURED on the appliance 2026-08-30: ~25-39 GB at `alice/linux`,
    /// stranded.
    ///
    /// The `HASH` column is the store's `OBJECT_FORMAT` marker, and `-` means
    /// the store predates it — that is the value to pass to `repo create
    /// --adopt --hash` if you want to KEEP the objects instead of reclaiming
    /// them.
    ListOrphans {
        /// Only this account's.
        #[arg(long, value_name = "ACCOUNT")]
        namespace: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Reclaim an orphan store's bytes.** No window, no undo.
    ///
    /// To KEEP the objects instead, `repo create <path> --adopt --hash <the
    /// HASH column of list-orphans>` takes the store over as a repository.
    Reclaim {
        /// `<account>/<name>`.
        path: String,
        /// Required, for the same reason `delete --yes` is.
        #[arg(long)]
        yes: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Set the branch a fresh clone checks out.
    SetDefaultBranch {
        /// `<account>/<name>`.
        path: String,
        /// A branch name (`main`) or a full ref (`refs/heads/main`). A short
        /// name is expanded to `refs/heads/<name>`; anything already under
        /// `refs/` is sent as given, so the server refuses a `refs/tags/…`
        /// rather than this quietly rewriting it.
        branch: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Pull one repository's stored bytes OFF the box, over the control
    /// plane.**
    ///
    /// `gunnar repo archive-out` writes the same bytes to a path *on* the
    /// appliance, which is no use as a backup: the box has no shell to copy it
    /// out with. This streams them to a file on the machine running the
    /// command, so a cron somewhere else can hold the copy.
    ///
    /// The file it writes is exactly the file the local verb writes —
    /// `gunnar repo archive-in <FILE> --as <ns/name>` restores it, and the
    /// digest the server computed while sending is checked against the bytes
    /// that arrived.
    ///
    /// **It needs a Read grant on the repository**, the same grant cloning it
    /// privately needs, because that is what it hands over.
    ///
    /// `--from-generation` is a WATERMARK, not a diff: pass the previous run's
    /// `to_generation` and only the new bytes travel. Safe while the server is
    /// serving; there is nothing to freeze.
    ArchiveOut {
        /// `<account>/<name>`.
        path: String,
        /// Where to write the archive, **on this machine**.
        #[arg(long, value_name = "FILE")]
        to: PathBuf,
        /// Start above this `objects.pack` offset. 0 = a full archive.
        #[arg(long, default_value_t = 0, value_name = "N")]
        from_generation: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Make a repository readable with no key at all, or stop it being.
    SetVisibility {
        /// `<account>/<name>`.
        path: String,
        /// `public` is anonymous READ. It never makes anything writable.
        #[arg(value_enum)]
        visibility: VisibilityArg,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Make a repository ENCRYPTED, or stop it being: on, the server refuses
    /// any push that would put plaintext on it. The account admin's decision.
    ///
    /// The server never holds a key either way; members encrypt with
    /// `gunnar crypt`. See `.nornir/encrypted-repos.md`.
    SetEncrypted {
        /// `<account>/<name>`.
        path: String,
        /// `on` or `off`.
        #[arg(value_parser = ["on", "off"])]
        state: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `--visibility`, one arm per [`gunnar_core::Visibility`].
#[cfg(feature = "control")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum VisibilityArg {
    /// Reachable only with a key that holds a grant. The default for a new
    /// repository.
    Private,
    /// Anonymously READABLE. Writing still needs a key and a grant, and the
    /// listener's `--no-anonymous` closes the door regardless.
    Public,
}

#[cfg(feature = "control")]
impl VisibilityArg {
    /// The proto's enum. One translation, in one place.
    pub fn to_proto(self) -> gunnar_proto::Visibility {
        match self {
            VisibilityArg::Private => gunnar_proto::Visibility::Private,
            VisibilityArg::Public => gunnar_proto::Visibility::Public,
        }
    }
}

/// `gunnar control namespace …`
/// `replication add --scope`, see the verb.
#[cfg(feature = "control")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ReplicationScopeArg {
    /// Every repository the target's scope covers — a standby.
    All,
    /// Only public repositories — a browse replica's feed.
    PublicOnly,
}

#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlNamespaceCommand {
    /// Create a namespace. Nested names (`team/sub`) are legal; grants do NOT
    /// inherit between them.
    ///
    /// There is deliberately **no `--description`**. `CreateNamespaceRequest`
    /// carries the field, `CoreControlPlane::create_namespace` takes it as
    /// `_description` and drops it, `gunnar_core::Namespace` has nowhere to put
    /// it and `list_namespaces` returns `String::new()` for every namespace.
    /// A flag that reached none of that would be the same defect this file is
    /// closing, one layer up.
    Create {
        /// The namespace name.
        name: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// List namespaces.
    List {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Delete a namespace. A namespace that still holds repositories is
    /// refused unless `--delete-repos` says otherwise; deleting them is never
    /// implicit.
    Delete {
        /// The namespace name.
        name: String,
        /// Delete the repositories in it too. **There is no undo.**
        #[arg(long)]
        delete_repos: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **The account admin's settings: is the namespace public, are its
    /// events public.** Both are private for every account until its admin
    /// says otherwise, and only the account admin may (`Repos.
    /// SetNamespaceSettings`). With no flag, prints the current settings.
    Settings {
        /// The namespace (the account).
        name: String,
        /// Show the namespace to everyone (`on`), or only through its public
        /// repositories (`off`).
        #[arg(long, value_parser = ["on", "off"])]
        public: Option<String>,
        /// Show the account's emitted events to everyone (`on`) or only inside
        /// the account (`off`).
        #[arg(long, value_parser = ["on", "off"])]
        events_public: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control user …`
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlUserCommand {
    /// Create a user with a key. **Needs gunnar-admin.**
    ///
    /// The new user is always admin of their own account — the namespace named
    /// after them — and that is intrinsic, not a grant. `--gunnar-admin` is the
    /// separate, grantable thing, and any gunnar-admin may hand it on.
    Add {
        /// Their display name. It is also their id — and therefore their
        /// account — unless `--id` says otherwise.
        name: String,
        /// Their OpenSSH public key line, or `@<path>`.
        #[arg(long, value_name = "KEY")]
        key: String,
        /// **Their id, if it is not the name.** The id is the account namespace
        /// and the key every grant, gate and membership is filed under; it is
        /// chosen here, once, and never moves. The name is a label — see
        /// `user rename`. Same character rules as a namespace.
        #[arg(long, value_name = "ID")]
        id: Option<String>,
        /// Also make them gunnar-admin: a server-wide Admin grant, exactly the
        /// one the first user got.
        #[arg(long)]
        gunnar_admin: bool,
        /// **What kind of identity this is**: a `user` (a human, the
        /// default), a `machine` (CI, a bot, or **a standby's replication
        /// source** — a `machine` key is the one a frozen standby lets push),
        /// or a `deploy` key. A standby refuses a direct `git push` from a
        /// `user` or `deploy` key while accepting the primary's replication
        /// push, and that is decided by this kind — so the deploy key a primary
        /// replicates with must be enrolled here as `machine`.
        #[arg(long, value_enum, default_value_t = PrincipalKindArg::User)]
        kind: PrincipalKindArg,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Enrol another key on a user who already exists.** One human, several
    /// machines, ONE principal.
    ///
    /// Without this verb the only way to reach a second machine was to create a
    /// second user — MEASURED 2026-08-06, when a desktop's key and a laptop's key
    /// became `alice` and `alice-desktop`. That is not a cosmetic split: every grant,
    /// every ownership and every revoke then fragments per machine, and
    /// `gunnar control user remove alice` stops meaning what an operator
    /// reads it as.
    ///
    /// The identity table has always held **many keys per principal** — the key
    /// table is `fingerprint -> {principal_id, …}` and `keys_of()` returns a
    /// list — and `Access.AddKey` has always existed on the wire. What was
    /// missing was only this: a way to call it for a principal that is already
    /// there, since `user add` calls `AddPrincipal` first and so can only ever
    /// key a brand-new one.
    ///
    /// **Needs gunnar-admin**, which is `Access.AddKey`'s existing rule; adding
    /// a key to yourself without one is a policy question, deliberately not
    /// decided here.
    AddKey {
        /// The user who is getting another key, by id. They must already exist.
        name: String,
        /// The OpenSSH public key line to add, or `@<path>` to read one from a
        /// file. This is the key of the OTHER machine, so it is normally
        /// `@~/.ssh/id_ed25519.pub` copied from there — not derivable from the
        /// key `-i` signs this call with.
        #[arg(long, value_name = "KEY")]
        key: String,
        /// **The user's own attestation that this key may act as them**, as
        /// `user attest-key` printed it, or `@<path>` to read it from a file.
        ///
        /// Required when the user already holds a key and you are not them:
        /// your credential proves who asked, their attestation proves they
        /// agreed, and without it an admin could quietly mint access as
        /// another person. Not needed for a user's first key (nobody to ask
        /// yet), nor when `-i` is one of the user's own keys (the call is
        /// already their signed word).
        #[arg(long, value_name = "ATTESTATION")]
        attestation: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Attest, as a user, that a key may act as you.** Run this on a machine
    /// that holds one of your keys; hand the output to the admin who runs
    /// `user add-key … --attestation`.
    ///
    /// It signs nothing but the fingerprint of the new key, your id and the
    /// time, under the sshsig namespace `gunnar-key-attestation`, so it cannot
    /// be spent on any other key, any other principal, a group change or a
    /// review. Nothing is sent anywhere: this verb makes no connection.
    AttestKey {
        /// Your id (what `user list` shows in the first column).
        name: String,
        /// The public key being added, or `@<path>`.
        #[arg(long, value_name = "KEY")]
        key: String,
        /// The private key you attest WITH — one already enrolled on you.
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
    /// **Retire ONE key and leave the principal standing** — the online
    /// counterpart of `gunnar key revoke`, which needs the server DOWN.
    ///
    /// The verb that a re-imaged machine needs. MEASURED on the live appliance
    /// 2026-09-19, rotating `gunnar-twin`'s one machine key after its box was
    /// re-imaged and the private half died with it:
    ///
    /// ```text
    ///   gunnar control key revoke <fp>      unrecognized subcommand 'key'
    ///   user add-key gunnar-twin --key …    FAILED_PRECONDITION: gunnar-twin already
    ///                                       holds 1 key(s), so adding another needs
    ///                                       gunnar-twin's own attestation
    ///   user remove gunnar-twin             removed: 1 keys, 1 GRANTS
    ///   user add gunnar-twin …              ALREADY_EXISTS: namespace already exists
    ///   namespace delete gunnar-twin        0 repositories went with it
    ///   user add gunnar-twin …              created
    ///   group member add twin gunnar-twin   added
    /// ```
    ///
    /// Six steps and four refusals, every one of them individually correct, to
    /// change one fingerprint. The first is the root of it: `gunnar key revoke`
    /// writes the control repository directly and therefore wants the server
    /// stopped — and an appliance is PID 1 with no shell, so on the machine
    /// that most needs the verb it can never be run. `Access.RevokeKey` has
    /// been on the wire all along and gunnar-ui has called it since the console
    /// shipped; no `gunnar control` verb reached it. An RPC nothing can call is
    /// a feature nobody has.
    ///
    /// With this, the rotation is two steps and no refusals:
    /// `user revoke-key <old-fp>` then `user add-key <name> --key <new>` — the
    /// attestation precondition is gone because the principal then holds no
    /// key, and the GRANTS never went anywhere, so nothing has to be put back.
    ///
    /// **Needs gunnar-admin**, which is `Access.RevokeKey`'s own rule at server
    /// scope. Unlike the console's `DELETE /api/account/keys`, this does not
    /// check the key is the caller's: see the handler for why.
    RevokeKey {
        /// The fingerprint to retire, exactly as `user keys` prints it —
        /// `SHA256:…`. The key is the thing named, not the person: which
        /// principal held it is read back and reported.
        fingerprint: String,
        /// **Revoke it even if it is the last key that could run this verb.**
        ///
        /// Without this the last admin key is refused, and that refusal is the
        /// one guard here. See the handler: an appliance that loses its last
        /// gunnar-admin key cannot get one back, because the offline verb that
        /// would needs a shell the appliance does not have.
        #[arg(long)]
        force: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// The keys a user holds, or every key on the server.
    ///
    /// The verb that makes the question *"is this one human or three?"*
    /// answerable at all.
    Keys {
        /// Only this user's keys. Omit for every key on the server.
        name: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **A user's passkeys** (`Access.ListCredentials`, Stage L): the web
    /// credentials gunnar verifies a console login with. Your own need no
    /// grant; somebody else's, or every one (omit the name), need gunnar-admin.
    Credentials {
        /// Only this user's. Omit for every passkey on the server.
        name: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Revoke a passkey** (`Access.RevokeCredential`), named by its id
    /// exactly as `user credentials` prints it (base64url). Your own need no
    /// grant; anybody's need gunnar-admin.
    RevokeCredential {
        /// The credential id, base64url.
        id: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// List users.
    List {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Change a user's display name, and nothing else.** Needs gunnar-admin.
    ///
    /// The id — the account namespace, and what every key, grant, membership
    /// and gate is filed under — stays exactly where it is; only the label
    /// moves. A console that pinned the id sees the same person afterwards.
    /// Refused if another principal already carries the name, as its name or
    /// as its id.
    Rename {
        /// Their id (what `user list` shows in the first column).
        id: String,
        /// The new display name.
        name: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Remove a user, with their keys and grants.
    ///
    /// This does NOT reopen the bootstrap window, not even if it removes the
    /// last user on the server.
    Remove {
        /// Their id.
        name: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control group …` — groups in the ACL (punkt 9).
///
/// A group is a principal that grants attach to and members inherit. Everything
/// here needs gunnar-admin, the same rule as a grant, because adding a member
/// to a group that holds a grant is handing that member the grant.
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlGroupCommand {
    /// **Create a group.** It holds no key; grant it access with
    /// `gunnar control grant <group> …` and add members below.
    Add {
        /// The group's name, its id in every grant and membership.
        name: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Membership**: add or remove a principal from a group.
    #[command(subcommand)]
    Member(ControlGroupMemberCommand),
    /// **List the groups** on the server.
    List {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **List the members of one group** (its direct members).
    Members {
        /// The group to list.
        group: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **The signed membership history** — every add and remove, in order, each
    /// a signed event a third party can verify. This is the evidence behind the
    /// live member list: who was in a group, when, and by whose hand.
    History {
        /// The group to show the history of. Omit for every group's history.
        group: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control group member …`
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlGroupMemberCommand {
    /// **Add a principal to a group.** They inherit the group's grants at once.
    Add {
        /// The group.
        group: String,
        /// The principal to add — a user, a machine, or another group (nesting).
        principal: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Remove a principal from a group.** They lose the inherited access at
    /// once.
    Remove {
        /// The group.
        group: String,
        /// The principal to remove.
        principal: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

// ───────────────────────────────────────────────────────────────────────────
// client
// ───────────────────────────────────────────────────────────────────────────

/// Where a client verb operates.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct RepoArgs {
    /// The repository to work in. Defaults to the current directory.
    #[arg(long, short = 'C', value_name = "DIR", default_value = ".")]
    pub repo: PathBuf,
}

/// `gunnar create`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct CreateArgs {
    /// `<namespace>/<repository>`.
    pub repo: String,
    /// sha1 instead of sha256.
    #[arg(long)]
    pub sha1: bool,
    /// The forge's SSH address: `ssh://git@git.gunnar.rs:2222` or `git@host`.
    /// Default: the `origin` of the clone you stand in.
    #[arg(long, value_name = "SSH-URL")]
    pub host: Option<String>,
    /// The SSH key to sign in with (default: whatever ssh picks).
    #[arg(short = 'i', long, value_name = "KEY")]
    pub identity: Option<std::path::PathBuf>,
}

/// `gunnar settings`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct SettingsArgs {
    /// `<namespace>/<repository>`.
    pub repo: String,
    /// Make it `public` (anyone may read, no key) or `private`.
    #[arg(long, value_name = "public|private")]
    pub visibility: Option<String>,
    /// The branch a new clone checks out: a short name (`main`) or `refs/heads/…`.
    #[arg(long, value_name = "BRANCH")]
    pub default_branch: Option<String>,
    /// The forge's SSH address: `ssh://git@git.gunnar.rs:2222` or `git@host`.
    /// Default: the `origin` of the clone you stand in.
    #[arg(long, value_name = "SSH-URL")]
    pub host: Option<String>,
    /// The SSH key to sign in with (default: whatever ssh picks).
    #[arg(short = 'i', long, value_name = "KEY")]
    pub identity: Option<std::path::PathBuf>,
}

/// `gunnar clone`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct CloneArgs {
    /// `git@host:ns/repo.git` or `ssh://git@host/ns/repo.git`.
    pub url: String,
    /// Where to put it. Defaults to the repository name.
    pub dest: Option<PathBuf>,
    /// The private key to authenticate with, and the ONLY one that will be:
    /// naming an identity switches off `ssh-agent` and the `~/.ssh` ladder, so
    /// a key this server does not accept is refused rather than quietly
    /// replaced. Omit it to let gunnar look (agent first, then `~/.ssh`).
    #[arg(long, short = 'i', value_name = "PATH")]
    pub identity: Option<PathBuf>,
    /// Truncate history to `<n>` commits, counted at the remote.
    ///
    /// The default of the common CI fetch action, and therefore the CI case.
    #[arg(long, value_name = "N")]
    pub depth: Option<u32>,
    /// Only history newer than this date, e.g. `@1700000000` or `2.weeks.ago`.
    #[arg(long, value_name = "DATE")]
    pub shallow_since: Option<String>,
    /// Exclude everything reachable from this revision. Repeatable, and a
    /// **short** name like `side` is the normal spelling.
    #[arg(long, value_name = "REV")]
    pub shallow_exclude: Vec<String>,
    /// Omit objects, and fetch them only when something reads them:
    /// `blob:none`, `tree:<depth>` or `blob:limit=<n>`.
    ///
    /// `blob:limit=<n>` omits a blob of exactly `n` bytes, as git does.
    #[arg(long, value_name = "SPEC")]
    pub filter: Option<String>,
}

#[cfg(feature = "client")]
impl CloneArgs {
    /// The shallow flags, as the client's own type.
    ///
    /// `git clone` has no `--unshallow` and no `--deepen` — both need a boundary
    /// to move — so neither is offered here, which is why this is a conversion
    /// rather than a field.
    pub fn depth_args(&self) -> gunnar_client::DepthArgs {
        gunnar_client::DepthArgs {
            depth: self.depth,
            deepen: None,
            since: self.shallow_since.clone(),
            exclude: self.shallow_exclude.clone(),
            unshallow: false,
        }
    }
}

/// `gunnar fetch`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct FetchArgs {
    /// The remote URL.
    pub url: String,
    /// The repository to fetch into.
    #[arg(long, short = 'C', value_name = "DIR", default_value = ".")]
    pub repo: PathBuf,
    /// The private key to authenticate with, and the ONLY one that will be:
    /// naming an identity switches off `ssh-agent` and the `~/.ssh` ladder, so
    /// a key this server does not accept is refused rather than quietly
    /// replaced. Omit it to let gunnar look (agent first, then `~/.ssh`).
    #[arg(long, short = 'i', value_name = "PATH")]
    pub identity: Option<PathBuf>,
    /// Refspecs to fetch, repeatable. Defaults to
    /// `+refs/heads/*:refs/remotes/origin/*` and `+refs/tags/*:refs/tags/*`.
    ///
    /// A refspec whose source is a glob and which names no destination —
    /// `refs/heads/*` — is REFUSED, the way `git` refuses it, because it would
    /// take the pack and write no reference at all. `refs/heads/main`, with no
    /// glob and no destination, is legal and updates `FETCH_HEAD` only.
    #[arg(long, value_name = "SPEC")]
    pub refspec: Vec<String>,
    /// Truncate history to `<n>` commits, counted at the remote. On an existing
    /// shallow repository this can also **shrink** the boundary.
    #[arg(long, value_name = "N")]
    pub depth: Option<u32>,
    /// `<n>` more commits past the boundary this repository already has.
    ///
    /// Not the same as `--depth`, which counts at the remote: `--deepen 1` on a
    /// depth-1 clone gains a commit, `--depth 1` on it gains nothing.
    #[arg(long, value_name = "N")]
    pub deepen: Option<u32>,
    /// Only history newer than this date, e.g. `@1700000000` or `2.weeks.ago`.
    #[arg(long, value_name = "DATE")]
    pub shallow_since: Option<String>,
    /// Exclude everything reachable from this revision. Repeatable, and a
    /// **short** name like `side` is the normal spelling.
    #[arg(long, value_name = "REV")]
    pub shallow_exclude: Vec<String>,
    /// Fetch the whole history and remove the shallow boundary.
    #[arg(long)]
    pub unshallow: bool,
    /// Omit objects, and fetch them only when something reads them:
    /// `blob:none`, `tree:<depth>` or `blob:limit=<n>`.
    #[arg(long, value_name = "SPEC")]
    pub filter: Option<String>,
}

#[cfg(feature = "client")]
impl FetchArgs {
    /// The shallow flags, as the client's own type. The refusals live in
    /// [`gunnar_client::DepthArgs::to_shallow`], where they can be tested
    /// against the real `git` binary.
    pub fn depth_args(&self) -> gunnar_client::DepthArgs {
        gunnar_client::DepthArgs {
            depth: self.depth,
            deepen: self.deepen,
            since: self.shallow_since.clone(),
            exclude: self.shallow_exclude.clone(),
            unshallow: self.unshallow,
        }
    }
}

/// `gunnar ls-remote`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct LsRemoteArgs {
    /// The remote URL: `git@host:ns/repo.git` or `ssh://git@host/ns/repo.git`.
    pub url: String,
    /// The private key to authenticate with, and the ONLY one that will be:
    /// naming an identity switches off `ssh-agent` and the `~/.ssh` ladder, so
    /// a key this server does not accept is refused rather than quietly
    /// replaced. Omit it to let gunnar look (agent first, then `~/.ssh`).
    #[arg(long, short = 'i', value_name = "PATH")]
    pub identity: Option<PathBuf>,
}

/// `gunnar push`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct PushArgs {
    /// The remote URL.
    pub url: String,
    /// Refspecs, e.g. `HEAD:refs/heads/main` or `+refs/heads/*:refs/heads/*`.
    /// Defaults to the current branch.
    pub refspecs: Vec<String>,
    /// The repository to push from.
    #[arg(long, short = 'C', value_name = "DIR", default_value = ".")]
    pub repo: PathBuf,
    /// The private key to authenticate with, and the ONLY one that will be:
    /// naming an identity switches off `ssh-agent` and the `~/.ssh` ladder, so
    /// a key this server does not accept is refused rather than quietly
    /// replaced. Omit it to let gunnar look (agent first, then `~/.ssh`).
    #[arg(long, short = 'i', value_name = "PATH")]
    pub identity: Option<PathBuf>,
    /// Allow non-fast-forward updates.
    #[arg(long, short = 'f')]
    pub force: bool,
    /// Negotiate and report, but send nothing.
    #[arg(long)]
    pub dry_run: bool,
}

/// `gunnar crypt` — encrypted repositories (Level 1: stock git plus a filter).
#[cfg(feature = "client")]
#[derive(Debug, Subcommand)]
pub enum CryptCommand {
    /// Make this repository encrypted: a new key ring, wrapped to your
    /// encryption key. QUANTUM-SAFE unless you ask for `--level classic`.
    ///
    /// Writes `.gitattributes`, `.gunnar-crypt/members` and
    /// `.gunnar-crypt/keys`, sets up the filter in this clone and commits.
    /// Files committed BEFORE this stay plaintext in history. Your encryption
    /// key is the forge's (origin's); when you have none yet, one is made
    /// (quantum-safe at a quantum-safe repository) and wrapped to your SSH key.
    Init {
        /// Your member name (your Gunnar user name). Defaults to the name the forge origin
        /// points at says you are (its `gunnar-whoami` door); without one it is required.
        #[arg(long, value_name = "NAME")]
        member: Option<String>,
        /// Your encryption public key (`age1…`) when the forge is not asked. Without it
        /// the forge origin points at gives yours.
        #[arg(long = "key", value_name = "PUBKEY")]
        keys: Vec<String>,
        /// How the key ring is wrapped. `quantum-safe` (the default): only to
        /// age1pq1… keys (ML-KEM-768 + X25519). `classic`: to X25519 age1… keys,
        /// for members whose one encryption key is classic; a ring harvested
        /// today opens once a quantum computer breaks X25519.
        #[arg(long, value_enum, value_name = "LEVEL")]
        level: Option<CryptLevel>,
        /// Stage the files but do not commit.
        #[arg(long)]
        no_commit: bool,
    },
    /// This repository's level, or `level quantum-safe`: re-wrap a classic
    /// repository to quantum-safe keys.
    ///
    /// Every member needs a quantum-safe (age1pq1…) key, given with
    /// `--key NAME=…` or the one Gunnar holds for them (`--from-server`); a
    /// member without one is named and nothing changes. The ring is rotated
    /// (content from now on is sealed under a key never wrapped classically)
    /// and wrapped only to those keys. The level only goes up: Gunnar refuses
    /// a quantum-safe repository that goes back to classic.
    Level {
        /// `quantum-safe` to upgrade; none to show the level.
        #[arg(value_enum, value_name = "LEVEL")]
        level: Option<CryptLevel>,
        /// A member's quantum-safe key, `NAME=age1pq1…` or `NAME=<file>` (repeat).
        #[arg(long = "key", value_name = "NAME=PUBKEY")]
        keys: Vec<String>,
        /// For members without `--key`: the encryption key Gunnar holds for them,
        /// asked of the forge `origin` pushes to (or, with `--at`, a control plane).
        #[arg(long)]
        from_server: bool,
        /// `NAME=SHA256:…`: the fingerprint of a member's key the first time this
        /// machine sees it (`--from-server`; the server's word alone is not taken).
        #[arg(
            long = "fingerprint",
            value_name = "NAME=SHA256:…",
            requires = "from_server"
        )]
        fingerprints: Vec<String>,
        /// The repository on the server, `<ns>/<repo>` (with `--from-server`).
        #[arg(long, value_name = "NS/REPO", requires = "from_server")]
        repo: Option<String>,
        /// A control plane to ask instead of the forge's SSH door (with `--from-server`).
        #[arg(long, value_name = "ADDR", requires = "from_server")]
        at: Option<String>,
        /// The key to sign in with (with `--from-server`).
        #[arg(long, short = 'i', value_name = "PATH", requires = "from_server")]
        identity: Option<PathBuf>,
        /// Stage the files but do not commit.
        #[arg(long)]
        no_commit: bool,
    },
    /// Make a quantum-safe KEY FILE: an age1pq1… key (age's hybrid
    /// ML-KEM-768 + X25519), made on this machine — a quantum-safe way to open
    /// your encryption key (`gunnar crypt key add-pq`).
    ///
    /// The private half is written mode 0600 and never leaves this machine.
    /// SSH keys cannot be quantum-safe recipients: their key exchange (X25519,
    /// RSA) is what a quantum computer breaks.
    Keygen {
        /// Where to write the private key. Defaults to
        /// `$XDG_CONFIG_HOME/gunnar/crypt-pq.key` (`~/.config/gunnar/…`).
        #[arg(long, short = 'o', value_name = "PATH")]
        out: Option<PathBuf>,
        /// Replace an existing key file. Rings wrapped to the old key no
        /// longer open with the new one.
        #[arg(long)]
        force: bool,
    },
    /// Wrap the key ring to one more member. They need not be present: their
    /// encryption PUBLIC key is enough — given here, or the one gunnar holds
    /// for them (`--from-server`). In a quantum-safe repository it is their
    /// quantum-safe (age1pq1…) encryption key.
    #[command(name = "add-member")]
    AddMember {
        /// The member's name (their gunnar user name, for `--from-server`).
        name: String,
        /// Their encryption public key (`age1…`), as a file or a key line.
        #[arg(
            long = "key",
            value_name = "PUBKEY",
            required_unless_present = "from_server"
        )]
        keys: Vec<String>,
        /// Use the encryption key gunnar holds for them (they must be able to
        /// read the repository, and so must you). Asked of the forge `origin`
        /// pushes to, over its SSH door (`gunnar-recipient-keys`, signed in by
        /// the ssh git runs) — or, with `--at`, of a control plane
        /// (`Repos.RecipientKeys`, `gunnar-cli` only).
        #[arg(long)]
        from_server: bool,
        /// The fingerprint of the member's key (`SHA256:…`, from them: their
        /// `gunnar crypt key status` or Account page). Required with
        /// `--from-server` the first time this machine sees their key: the
        /// server's word alone is not taken (RA4-1).
        #[arg(long, value_name = "SHA256:…", requires = "from_server")]
        fingerprint: Option<String>,
        /// The repository on the server, `<ns>/<repo>`. Defaults to the one
        /// `origin` points at.
        #[arg(long, value_name = "NS/REPO", requires = "from_server")]
        repo: Option<String>,
        /// A control plane to ask instead of the forge's SSH door (with
        /// `--from-server`; an installed estate binds it to its WireGuard
        /// overlay, so its members leave this off).
        #[arg(long, value_name = "ADDR", requires = "from_server")]
        at: Option<String>,
        /// The key to sign in with (with `--from-server`): the control call's
        /// signer, or `ssh -i` at the forge's door.
        #[arg(long, short = 'i', value_name = "PATH", requires = "from_server")]
        identity: Option<PathBuf>,
        /// Stage the files but do not commit.
        #[arg(long)]
        no_commit: bool,
    },
    /// Remove a member and rotate: content committed from now on is sealed
    /// under a new key they never get. What they already had, they keep.
    #[command(name = "remove-member")]
    RemoveMember {
        /// The member's name.
        name: String,
        /// Stage the files but do not commit.
        #[arg(long)]
        no_commit: bool,
    },
    /// Rotate: add a new key epoch; new content is sealed under it.
    Rotate {
        /// Stage the files but do not commit.
        #[arg(long)]
        no_commit: bool,
    },
    /// Open your encryption key with one of its unlock methods — your SSH
    /// key FILE, your security key, or your recovery code — and with it this
    /// repository's key ring; decrypt this clone.
    ///
    /// ssh-agent cannot help: it only signs. An encrypted key file asks for
    /// its passphrase on the terminal.
    Unlock {
        #[command(flatten)]
        open: KeyOpenArgs,
    },
    /// Your encryption key: one per person, for every encrypted repository you
    /// are a member of, opened by any of its unlock methods (an SSH key, a
    /// security key, a recovery code). Adding or removing a method changes no
    /// repository.
    #[command(subcommand)]
    Key(CryptKeyCommand),
    /// Forget the local key ring and put ciphertext back in the work tree.
    Lock,
    /// Members, key epochs, and whether this clone is unlocked.
    Status,
    /// Diff two revisions in plaintext — the same diff the browser console
    /// computes.
    Diff {
        /// The old revision.
        from: String,
        /// The new revision.
        to: String,
        /// Limit to these paths.
        #[arg(last = true)]
        paths: Vec<String>,
    },
    /// git filter: seal stdin to stdout (`%f` is the path).
    #[command(hide = true)]
    Clean {
        /// The path git names.
        path: Option<String>,
    },
    /// git filter: open stdin to stdout.
    #[command(hide = true)]
    Smudge {
        /// The path git names.
        path: Option<String>,
    },
    /// git filter, long-running protocol (`filter.<driver>.process`).
    #[command(name = "filter-process", hide = true)]
    FilterProcess,
    /// git diff driver: print a sealed file's plaintext.
    #[command(hide = true)]
    Textconv {
        /// The file git hands over.
        file: PathBuf,
    },
    /// git merge driver: open the three versions, merge the plaintext, seal
    /// the result.
    #[command(hide = true)]
    Merge {
        /// `%O`, the common ancestor.
        base: PathBuf,
        /// `%A`, ours; the result is written here.
        ours: PathBuf,
        /// `%B`, theirs.
        theirs: PathBuf,
        /// `%L`, the conflict marker size.
        #[arg(default_value_t = 7)]
        marker_size: usize,
        /// `%P`, the path.
        path: Option<String>,
    },
}

/// An encrypted repository's level (`--level`).
#[cfg(feature = "client")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum CryptLevel {
    /// Wrapped only to quantum-safe age1pq1… keys (ML-KEM-768 + X25519). The default.
    QuantumSafe,
    /// Wrapped to classic X25519 age1… keys.
    Classic,
}

/// How `gunnar crypt` opens your encryption key.
#[cfg(feature = "client")]
#[derive(Debug, Clone, Default, clap::Args)]
pub struct KeyOpenArgs {
    /// The key file to open it with: an SSH key file or a `gunnar crypt keygen`
    /// file. Defaults to `~/.ssh/id_ed25519`, `~/.ssh/id_rsa` and
    /// `~/.config/gunnar/crypt-pq.key`, whichever exist.
    #[arg(long, short = 'i', value_name = "PATH")]
    pub identity: Vec<PathBuf>,
    /// Open it with your FIDO2 security key (a YubiKey 5: its hmac-secret), over USB.
    #[arg(long, conflicts_with = "recovery_code")]
    pub security_key: bool,
    /// Open it with your printed recovery code (asked on the terminal).
    #[arg(long)]
    pub recovery_code: bool,
}

/// `gunnar crypt key …`: your encryption key and its unlock methods.
#[cfg(feature = "client")]
#[derive(Debug, Subcommand)]
pub enum CryptKeyCommand {
    /// Your encryption key's public half and its unlock methods.
    Status,
    /// Make your encryption key (the first time), wrapped to your SSH key:
    /// quantum-safe (age1pq1…) unless you ask for `--classic`.
    New {
        /// A classic X25519 key (age1…) instead: for classic repositories only.
        /// A person has ONE key, so this cannot be changed later.
        #[arg(long)]
        classic: bool,
        /// The SSH public key that opens it. Defaults to `~/.ssh/id_ed25519.pub`.
        #[arg(long, value_name = "PUBKEY")]
        ssh_key: Option<String>,
    },
    /// One more SSH key opens your encryption key.
    AddSsh {
        /// The SSH public key, as a file or a key line. Defaults to `~/.ssh/id_ed25519.pub`.
        key: Option<String>,
        #[command(flatten)]
        open: KeyOpenArgs,
    },
    /// Your `gunnar crypt keygen` key (age1pq1…) opens your encryption key.
    AddPq {
        /// The age1pq1… public key, as a file or a key line. Defaults to the keygen file's.
        key: Option<String>,
        #[command(flatten)]
        open: KeyOpenArgs,
    },
    /// A FIDO2 security key opens your encryption key, here and in the console.
    AddSecurityKey {
        /// The console's host name: the WebAuthn relying party the credential is
        /// bound to, so the same key opens it in the browser too.
        #[arg(long, value_name = "HOST")]
        rp_id: String,
        /// Your name for this key ("YubiKey 5C, keyring").
        #[arg(long)]
        label: Option<String>,
        #[command(flatten)]
        open: KeyOpenArgs,
    },
    /// A printed recovery code opens your encryption key (shown once).
    AddRecoveryCode {
        #[command(flatten)]
        open: KeyOpenArgs,
    },
    /// Delete one unlock method (its id from `status`). The last one stays.
    Remove {
        /// The method's id.
        id: String,
    },
    /// Trust the encryption key the forge holds for you NOW: after a refused
    /// changed key, account name or forge host key, once you checked the new
    /// key's fingerprint on your Account page.
    Repin {
        /// The fingerprint of the key the forge holds (`SHA256:…`), as your Account page shows it.
        #[arg(long, value_name = "SHA256")]
        fingerprint: String,
    },
}

/// Mirror verbs — the pull mirror.
#[cfg(feature = "client")]
#[derive(Debug, Subcommand)]
pub enum MirrorCommand {
    /// Register a remote to mirror.
    Add {
        /// A local name for the mirror.
        name: String,
        /// The remote URL.
        url: String,
        /// Where the mirror registry and its bare repositories live.
        #[arg(long, env = "GUNNAR_MIRROR_ROOT", value_name = "DIR")]
        root: Option<PathBuf>,
    },
    /// ls-remote, fetch the deltas, apply the refs.
    Sync {
        /// The mirror name.
        name: String,
        #[arg(long, env = "GUNNAR_MIRROR_ROOT", value_name = "DIR")]
        root: Option<PathBuf>,
        /// The private key to authenticate with, and the ONLY one that will be:
        /// naming an identity switches off `ssh-agent` and the `~/.ssh` ladder, so
        /// a key this server does not accept is refused rather than quietly
        /// replaced. Omit it to let gunnar look (agent first, then `~/.ssh`).
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
    },
    /// What is registered, and what is on disk.
    Status {
        #[arg(long, env = "GUNNAR_MIRROR_ROOT", value_name = "DIR")]
        root: Option<PathBuf>,
    },
}

/// `gunnar log`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct LogArgs {
    /// The repository.
    #[arg(long, short = 'C', value_name = "DIR", default_value = ".")]
    pub repo: PathBuf,
    /// Where to start. Defaults to `HEAD`.
    #[arg(long, value_name = "REV")]
    pub start: Option<String>,
    /// How many commits to show.
    #[arg(long, short = 'n', default_value_t = 20)]
    pub max: usize,
}

/// `gunnar commit`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct CommitArgs {
    /// The commit message.
    #[arg(long, short = 'm')]
    pub message: String,
    /// The repository.
    #[arg(long, short = 'C', value_name = "DIR", default_value = ".")]
    pub repo: PathBuf,
}

/// `gunnar branch`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct BranchArgs {
    /// Create this branch. Omit to list.
    pub name: Option<String>,
    /// Delete `name` instead of creating it.
    #[arg(long, short = 'd')]
    pub delete: bool,
    /// The repository.
    #[arg(long, short = 'C', value_name = "DIR", default_value = ".")]
    pub repo: PathBuf,
}

/// `gunnar tag`.
#[cfg(feature = "client")]
#[derive(Debug, clap::Args)]
pub struct TagArgs {
    /// Create this tag. Omit to list.
    pub name: Option<String>,
    /// Make it an annotated tag with this message.
    #[arg(long, short = 'm')]
    pub message: Option<String>,
    /// The repository.
    #[arg(long, short = 'C', value_name = "DIR", default_value = ".")]
    pub repo: PathBuf,
}

// ───────────────────────────────────────────────────────────────────────────
// systemd
// ───────────────────────────────────────────────────────────────────────────

/// `gunnar service` — the `systemd` integration.
#[cfg(feature = "systemd")]
#[derive(Debug, Subcommand)]
pub enum ServiceCommand {
    /// Render and install the unit.
    Install(ServiceArgs),
    /// Start the service.
    Start(ServiceArgs),
    /// Stop the service.
    Stop(ServiceArgs),
    /// Is it active?
    Status(ServiceArgs),
    /// Remove the unit.
    ///
    /// Skidbladnir 0.1.12 has no `uninstall.rs`, so this is the thinner
    /// `Result<()>` — no `UninstallReport`, no guarded-delete purge law. Those
    /// arrived in the unpublished 0.1.13.
    Uninstall(ServiceArgs),
    /// Print the rendered unit and exit. Touches nothing.
    Unit(ServiceArgs),
}

/// Shared arguments for every `gunnar service` verb.
#[cfg(feature = "systemd")]
#[derive(Debug, clap::Args, Clone)]
pub struct ServiceArgs {
    /// The installed binary the unit runs.
    #[arg(long, value_name = "PATH")]
    pub exec: Option<PathBuf>,
    /// Where the unit's `gunnar serve` binds SSH.
    #[arg(long, default_value = "0.0.0.0:2222", value_name = "ADDR")]
    pub ssh_bind: String,
    /// Where the unit's `gunnar serve` binds gRPC. Loopback: two listeners, one identity table.
    #[arg(long, default_value = "127.0.0.1:50051", value_name = "ADDR")]
    pub grpc_bind: String,
    /// Install a `--user` unit rather than a system one.
    #[arg(long)]
    pub user: bool,
    /// The system user the unit runs as. System scope only.
    #[arg(long, default_value = "gunnar", value_name = "USER")]
    pub run_as: String,
    /// The data root the unit passes to `gunnar serve`.
    #[arg(long, value_name = "DIR")]
    pub data_root: Option<PathBuf>,
    /// The `RUST_LOG` the unit runs with.
    ///
    /// Defaults to `gunnar_core::observe::service_log_filter()`, which names
    /// every one of gunnar's targets explicitly. **A unit that names no filter
    /// is not a unit with no opinion** — the process then falls through to a
    /// bare `info`, and which of gunnar's lines that selects is decided
    /// somewhere the operator cannot see. See `service::spec`.
    #[arg(long, value_name = "FILTER", env = "RUST_LOG")]
    pub log_filter: Option<String>,
}

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

    /// clap's own consistency check. It catches a duplicated short flag, a
    /// group naming an argument that does not exist, and every other way a
    /// derive can be wrong that would otherwise only show up as a panic the
    /// first time a user runs the binary.
    #[test]
    fn the_command_tree_is_well_formed() {
        Cli::command().debug_assert();
    }

    /// **The metered appliance's blocker, at the argv it actually boots with.**
    ///
    /// `--monetize-pubkey <64 hex>` must arrive as monetize's 32 verifying-key
    /// bytes. Asserting `is_ok()` here would pass on a byte-swapped key and on
    /// a key read as a filename, so the assertion is the bytes — written out
    /// by hand, not produced by the parser being tested.
    /// **A flag that only means something with `--from-server` is refused
    /// without it** (wiring tracer B 2026-10-08): `crypt add-member bob --key
    /// k --at addr` parsed and ignored `--at`, `--repo` and `-i`, and a
    /// `GUNNAR_CONTROL_ADDR` in the environment quietly turned the forge's
    /// door into a control-plane call.
    #[cfg(feature = "client")]
    #[test]
    fn crypt_flags_that_need_from_server_are_refused_without_it() {
        for args in [
            &[
                "gunnar",
                "crypt",
                "add-member",
                "bob",
                "--key",
                "k.pub",
                "--at",
                "10.0.0.1:50051",
            ][..],
            &[
                "gunnar",
                "crypt",
                "add-member",
                "bob",
                "--key",
                "k.pub",
                "--repo",
                "acme/vault",
            ][..],
            &[
                "gunnar",
                "crypt",
                "add-member",
                "bob",
                "--key",
                "k.pub",
                "-i",
                "id",
            ][..],
            &["gunnar", "crypt", "upgrade-pq", "--key", "bob=age1pq1x"][..],
        ] {
            assert!(
                Cli::try_parse_from(args).is_err(),
                "{args:?} parsed with a flag that does nothing"
            );
        }
        assert!(Cli::try_parse_from([
            "gunnar",
            "crypt",
            "add-member",
            "bob",
            "--from-server",
            "--at",
            "10.0.0.1:50051",
            "-i",
            "id"
        ])
        .is_ok());
        std::env::set_var("GUNNAR_CONTROL_ADDR", "10.0.0.9:50051");
        let parsed = Cli::try_parse_from(["gunnar", "crypt", "add-member", "bob", "--from-server"])
            .expect("parses");
        std::env::remove_var("GUNNAR_CONTROL_ADDR");
        let text = format!("{parsed:?}");
        assert!(
            !text.contains("10.0.0.9"),
            "the environment chose the control plane for the forge's door: {text}"
        );
    }

    #[cfg(feature = "server")]
    #[test]
    fn serve_takes_the_monetize_key_inline_on_the_command_line() {
        const LIVE: &str = "1c3663248d60900e2996389fba4efa1d7179d6dbd08627d0426f16f94e44c4e6";
        const LIVE_BYTES: [u8; 32] = [
            0x1c, 0x36, 0x63, 0x24, 0x8d, 0x60, 0x90, 0x0e, 0x29, 0x96, 0x38, 0x9f, 0xba, 0x4e,
            0xfa, 0x1d, 0x71, 0x79, 0xd6, 0xdb, 0xd0, 0x86, 0x27, 0xd0, 0x42, 0x6f, 0x16, 0xf9,
            0x4e, 0x44, 0xc4, 0xe6,
        ];
        let cli = Cli::try_parse_from(["gunnar", "serve", "--monetize-pubkey", LIVE])
            .expect("the live key is accepted on the command line");
        let Command::Serve(args) = cli.command else {
            panic!("expected serve")
        };
        let key = args.monetize_pubkey.expect("the flag was given");
        assert_eq!(
            key.literal(),
            Some(LIVE_BYTES),
            "an appliance whose only writable channel is the cmdline must get the \
             key itself, not a filename: {key:?}"
        );
    }

    /// **The open build is unaffected by `monetize_vital`** (owner ruling 2026-09-22): it has no
    /// monetize, so it has no such flag — neither on its argv nor in its `--help` — and nothing
    /// in it can raise `entitlement.key_mismatch` or report maintenance for a key.
    #[cfg(all(feature = "server", not(feature = "metered")))]
    #[test]
    fn the_open_build_has_no_monetize_vital() {
        assert!(Cli::try_parse_from(["gunnar", "serve", "--monetize-vital", "true"]).is_err());
        let help = <Cli as clap::CommandFactory>::command()
            .find_subcommand_mut("serve")
            .expect("serve")
            .render_long_help()
            .to_string();
        assert!(!help.contains("monetize-vital"), "{help}");
    }

    /// **The usage share's flags read the medium's tokens**: `admit_limit`
    /// lands `korp.env.GUNNAR_ADMIT_LIMIT` (gunnar-recipe `ADMIT_LIMIT_ENV`)
    /// and `admit_window_days` `korp.env.GUNNAR_ADMIT_WINDOW_DAYS`; the flag
    /// wins over the env, and neither exists without the feature.
    #[cfg(all(feature = "server", feature = "admit-share"))]
    #[test]
    fn serve_reads_the_admit_flags_and_their_env() {
        let cli = Cli::try_parse_from([
            "gunnar",
            "serve",
            "--admit-limit",
            "100GB",
            "--admit-window-days",
            "7",
        ])
        .expect("parses");
        let Command::Serve(args) = cli.command else {
            panic!("expected serve")
        };
        assert_eq!(
            (args.admit_limit.as_deref(), args.admit_window_days),
            (Some("100GB"), Some(7))
        );
        let serve = <Cli as clap::CommandFactory>::command();
        let serve = serve.find_subcommand("serve").expect("serve");
        let env_of = |id: &str| {
            serve
                .get_arguments()
                .find(|a| a.get_id() == id)
                .and_then(|a| a.get_env())
                .map(|e| e.to_string_lossy().into_owned())
        };
        assert_eq!(env_of("admit_limit").as_deref(), Some("GUNNAR_ADMIT_LIMIT"));
        assert_eq!(
            env_of("admit_window_days").as_deref(),
            Some("GUNNAR_ADMIT_WINDOW_DAYS")
        );
    }

    #[cfg(all(feature = "server", not(feature = "admit-share")))]
    #[test]
    fn without_the_share_there_is_no_admit_flag() {
        assert!(Cli::try_parse_from(["gunnar", "serve", "--admit-limit", "none"]).is_err());
    }

    /// The path spelling is unchanged, and the literal arm has not swallowed
    /// it: a path that does not exist is still carried as a PATH, to fail when
    /// it is read rather than at parse time.
    #[cfg(feature = "server")]
    #[test]
    fn serve_still_takes_the_monetize_key_as_a_path() {
        let cli = Cli::try_parse_from([
            "gunnar",
            "serve",
            "--monetize-pubkey",
            "/no/such/monetize.pub",
        ])
        .expect("a path parses whether or not it exists");
        let Command::Serve(args) = cli.command else {
            panic!("expected serve")
        };
        let key = args.monetize_pubkey.expect("the flag was given");
        assert_eq!(
            key.path(),
            Some(std::path::Path::new("/no/such/monetize.pub")),
            "the literal arm swallowed the path arm: {key:?}"
        );
    }

    /// A near-miss key is refused BY CLAP, naming what was wrong — not read as
    /// a filename, and not truncated to 32 bytes.
    #[cfg(feature = "server")]
    #[test]
    fn a_near_miss_monetize_key_is_refused_on_the_command_line() {
        let short = "1c3663248d60900e2996389fba4efa1d7179d6dbd08627d0426f16f94e44c4e";
        let err = Cli::try_parse_from(["gunnar", "serve", "--monetize-pubkey", short])
            .expect_err("a 63-character key must be refused")
            .to_string();
        assert!(
            err.contains("63") && err.contains("64"),
            "the refusal must name the length that was wrong: {err}"
        );
    }

    #[cfg(feature = "server")]
    #[test]
    fn serve_defaults_grpc_to_loopback() {
        let cli = Cli::try_parse_from(["gunnar", "serve"]).expect("serve parses with no arguments");
        let Command::Serve(args) = cli.command else {
            panic!("expected serve")
        };
        assert_eq!(
            args.grpc_bind.to_string(),
            "127.0.0.1:50051",
            "the gRPC control plane's default bind must be \
             loopback. Anything else makes an open admin port the default."
        );
        assert!(
            args.grpc_bind.is_loopback_addr(),
            "the default gRPC bind must be a loopback address"
        );
        assert!(
            !args.ssh_bind.ip().is_loopback(),
            "SSH authenticates every connection by public key, so its default is public; a \
             loopback default here would mean this test is asserting the wrong field"
        );
    }

    /// Every spelling `--prune-grace` accepts, and the ones it must refuse.
    ///
    /// The refusals are the half that matters: a parser that fell back to zero
    /// on anything it did not understand would turn `--prune-grace 2.weeks.ago`
    /// — the spelling a git operator will type first — into `--prune=now`
    /// against a live server. So `2.weeks.ago` is asserted to be an **error**,
    /// not silently anything.
    #[cfg(feature = "server")]
    #[test]
    fn prune_grace_parses_what_it_claims_and_refuses_the_rest() {
        use std::time::Duration;
        for (raw, want) in [
            ("now", Duration::ZERO),
            ("NOW", Duration::ZERO),
            ("0", Duration::ZERO),
            ("90", Duration::from_secs(90)),
            ("45s", Duration::from_secs(45)),
            ("5m", Duration::from_secs(300)),
            ("2h", Duration::from_secs(7200)),
            ("3d", Duration::from_secs(259_200)),
            ("2w", Duration::from_secs(1_209_600)),
        ] {
            assert_eq!(
                parse_prune_grace(raw),
                Ok(want),
                "--prune-grace {raw} did not parse to {want:?}"
            );
        }
        for raw in ["2.weeks.ago", "yesterday", "", "w", "-1", "2 weeks", "2y"] {
            assert!(
                parse_prune_grace(raw).is_err(),
                "--prune-grace {raw:?} was accepted; a grace this parser does not understand \
                 must be refused, never defaulted"
            );
        }
        // And the flag reaches the struct, so a parser that worked in isolation
        // and was not wired would still fail here.
        let cli = Cli::try_parse_from(["gunnar", "gc", "--prune", "--prune-grace", "now"])
            .expect("gc --prune-grace now parses");
        let Command::Gc(args) = cli.command else {
            panic!("expected gc")
        };
        assert_eq!(args.prune_grace, Duration::ZERO);
        assert_ne!(args.prune_grace, GcArgs::default().prune_grace);
    }

    #[cfg(feature = "server")]
    #[test]
    fn grant_requires_exactly_one_scope() {
        Cli::try_parse_from(["gunnar", "grant", "alice", "write"])
            .expect_err("a grant with no scope must be refused");
        Cli::try_parse_from([
            "gunnar",
            "grant",
            "alice",
            "write",
            "--server",
            "--namespace",
            "team",
        ])
        .expect_err("a grant with two scopes must be refused");
        let cli = Cli::try_parse_from(["gunnar", "grant", "alice", "write", "--repo", "team/x"])
            .expect("one scope parses");
        let Command::Grant(args) = cli.command else {
            panic!("expected grant")
        };
        assert_eq!(args.repo.as_deref(), Some("team/x"));
        assert_eq!(args.level, LevelArg::Write);
    }

    #[cfg(feature = "server")]
    #[test]
    fn repo_create_defaults_to_sha256() {
        let cli = Cli::try_parse_from(["gunnar", "repo", "create", "team/x"]).expect("parses");
        let Command::Repo(RepoCommand::Create { hash, .. }) = cli.command else {
            panic!("expected repo create")
        };
        assert_eq!(hash, HashArg::Sha256, "sha256 is the default hash kind");
    }

    /// The appliance build must not offer a verb it cannot perform, and the
    /// default build must offer both. Asserted in both directions so the test
    /// cannot pass vacuously on a binary that has no subcommands at all.
    #[test]
    fn the_feature_split_reaches_the_command_line() {
        let has = |name: &str| {
            Cli::command()
                .get_subcommands()
                .any(|sub| sub.get_name() == name)
        };
        assert_eq!(
            has("serve"),
            cfg!(feature = "server"),
            "`serve` exists exactly when the server feature is on"
        );
        assert_eq!(
            has("clone"),
            cfg!(feature = "client"),
            "`clone` exists exactly when the client feature is on"
        );
        assert_eq!(
            has("service"),
            cfg!(feature = "systemd"),
            "`service` exists exactly when the systemd feature is on"
        );
    }

    /// ★ **The verb that reads the key a tenant's own renewal depends on.**
    ///
    /// `Billing.ApplianceIdentity` was served from the day the tenant path
    /// shipped, with a proto comment saying it exists "so an operator can
    /// configure their monetize with it" — and nothing but a test ever called
    /// it, because no verb existed. MEASURED on gunnar.rs 2026-09-19: every
    /// self-service renewal answered 501, monetize's `[products.gunnar]`
    /// carried no `appliance_key`, and there was no way to obtain one. An RPC
    /// nothing can call is a feature nobody has.
    ///
    /// Metered only, like the service it calls: `billing.proto` is not in
    /// codegen without the feature, so on a community build this verb must not
    /// exist at all rather than fail at the far end.
    #[cfg(all(feature = "metered", feature = "control"))]
    #[test]
    fn appliance_identity_parses_and_takes_an_address_and_an_identity() {
        let cli = Cli::try_parse_from([
            "gunnar",
            "control",
            "appliance-identity",
            "--at",
            "10.13.8.101:50051",
            "-i",
            "/var/lib/monetize/gunnar-identity",
        ])
        .expect("the verb parses");
        match cli.command {
            Command::Control(ControlCommand::ApplianceIdentity { at, identity }) => {
                assert_eq!(at, "10.13.8.101:50051");
                assert_eq!(
                    identity.as_deref(),
                    Some(std::path::Path::new("/var/lib/monetize/gunnar-identity"))
                );
            }
            other => panic!("parsed as something else: {other:?}"),
        }
    }

    /// And it defaults its address like every other control verb, so the
    /// common case is two words.
    #[cfg(all(feature = "metered", feature = "control"))]
    #[test]
    fn appliance_identity_defaults_its_address() {
        let cli = Cli::try_parse_from(["gunnar", "control", "appliance-identity"])
            .expect("the verb parses bare");
        match cli.command {
            Command::Control(ControlCommand::ApplianceIdentity { at, .. }) => {
                assert_eq!(at, crate::DEFAULT_CONTROL_ADDR);
            }
            other => panic!("parsed as something else: {other:?}"),
        }
    }

    /// `gunnar control entitlement set|get|list` parse, and `set` takes a PATH
    /// to a fact monetize signed — never a namespace and a state, because this
    /// verb signs nothing and a verb that took a state would be one that could.
    #[cfg(all(feature = "metered", feature = "control"))]
    #[test]
    fn entitlement_verbs_parse_and_set_takes_only_a_signed_fact() {
        let cli = Cli::try_parse_from([
            "gunnar",
            "control",
            "entitlement",
            "set",
            "/tmp/fact.json",
            "--at",
            "10.0.0.1:50051",
        ])
        .expect("set parses");
        match cli.command {
            Command::Control(ControlCommand::Entitlement(ControlEntitlementCommand::Set {
                fact,
                at,
                ..
            })) => {
                assert_eq!(fact, std::path::PathBuf::from("/tmp/fact.json"));
                assert_eq!(at, "10.0.0.1:50051");
            }
            other => panic!("parsed as something else: {other:?}"),
        }
        assert!(
            Cli::try_parse_from(["gunnar", "control", "entitlement", "set", "team", "paid"])
                .is_err(),
            "`set` must not take a namespace and a state"
        );
        let cli = Cli::try_parse_from(["gunnar", "control", "entitlement", "get", "team"])
            .expect("get parses");
        match cli.command {
            Command::Control(ControlCommand::Entitlement(ControlEntitlementCommand::Get {
                namespace,
                at,
                ..
            })) => {
                assert_eq!(namespace, "team");
                assert_eq!(at, crate::DEFAULT_CONTROL_ADDR);
            }
            other => panic!("parsed as something else: {other:?}"),
        }
        Cli::try_parse_from(["gunnar", "control", "entitlement", "list"]).expect("list parses");
    }

    /// ★ **The ONLINE revoke exists, and it takes a bare fingerprint.**
    ///
    /// MEASURED on the live appliance 2026-09-19: `gunnar control key revoke
    /// <fp>` answered *"unrecognized subcommand 'key'"*, because the only
    /// `Revoke` in the CLI was `gunnar key revoke` — a `server`-feature verb
    /// that writes the control repository directly and therefore needs the
    /// server DOWN. An appliance is PID 1 with no shell, so the machine that
    /// most needs the verb is the one that can never run it, and rotating one
    /// dead machine key took six steps and four refusals instead.
    ///
    /// The shape is the transcript's: the fingerprint is positional, as the
    /// operator pastes it out of `user keys`, and nothing else is required.
    #[cfg(feature = "control")]
    #[test]
    fn user_revoke_key_parses_a_bare_fingerprint_and_defaults_its_address() {
        let cli = Cli::try_parse_from([
            "gunnar",
            "control",
            "user",
            "revoke-key",
            "SHA256:Bw3OsBmcabcdefghijklmnopqrstuvwxyz0123456789",
        ])
        .expect("the online revoke parses");
        match cli.command {
            Command::Control(ControlCommand::User(ControlUserCommand::RevokeKey {
                fingerprint,
                force,
                at,
                identity,
            })) => {
                assert_eq!(
                    fingerprint,
                    "SHA256:Bw3OsBmcabcdefghijklmnopqrstuvwxyz0123456789"
                );
                assert!(
                    !force,
                    "the lockout guard is on unless --force says otherwise"
                );
                assert_eq!(at, crate::DEFAULT_CONTROL_ADDR);
                assert!(identity.is_none());
            }
            other => panic!("parsed as something else: {other:?}"),
        }
    }

    /// And `--force` is spelled, because the guard it turns off is the only
    /// thing standing between a slip and a box that must be re-imaged.
    #[cfg(feature = "control")]
    #[test]
    fn user_revoke_key_takes_force_to_get_past_the_last_admin_guard() {
        let cli = Cli::try_parse_from([
            "gunnar",
            "control",
            "user",
            "revoke-key",
            "SHA256:zzz",
            "--force",
            "-i",
            "/root/.ssh/id_ed25519",
            "--at",
            "10.13.8.101:50051",
        ])
        .expect("the verb parses with --force");
        match cli.command {
            Command::Control(ControlCommand::User(ControlUserCommand::RevokeKey {
                force,
                at,
                identity,
                ..
            })) => {
                assert!(force);
                assert_eq!(at, "10.13.8.101:50051");
                assert_eq!(
                    identity.as_deref(),
                    Some(std::path::Path::new("/root/.ssh/id_ed25519"))
                );
            }
            other => panic!("parsed as something else: {other:?}"),
        }
    }
}

/// `gunnar control account …`: the gate and the hard purge.
///
/// Gated on `control` like every other `gunnar control` enum, and it has to be:
/// each variant's `--at` carries [`CONTROL_ADDR_HELP`] as its `long_help`, and
/// that const is behind the same feature. A build without `control` has no
/// control plane to send these to, so an ungated enum would be four subcommands
/// that cannot exist referring to a string that does not.
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlAccountCommand {
    /// **Lock a user out. Completely.**
    ///
    /// Not read-only. Every level, both doors: the SSH listener and the control
    /// plane ask the same table, so a gated user can neither push nor fetch nor
    /// read a repository they own — and nobody else can reach into the account
    /// either, including a stranger cloning a public repository out of it.
    ///
    /// **Reads are not safe to allow**, which is why there is no `--read-only`.
    /// A fetch opens the store and lazily explodes objects into the read cache,
    /// the first read of a pack with no index builds one and writes it, and a
    /// log walk caches: a "harmless" reader puts bytes back into an account
    /// something else is emptying.
    ///
    /// Standalone and idempotent. It is not part of `purge` — a lapsed account
    /// is locked out without deleting anything, and an operator freezes an
    /// account under investigation the same way.
    Gate {
        /// The account: a user's name, which is also their namespace.
        account: String,
        /// **Why.** Required: it is what the locked-out user is shown in every
        /// refusal from that moment on, and a lockout with no reason is a
        /// support ticket.
        #[arg(long, value_name = "TEXT")]
        note: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Let them back in.**
    ///
    /// Unconditional: it does not care who took the lockout, so a lease left
    /// behind by a purge that died can always be cleared by hand. That is the
    /// escape hatch, and it is why an account can never be permanently bricked.
    ///
    /// Ungating an account that is not locked is a success and not an error.
    Ungate {
        /// The account.
        account: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Who is locked out**, and by what.
    ///
    /// Purge leases that have expired are not listed: a lease that ran out is
    /// not a lockout in force, and showing one would say an account is shut
    /// when it is open.
    Gates {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Empty an account: everything the user owns, gone. NO undo.**
    ///
    /// Every repository, every soft-delete tombstone still holding bytes, every
    /// orphan store with no catalog row, the namespace rows, and — with
    /// `--remove-principal` — the user's keys, grants, tokens and group
    /// memberships. Nested namespaces under the account's name go with it: they
    /// live in the same directory subtree, and leaving them would leave bytes
    /// on the disk and in the meters after you were told the account was
    /// emptied.
    ///
    /// **The user is locked out before this command returns**, and let back in
    /// when it is over — including when it FAILS. The walk itself is queued
    /// (one account at a time for the whole box) and this waits for it, unless
    /// `--no-wait`.
    ///
    /// `repo delete` without `--purge` leaves a dated tombstone precisely so a
    /// fat finger is recoverable. This is the verb that says the account is
    /// finished: it reclaims tombstones rather than making them, so `--yes` is
    /// required.
    Purge {
        /// The account.
        account: String,
        /// **Why.** Required, like `gate --note`.
        #[arg(long, value_name = "TEXT")]
        reason: String,
        /// Also remove the user: keys, grants, tokens, memberships, and the
        /// account's own lockout row.
        ///
        /// Without it the account shell survives, still locked, and `ungate`
        /// hands the user an empty account back. With it the name is free for
        /// somebody else.
        #[arg(long)]
        remove_principal: bool,
        /// **Refuse rather than destroy** if the account still holds a live
        /// repository. Names what is in the way and touches nothing.
        ///
        /// For a caller that believes it has already emptied the account by
        /// other means and wants the server to check rather than to act.
        #[arg(long)]
        expect_empty: bool,
        /// Say it. There is no retention window and no undelete after this.
        #[arg(long)]
        yes: bool,
        /// Enqueue and return, printing the job instead of waiting for it.
        #[arg(long)]
        no_wait: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Where an account's purge got to, and whether the lockout is off.**
    ///
    /// Both, because neither answers the question on its own: a finished purge
    /// beside a lockout still in force means the account is empty and still
    /// shut, which is either a suspension the purge correctly refused to lift
    /// or a lease nothing released — and those need different actions.
    PurgeStatus {
        /// The account.
        account: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Claim the estate's operator, and record the break-glass token as his
    /// first invite** — the installer's word, for a box no installer fed (a
    /// standalone gunnar, a test rig). Server admin only.
    ///
    /// gunnar names the operator (an installer-fed `operator_name` wins over
    /// NAME), makes him a person and gunnar-admin with his account namespace
    /// (an ownerless namespace of that name is adopted, never a refusal), and
    /// keeps the SHA-256 of `--bootstrap-file`'s contents as the invite for his
    /// FIRST passkey: the console registers it with `Access.WebRegister`, the
    /// token as the invite secret. The token is read here and hashed here; only
    /// its hash leaves this machine. Once he holds a passkey the bootstrap is
    /// spent and nothing is recorded.
    ClaimOperator {
        /// The operator's name — his account, and the namespace named after it.
        name: String,
        /// A file holding the break-glass token (one line). Absent: the
        /// operator is claimed and no invite is recorded.
        #[arg(long, value_name = "PATH")]
        bootstrap_file: Option<PathBuf>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// **Enroll an employee: a NEW user, created by and bound to the
    /// account.** An account with employees is an enterprise account; that is
    /// not a tier and not a setting. An existing user can never become an employee. The
    /// employee reads the account; only the account admin makes anything
    /// public. Account admin only.
    ///
    /// **"Add users"** is this verb, as the console's dialog asks it: each user
    /// holds `--room-gib` of the account's room (default 10, raised never
    /// lowered), out of what the account holds and has neither stored nor
    /// promised; `--count` above 1 adds that many SEATS with no names, and
    /// `--from-seat` fills one with the named user (what an invite does).
    #[command(visible_alias = "add-users")]
    Enroll {
        /// The account (its namespace).
        account: String,
        /// The new user's id. Absent for seats (`--count` above 1).
        id: Option<String>,
        /// Display name; the id when absent.
        #[arg(long)]
        name: Option<String>,
        /// How many users: 1 names one (the id), more adds that many seats
        /// with no names. At most 10000.
        #[arg(long, default_value_t = 1)]
        count: u32,
        /// Room per user, GiB, out of the account's room. Default 10; less is
        /// refused.
        #[arg(long, value_name = "GIB")]
        room_gib: Option<u64>,
        /// Fill one of the account's open seats with this new user; the seat
        /// decides the room.
        #[arg(long)]
        from_seat: bool,
        /// Ask whether it fits and how much room is missing; change nothing.
        #[arg(long)]
        dry_run: bool,
        /// Also make the new named user's invite (as the console does) and
        /// print it once: its id and the secret a `/login?invite=` link carries.
        #[arg(long)]
        invite: bool,
        /// An OpenSSH public key file to register on the new user at once.
        #[arg(long, value_name = "PATH")]
        key: Option<PathBuf>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// The account's employees, and its seats (all, open). Account admin only.
    Employees {
        /// The account (its namespace).
        account: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control clan …` — clans (2026-10-05): every verb is the caller's
/// own, signed with its key; gunnar decides from the clan. Sizes are typed as
/// `10GiB`, `512MiB` or plain bytes.
#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlClanCommand {
    /// Make a clan: NAME becomes its namespace (private); you are its admin.
    Create {
        name: String,
        /// What you give it out of your own room (e.g. `5GiB`).
        #[arg(long, default_value = "0")]
        give: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Your clans and invitations; with CLAN, that one in full.
    Show {
        clan: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Invite an ordinary account into CLAN (its admin's).
    Invite {
        clan: String,
        account: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Join CLAN, which invited you, giving `--give` of your own room.
    Accept {
        clan: String,
        #[arg(long, default_value = "0")]
        give: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Decline your invitation to CLAN — or, as its admin, withdraw
    /// `--account`'s.
    Decline {
        clan: String,
        #[arg(long)]
        account: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Set what you give CLAN (up out of your own room; down no lower than
    /// what the clan stores).
    Give {
        clan: String,
        size: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Leave CLAN; what you gave comes back (refused while it is in use, and
    /// to its last admin).
    Leave {
        clan: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Remove a member from CLAN (its admin's).
    Remove {
        clan: String,
        account: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Make a member of CLAN admin (`--no` to make it a plain member).
    Admin {
        clan: String,
        account: String,
        #[arg(long)]
        no: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Dissolve an EMPTY clan (its admin's): every contribution goes back.
    Dissolve {
        clan: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Offer CLAN/REPO to ACCOUNT, to move it out of the clan (its admin's);
    /// the account's admin takes or declines it.
    Offer {
        clan: String,
        repo: String,
        account: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Take CLAN/REPO, offered to your account: it moves to <account>/<repo>.
    /// `--no` declines it — or, as the clan's admin, withdraws the offer.
    Take {
        clan: String,
        repo: String,
        #[arg(long)]
        no: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

/// `gunnar control mirror …` — **the pull mirror, told to the APPLIANCE.**
///
/// # Why there are two `mirror` verbs and this is the one with `control` in it
///
/// `gunnar mirror add/sync/status` (no `control`) already exists and stays. It
/// mirrors into a LOCAL data root on the machine you typed it on, over gix
/// porcelain, and it is a git client's verb: my laptop keeps a copy. These are
/// the opposite job — *tell the server over there to keep the copy* — and the
/// `control` prefix is that line, the same line every other `gunnar control`
/// verb draws. Confusing the two is not a cosmetic mistake: one of them writes
/// to a disk you can `ls`, and the other writes to a box that has no shell.
///
/// # The one rule that shapes every verb below: `Sync` ENQUEUES
///
/// A fetch is minutes of somebody else's network, so `Mirror.Sync` puts a job on
/// the server's single runner and answers immediately — with `refs_changed = 0`
/// and no updates, **deliberately**, because at enqueue nothing has happened
/// yet. Reading that as "0 refs changed" is reading "I have not started" as "I
/// found nothing", and those are the same sentence about two different worlds.
/// So the answer to *what did the mirror do* is always `status`, never the echo
/// `sync` returns, and `sync --wait` is `status` in a loop with a human at the
/// other end.
///
/// # `has_progress` is read BEFORE the pair, everywhere
///
/// `(progress_done, progress_total) = (0, 0)` with `has_progress = false` means
/// the server has no denominator yet — the upstream has not said how many
/// objects there are. It is not zero percent, and a percentage bar drawn from it
/// sits at 0% for a minute and then jumps, which reads as a hang. Every renderer
/// here prints `counting…` for that case and `n/N` only when the server says the
/// pair is real.
/// `gunnar control entitlement …`. See [`ControlCommand::Entitlement`].
#[cfg(all(feature = "control", feature = "metered"))]
#[derive(Debug, Subcommand)]
pub enum ControlEntitlementCommand {
    /// **Hand the box ONE fact monetize signed.** Admin at server scope.
    ///
    /// The file is monetize's own `EntitlementFact` as JSON — the value
    /// `monetize_embed::signing::fact_message` canonicalises and signs, with its
    /// signatures — so what is pushed is byte for byte what monetize minted. This
    /// verb SIGNS NOTHING and holds no monetize key: the box verifies the fact
    /// against its own `--monetize-pubkey`, and a fact that does not verify is
    /// refused by name and nothing moves.
    ///
    /// **Operator-only** (monetize v2.0 P2 T13, A28 L13): monetize no longer
    /// calls this door. The ONE box pulls every Gunnar estate, so a paid plan
    /// reaches the box as a signed order its main pulls. This verb is the
    /// operator's hand tool for one fact, under the server's admin key.
    Set {
        /// Path to the signed fact (JSON), or `-` for stdin.
        #[arg(value_name = "FACT.json")]
        fact: PathBuf,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// The fact this box ENFORCES for one namespace, or `free` when it enforces
    /// none. Read on the namespace (a tenant may ask about their own).
    Get {
        #[arg(value_name = "NAMESPACE")]
        namespace: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
    /// Every fact this box ENFORCES, one line per namespace. A namespace absent
    /// here is Free — including one whose stored fact was refused at boot.
    List {
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}

#[cfg(feature = "control")]
#[derive(Debug, Subcommand)]
pub enum ControlMirrorCommand {
    /// **Point a repository at a remote.** A document write; it fetches nothing.
    ///
    /// `add` then `sync` is deliberate and not a missing convenience: registering
    /// where a repository's history comes from and pulling it are different
    /// decisions with different failure modes, and an `add` that fetched would
    /// make a typo in a URL into a minutes-long timeout instead of a stored
    /// string you can look at.
    ///
    /// Needs **Admin** on the repository — or on the namespace with `--create`,
    /// because there is nothing narrower than a namespace to hold the right to
    /// make a repository that does not exist yet.
    Add {
        /// `<namespace>/<repo>` on THIS server: where the mirror lands.
        #[arg(value_name = "NS/REPO")]
        path: String,
        /// The upstream. `ssh://git@host/ns/repo.git`, the scp-like
        /// `git@host:ns/repo.git`, or `https://host/ns/repo.git`. The URL — and
        /// nothing else — decides which transport is dialled and therefore which
        /// kind of credential is legal; see `credential`.
        #[arg(value_name = "URL")]
        url: String,
        /// Delete local refs the upstream has deleted. Off by default: a mirror
        /// that prunes is a mirror that can lose a branch because somebody else
        /// tidied theirs.
        #[arg(long)]
        prune: bool,
        /// Create the repository if it is not there.
        ///
        /// The hash kind is **not** a flag here and must not become one: the
        /// server takes it from the remote — the wire negotiates it — because a mirror of a sha256
        /// repository into a sha1 one is not a mirror, and a caller who guessed
        /// would find that out after the first fetch.
        #[arg(long)]
        create: bool,
        /// With `--create`: take over a repository of that name that exists
        /// and is NOT a mirror — it becomes a mirror, and its next sync moves
        /// its refs to the upstream's. Without it gunnar refuses the take-over.
        #[arg(long, requires = "create")]
        adopt: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Fetch from the upstream now** — enqueued on the server's one runner.
    ///
    /// Returns as soon as the job is on the queue. `--wait` is the shape a human
    /// wants and `--wait`'s absence is the shape a script wants, which is why
    /// the default here is the opposite of `repo gc`'s: a gc is seconds and a
    /// mirror of a real repository is minutes to hours, so waiting is the thing
    /// you ask for rather than the thing you opt out of.
    ///
    /// Asking twice while a job is live is ONE job, not two. Needs **Write**.
    Sync {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        path: String,
        /// Poll until the job is DONE or FAILED, printing each state as it
        /// moves, and exit non-zero if it failed.
        #[arg(long)]
        wait: bool,
        /// Give up waiting after this many seconds and say where to look. The
        /// job is NOT cancelled — it is the server's, and it keeps running.
        ///
        /// A bound rather than "forever" because `--wait` is what a person leaves
        /// running in a terminal, and a wait with no end is indistinguishable
        /// from a hang at exactly the moment you most want to know which it is.
        #[arg(long, default_value_t = 3600, value_name = "SECS")]
        timeout: u64,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **What is registered, what it dials with, and where its job got to.**
    ///
    /// The applied output, as against the request echo `add` and `sync` return.
    /// The ref updates are printed only on a DONE job, because a mirror's whole
    /// ref update set lands in one compare-and-swap or none of it does — a list of
    /// updates from a running job is a list of refs that have not moved.
    ///
    /// The credential's KIND and username are shown. The value is not, and there
    /// is no flag that shows it: no RPC in this service returns it.
    Status {
        /// One repository, `<namespace>/<repo>`. Omit for every mirror you can
        /// read.
        #[arg(value_name = "NS/REPO")]
        path: Option<String>,
        /// Only this namespace's mirrors. Ignored when a path is given.
        #[arg(long, value_name = "NAME")]
        namespace: Option<String>,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Stop mirroring.** The repository and everything already fetched stay;
    /// only the upstream link and its credential go.
    Remove {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        path: String,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Store what this mirror authenticates to its upstream with.**
    ///
    /// # The secret is read from a FILE or from stdin, never from an argument
    ///
    /// There is no `--secret <VALUE>` and there will not be one. An argument is
    /// in `~/.bash_history`, in `ps aux` for every user on the box while the
    /// command runs, and in the shell's job table — three copies of a long-lived
    /// bearer credential made by a convenience nobody needed. `--ssh-key` and
    /// `--token-file` name a path (a leading `@` is accepted, and `-` means
    /// stdin), which is where a key already lives.
    ///
    /// # The kind must match the transport, and the server refuses by name
    ///
    /// An `ssh://` remote takes `--ssh-key`; an `https://` remote takes
    /// `--token-file`. The mismatch is refused BEFORE anything is dialled,
    /// because it is otherwise the quietest failure in the whole feature: an ssh
    /// key has nowhere to go in an HTTP request, so the fetch goes out
    /// anonymous, the upstream answers 401, and an operator who can see that a
    /// credential IS stored rotates the key. For ever.
    ///
    /// A public `https://` upstream needs no credential at all, and `--forget`
    /// is how a stored one is taken back.
    Credential {
        /// `<namespace>/<repo>`.
        #[arg(value_name = "NS/REPO")]
        path: String,
        /// An OpenSSH **private** key file, for an `ssh://` upstream. `@<path>`
        /// and `-` (stdin) are accepted.
        #[arg(long, value_name = "PATH", conflicts_with_all = ["token_file", "forget"])]
        ssh_key: Option<String>,
        /// A file holding a personal access token, for an `https://` upstream.
        /// `@<path>` and `-` (stdin) are accepted. Trailing newlines are
        /// stripped — a token file written by a human has one, and a token sent
        /// with it is a token the forge rejects.
        #[arg(long, value_name = "PATH", conflicts_with = "forget")]
        token_file: Option<String>,
        /// The username the token is offered with (HTTP Basic). GitHub, Codeberg
        /// and GitLab personal access tokens all want one; with none the token
        /// is sent as `Authorization: Bearer`.
        #[arg(long, value_name = "NAME")]
        username: Option<String>,
        /// Forget the stored credential. The mirror stays; it dials anonymously
        /// from now on, which is right for a public upstream and a 401 for any
        /// other.
        #[arg(long)]
        forget: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },

    /// **Take a whole forge account off GitHub, Codeberg, GitLab or a self-hosted
    /// Forgejo — list it, choose, mirror it.** The verb that makes gunnar
    /// adoptable without a migration project.
    ///
    /// # Why this needs a REST call at all, in a git server
    ///
    /// git has no verb for "enumerate an account". The protocol starts from a
    /// URL you already know; `git ls-remote github.com` is not a shorter version
    /// of this, it is a question with no answer. Every forge exposes the list
    /// over its own HTTPS API and nowhere else, which is why `gunnar-forge`
    /// exists and why it is linked by **this** binary and never by the
    /// appliance: it holds a personal access token for the length of one call,
    /// and a box whose whole design is that it holds only repositories has no
    /// business with a bearer credential for somebody's entire GitHub.
    ///
    /// # The order, per chosen repository
    ///
    /// `Mirror.Add` with `create_repo` (the hash kind comes from the remote
    /// — it is not a flag), then `Mirror.SetCredential` if `--https`, then
    /// `Mirror.Sync`. A repository that fails does not stop the ones after it;
    /// the summary at the end says how many were queued and names every failure
    /// with its reason. A forge **401 or 403**, though, stops before anything is
    /// queued at all: half an import is worse than none, because it leaves an
    /// operator guessing which half.
    ///
    /// Re-running it is safe. `Add` on a mirror that is already there is a
    /// no-op and a second `Sync` while one is live is the same job, so `import
    /// --all` after adding one repository upstream mirrors the new one and
    /// bores the other twenty.
    Import {
        /// Which forge, and where. `github`, `codeberg`, `gitlab`, or any of
        /// them with `=<base-url>` for a self-hosted instance:
        /// `forgejo=https://git.example.com`, `github=https://ghe.example.com/api/v3`,
        /// `gitlab=https://gitlab.example.com`.
        #[arg(long, value_name = "FORGE[=URL]")]
        from: String,
        /// A file holding the forge token. `-` means stdin, which
        /// `--pick` also wants — so use a file when you use `--pick`.
        ///
        /// Without it the environment is read, in this order:
        /// `GUNNAR_FORGE_TOKEN`, then the forge's own conventional variable
        /// (`GITHUB_TOKEN`, `CODEBERG_TOKEN`, `GITLAB_TOKEN`, `FORGEJO_TOKEN`).
        /// There is deliberately no `--token <VALUE>`; see `credential`.
        #[arg(long, value_name = "PATH")]
        token_file: Option<String>,
        /// Mirror every listed repository.
        #[arg(long, conflicts_with = "pick")]
        all: bool,
        /// Read the choice from **stdin**: the `#` numbers as printed, or names
        /// (`octocat/hello-world` or just `hello-world`), separated by
        /// whitespace or commas. A `#` starts a comment to end of line.
        ///
        /// stdin and not a terminal picker, so the choice can be piped, kept in
        /// a file, and re-run. A chooser that only works at a tty is one a
        /// script cannot repeat.
        #[arg(long)]
        pick: bool,
        /// The gunnar namespace the mirrors land in — `<into>/<repo-name>`.
        ///
        /// Defaults to your login name (`$USER`), because that is your account.
        /// It is NOT asked of the server: the control plane authenticates a KEY
        /// and has no verb that names an account back, so guessing from the
        /// fingerprint would be a guess. Say `--into` when the two differ.
        #[arg(long, value_name = "NAMESPACE")]
        into: Option<String>,
        /// Mirror over `ssh://` (the forge's ssh clone URL) and store NO
        /// credential: a deploy key has to be enrolled on the upstream side,
        /// which is the upstream forge's business and not gunnar's. The command
        /// says where to put the private half afterwards.
        #[arg(long, conflicts_with = "https")]
        ssh: bool,
        /// Mirror over `https://` and store the SAME token the listing used —
        /// the forge that enumerated these repositories is the forge that will
        /// serve the clone. The default.
        #[arg(long)]
        https: bool,
        /// Include archived repositories, which are excluded by default.
        ///
        /// Excluded rather than shown-and-skipped because an account with ten
        /// years of archived experiments is mostly archived experiments, and
        /// `--all` should not mean "and 200 things you last touched in 2016".
        /// Mirroring one on purpose is exactly why the flag exists.
        #[arg(long)]
        include_archived: bool,
        /// Take over repositories of the same name that exist and are NOT
        /// mirrors. Without it gunnar refuses each such import by name and the
        /// rest go ahead.
        #[arg(long)]
        adopt: bool,
        #[arg(long, short = 'i', value_name = "PATH")]
        identity: Option<PathBuf>,
        #[arg(long, default_value = crate::DEFAULT_CONTROL_ADDR, value_name = "ADDR", env = "GUNNAR_CONTROL_ADDR", long_help = CONTROL_ADDR_HELP)]
        at: String,
    },
}