gunnar-server 2.0.0

The gunnar git server: SSH and smart-HTTP git transports and the gRPC control plane. The appliance half, extracted from gunnar-cli so the server code lives in its own crate.
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
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
//! `gunnar-grpc`'s [`ControlPlane`] seam, over `gunnar-core` and
//! `gunnar-store`: the adapter its module docs asked for.
//!
//! `gunnar-grpc` was written before `gunnar-core` existed and defined a local
//! trait describing what the seven services need. Its own docs say the trait
//! must become *"a thin adapter, one impl in this crate"* and must never be a
//! second source of truth for what a `Repo` is. This is that adapter, living
//! one level up because it is the binary that knows both halves.
//!
//! # What is real here, and what is not
//!
//! | surface | status |
//! |---|---|
//! | namespaces, repos | real, [`RepoCatalog`] |
//! | principals, keys, grants | real, [`AuthTable`] |
//! | `Refs.List` / `Get` / `ReadObject` / `Log` | real, the repository's own stores |
//! | `Admin.Stats` / `StorageInfo` | real, measured off the `fs` backend |
//! | `Refs.Diff` | **`Unimplemented`**: no diff engine on the server side |
//! | `Policy.*` | **`Unimplemented`**: `gunnar-core` has no protection store |
//! | `Mirror.*` | **`Unimplemented`**: mirroring needs `gunnar-client`, which an `S` crate must never link |
//!
//! Every one of those is an explicit [`ControlError::Unimplemented`] and never
//! an empty success. An empty ref list is indistinguishable from a working
//! server with no refs (measured, not asserted), and the same is true of "0 mirrors synced".
//!
//! # Three model mismatches, recorded rather than papered over
//!
//! 1. **`RepoPath` cannot express a nested namespace.** `gunnar-proto`'s
//!    `RepoPath::validate` rejects a `/` inside `namespace`, but nesting makes
//!    `team/sub/repo.git` legal over SSH. Such a repository is reachable by git
//!    and invisible to gRPC. That is a `gunnar-proto` change, not one to make
//!    here.
//! 2. **`Scope::Server` has no `RepoPath`.** A server-wide grant is carried as
//!    an empty namespace and an empty repo, which `MemoryControlPlane` refuses
//!    on the way in. The test double is the one that is wrong: without a
//!    server-scoped grant the bootstrap admin cannot create the first namespace
//!    (the secret-store seam).
//! 3. **`Namespace` in `gunnar-core` carries only a name** — no description, no
//!    creation time — so those two proto fields come back empty rather than
//!    invented.

use std::sync::Arc;

use gunnar_core::{Grant, HashKind, Level, PrincipalKind, RepoRef, Scope, UnixMillis, Visibility};
use gunnar_grpc::seam::ControlCounts;
use gunnar_grpc::MergedRef;
use gunnar_grpc::{ControlError, ControlPlane, ControlResult, NewRepo as ProtoNewRepo};
use gunnar_proto::{
    BranchProtection, Commit, FileChange, GrantLevel, MirrorConfig, Namespace, Principal,
    PublicKey, PullRequest, PullRequestState, ReadLfsObjectResponse, ReadObjectResponse,
    RefNamePolicy, RefTarget,
    Repo, RepoPath, RepoStorage, Signature, StorageInfoResponse,
};
use gunnar_store::git_storage_trait::{GitServe, ObjType, RefRow};
use gunnar_store::object;
use gunnar_wire::RefSnapshot;

use crate::storage::OpenRepo;
use crate::stores::ServerStores;

/// **How long abdication waits for the standby's queues to drain**, seconds.
///
/// A ceiling, not a promise: a standby that is down must not wedge the
/// hand-off, so after this the roster is cleared anyway (a recovered standby
/// replays from this box when it is re-added the other way round). Long enough
/// that a reachable standby with a normal backlog finishes first.
///
/// The wait itself is already a POLL (drained-or-deadline, below) — it returns
/// the instant every queue is empty and never sleeps a fixed span. The one
/// thing a fixed default cannot know is the box's LOAD: on a heavily loaded rig
/// a healthy standby's normal backlog can take longer than 30 s to drain, and
/// clearing the roster early truncates the flush. So the ceiling is TUNABLE —
/// `GUNNAR_ABDICATE_FLUSH_SECS` raises it for a loaded deployment without
/// changing the poll's shape (still drained-or-deadline, still short-circuits).
#[cfg(feature = "replication")]
const ABDICATE_FLUSH_SECS: u64 = 30;

/// The abdication flush ceiling in effect: `GUNNAR_ABDICATE_FLUSH_SECS` if it
/// parses to a positive value, else the [`ABDICATE_FLUSH_SECS`] default. A zero
/// or unparseable value is ignored (a 0 s ceiling would clear the roster before
/// a single job could drain — never what an operator means).
#[cfg(feature = "replication")]
fn abdicate_flush_secs() -> u64 {
    // The raw string is HANDED IN to the pure resolver so the parse is unit
    // tested without `set_var` — which is process-global and flakes the whole
    // suite across threads (see `wg.rs`'s note on the same hazard).
    resolve_flush_secs(std::env::var("GUNNAR_ABDICATE_FLUSH_SECS").ok().as_deref())
}

/// Pure ceiling resolver: a positive parsed override wins; anything else
/// (absent, blank, non-numeric, zero) falls back to [`ABDICATE_FLUSH_SECS`].
#[cfg(feature = "replication")]
fn resolve_flush_secs(raw: Option<&str>) -> u64 {
    raw.and_then(|v| v.trim().parse::<u64>().ok())
        .filter(|&s| s > 0)
        .unwrap_or(ABDICATE_FLUSH_SECS)
}

/// Company SSO's storage on the identity table (`gunnar_grpc::sso::plane::SsoPlane`).
mod sso_plane;

/// **The refusal a read of the transaction log answers** — one spelling for `Mirror.LogFetch`
/// gathered and streamed: a released log is the named, retryable [`gunnar_grpc::PRIMARY_GROWING`],
/// a range retention dropped is `FailedPrecondition` (a snapshot is needed), a sequence above the
/// head is `InvalidArgument`.
fn log_read_refusal(e: gunnar_core::txlog::Error) -> ControlError {
    match e {
        gunnar_core::txlog::Error::Released(_) => ControlError::Unavailable(format!(
            "{} this box's data set is being grown (unmounted): its transaction log is back after the remount — ask again",
            gunnar_grpc::PRIMARY_GROWING
        )),
        gunnar_core::txlog::Error::NotRetained { seq, first } => ControlError::FailedPrecondition(format!(
            "seq {seq} is no longer retained; the oldest is {first} — a snapshot is needed, not a range"
        )),
        gunnar_core::txlog::Error::BeyondHead { seq, head } => ControlError::InvalidArgument(format!("seq {seq} is beyond the head {head}")),
        other => ControlError::Internal(format!("transaction log: {other}")),
    }
}

/// **A streamed range onto the wire as `LogChunk` pieces** (twin-streaming, 2026-10-06): `meta`
/// on an entry's first piece, `last` on the piece that completes its declared length — which
/// [`crate::twin::stream_range`] hands over only after the entry's payload crc checked — and an
/// entry with no blob as one empty last piece at its end.
///
/// Since restore-large-entry (2026-10-07) every piece says the byte of the blob it starts at
/// (`offset`), an entry may begin part-way ([`crate::twin::stream_range_at`], the resumed
/// restore's `from_offset`), and the last piece carries the entry's checked payload crc
/// (`entry_crc`), so a box that put the entry together across several streams applies it only
/// if it IS the entry.
#[allow(clippy::type_complexity)] // the seam's sink, spelled as the seam spells it
struct ChunkOut<'s> {
    sink: &'s mut dyn FnMut(gunnar_proto::LogChunk) -> ControlResult<()>,
    open: Option<OutEntry>,
}

/// The entry [`ChunkOut`] is sending.
struct OutEntry {
    seq: u64,
    kind: u32,
    /// Not yet sent: it goes on the first piece.
    meta: Option<Vec<u8>>,
    blob_len: u64,
    /// The byte of the blob the next piece starts at.
    at: u64,
    /// The checked payload crc, once the source said it (before the last piece).
    crc: Option<u32>,
    /// The `last` piece went out.
    ended: bool,
}

impl ChunkOut<'_> {
    fn send(&mut self, blob: &[u8]) -> anyhow::Result<()> {
        let Some(o) = self.open.as_mut() else {
            anyhow::bail!("a piece outside an entry");
        };
        let offset = o.at;
        o.at += blob.len() as u64;
        anyhow::ensure!(o.at <= o.blob_len, "seq {}: more than its {} blob bytes", o.seq, o.blob_len);
        let last = o.at == o.blob_len;
        o.ended |= last;
        let chunk = gunnar_proto::LogChunk {
            seq: o.seq,
            kind: o.kind,
            meta: o.meta.take().unwrap_or_default(),
            blob_len: o.blob_len,
            blob: blob.to_vec(),
            last,
            restore_head: 0,
            restore_bytes: 0,
            log_id: String::new(),
            offset: Some(offset),
            entry_crc: if last { o.crc } else { None },
            snapshot_item: None,
            snapshot_id: String::new(),
        };
        (self.sink)(chunk).map_err(anyhow::Error::from)
    }
}

impl crate::twin::FrameSink for ChunkOut<'_> {
    fn begin(&mut self, seq: u64, kind: u16, meta: &[u8], blob_len: u64) -> anyhow::Result<()> {
        self.begin_at(seq, kind, meta, blob_len, 0)
    }
    fn begin_at(&mut self, seq: u64, kind: u16, meta: &[u8], blob_len: u64, offset: u64) -> anyhow::Result<()> {
        anyhow::ensure!(self.open.is_none(), "seq {seq} began inside another entry");
        anyhow::ensure!(offset <= blob_len, "seq {seq}: from byte {offset} of a {blob_len}-byte blob");
        self.open = Some(OutEntry { seq, kind: u32::from(kind), meta: Some(meta.to_vec()), blob_len, at: offset, crc: None, ended: false });
        Ok(())
    }
    fn checked(&mut self, payload_crc: u32) -> anyhow::Result<()> {
        if let Some(o) = self.open.as_mut() {
            o.crc = Some(payload_crc);
        }
        Ok(())
    }
    fn piece(&mut self, bytes: &[u8]) -> anyhow::Result<()> {
        self.send(bytes)
    }
    fn end(&mut self) -> anyhow::Result<()> {
        // An empty blob, or one resumed AT its end: one empty last piece carries the end (and
        // the crc).
        if matches!(&self.open, Some(o) if !o.ended) {
            self.send(&[])?;
        }
        let Some(o) = self.open.take() else {
            anyhow::bail!("an entry ended that never began");
        };
        anyhow::ensure!(o.at == o.blob_len && o.ended, "seq {}: {} of {} blob bytes went out", o.seq, o.at, o.blob_len);
        Ok(())
    }
}

impl CoreControlPlane {
    /// **The log `Mirror.LogFetch` reads**, or the named refusal while it cannot be read: a set
    /// held for its own growth (the guard over an unmounted set; MEASURED release-3 mock
    /// 2026-09-29: `txlog: No such file or directory` mid twin-grow), or a PRIMARY whose log is
    /// released for its own growth's remount (M1, release-3 test2 mock 2026-09-29) — both named
    /// and retryable, never `Internal: txlog: No such file or directory`.
    fn readable_log(&self) -> ControlResult<&gunnar_core::txlog::Log> {
        if crate::twin::maintenance::is_held(self.stores.root()) {
            return Err(ControlError::Unavailable(
                "this box's data set is held for its own growth (unmounted): its transaction log is not readable until the growth mounts it back".into(),
            ));
        }
        if !self.stores.is_twin() {
            if let Some(why) = crate::twin::fenced_why(self.stores.root()) {
                return Err(ControlError::FailedPrecondition(format!("{why}. Nothing is read from it")));
            }
        }
        let log: &gunnar_core::txlog::Log = self.stores.txlog();
        if log.is_released() {
            return Err(log_read_refusal(gunnar_core::txlog::Error::Released(log.dir().to_path_buf())));
        }
        // ★ twin-resync-space (2026-10-06): a twin that gave its stale copy up for a resync, or
        // is mid-install, holds no state at any one sequence — its log is not half a recharge.
        if self.stores.is_twin() {
            if let Some(why) = crate::twin::snapshot::not_whole(self.stores.root()) {
                return Err(ControlError::FailedPrecondition(format!("{why}. Nothing is read from it")));
            }
        }
        Ok(log)
    }
}

/// The control plane, backed by the real catalog and identity table.
pub struct CoreControlPlane {
    stores: Arc<ServerStores>,
    /// **The runtime data-set growth** (`crate::grow`), when `serve` wired
    /// one. `None` on a bare plane (tests, `--dry-run`): `GrowStatus` then
    /// answers the seam's honest default and `GrowStart` is refused by name.
    grow: Option<Arc<crate::grow::GrowMachine>>,
    /// Started `--role twin` ([`CoreControlPlane::with_twin_role`]).
    twin_role: bool,
    /// **The git listener this server actually bound**, when `serve` handed it
    /// in ([`CoreControlPlane::with_git_listener`]) — the fact
    /// `Bootstrap.Status.serving_git` reports. `None` on a bare plane, and the
    /// status door then falls back to the boot window alone, exactly as it
    /// always answered. See [`crate::readiness::GitListener`].
    git_listener: Option<crate::readiness::GitListener>,
    /// **The ONE admission gate** the three git fronts share, when `serve`
    /// handed it in — read by `Mirror.FlushReplication` for the in-flight
    /// count the watermark needs (T11). `None` on a bare plane.
    admission: Option<Arc<gunnar_ssh::Admission>>,
    /// **What replication is doing**, for `Admin.Stats`.
    ///
    /// A [`ReplicationView`](crate::replication_view::ReplicationView) and not
    /// a replicator: this plane is built before the replicator is started
    /// (replication is started last on purpose, so nothing above it can be
    /// slowed by it), and the view is the slot `serve` drops it into
    /// afterwards. It also keeps `feature = "replication"` and every replication type
    /// out of this file, which is what lets the two lanes working on that
    /// module and on this one stay out of each other's way.
    ///
    /// Unfilled it reads `configured: false` — what a box with no standby *is*,
    /// and a fact rather than an absence.
    replication: crate::replication_view::ReplicationView,
    /// **What replication is CONFIGURED to do**, for `Mirror.SetReplication` /
    /// `RemoveReplication` / `ReplicationStatus`.
    ///
    /// The write half beside the read half above, and the two are not twins: the
    /// view answers *what has happened*, the slot decides *what runs*. It is
    /// `Option` and behind the feature's own name only through
    /// [`with_replication`](Self::with_replication), so a build without
    /// `replication` — and a `CoreControlPlane` built by a test that has no
    /// server around it — refuses the three verbs by name instead of failing to
    /// compile.
    ///
    /// **This is the whole reason the appliance can be told about a standby.**
    /// the reference appliance is an OS-less image running as PID 1: no shell, no
    /// editor, no `scp`. Before this, `replication.json` could only be written
    /// by something with a filesystem to write it from, which on that box is
    /// nothing at all.
    #[cfg(feature = "replication")]
    replication_slot: Option<Arc<crate::mirror::ReplicationSlot>>,
    /// **The live webhook slot**, so an operator can name an outbound endpoint
    /// over the control plane — the appliance has no shell, exactly as with the
    /// replication slot above.
    #[cfg(feature = "webhooks")]
    webhook_slot: Option<Arc<crate::webhook::WebhookSlot>>,
    /// **The live entitlement slot** (`metered` only): what `Entitlement.Set`
    /// writes and the front doors read. `None` on a metered build started
    /// without `--monetize-pubkey`: every namespace Free, and `Set` refuses by
    /// name rather than accepting a fact it could not verify.
    #[cfg(feature = "metered")]
    entitlement: Option<Arc<crate::entitlement::EntitlementSlot>>,
    /// **The disk-headroom gate** `Repos.Create` asks — the SAME object the
    /// front doors' chain holds, so "the disk is full" is one line on both
    /// doors (one implementation). `None` on a bare plane (a test not about the disk).
    headroom: Option<Arc<gunnar_ssh::DiskHeadroomGate>>,
    /// The largest object `Refs.ReadObject` will inflate. See
    /// [`DEFAULT_MAX_OBJECT_BYTES`] for the arithmetic and
    /// [`with_max_object_bytes`](Self::with_max_object_bytes) for changing it.
    max_object_bytes: u64,
    /// **The one gc at a time this box runs**, behind `Repos.Gc` and
    /// `Repos.GcStatus`.
    ///
    /// It belongs to the plane and not to a caller for the reason
    /// [`crate::gc_queue`] opens with: a console can serialise itself, and
    /// nothing else. Built here so every door onto this plane — the console, the
    /// CLI over gRPC, anything else holding a credential — queues behind the
    /// same worker. No thread is started until something is actually enqueued.
    gc: crate::gc_queue::GcQueue,
    /// **The one account purge at a time this box runs**, behind
    /// `Accounts.Purge` and `Accounts.PurgeStatus`.
    ///
    /// Its own queue and not the gc one — see [`crate::purge_queue`]: a gc
    /// waits holding nothing, a purge waits holding a total lockout on a
    /// customer's account, and putting them in one line would keep a user shut
    /// out through somebody else's repository maintenance.
    purge: crate::purge_queue::PurgeQueue,
    /// **The one mirror sync at a time this box runs**, behind `Mirror.Sync`
    /// and `Mirror.Status`.
    ///
    /// Its own queue and not the gc one — see [`crate::mirror_queue`]: a gc
    /// waits holding nothing, a mirror waits holding a repository that is not
    /// yet usable, and making a first sync queue behind somebody else's hour of
    /// compaction is the mistake `job_queue`'s module doc names in advance.
    mirror: crate::mirror_queue::MirrorQueue,
    /// **Where the event bus arrives, if this plane is ever given one.**
    ///
    /// The mirror runner is built in [`CoreControlPlane::new`] and the bus is
    /// handed over later by [`CoreControlPlane::with_bus`] (`serve.rs` builds
    /// the bus first and the plane after, but `new` is also what every test
    /// calls). A slot the closure captures is what lets the runner publish
    /// `MirrorSynced` **when the sync finishes** rather than when it was asked
    /// for — an event announcing a fetch that has not happened is worse than no
    /// event.
    ///
    /// `OnceLock`, so it is written once and read without a lock on every
    /// completed sync. A plane that never gets one simply publishes nothing,
    /// which is what every test plane wants.
    bus: Arc<std::sync::OnceLock<Arc<gunnar_grpc::EventBus>>>,
    /// **The keys `Bootstrap.Restore` is taken from, as the medium named them**
    /// (`--restore-pubkey`, [`CoreControlPlane::with_restore_keys`]). The installer's fed
    /// keys are added at each ask ([`gunnar_grpc::ControlPlane::restore_keys`]). Empty on a
    /// bare plane, which with no feed is a box that refuses every restore by name.
    restore_keys: Vec<String>,
}

impl CoreControlPlane {
    /// Serve out of `stores`, with the default object ceiling.
    pub fn new(stores: Arc<ServerStores>) -> Self {
        let for_gc = Arc::clone(&stores);
        let bus: Arc<std::sync::OnceLock<Arc<gunnar_grpc::EventBus>>> = Arc::default();
        CoreControlPlane {
            stores,
            grow: None,
            twin_role: false,
            git_listener: None,
            admission: None,
            replication: crate::replication_view::ReplicationView::new(),
            #[cfg(feature = "replication")]
            replication_slot: None,
            #[cfg(feature = "webhooks")]
            webhook_slot: None,
            #[cfg(feature = "metered")]
            entitlement: None,
            headroom: None,
            max_object_bytes: DEFAULT_MAX_OBJECT_BYTES,
            gc: Self::gc_queue(Arc::clone(&for_gc)),
            purge: Self::purge_queue(Arc::clone(&for_gc)),
            mirror: Self::mirror_queue(Arc::clone(&for_gc), Arc::clone(&bus)),
            bus,
            restore_keys: Vec::new(),
        }
    }

    /// **Keys this box takes a `Bootstrap.Restore` from** (h-v1-6a, 2026-09-28): OpenSSH
    /// public key lines, from `--restore-pubkey`. For a box that no installer feeds — the
    /// kit, a drill — this is the only way a restore can be taken at all.
    pub fn with_restore_keys(mut self, keys: Vec<String>) -> Self {
        self.restore_keys = keys;
        self
    }

    /// **Publish this plane's event-stream events onto `bus`.**
    ///
    /// Today that is one event and one producer: `MirrorSynced`, from the
    /// mirror queue's worker, when a sync actually completes. It is a slot
    /// rather than a constructor argument because `CoreControlPlane::new` is
    /// what every test calls and a bus is not something a test of the disk
    /// should have to build.
    pub fn with_bus(self, bus: Arc<gunnar_grpc::EventBus>) -> Self {
        // A second `with_bus` is the caller's mistake and is ignored rather
        // than panicking a running server; the first bus wins, which is the
        // one the listener is serving from.
        let _ = self.bus.set(bus);
        self
    }

    /// **This box was started `--role twin`** (`serve.rs`). `Bootstrap.Status`
    /// then answers `role twin` before the join, when `twin.json` does not
    /// exist yet and [`ServerStores::is_twin`] still says no — the moment an
    /// installer door and a re-image verify ask.
    pub fn with_twin_role(mut self, twin_role: bool) -> Self {
        self.twin_role = twin_role;
        self
    }

    /// **The address the git listener took**, handed in by `serve::start` from
    /// `local_addr()` beside the address that was asked for.
    ///
    /// This is what makes `Bootstrap.Status.serving_git` a reading of a SOCKET
    /// rather than of a boot latch. Per-plane and not a static: two servers in
    /// one test process are two listeners, and a process-wide slot would let
    /// the second answer for the first.
    pub fn with_git_listener(mut self, listener: crate::readiness::GitListener) -> Self {
        self.git_listener = Some(listener);
        self
    }

    /// **Release every purge lease this box is still holding.**
    ///
    /// Called once at start-up, and it is the fast half of the crash-recovery
    /// story. A purge that was interrupted by a SIGKILL or a power cut left its
    /// lease in the identity table; nothing is running any more, so every one
    /// of them is stale by construction — this process has just started and has
    /// enqueued nothing.
    ///
    /// Without it those accounts stay shut until their leases expire, which is
    /// up to [`gunnar_core::PURGE_LEASE_MS`] of a paying customer being told
    /// their account is locked by a purge that is not happening. The lease is
    /// still there as the backstop for the case this cannot cover — a box that
    /// never comes back up.
    ///
    /// **Administrative gates are left alone.** They carry no deadline and were
    /// set by a person; a restart must not un-suspend an account.
    ///
    /// Returns how many were released. Failures are logged and not fatal: a
    /// server that refused to start because it could not tidy a lease would
    /// turn a recoverable state into an outage.
    pub fn release_stale_purge_leases(stores: &ServerStores) -> u64 {
        let gates = match stores.auth().gates() {
            Ok(gates) => gates,
            Err(err) => {
                tracing::error!(
                    target: "gunnar::audit",
                    error = %err,
                    "the account gates could not be read at start-up; any purge lease left by a \
                     crash will stay in force until it expires"
                );
                return 0;
            }
        };
        let mut released = 0;
        for gate in gates {
            if gate.reason != gunnar_core::GateReason::Purge {
                continue;
            }
            match stores.auth().lift_gate_held_by(&gate.account, &gate.holder) {
                Ok(Some(_)) => {
                    released += 1;
                    tracing::warn!(
                        target: "gunnar::audit",
                        event = "account.stale_lease_released",
                        account = %gate.account,
                        job = %gate.holder,
                        "an account was still locked by a purge that did not finish; the lockout \
                         has been lifted and the account may still hold bytes the purge did not \
                         reclaim — `repo list-orphans` shows them"
                    );
                }
                Ok(None) => {}
                Err(err) => tracing::error!(
                    target: "gunnar::audit",
                    account = %gate.account,
                    error = %err,
                    "a stale purge lease could not be lifted at start-up"
                ),
            }
        }
        released
    }

    /// The purge queue's two closures: the walk, and the unlock.
    ///
    /// The walk is [`crate::account_purge::purge_account`] — the same function
    /// the CLI verb calls, so there is one definition of what emptying an
    /// account means (one implementation). The unlock is
    /// `AuthTable::lift_gate_held_by`, **held_by** and not the unconditional
    /// lift, so a purge finishing cannot clear a suspension an operator put on
    /// while it ran.
    ///
    /// The lease is re-stamped on every store reclaimed. A purge of a large
    /// account outlives [`gunnar_core::PURGE_LEASE_MS`] easily, and a lease
    /// that ran out mid-walk would unlock the account the walk is still
    /// emptying — a reader could then start re-exploding a read cache into a
    /// directory the purge has not reached yet. A renewal that FAILS is logged
    /// and not fatal: it means the row is somebody else's now, the account is
    /// still shut, and stopping the purge over it would leave more behind.
    fn purge_queue(stores: Arc<ServerStores>) -> crate::purge_queue::PurgeQueue {
        let for_release = Arc::clone(&stores);
        crate::purge_queue::PurgeQueue::new(
            Arc::new(
                move |order: &crate::purge_queue::PurgeOrder,
                      progress: &crate::purge_queue::Progress| {
                    let request = crate::account_purge::PurgeRequest {
                        account: order.account.clone(),
                        principal_id: order.principal_id.clone(),
                        reason: order.reason.clone(),
                        remove_principal: order.remove_principal,
                        expect_empty: order.expect_empty,
                    };
                    let auth = stores.auth();
                    let account = order.account.clone();
                    let job_id = order.job_id.clone();
                    let mut step = |step: crate::account_purge::Step| match step {
                        crate::account_purge::Step::Found(stores_found) => {
                            progress.found(stores_found)
                        }
                        crate::account_purge::Step::Reclaimed { bytes, .. } => {
                            progress.reclaimed(bytes);
                            // **The heartbeat.** Pushed out after every store,
                            // so a purge that takes an hour never runs out of
                            // lease — and a purge that dies still hands the
                            // account back within PURGE_LEASE_MS.
                            let until = gunnar_core::now_ms() + gunnar_core::PURGE_LEASE_MS;
                            if let Err(err) = auth.renew_gate(&account, &job_id, until) {
                                tracing::warn!(
                                    target: "gunnar::audit",
                                    account = %account,
                                    job = %job_id,
                                    error = %err,
                                    "a purge could not renew its lockout lease; the account is \
                                     still shut and the walk continues"
                                );
                            }
                        }
                        crate::account_purge::Step::Failed(note) => progress.failed(note),
                        crate::account_purge::Step::PrincipalRemoved => {
                            progress.principal_removed()
                        }
                    };
                    let report =
                        crate::account_purge::purge_account(&stores, request, &mut step)
                            .map_err(|err| format!("{err:#}"))?;
                    // A walk that ran and left stores behind is a FAILURE, and
                    // the queue is told so here rather than left to infer it
                    // from a report it cannot see. The names are already on the
                    // job through `Step::Failed`; this is the sentence.
                    if report.failures.is_empty() {
                        Ok(())
                    } else {
                        Err(format!(
                            "{} of {} stores could not be reclaimed and are still on the disk; \
                             `repo list-orphans` shows them",
                            report.failures.len(),
                            report.stores_found
                        ))
                    }
                },
            ),
            Arc::new(move |account: &str, job_id: &str| {
                for_release
                    .auth()
                    .lift_gate_held_by(account, job_id)
                    .map(|lifted| lifted.is_some())
                    .map_err(|err| format!("{err}"))
            }),
        )
    }

    /// The queue's runner: resolve the catalog row, then **call the same
    /// `admin::gc_one` the CLI verb calls** (one implementation).
    ///
    /// Errors come back as strings because they are going onto a job a console
    /// will read, not up a call stack. The resolution happens *inside* the
    /// runner rather than at enqueue time on purpose: a repository can be
    /// deleted while its job waits, and discovering that when the work starts
    /// is a FAILED job saying so, which is the truth. Resolving early would
    /// have queued a row that no longer describes anything.
    fn gc_queue(stores: Arc<ServerStores>) -> crate::gc_queue::GcQueue {
        crate::gc_queue::GcQueue::new(Arc::new(move |path: &str| {
            let repo_ref = gunnar_core::resolve_repo_path(path)
                .map_err(|err| format!("`{path}` is not a valid <namespace>/<name>: {err:#}"))?;
            let repo = stores
                .catalog()
                .get(&repo_ref)
                .map_err(|err| format!("reading the catalog row for {path}: {err:#}"))?
                .ok_or_else(|| format!("{path} is no longer a live repository"))?;
            let report = crate::admin::gc_one(&stores, &repo)
                .map_err(|err| format!("maintaining {path}: {err:#}"))?;
            Ok(crate::admin::reclaimed_bytes(&report))
        }))
    }

    /// **The mirror queue's runner: read the sealed credential, then run the
    /// one fetch (one implementation).**
    ///
    /// The credential is read **here, on the worker**, and not carried on the
    /// order. Two reasons, and both are about where a secret is allowed to be:
    /// an order is `Debug` and lives on a job a status RPC renders, so a key on
    /// it would be one `{:?}` away from a log line; and a credential rotated
    /// while a sync waited should be the one the sync uses, not the one that
    /// was current when somebody clicked.
    ///
    /// Errors come back as strings because they are going onto a job a console
    /// will read, not up a call stack — the same reason `gc_queue`'s runner
    /// returns one. None of them can contain the credential: the only paths out
    /// of `mirror_fetch` that mention the remote scrub its userinfo first.
    fn mirror_queue(
        stores: Arc<ServerStores>,
        bus: Arc<std::sync::OnceLock<Arc<gunnar_grpc::EventBus>>>,
    ) -> crate::mirror_queue::MirrorQueue {
        crate::mirror_queue::MirrorQueue::new(Arc::new(
            move |order: &crate::mirror_queue::MirrorOrder,
                  report: &crate::job_queue::Reporter<crate::mirror_queue::Mirror>| {
                let repo_ref = gunnar_core::resolve_repo_path(&order.path).map_err(|err| {
                    format!("`{}` is not a valid <namespace>/<name>: {err:#}", order.path)
                })?;
                // **In flight, durably**, before anything is dialled: a restart
                // during the sync leaves this mark, and the next start settles
                // the sync as interrupted and resumes it
                // (`resume_interrupted_mirrors`) instead of leaving a
                // repository with nothing in it and a registration that says
                // nothing went wrong.
                let first = stores
                    .mirrors()
                    .mark_started(&repo_ref, gunnar_grpc::bus::now_unix_ms())
                    .ok()
                    .flatten()
                    .is_some_and(|record| record.creates_repo || record.sync_count == 0);
                let outcome = read_credential(&stores, &repo_ref).and_then(|credential| {
                    crate::mirror_fetch::sync_once(&stores, order, &credential, report)
                });
                audit_mirror_outcome(&stores, &repo_ref, order, first, outcome.as_ref().err().map(String::as_str), report);

                // **The registration records every attempt, good or bad.**
                // `record_sync` moves `last_sync_at_unix_ms` only on success —
                // that field means "when this mirror was last correct", and
                // moving it on a failure would make a mirror that has been
                // broken for a week look fresh.
                let error = outcome.as_ref().err().map(String::as_str);
                if let Err(err) = stores.mirrors().record_sync(
                    &repo_ref,
                    gunnar_grpc::bus::now_unix_ms(),
                    error,
                ) {
                    tracing::warn!(
                        target: "gunnar::git",
                        repo = %order.path,
                        %err,
                        "a mirror sync finished and its registration could not be updated; the \
                         fetch itself is unaffected"
                    );
                }

                // The event stream, **after** the work and only on success. An event that
                // announced a fetch which had not happened would be worse than
                // no event, which is why `Mirror.Sync` no longer publishes one.
                if outcome.is_ok() {
                    if let Some(bus) = bus.get() {
                        let job = report.snapshot();
                        let updates = job
                            .map(|job| job.report.updates)
                            .unwrap_or_default()
                            .into_iter()
                            .map(|(ref_name, old_oid, new_oid)| gunnar_proto::RefUpdate {
                                ref_name,
                                old_oid,
                                new_oid,
                            })
                            .collect::<Vec<_>>();
                        bus.publish(gunnar_proto::event::Payload::MirrorSynced(
                            gunnar_proto::MirrorSynced {
                                repo: Some(RepoPath::new(repo_ref.namespace(), repo_ref.name())),
                                remote_url: order.upstream.clone(),
                                refs_changed: updates.len() as u32,
                                updates,
                            },
                        ));
                    }
                }
                outcome
            },
        ))
    }

    /// **Settle every sync a stopped process left in flight, and resume it**
    /// (import-big, 2026-10-26).
    ///
    /// The job queue is memory: a restart in the middle of an import (an
    /// out-of-memory kill, an update, a power cut) forgot the job, and what was
    /// left was a repository with nothing in it and a registration with no
    /// error — a console that showed no failure for an import that never
    /// landed. The registration now carries an in-flight mark
    /// (`MirrorRecord::sync_started_at_unix_ms`); here, once at start, each
    /// marked sync is settled as interrupted (its `last_error` says so, and the
    /// account's audit log has a line) and enqueued again, up to
    /// [`gunnar_core::MAX_RESUMES`] times in a row. Past that it stays FAILED
    /// with the reason, for a person to press Sync. Returns how many were
    /// resumed.
    pub fn resume_interrupted_mirrors(&self) -> usize {
        let settled = match self.stores.mirrors().settle_interrupted(gunnar_grpc::bus::now_unix_ms()) {
            Ok(settled) => settled,
            Err(err) => {
                tracing::warn!(target: "gunnar::git", %err, "the mirror registrations could not be read to resume interrupted syncs");
                return 0;
            }
        };
        let mut resumed = 0;
        for record in settled {
            let Ok(repo_ref) = gunnar_core::resolve_repo_path(&record.repo) else { continue };
            let again = record.interrupted <= gunnar_core::MAX_RESUMES;
            audit_line(
                &self.stores,
                &repo_ref,
                if again { "mirror.sync.interrupted" } else { "mirror.sync.failed" },
                &record.last_error,
                true,
            );
            tracing::warn!(
                target: "gunnar::git",
                event = "mirror.sync.interrupted",
                repo = %record.repo,
                interrupted = record.interrupted,
                resumed = again,
                "a mirror sync was in flight when the server stopped"
            );
            if again {
                self.mirror.enqueue(crate::mirror_queue::MirrorOrder {
                    path: repo_ref.key(),
                    upstream: record.remote_url.clone(),
                    prune: record.prune,
                });
                resumed += 1;
            }
        }
        resumed
    }

    /// **Take the lockout a purge runs under, without downgrading one that is
    /// already there.**
    ///
    /// A lease is written only when the account is *not* already gated. If it
    /// is — an operator suspending a customer, monetize locking a non-payer —
    /// that gate stands, and the purge runs under it. Two consequences, both
    /// deliberate:
    ///
    /// * the account does not quietly acquire a **deadline** it did not have.
    ///   Overwriting an administrative gate with a lease would mean a
    ///   suspension expiring ten minutes after a purge finished with it, which
    ///   is a suspended account silently coming back.
    /// * the job will report `gate_released: false` and the account stays shut,
    ///   because `lift_gate_held_by` will find a holder that is not this job.
    ///   That is the correct outcome: the purge did not take that lockout and
    ///   has no standing to lift it.
    fn gate_for_purge(
        &self,
        account: &str,
        job_id: &str,
        options: &gunnar_grpc::seam::PurgeAccountOptions,
    ) -> ControlResult<()> {
        if self
            .stores
            .auth()
            .gate_covering(account)
            .map_err(internal)?
            .is_some()
        {
            return Ok(());
        }
        let lease = gunnar_core::AccountGate::purge_lease(
            account,
            job_id,
            gunnar_core::now_ms() + gunnar_core::PURGE_LEASE_MS,
        )
        .by(&options.principal_id)
        .noted(format!(
            "this account is being permanently deleted: {}",
            options.reason
        ));
        self.stores.auth().gate(lease).map_err(gate_error)?;
        Ok(())
    }

    /// **Hand the disk-headroom gate in.** From here on `Repos.Create` refuses
    /// under the floor with `RESOURCE_EXHAUSTED` and the gate's own line —
    /// the one a refused `git push` prints, because it is the same function.
    #[must_use]
    pub fn with_headroom(mut self, gate: Arc<gunnar_ssh::DiskHeadroomGate>) -> Self {
        self.headroom = Some(gate);
        self
    }

    /// **Hand this plane the runtime growth** (`crate::grow`). Called by
    /// `serve` once the admission gate and the stores exist.
    pub fn with_grow(mut self, grow: Arc<crate::grow::GrowMachine>) -> Self {
        self.grow = Some(grow);
        self
    }

    /// **Hand this plane the admission gate** the git fronts share, for the
    /// in-flight count `Mirror.FlushReplication` reports.
    pub fn with_admission(mut self, admission: Arc<gunnar_ssh::Admission>) -> Self {
        self.admission = Some(admission);
        self
    }

    /// The growth, or the seam's refusal by name.
    fn grow_machine(&self) -> ControlResult<&Arc<crate::grow::GrowMachine>> {
        self.grow.as_ref().ok_or(ControlError::Unimplemented(
            "this control plane was built with no runtime growth wired in, so it cannot grow the data set",
        ))
    }

    /// Verify a signed membership event before it changes anything.
    ///
    /// The same shape as `forge_append`'s check and for the same reason (one
    /// implementation): a membership log that took an event it could not verify would be a
    /// log of claims, and the point of the design is that it is a log of
    /// evidence. The key must be in the ACL table (or no later reader could
    /// check it), it must be the claimed actor's own, and the event must
    /// describe the change the caller named — re-checked here at the seam
    /// because this door can also be reached without a connection.
    fn verify_membership_event(
        &self,
        signed: gunnar_proto::SignedMembershipEvent,
        group_id: &str,
        member_id: &str,
        action: gunnar_core::MembershipAction,
    ) -> ControlResult<gunnar_core::SignedMembershipEvent> {
        let signed = from_proto_membership(signed)?;
        if signed.event.group != group_id || signed.event.member != member_id {
            return Err(ControlError::InvalidArgument(format!(
                "the signed event is about {:?}/{:?} but the change is {:?}/{:?}",
                signed.event.group, signed.event.member, group_id, member_id
            )));
        }
        if signed.event.action != action {
            return Err(ControlError::InvalidArgument(
                "the signed event's action does not match the change (add vs remove)".to_owned(),
            ));
        }
        let key = self
            .stores
            .auth()
            .signing_keys()
            .map_err(|err| ControlError::Unavailable(format!("{err:#}")))?
            .into_iter()
            .find(|row| row.fingerprint_sha256 == signed.key_fingerprint)
            .ok_or_else(|| {
                ControlError::InvalidArgument(format!(
                    "{} is not registered on this server, so nobody reading this event later \
                     could check its signature",
                    signed.key_fingerprint
                ))
            })?;
        if key.principal_id != signed.event.actor {
            return Err(ControlError::InvalidArgument(format!(
                "this membership change is attributed to {:?} and is signed by {}, which is \
                 {:?}'s key; a membership change is the actor's own word, so it must carry the \
                 actor's own signature",
                signed.event.actor, signed.key_fingerprint, key.principal_id
            )));
        }
        let public = gunnar_core::ssh_key::PublicKey::from_openssh(&key.openssh)
            .map_err(|err| ControlError::Internal(format!("stored key is unreadable: {err}")))?;
        gunnar_core::membership::verify_event(&signed, &public)
            .map_err(|problem| ControlError::InvalidArgument(format!("{problem}")))?;
        Ok(signed)
    }

    /// Append a verified membership event to the signed membership log, and
    /// return the index it landed at — the index an inclusion proof is taken
    /// at. Append-only and never rewritten, so a removal followed by a re-add
    /// leaves two standing events, which is what makes the history evidence.
    fn append_membership_event(
        &self,
        signed: &gunnar_core::SignedMembershipEvent,
    ) -> ControlResult<u64> {
        let log = self.stores.membership_log();
        let mut line = serde_json::to_string(signed)
            .map_err(|err| ControlError::Internal(format!("encoding the event: {err}")))?;
        line.push('\n');
        let _framed = gunnar_core::txlog::sink::append_line(log.records_path(), line.trim_end_matches('\n'))
            .map_err(|err| ControlError::Unavailable(format!("framing the line in the transaction log: {err}")))?;
        use std::io::Write as _;
        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(log.records_path())
            .map_err(|err| ControlError::Unavailable(format!("opening the membership log: {err}")))?;
        file.write_all(line.as_bytes()).map_err(|err| {
            ControlError::Unavailable(format!("appending to the membership log: {err}"))
        })?;
        let count = log
            .lines_of()
            .map_err(|err| ControlError::Unavailable(format!("{err:#}")))?
            .len() as u64;
        Ok(count.saturating_sub(1))
    }

    /// Every membership event on the server, decoded, in append order.
    fn membership_log_events(&self) -> ControlResult<Vec<gunnar_core::SignedMembershipEvent>> {
        self.stores
            .membership_log()
            .lines_of()
            .map_err(|err| ControlError::Unavailable(format!("{err:#}")))?
            .iter()
            .map(|line| {
                serde_json::from_str(line).map_err(|err| {
                    ControlError::Internal(format!("decoding a membership event: {err}"))
                })
            })
            .collect()
    }

    /// **Hand this plane the live replication slot**, so an operator can name a
    /// standby over the control plane.
    ///
    /// Called by `Server::start` before the plane is wrapped in an `Arc`, and
    /// before anything is running in the slot — which is the point: a target has
    /// to be settable on a box that has never had one and holds no repositories
    /// yet, and that is every box on its first boot.
    #[cfg(feature = "replication")]
    pub fn with_replication(mut self, slot: Arc<crate::mirror::ReplicationSlot>) -> Self {
        self.replication_slot = Some(slot);
        self
    }

    /// The slot, or a refusal that names WHY there is none.
    ///
    /// `Unimplemented` and not `Internal`: a plane built without a slot is a
    /// plane with no server around it (a unit test), and telling a caller "this
    /// server cannot do that" is true, actionable and not an incident.
    #[cfg(feature = "replication")]
    fn replication_slot(&self) -> ControlResult<&Arc<crate::mirror::ReplicationSlot>> {
        self.replication_slot.as_ref().ok_or(ControlError::Unimplemented(
            "this control plane was built with no replication slot, so it cannot configure                  a standby",
        ))
    }

    /// **Hand this plane the live webhook slot**, so an operator can name an
    /// outbound endpoint over the control plane. Called by `Server::start`
    /// before the plane is wrapped in an `Arc`.
    #[cfg(feature = "webhooks")]
    pub fn with_webhooks(mut self, slot: Arc<crate::webhook::WebhookSlot>) -> Self {
        self.webhook_slot = Some(slot);
        self
    }

    /// Hand the entitlement slot in (`metered` only).
    #[cfg(feature = "metered")]
    pub fn with_entitlement(mut self, slot: Arc<crate::entitlement::EntitlementSlot>) -> Self {
        self.entitlement = Some(slot);
        self
    }

    /// The entitlement slot, or a refusal that names WHY there is none.
    #[cfg(feature = "metered")]
    fn entitlement(&self) -> ControlResult<&Arc<crate::entitlement::EntitlementSlot>> {
        self.entitlement.as_ref().ok_or_else(|| {
            ControlError::FailedPrecondition(
                "this metered server was started without `--monetize-pubkey`, so it holds no \
                 key to verify an entitlement fact against and refuses every one; every \
                 namespace is Free"
                    .into(),
            )
        })
    }

    /// The webhook slot, or a refusal that names WHY there is none.
    #[cfg(feature = "webhooks")]
    fn webhook_slot(&self) -> ControlResult<&Arc<crate::webhook::WebhookSlot>> {
        self.webhook_slot.as_ref().ok_or(ControlError::Unimplemented(
            "this control plane was built with no webhook slot, so it cannot configure                  an outbound endpoint",
        ))
    }

    /// Configuration **and** running state, in one answer.
    ///
    /// Both halves, always, because they can disagree and the disagreement is
    /// the interesting part: `targets` non-empty with `standbys` empty is a
    /// server that has the configuration and is not running it.
    #[cfg(feature = "replication")]
    ///
    /// **`include_refs` is the operator's, and it is false for everything but a
    /// `replication list --refs`.** The mutating verbs print a snapshot back to
    /// confirm the roster, and the ref-coverage walk they used to trigger opens
    /// every repository's reference database for a number nobody asked
    /// for — so they pass `false`, and only the explicit status verb forwards
    /// the flag the operator set.
    fn replication_snapshot(
        &self,
        include_refs: bool,
    ) -> ControlResult<gunnar_proto::ReplicationStatusResponse> {
        let slot = self.replication_slot()?;
        let config = slot
            .config()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        let mut out = gunnar_proto::ReplicationStatusResponse {
            targets: config
                .targets
                .iter()
                .map(crate::replication_wire::target_to_proto)
                .collect(),
            role: config.role.to_proto() as i32,
            ..Default::default()
        };
        if let Some(replicator) = slot.replicator() {
            crate::replication_wire::running_to_proto(&replicator, include_refs, &mut out);
        }
        Ok(out)
    }

    /// **The slot `serve` drops the replicator's counters into**, so
    /// `Admin.Stats` can report them.
    ///
    /// Without it the counters exist and nothing reads them, which is exactly
    /// the state that let every configured standby receive NOTHING from
    /// `e31ab8f4` to 2026-08-30 while five log lines out of five said so into a
    /// file nobody was tailing.
    pub fn replication_view(&self) -> crate::replication_view::ReplicationView {
        self.replication.clone()
    }

    /// Every forge event, as it was written.
    ///
    /// Verifying nothing: the fold is over what is in the log, and whether an
    /// event is evidence is a separate question with its own answer, asked
    /// per approval in [`CoreControlPlane::thread_state`].
    fn forge_events(&self) -> ControlResult<Vec<gunnar_core::SignedEvent>> {
        self.stores
            .forge_log()
            .lines_of()
            .map_err(|err| ControlError::Unavailable(format!("reading the forge log: {err:#}")))?
            .iter()
            .map(|line| {
                serde_json::from_str(line).map_err(|err| {
                    ControlError::Internal(format!("a forge event will not decode: {err}"))
                })
            })
            .collect()
    }

    /// A folded review, with **every approval re-checked against the ACL key
    /// table right now** — not trusted because it is in the file.
    ///
    /// That re-check is the difference the whole design is about, and it is why
    /// the wire carries a verdict per approval rather than a count: an approval
    /// whose key was since removed has not failed and has not passed, and a
    /// number cannot say so.
    ///
    /// **The key must be the claimed actor's own.** A signature proves which
    /// KEY spoke; only the key table's `principal_id` says whose voice that
    /// is. Until 2026-08-31 the fingerprint was looked up across the whole
    /// table, so an approval claiming `actor: alice` signed by any other
    /// registered principal's key verified — and merged. The verdict for that
    /// case names the key's real owner, because "your signature failed" and
    /// "that is somebody else's key" send an operator down different roads.
    fn review_state(
        &self,
        repo: &str,
        state: &gunnar_core::forge::Review,
        all: &[gunnar_core::SignedEvent],
    ) -> ControlResult<gunnar_proto::ReviewState> {
        let keys: Vec<(String, String, gunnar_core::ssh_key::PublicKey)> = self
            .stores
            .auth()
            .signing_keys()
            .map_err(|err| ControlError::Unavailable(format!("{err:#}")))?
            .iter()
            .filter_map(|row| {
                gunnar_core::ssh_key::PublicKey::from_openssh(&row.openssh)
                    .ok()
                    .map(|key| {
                        (
                            row.fingerprint_sha256.clone(),
                            row.principal_id.clone(),
                            key,
                        )
                    })
            })
            .collect();

        let approvals = state
            .approvals
            .iter()
            .map(|(actor, commit)| {
                let signed = all.iter().rev().find(|e| {
                    e.event.repo == repo
                        && e.event.pull == state.pull
                        && e.event.actor == *actor
                        && matches!(&e.event.event, gunnar_core::Event::Approved { commit: c } if c == commit)
                });
                let (verified, verdict) = match signed {
                    None => (false, "NO EVENT".to_owned()),
                    Some(signed) => match keys
                        .iter()
                        .find(|(fingerprint, _, _)| *fingerprint == signed.key_fingerprint)
                    {
                        None => (false, "UNKNOWN KEY".to_owned()),
                        // The key is registered — to somebody else. The
                        // signature may be perfectly good; it is still not
                        // this actor's word, and saying whose it is lets the
                        // operator see a filed-in-another's-name attempt for
                        // what it is.
                        Some((_, owner, _)) if *owner != *actor => {
                            (false, format!("KEY OF {owner}, NOT {actor}"))
                        }
                        Some((_, _, key)) => match gunnar_core::forge::verify_event(signed, key) {
                            Ok(()) => (true, "verified".to_owned()),
                            Err(problem) => (false, format!("BAD ({problem})")),
                        },
                    },
                };
                gunnar_proto::Approval {
                    actor: actor.clone(),
                    commit: commit.clone(),
                    verified,
                    verdict,
                }
            })
            .collect();

        Ok(gunnar_proto::ReviewState {
            repo: repo.to_owned(),
            pull: state.pull,
            approvals,
            comments: state.comments as u64,
        })
    }

    /// **Set the deployment's object ceiling** for `Refs.ReadObject`.
    ///
    /// `0` disables the ceiling, which restores the unbounded behaviour: the
    /// server will inflate an object of any size to answer a request. That is a
    /// real choice for a single-tenant box with a trusted control port and a
    /// repository full of large blobs, and it is spelled explicitly rather than
    /// being what you get by forgetting to configure anything.
    ///
    /// This exists as much for the tests as for the operator: a ceiling that can
    /// only be a compile-time constant can only be exercised by writing an object
    /// bigger than it, which for the real default means a 64 MiB fixture. Being
    /// able to set it small is what lets the refusal be seen red cheaply — and it
    /// proves the configuration is *wired*, which a test against the constant
    /// could never show.
    pub fn with_max_object_bytes(mut self, bytes: u64) -> Self {
        self.max_object_bytes = bytes;
        self
    }

    /// The pull-request table, opened against the same control store the
    /// catalog and the identity table live in. A fresh handle per call: the
    /// document cache rides the handle, and a pull-request operation is rare
    /// enough that re-parsing beats holding one more long-lived Arc chain.
    fn pulls(&self) -> ControlResult<gunnar_core::Pulls> {
        gunnar_core::Pulls::new(Arc::clone(self.stores.control_store()))
            .map_err(|err| ControlError::Internal(format!("opening the pulls table: {err:#}")))
    }

    fn repo_ref(path: &RepoPath) -> ControlResult<RepoRef> {
        path.validate()
            .map_err(|err| ControlError::InvalidArgument(err.to_string()))?;
        RepoRef::new(&path.namespace, &path.repo)
            .map_err(|err| ControlError::InvalidArgument(err.to_string()))
    }

    /// Resolve a tree-ish — a ref name, a hex oid, or `HEAD` — to the **tree**
    /// it names.
    ///
    /// The resolution half is the one `log` already does: a hex oid is taken as
    /// one, anything else is validated as a reference name and looked up in the
    /// snapshot, and an oid of the wrong hash kind is refused with a sentence
    /// that says which kind the repository is. What is added here is the last
    /// hop — a commit is followed to its tree, a tag is peeled first, and a tree
    /// is already the answer — so `from`/`to` accept everything `git diff`
    /// accepts in the same position.
    fn tree_of(
        &self,
        git: &dyn GitServe,
        hash: gix_hash::Kind,
        path: &RepoPath,
        spec: &str,
    ) -> ControlResult<gix_hash::ObjectId> {
        let id = match gix_hash::ObjectId::from_hex(spec.as_bytes()) {
            Ok(id) => {
                if id.kind() != hash {
                    return Err(ControlError::InvalidArgument(format!(
                        "{spec} is a {} oid; this repository is {hash}",
                        id.kind()
                    )));
                }
                id
            }
            Err(_) => {
                gunnar_store::refname::validate(spec)
                    .map_err(|err| ControlError::InvalidArgument(err.to_string()))?;
                let snapshot = RefSnapshot::read(git).map_err(wire_error)?;
                let resolved = if spec == gunnar_store::HEAD {
                    snapshot.head(git).map_err(wire_error)?
                } else {
                    snapshot.resolve(spec).map_err(wire_error)?
                };
                resolved.ok_or_else(|| ControlError::NotFound(format!("{spec} in {path}")))?
            }
        };
        let id = peel(git, hash, id)?;
        let (kind, bytes) = git
            .read(id.as_bytes())
            .map_err(store_error)?
            .ok_or_else(|| ControlError::NotFound(format!("object {id} in {path}")))?;
        match kind {
            ObjType::Tree => Ok(id),
            ObjType::Commit => object::commit(&bytes, hash)
                .map(|commit| commit.tree)
                .map_err(|err| ControlError::Internal(format!("decoding commit {id}: {err}"))),
            // A blob is a legal object and not a legal side of a tree diff.
            // Saying so beats walking it and reporting that nothing changed.
            other => Err(ControlError::InvalidArgument(format!(
                "{spec} names a {other:?}; a diff needs a commit, a tag or a tree"
            ))),
        }
    }

    /// The repository's policy as `gunnar-policy` understands it.
    ///
    /// A repository with no stored policy reads as
    /// [`PolicyConfig::default`](gunnar_policy::PolicyConfig) — no gates —
    /// which is the same thing the push path concludes and is stated in one
    /// place rather than two. A stored document that does **not parse** is an
    /// error here and not an empty policy: this path is a caller asking what
    /// the rules are, and answering "there are none" about a document that
    /// exists and is broken is the worst available answer.
    fn policy_of(&self, repo: &gunnar_core::Repo) -> ControlResult<gunnar_policy::PolicyConfig> {
        let stored = self.stores.policies().get(&repo.path()).map_err(internal)?;
        match stored {
            None => Ok(gunnar_policy::PolicyConfig::default()),
            Some(document) => gunnar_policy::PolicyConfig::from_json(&document).map_err(|err| {
                ControlError::Internal(format!(
                    "the stored policy for {} does not parse: {err}",
                    repo.key()
                ))
            }),
        }
    }

    /// Write `config` back, or delete the document when it configures nothing.
    ///
    /// Deleting rather than storing an empty document is what keeps "nobody has
    /// configured this repository" and "somebody configured nothing" the same
    /// state. Two states that behave identically and read differently are a
    /// question an operator cannot answer.
    fn store_policy(
        &self,
        repo: &gunnar_core::Repo,
        config: &gunnar_policy::PolicyConfig,
    ) -> ControlResult<()> {
        let policies = self.stores.policies();
        if *config == gunnar_policy::PolicyConfig::default() {
            policies.remove(&repo.path()).map_err(internal)?;
            return Ok(());
        }
        let json = config
            .to_json()
            .map_err(|err| ControlError::Internal(format!("rendering the policy: {err}")))?;
        policies.set(&repo.path(), &json).map_err(internal)
    }

    fn open(&self, path: &RepoPath) -> ControlResult<(gunnar_core::Repo, Arc<OpenRepo>)> {
        let repo_ref = Self::repo_ref(path)?;
        let repo = self
            .stores
            .catalog()
            .get(&repo_ref)
            .map_err(internal)?
            .ok_or_else(|| ControlError::NotFound(format!("repository {path}")))?;
        let store = self.stores.repo_store(&repo).map_err(|err| {
            ControlError::Internal(format!("opening the repository's stores: {err:#}"))
        })?;
        Ok((repo, store))
    }

    /// **A mirror's registration, with its repository opened when it has
    /// one.** A registration whose repository is still to come (an import's
    /// first sync has not landed: `MirrorRecord::creates_repo`) has none to
    /// open, and that is not an error; every other registration's repository
    /// must open, as it always had to.
    fn mirror_record(&self, path: &RepoPath) -> ControlResult<gunnar_core::MirrorRecord> {
        let repo_ref = Self::repo_ref(path)?;
        let record = self.stores.mirrors().get(&repo_ref).map_err(internal)?;
        match record {
            Some(record) if record.creates_repo && self.stores.catalog().get(&repo_ref).map_err(internal)?.is_none() => {
                Ok(record)
            }
            record => {
                self.open(path)?;
                record.ok_or_else(|| ControlError::NotFound(format!("no mirror registered for {path}")))
            }
        }
    }
}

/// **The one place a [`crate::gc_queue::GcJob`] becomes a seam job.**
///
/// The queue keys on `<namespace>/<name>` because that is what its runner
/// needs; the seam speaks [`RepoPath`] because that is what the wire does.
/// `path` is threaded in rather than re-parsed out of the job's own string: it
/// is the request's own path, already validated, and re-parsing it here would
/// be a second resolver that could disagree with the first (one implementation).
fn gc_job_out(path: &RepoPath, job: crate::gc_queue::GcJob) -> gunnar_grpc::seam::GcJob {
    gunnar_grpc::seam::GcJob {
        job_id: job.job_id,
        path: path.clone(),
        state: match job.state {
            crate::gc_queue::GcState::Queued => gunnar_grpc::seam::GcState::Queued,
            crate::gc_queue::GcState::Running => gunnar_grpc::seam::GcState::Running,
            crate::gc_queue::GcState::Done => gunnar_grpc::seam::GcState::Done,
            crate::gc_queue::GcState::Failed => gunnar_grpc::seam::GcState::Failed,
        },
        queue_position: job.queue_position,
        // Named through `report` rather than through the job's `Deref`: the
        // job is being taken apart field by field here, and a deref borrow in
        // the middle of that would be reading a value that is half moved.
        bytes_reclaimed: job.report.bytes_reclaimed,
        error: job.error,
        enqueued_at_unix_ms: job.enqueued_at_unix_ms,
        finished_at_unix_ms: job.finished_at_unix_ms,
    }
}

/// `gunnar_core`'s gate onto the seam's.
fn gate_out(gate: gunnar_core::AccountGate) -> gunnar_grpc::seam::AccountGate {
    gunnar_grpc::seam::AccountGate {
        account: gate.account,
        reason: match gate.reason {
            gunnar_core::GateReason::Administrative => {
                gunnar_grpc::seam::GateReason::Administrative
            }
            gunnar_core::GateReason::Purge => gunnar_grpc::seam::GateReason::Purge,
        },
        holder: gate.holder,
        actor: gate.actor,
        note: gate.note,
        at_unix_ms: gate.at,
        // **0 on the seam means "no deadline"**, which is what `None` means
        // here. Flattened at this boundary rather than on the wire so the proto
        // stays a plain `int64` and every reader of it applies the same rule.
        expires_unix_ms: gate.expires.unwrap_or(0),
    }
}

/// The queue's job onto the seam's.
fn purge_job_out(job: crate::purge_queue::PurgeJob) -> gunnar_grpc::seam::PurgeJob {
    // The purge's own half, taken out whole before the queue's half is: the
    // failure list is owned and has to be MOVED onto the seam, and a job's
    // `Deref` only ever lends its report.
    let report = job.report;
    gunnar_grpc::seam::PurgeJob {
        job_id: job.job_id,
        // The queue keys on the account, so the account IS the job's key.
        account: job.key,
        state: match job.state {
            crate::purge_queue::PurgeState::Queued => gunnar_grpc::seam::PurgeState::Queued,
            crate::purge_queue::PurgeState::Running => gunnar_grpc::seam::PurgeState::Running,
            crate::purge_queue::PurgeState::Done => gunnar_grpc::seam::PurgeState::Done,
            crate::purge_queue::PurgeState::Failed => gunnar_grpc::seam::PurgeState::Failed,
        },
        queue_position: job.queue_position,
        stores_found: report.stores_found,
        stores_purged: report.stores_purged,
        bytes_reclaimed: report.bytes_reclaimed,
        principal_removed: report.principal_removed,
        gate_released: report.gate_released,
        error: job.error,
        failures: report.failures,
        enqueued_at_unix_ms: job.enqueued_at_unix_ms,
        started_at_unix_ms: job.started_at_unix_ms,
        finished_at_unix_ms: job.finished_at_unix_ms,
    }
}

/// A gate write that was refused, as the error the caller wants.
///
/// A reserved or malformed account name is the caller's mistake and comes back
/// as `INVALID_ARGUMENT`; anything else is the table failing to be written and
/// is not the caller's fault. Folding the first into `Internal` would send an
/// operator looking at the disk over a typo.
fn gate_error(err: gunnar_core::Error) -> ControlError {
    match err {
        gunnar_core::Error::ReservedPrincipalId(_) | gunnar_core::Error::InvalidPath { .. } => {
            ControlError::InvalidArgument(format!("{err}"))
        }
        other => internal(other),
    }
}

/// **One stored flow row → one `DayActivity`.** The single writer of that
/// mapping, so the wire and the ledger cannot drift by a field.
///
/// `refused_by_reason` carries only the reasons that HAPPENED. A reason with no
/// refusals that day is absent rather than 0, because the map is a breakdown of
/// a number the caller already has (`refused`) and a zero entry in it adds a
/// row to a console's list that says nothing.
fn day_activity(day: i64, row: &gunnar_core::FlowDay) -> gunnar_proto::DayActivity {
    gunnar_proto::DayActivity {
        day_unix_ms: gunnar_core::midnight_of(day),
        bytes_in: row.bytes_in,
        bytes_out: row.bytes_out,
        pushes: row.pushes,
        fetches: row.fetches,
        lfs_bytes_in: row.lfs_bytes_in,
        lfs_bytes_out: row.lfs_bytes_out,
        refused: row.refused(),
        refused_by_reason: gunnar_core::Refusal::ALL
            .into_iter()
            .filter(|reason| row.refused_for(*reason) > 0)
            .map(|reason| (reason.name().to_owned(), row.refused_for(reason)))
            .collect(),
        auth_failures: row.auth_failures,
        last_push_unix_ms: row.last_push_unix_ms,
        last_fetch_unix_ms: row.last_fetch_unix_ms,
        distinct_principals: row.distinct_principals(),
        distinct_principals_capped: row.principals_capped,
    }
}

/// **A create's refusal, classified** — the repository or namespace named, a box being
/// restored (or off the stripe) as UNAVAILABLE (RUN A 2026-10-08: a create on a main being
/// restored answered INTERNAL, and the console showed "transaction log" and "twin" to a
/// customer), any other core error INTERNAL, anything else (the disk's own refusal) as is.
pub(crate) fn create_error(err: &anyhow::Error, path: &RepoPath) -> ControlError {
    match err.downcast_ref::<gunnar_core::Error>() {
        Some(gunnar_core::Error::RepoExists(_)) => ControlError::AlreadyExists(format!("repository {path}")),
        Some(gunnar_core::Error::NoSuchNamespace(ns)) => ControlError::NotFound(format!("namespace {ns}")),
        Some(e @ (gunnar_core::Error::LogFollows | gunnar_core::Error::OffStripe { .. })) => ControlError::Unavailable(e.to_string()),
        Some(_) => ControlError::Internal(format!("{err:#}")),
        None => ControlError::FailedPrecondition(format!("{err:#}")),
    }
}

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

    /// ★ **A create on a box being restored is UNAVAILABLE, never INTERNAL** (RUN A R8,
    /// 2026-10-08): the console turns UNAVAILABLE + this sentence into its own word.
    #[test]
    fn a_create_on_a_restoring_box_is_unavailable() {
        let path = RepoPath::new("acme", "site");
        let restoring = anyhow::Error::new(gunnar_core::Error::LogFollows);
        assert!(matches!(create_error(&restoring, &path), ControlError::Unavailable(m) if m.contains("being restored")));
        let exists = anyhow::Error::new(gunnar_core::Error::RepoExists(gunnar_core::RepoRef::new("acme", "site").unwrap()));
        assert!(matches!(create_error(&exists, &path), ControlError::AlreadyExists(_)));
        assert!(matches!(create_error(&anyhow::anyhow!("a store already stands there"), &path), ControlError::FailedPrecondition(_)));
    }
}

/// A catalog error, mapped to the status code that says **whose fault it is**.
///
/// This used to be `ControlError::Internal(err.to_string())` for every one of
/// its thirty-four call sites, so `gunnar control repo set-default-branch
/// team/project trunk` came back as
///
/// ```text
/// gunnar: Internal error: internal error: not a legal default branch name: "trunk"
/// ```
///
/// An `INTERNAL` says *the server is broken*. What actually happened is that
/// the caller typed a short branch name where a full ref was required, and
/// nothing in that sentence tells them to fix their argument rather than read
/// the server's logs. Every "this repository does not exist", "that name is
/// taken" and "you are not allowed to" arrived the same way.
///
/// `enrolment_error` already classified its own errors for exactly this
/// reason; this is the same job for the rest of the surface, in one function
/// rather than at thirty-four call sites (one implementation). The mapping follows gRPC's
/// own definitions:
///
/// * **INVALID_ARGUMENT** — the request is malformed however the server feels.
/// * **NOT_FOUND** / **ALREADY_EXISTS** — the named thing is or is not there.
/// * **FAILED_PRECONDITION** — well formed, and the server's *state* refuses.
/// * **PERMISSION_DENIED** — authenticated, not allowed.
/// * **UNAVAILABLE** — storage did not answer; retrying may work.
/// * **INTERNAL** — only what is genuinely a bug here, which is the point:
///   an `INTERNAL` an operator sees now means something.
fn internal(err: gunnar_core::Error) -> ControlError {
    use gunnar_core::Error as E;
    match err {
        // The caller's argument.
        e @ (E::InvalidPath { .. }
        | E::PathEscape { .. }
        | E::ReservedPrincipalId(_)
        | E::BadBranchName(_)
        | E::BadFingerprint(_)
        | E::Key(_)
        | E::InvalidInput { .. }) => ControlError::InvalidArgument(e.to_string()),
        // What is not there.
        e @ (E::NoSuchRepo(_)
        | E::NoSuchNamespace(_)
        | E::NoSuchPrincipal(_)
        | E::NoSuchCredential(_)) => ControlError::NotFound(e.to_string()),
        // …and what already is.
        e @ (E::RepoExists(_)
        | E::NamespaceExists(_)
        | E::PrincipalExists(_)
        | E::NameExists { .. }
        | E::KeyExists { .. }
        | E::CredentialExists { .. }
        | E::InviteExists(_)
        | E::TokenExists { .. }
        | E::AlreadyBootstrapped { .. }
        | E::AlreadyProvisioned { .. }) => ControlError::AlreadyExists(e.to_string()),
        // Well formed; the server's state says no. A namespace that still holds
        // repositories is the case an operator meets, and `--delete-repos` is
        // the answer — which is a precondition, not a bad request.
        e @ (E::NamespaceNotEmpty { .. }
        | E::Contended { .. }
        | E::NotAPerson { .. }
        | E::NotAMachine { .. }) => {
            ControlError::FailedPrecondition(e.to_string())
        }
        e @ (E::Denied { .. } | E::CounterRollback { .. } | E::InviteInvalid) => {
            ControlError::PermissionDenied(e.to_string())
        }
        // Storage did not answer. NOT `Internal`: the request may well succeed
        // on a retry, and telling a caller their request was wrong when the
        // disk was busy sends them to fix the wrong thing.
        e @ (E::Store(_) | E::Json(_)) => ControlError::Unavailable(e.to_string()),
        // The control store is OFF THE STRIPE while the data set grows: the
        // write is refused by name and the caller retries after the growth —
        // D7's "refuse", and UNAVAILABLE says exactly that to a generated
        // client where INTERNAL would say "look at this server".
        e @ E::OffStripe { .. } => ControlError::Unavailable(e.to_string()),
        // A box being restored takes no write until the restore is whole: "try again".
        e @ E::LogFollows => ControlError::Unavailable(e.to_string()),
        // A document that will not parse, and anything unclassified. These are
        // what genuinely mean "look at this server". `gunnar_core::Error` is
        // `#[non_exhaustive]`, so a variant added later lands here — `INTERNAL`
        // is the right default for "gunnar does not know what this is", and it
        // errs toward the server's fault rather than toward blaming the caller
        // for something nobody has classified.
        e => ControlError::Internal(e.to_string()),
    }
}

/// **An archive cut's error, classified by whose fault it is** — the same job
/// [`internal`] does for `gunnar_core::Error`, for the one path that reports an
/// `anyhow` chain instead.
///
/// Two classes, and they are told apart by what is *in* the chain rather than
/// by matching on a message:
///
/// * an `io::Error` anywhere in it means the disk or the socket did not answer
///   — `UNAVAILABLE`, because a retry may well work, and a `BrokenPipe` is the
///   *client* having hung up rather than this server being broken;
/// * anything else is a refusal the cut made on purpose — the watermark above a
///   pack a GC has rewritten, a directory with no `objects.pack`, a repository
///   directory holding two stores. Those are `FAILED_PRECONDITION`: the request
///   is well formed and the server's state says no. A full archive
///   (`--from-generation 0`) is the answer to the first, and the message says so
///   in the plugin's own words.
#[cfg(feature = "engine-znippy")]
fn archive_error(err: anyhow::Error) -> ControlError {
    let io = err
        .chain()
        .any(|cause| cause.downcast_ref::<std::io::Error>().is_some());
    let message = format!("{err:#}");
    if io {
        ControlError::Unavailable(message)
    } else {
        ControlError::FailedPrecondition(message)
    }
}

/// **The one storage-fault conversion in this file** (one implementation).
///
/// `GitOps` and `GitServe` answer in `anyhow`, so every read of a repository
/// arrives here. `{:#}` and not `to_string()`: the cause chain is the whole of
/// what an operator has to go on, and `to_string()` prints only the outermost
/// context — *"reading the ref namespace"* with the errno dropped.
///
/// **The status code is unchanged, deliberately.** `Internal` is what this
/// answered before, and `internal_or_denied` twenty lines above classifies
/// `gunnar_core::Error::Store` as `Unavailable` for a reason that applies here
/// too — a storage fault may well succeed on a retry. Changing it is a change
/// to what every gRPC client of `Refs.*` retries on, so it is **recorded here
/// and not taken as a drive-by** of a compile fix.
///
/// ⚠ **A lost compare-and-swap and a broken disk arrive as the same string** on
/// this path. `git-storage-trait` carries [`RefRejection`] for exactly that
/// distinction and `RefRejection::of(&err)` is how it is recovered; nothing in
/// this file needs it yet. Whatever does must use that, and **never** match on
/// the message text.
///
/// [`RefRejection`]: gunnar_store::git_storage_trait::RefRejection
fn store_error(err: anyhow::Error) -> ControlError {
    ControlError::Internal(format!("{err:#}"))
}

/// The same, for the one authority on following a symbolic reference.
///
/// [`gunnar_wire::refs`] returns `gunnar_wire::Error` rather than
/// `anyhow::Error`; a symref walk that refuses is a fault in what the store
/// holds, which is the same `Internal` this control plane already reports for
/// [`store_error`], so the two funnel to one variant rather than inventing a
/// second grade of failure for the same event.
fn wire_error(err: gunnar_wire::Error) -> ControlError {
    ControlError::Internal(format!("{err:#}"))
}

// ── model translation ───────────────────────────────────────────────────────

/// The one translation of a hash kind into the proto enum. `transport.rs`
/// reuses it for the push attestation rather than writing a second `match`
/// that could drift from this one (one implementation).
pub(crate) fn hash_kind(kind: HashKind) -> gunnar_proto::HashKind {
    match kind {
        HashKind::Sha1 => gunnar_proto::HashKind::Sha1,
        HashKind::Sha256 => gunnar_proto::HashKind::Sha256,
    }
}

/// gunnar has **two** visibilities, not three.
///
/// The proto still carries `VISIBILITY_INTERNAL`, and it used to alias
/// `PUBLIC` here — honestly, at the time: with no anonymous path at all,
/// "readable by any authenticated principal" and "public" named the same set.
/// Anonymous read (2026-08-03) broke that equivalence — `Public` now means readable by
/// ANYONE, with no key — and the alias survived the redefinition. What that
/// cost, MEASURED 2026-08-19 through the console: an operator chose
/// "internal" and the repository came out anonymous-readable. Silently
/// WIDENING an access request is the one direction a coercion must never
/// fail, so `INTERNAL` is now refused by name instead of mapped. The day a
/// real internal tier exists in [`Visibility`], this arm becomes its
/// translation; until then the wire value is a claim with no implementation.
fn visibility_in(v: gunnar_proto::Visibility) -> ControlResult<Visibility> {
    match v {
        gunnar_proto::Visibility::Public => Ok(Visibility::Public),
        gunnar_proto::Visibility::Internal => Err(ControlError::InvalidArgument(
            "visibility \"internal\" has no implementation: since 2026-08-03, \"public\" means \
             readable with no key at all, so \"internal\" (any authenticated principal) \
             no longer aliases it and gunnar refuses to guess which you meant. Choose \
             \"private\" or \"public\""
                .into(),
        )),
        gunnar_proto::Visibility::Private | gunnar_proto::Visibility::Unspecified => {
            Ok(Visibility::Private)
        }
    }
}

/// The one translation of a stored pull request into the proto shape (one implementation).
fn pull_out(path: &RepoPath, record: gunnar_core::PullRecord) -> PullRequest {
    PullRequest {
        repo: Some(path.clone()),
        number: record.number,
        title: record.title,
        description: record.description,
        source_ref: record.source_ref,
        target_ref: record.target_ref,
        state: match record.state {
            gunnar_core::PullState::Open => PullRequestState::Open,
            gunnar_core::PullState::Merged => PullRequestState::Merged,
            gunnar_core::PullState::Closed => PullRequestState::Closed,
        } as i32,
        author: record.author,
        created_at_unix_ms: record.created_ms,
        updated_at_unix_ms: record.updated_ms,
        source_oid: record.source_oid,
        merge_oid: record.merge_oid.unwrap_or_default(),
    }
}

fn visibility_out(v: Visibility) -> gunnar_proto::Visibility {
    match v {
        Visibility::Private => gunnar_proto::Visibility::Private,
        Visibility::Public => gunnar_proto::Visibility::Public,
    }
}

fn principal_kind_in(kind: gunnar_proto::PrincipalKind) -> PrincipalKind {
    match kind {
        gunnar_proto::PrincipalKind::Machine => PrincipalKind::Machine,
        gunnar_proto::PrincipalKind::Deploy => PrincipalKind::Deploy,
        gunnar_proto::PrincipalKind::Group => PrincipalKind::Group,
        gunnar_proto::PrincipalKind::User | gunnar_proto::PrincipalKind::Unspecified => {
            PrincipalKind::User
        }
    }
}

impl CoreControlPlane {
    /// **Whose account the namespace `name` is** (`Namespace.owner_kind`): the
    /// kind of the principal whose id it is, else UNSPECIFIED — so a reader
    /// that bills per namespace can leave out the estate's own machines by
    /// what they ARE, not by a list of their names. A store that cannot be
    /// read says UNSPECIFIED (the namespace is still listed).
    ///
    /// A GROUP whose every direct member is a machine is the estate's own too
    /// (the `twin` group, the twin's log readers — MEASURED on the mock
    /// 2026-09-29, listed as a tenant) and answers MACHINE; a group with anyone
    /// else in it, or with nobody, stays a group.
    fn owner_kind(&self, name: &str) -> i32 {
        let auth = self.stores.auth();
        match auth.principal(name) {
            Ok(Some(p)) if p.kind == PrincipalKind::Group => {
                let members = auth.members_of(name).unwrap_or_default();
                let machines = !members.is_empty() && members.iter().all(|m| matches!(auth.principal(m), Ok(Some(q)) if q.kind == PrincipalKind::Machine));
                if machines { gunnar_proto::PrincipalKind::Machine as i32 } else { principal_kind_out(p.kind) as i32 }
            }
            Ok(Some(p)) => principal_kind_out(p.kind) as i32,
            _ => gunnar_proto::PrincipalKind::Unspecified as i32,
        }
    }

    /// The catalog's namespace onto the wire — one mapping for create, list
    /// and the single lookup, so the account's settings and its employee count
    /// cannot be on one and missing from another. `employees` is derived (an
    /// account with any is an enterprise account; nothing is set).
    fn namespace_out(&self, namespace: gunnar_core::Namespace, employees: u32) -> Namespace {
        Namespace {
            owner_kind: self.owner_kind(&namespace.name),
            // A store that cannot be read says SELLER: a customer left out for one tick is given
            // its fact on the next, while a fact given to the operator's own namespace stays.
            owner_server_grant: self.stores.auth().holds_server_grant(&namespace.name).unwrap_or(true),
            name: namespace.name,
            description: String::new(),
            created_at_unix_ms: 0,
            public: namespace.public,
            events_public: namespace.events_public,
            employees,
        }
    }

    /// How many employees `account` has enrolled.
    fn employee_count(&self, account: &str) -> ControlResult<u32> {
        Ok(self
            .stores
            .auth()
            .employees_of(account)
            .map_err(internal)?
            .len() as u32)
    }
}

fn principal_kind_out(kind: PrincipalKind) -> gunnar_proto::PrincipalKind {
    match kind {
        PrincipalKind::User => gunnar_proto::PrincipalKind::User,
        PrincipalKind::Machine => gunnar_proto::PrincipalKind::Machine,
        PrincipalKind::Deploy => gunnar_proto::PrincipalKind::Deploy,
        PrincipalKind::Group => gunnar_proto::PrincipalKind::Group,
        // **Unreachable, and mapped honestly rather than plausibly.**
        // Every principal that reaches this function came out of the identity
        // table, and `AuthTable::add_principal` refuses the anonymous id, so
        // there is no anonymous row to list. `gunnar-proto` has no `ANONYMOUS`
        // value, and picking `USER` would put a fabricated human in an operator's
        // principal list; `UNSPECIFIED` is the value that means "gunnar cannot
        // name this", which is the truth. Adding the enum value is a
        // `gunnar-proto` change and is recorded there, not invented here.
        PrincipalKind::Anonymous => gunnar_proto::PrincipalKind::Unspecified,
    }
}

fn level_in(level: GrantLevel) -> ControlResult<Level> {
    match level {
        GrantLevel::Read => Ok(Level::Read),
        GrantLevel::Write => Ok(Level::Write),
        GrantLevel::Admin => Ok(Level::Admin),
        GrantLevel::Unspecified => Err(ControlError::InvalidArgument(
            "grant level unspecified".into(),
        )),
    }
}

fn level_out(level: Level) -> GrantLevel {
    match level {
        Level::Read => GrantLevel::Read,
        Level::Write => GrantLevel::Write,
        Level::Admin => GrantLevel::Admin,
    }
}

fn repo_out(repo: &gunnar_core::Repo) -> Repo {
    Repo {
        path: Some(RepoPath::new(&repo.namespace, &repo.name)),
        hash_kind: hash_kind(repo.hash_kind) as i32,
        default_branch: repo.default_branch.clone(),
        visibility: visibility_out(repo.visibility) as i32,
        created_at_unix_ms: repo.created,
        description: repo.description.clone(),
        encrypted: repo.encrypted,
    }
}

/// A stored web credential, as the wire carries it (no key material).
fn web_credential_out(row: &gunnar_core::WebCredential) -> ControlResult<gunnar_proto::WebCredential> {
    let credential_id = gunnar_grpc::webauthn::from_b64url(&row.id).ok_or_else(|| {
        ControlError::Internal(format!("a stored web credential has an id that is not base64url: {}", row.id))
    })?;
    Ok(gunnar_proto::WebCredential {
        credential_id,
        principal_id: row.principal_id.clone(),
        label: row.label.clone(),
        created_at_unix_ms: row.created,
        last_used_unix_ms: row.last_used,
        sign_count: row.sign_count,
    })
}

/// A level that may be absent, wire to core (`Unspecified` = none).
fn level_in_opt(level: GrantLevel) -> Option<Level> {
    level_in(level).ok()
}

/// A stored invite, as the wire carries it (never the hash).
fn invite_out(row: &gunnar_core::Invite) -> gunnar_proto::Invite {
    gunnar_proto::Invite {
        invite_id: row.id.clone(),
        principal_id: row.principal_id.clone(),
        created_by: row.created_by.clone(),
        created_at_unix_ms: row.created,
        expires_at_unix_ms: row.expires,
        note: row.note.clone(),
        server_level: row.server_level.map(level_out).unwrap_or(GrantLevel::Unspecified) as i32,
    }
}

fn principal_out(principal: &gunnar_core::Principal) -> Principal {
    Principal {
        id: principal.id.clone(),
        name: principal.name.clone(),
        kind: principal_kind_out(principal.kind) as i32,
        // The table's stamp. `0` for a row from before the field existed,
        // which is exactly what this reported for every row until then.
        created_at_unix_ms: principal.created,
    }
}

/// Clans on the identity table (`gunnar_grpc::clans::ClanPlane`, 2026-10-05).
mod clan_plane;

fn key_out(key: &gunnar_core::PublicKey) -> PublicKey {
    PublicKey {
        fingerprint: key.fingerprint_sha256.clone(),
        algo: key.algo.clone(),
        principal_id: key.principal_id.clone(),
        // The OpenSSH comment field is part of the stored line; gunnar-core
        // normalises the line and does not split it out.
        comment: String::new(),
        added_at_unix_ms: key.added,
        last_used_unix_ms: key.last_used,
        expires_at_unix_ms: key.expires,
    }
}

/// A grant, as `<namespace, repo>` strings.
///
/// A [`Scope::Server`] grant has neither, and is carried as two empty strings.
/// See the module docs: that is a proto gap, not an invention here.
fn grant_out(grant: &Grant) -> gunnar_proto::Grant {
    let (namespace, repo) = match &grant.scope {
        Scope::Server => (String::new(), String::new()),
        Scope::Namespace(name) => (name.clone(), String::new()),
        Scope::Repo(path) => (path.namespace().to_owned(), path.name().to_owned()),
    };
    gunnar_proto::Grant {
        principal_id: grant.principal.clone(),
        namespace,
        repo,
        level: level_out(grant.level) as i32,
        granted_at_unix_ms: 0,
    }
}

fn scope_in(namespace: &str, repo: &str) -> ControlResult<Scope> {
    match (namespace.is_empty(), repo.is_empty()) {
        (true, true) => Ok(Scope::Server),
        (false, true) => Ok(Scope::Namespace(namespace.to_owned())),
        (false, false) => RepoRef::new(namespace, repo)
            .map(Scope::Repo)
            .map_err(|err| ControlError::InvalidArgument(err.to_string())),
        (true, false) => Err(ControlError::InvalidArgument(
            "a repository-scoped grant must name a namespace (multi-tenancy has \
             no ungrouped repos)"
                .into(),
        )),
    }
}

/// The contract's object kind, in the proto's vocabulary.
///
/// [`ObjType`] also has `OfsDelta` and `RefDelta`, and neither can appear here:
/// [`GitServe::read`] and [`GitServe::header`] answer with the **resolved**
/// type by contract — that is the difference between them and
/// `GitOps::get`, which hands back the pack entry delta and all. A delta
/// reaching this function is a backend that broke its own promise, so it is
/// named as one rather than folded into `Unspecified`, which a client would
/// read as "an object of a kind this server is too old to name".
fn object_kind_out(kind: ObjType) -> ControlResult<gunnar_proto::ObjectKind> {
    match kind {
        ObjType::Blob => Ok(gunnar_proto::ObjectKind::Blob),
        ObjType::Tree => Ok(gunnar_proto::ObjectKind::Tree),
        ObjType::Commit => Ok(gunnar_proto::ObjectKind::Commit),
        ObjType::Tag => Ok(gunnar_proto::ObjectKind::Tag),
        other => Err(ControlError::Internal(format!(
            "the store answered a read with `{}`, which is a delta; GitServe::read is \
             documented to return the resolved type",
            other.as_str()
        ))),
    }
}

/// Follow an annotated tag down to the object it names.
///
/// A bounded loop, not a recursion: a tag chain is legal git and a cycle is
/// not, but a cycle is also cheap to write and would otherwise hang a control
/// plane that has no timeout.
///
/// What object id `segments` names under `tree` — a blob's id, a subtree's id,
/// or `None` when the path names nothing there.
///
/// The log's path filter rests on this: a commit changed a path exactly when
/// this answer differs from its first parent's. A path that continues THROUGH
/// a non-directory names nothing, the same rule the wire's tree walk applies.
fn oid_at_path(
    git: &dyn GitServe,
    hash_kind: gix_hash::Kind,
    tree: gix_hash::ObjectId,
    segments: &[&[u8]],
) -> ControlResult<Option<gix_hash::ObjectId>> {
    let mut current = tree;
    let last = segments.len().saturating_sub(1);
    for (index, segment) in segments.iter().enumerate() {
        let Some((kind, bytes)) = git.read(current.as_bytes()).map_err(store_error)? else {
            return Ok(None);
        };
        if kind != ObjType::Tree {
            return Ok(None);
        }
        let Some(entry) = object::tree_entry_named(&bytes, hash_kind, segment)
            .map_err(|err| ControlError::Internal(format!("decoding tree {current}: {err}")))?
        else {
            return Ok(None);
        };
        if index == last {
            return Ok(Some(entry.oid));
        }
        if entry.kind != object::EntryKind::Tree {
            return Ok(None);
        }
        current = entry.oid;
    }
    Ok(Some(current))
}

/// `hash_kind` is a parameter and never a default: it comes from
/// [`OpenRepo::hash_kind`], which comes from the catalog entry, and answering
/// `sha1` for a sha256 repository does not error — it decodes garbage.
/// Where a `Refs.Log` walk begins: one start (a ref name, an oid, or empty
/// for `HEAD`), or every branch and tag tip plus `HEAD`.
#[derive(Clone, Copy)]
enum LogStart<'a> {
    One(&'a str),
    AllRefs,
}

/// One `Refs.Log` start resolved to an oid: an oid as given, otherwise a ref
/// name (empty means `HEAD`) resolved against one snapshot.
fn resolve_log_start(
    git: &dyn GitServe,
    hash: gix_hash::Kind,
    path: &RepoPath,
    start: &str,
) -> ControlResult<gix_hash::ObjectId> {
    let start = if start.is_empty() {
        gunnar_store::HEAD
    } else {
        start
    };
    let head = match gix_hash::ObjectId::from_hex(start.as_bytes()) {
        Ok(id) => id,
        Err(_) => {
            gunnar_store::refname::validate(start)
                .map_err(|err| ControlError::InvalidArgument(err.to_string()))?;
            let snapshot = RefSnapshot::read(git).map_err(wire_error)?;
            // `HEAD` is not in the snapshot (the `GitServe` HEAD ruling) and it is this verb's
            // own default, so it is asked through the accessor pair. Both
            // branches resolve against the same snapshot.
            let resolved = if start == gunnar_store::HEAD {
                snapshot.head(git).map_err(wire_error)?
            } else {
                snapshot.resolve(start).map_err(wire_error)?
            };
            resolved.ok_or_else(|| ControlError::NotFound(format!("{start} in {path}")))?
        }
    };
    if head.kind() != hash {
        return Err(ControlError::InvalidArgument(format!(
            "{start} is a {} oid; this repository is {hash}",
            head.kind()
        )));
    }
    Ok(head)
}

impl CoreControlPlane {
    fn log_walk(
        &self,
        path: &RepoPath,
        start: LogStart<'_>,
        limit: u32,
        touching: &str,
    ) -> ControlResult<Vec<Commit>> {
        use std::collections::{BinaryHeap, HashMap, HashSet};

        let (_, store) = self.open(path)?;
        let git = store.serve();
        let hash = store.hash_kind();

        // The path filter, refused loudly rather than normalised: a filter
        // that silently ate `..` would answer for a different path than the
        // caller named.
        let filter: Option<Vec<&[u8]>> = if touching.is_empty() {
            None
        } else {
            let mut segments = Vec::new();
            for segment in touching.split('/').filter(|s| !s.is_empty()) {
                if segment == "." || segment == ".." {
                    return Err(ControlError::InvalidArgument(format!(
                        "the log path filter cannot contain {segment:?}"
                    )));
                }
                segments.push(segment.as_bytes());
            }
            (!segments.is_empty()).then_some(segments)
        };

        let heads: Vec<gix_hash::ObjectId> = match start {
            LogStart::One(start) => vec![resolve_log_start(git, hash, path, start)?],
            LogStart::AllRefs => {
                let snapshot = RefSnapshot::read(git).map_err(wire_error)?;
                let mut heads = Vec::new();
                if let Some(head) = snapshot.head(git).map_err(wire_error)? {
                    heads.push(head);
                }
                for row in snapshot
                    .rows()
                    .iter()
                    .filter(|r| r.name.starts_with("refs/heads/") || r.name.starts_with("refs/tags/"))
                {
                    if let Some(id) = snapshot.resolve_row(row).map_err(wire_error)? {
                        heads.push(id);
                    }
                }
                heads
            }
        };

        // Newest first, by EACH COMMIT'S OWN committer time — so tips of
        // several branches interleave the way `git log --date-order --all`
        // does, and a page cut by `limit` is the newest `limit` commits.
        // Each commit is decoded once, when it is queued, and kept until it
        // is popped.
        let limit = if limit == 0 { 50 } else { limit } as usize;
        let mut heap: BinaryHeap<(i64, gix_hash::ObjectId)> = BinaryHeap::new();
        let mut seen: HashSet<gix_hash::ObjectId> = HashSet::new();
        let mut queued: HashMap<gix_hash::ObjectId, object::Commit> = HashMap::new();
        let mut enqueue = |id: gix_hash::ObjectId,
                           heap: &mut BinaryHeap<(i64, gix_hash::ObjectId)>,
                           queued: &mut HashMap<gix_hash::ObjectId, object::Commit>|
         -> ControlResult<()> {
            if !seen.insert(id) {
                return Ok(());
            }
            // A shallow edge (not in this store) or a tip that peels to a
            // non-commit ends that line quietly, as it always did.
            let Some((kind, bytes)) = git.read(id.as_bytes()).map_err(store_error)? else {
                return Ok(());
            };
            if kind != ObjType::Commit {
                return Ok(());
            }
            let commit = object::commit(&bytes, hash)
                .map_err(|err| ControlError::Internal(format!("decoding commit {id}: {err}")))?;
            heap.push((commit.committer.seconds, id));
            queued.insert(id, commit);
            Ok(())
        };
        for head in heads {
            let head = peel(git, hash, head)?;
            enqueue(head, &mut heap, &mut queued)?;
        }
        let mut out = Vec::new();

        // What a FILTERED walk may visit before giving up. A path nothing ever
        // touched must not cost a full traversal of a quarter-million commits
        // per page; a page that comes back short because of this bound is a
        // short page, not the end of history — the proto says so.
        const MAX_FILTERED_SCAN: usize = 20_000;
        let mut scanned = 0usize;
        // commit → its tree, remembered so a parent decoded for the filter is
        // not decoded again when the walk reaches it — and vice versa.
        let mut tree_of: HashMap<gix_hash::ObjectId, gix_hash::ObjectId> = HashMap::new();

        while let Some((_, id)) = heap.pop() {
            if out.len() >= limit {
                break;
            }
            let Some(commit) = queued.remove(&id) else {
                continue;
            };
            let object::Commit {
                tree,
                parents,
                author,
                committer,
                message,
            } = commit;

            // ── the path filter: did THIS commit change what the path names? ─
            //
            // Judged against the FIRST parent, which is what `git log -- path`
            // shows for ordinary history: "what did landing this commit change
            // here". Identical ids mean identical content all the way down, so
            // the question costs two short descents, never a blob.
            if let Some(segments) = &filter {
                scanned += 1;
                if scanned > MAX_FILTERED_SCAN {
                    break;
                }
                tree_of.insert(id, tree);
                let current = oid_at_path(git, hash, tree, segments)?;
                let previous = match parents.first() {
                    None => None,
                    Some(parent) => {
                        let parent_tree = match tree_of.get(parent) {
                            Some(known) => Some(*known),
                            None => match git.read(parent.as_bytes()).map_err(store_error)? {
                                Some((ObjType::Commit, parent_bytes)) => {
                                    let decoded =
                                        object::commit(&parent_bytes, hash).map_err(|err| {
                                            ControlError::Internal(format!(
                                                "decoding commit {parent}: {err}"
                                            ))
                                        })?;
                                    tree_of.insert(*parent, decoded.tree);
                                    Some(decoded.tree)
                                }
                                // A shallow edge: the parent is not in this
                                // store. Comparing against nothing keeps the
                                // commit visible rather than silently dropped.
                                _ => None,
                            },
                        };
                        match parent_tree {
                            Some(parent_tree) => oid_at_path(git, hash, parent_tree, segments)?,
                            None => None,
                        }
                    }
                };
                if current == previous {
                    // Untouched here — keep walking, show nothing.
                    for parent in parents {
                        enqueue(parent, &mut heap, &mut queued)?;
                    }
                    continue;
                }
            }

            out.push(Commit {
                oid: id.to_string(),
                parent_oids: parents.iter().map(|p| p.to_string()).collect(),
                tree_oid: tree.to_string(),
                author: Some(signature_out(
                    &author.name,
                    &author.email,
                    author.seconds,
                    author.offset_seconds,
                )),
                committer: Some(signature_out(
                    &committer.name,
                    &committer.email,
                    committer.seconds,
                    committer.offset_seconds,
                )),
                message: String::from_utf8_lossy(&message).into_owned(),
            });
            for parent in parents {
                enqueue(parent, &mut heap, &mut queued)?;
            }
        }
        Ok(out)
    }
}

fn peel(
    git: &dyn GitServe,
    hash_kind: gix_hash::Kind,
    mut id: gix_hash::ObjectId,
) -> ControlResult<gix_hash::ObjectId> {
    for _ in 0..16 {
        let Some((kind, bytes)) = git.read(id.as_bytes()).map_err(store_error)? else {
            return Ok(id);
        };
        if kind != ObjType::Tag {
            return Ok(id);
        }
        id = object::tag_target(&bytes, hash_kind)
            .map_err(|err| ControlError::Internal(format!("decoding tag {id}: {err}")))?;
    }
    Err(ControlError::FailedPrecondition(format!(
        "the tag chain at {id} is longer than 16 links, or cyclic"
    )))
}

/// One [`RefRow`] as the proto's `RefTarget`, resolved against `snapshot` — the
/// **same** snapshot the row came out of, so an answer cannot name an oid for a
/// reference that had already moved. See [`gunnar_wire::refs`].
fn ref_target_out(
    git: &dyn GitServe,
    hash_kind: gix_hash::Kind,
    snapshot: &RefSnapshot,
    row: &RefRow,
    want_peeled: bool,
) -> ControlResult<RefTarget> {
    let (oid, symbolic) = match (&row.oid, &row.symref_target) {
        // A symbolic reference is resolved through the snapshot, whatever else
        // it carries: the row's own `oid` on a symref is the store's cache of
        // the same walk, and one authority is enough.
        (_, Some(inner)) => (snapshot.resolve(inner).map_err(wire_error)?, inner.clone()),
        (Some(raw), None) => (
            Some(gunnar_wire::refs::oid(raw).map_err(wire_error)?),
            String::new(),
        ),
        (None, None) => (None, String::new()),
    };
    let peeled = match (want_peeled, oid) {
        // `row.peeled` is not used even when the store filled it in: `peel`
        // follows the whole chain and a stored peel is one hop, so taking the
        // cheaper answer where one exists would make two references with the
        // same tag chain answer differently.
        (true, Some(id)) => {
            let peeled = peel(git, hash_kind, id)?;
            if peeled == id {
                String::new()
            } else {
                peeled.to_string()
            }
        }
        _ => String::new(),
    };
    Ok(RefTarget {
        ref_name: row.name.clone(),
        oid: oid.map(|id| id.to_string()).unwrap_or_default(),
        symbolic_target: symbolic,
        peeled_oid: peeled,
    })
}

/// A commit's author or committer line, as the gRPC message spells it.
///
/// **Bytes and numbers, not `gix_actor::SignatureRef`.** That was the parameter
/// type until 2026-08-10, and it was the whole reason `gix-actor` was a direct
/// dependency of this crate: one private four-line function, in the manifest
/// beside `gix-pack`, where the next reader had to work out whether the server
/// was *using* an actor parser or merely naming one. It was merely naming one.
/// `gix-object` still arrives here — it is what decodes the commit these fields
/// come out of — and it brings `gix-actor` with it; what is gone is gunnar
/// asserting a need it does not have.
///
/// `from_utf8_lossy` matches what `BStr`'s own `Display` did before: a name in
/// a commit header is whatever the committing client wrote, a gRPC string field
/// is UTF-8, and this is a *report* about history rather than anything looked
/// up by name.
fn signature_out(name: &[u8], email: &[u8], seconds: i64, tz_offset_seconds: i32) -> Signature {
    Signature {
        name: String::from_utf8_lossy(name).into_owned(),
        email: String::from_utf8_lossy(email).into_owned(),
        time_unix_seconds: seconds,
        tz_offset_minutes: tz_offset_seconds / 60,
    }
}

// ───────────────────────────────────────────────────────────────────────────

/// **First boot, delegated straight to `gunnar_core::AuthTable`.**
///
/// Nothing is decided here. `bootstrap_state` reads the one predicate the
/// writer also reads, and `enroll_first_identity` is a call into the one
/// compare-and-swap that can produce a `BootstrapRecord`. A second opinion in
/// this adapter — "the table looks empty, so the window is open" — would be a
/// status that could disagree with the gate, and the permissive one would win
/// silently (one implementation).
impl gunnar_grpc::FirstBoot for CoreControlPlane {
    fn bootstrap_state(&self) -> ControlResult<gunnar_grpc::BootstrapState> {
        let auth = self.stores.auth();
        // Every one of these is a `Result`. A read fault becomes UNAVAILABLE
        // and never a window that is reported as open or as shut on a guess.
        let window_open = auth.bootstrap_window_open().map_err(unavailable)?;
        let record = auth.bootstrap_record().map_err(unavailable)?;
        let (principals, keys, _grants) = auth.counts().map_err(unavailable)?;
        Ok(gunnar_grpc::BootstrapState {
            window_open,
            bootstrapped: record.is_some(),
            bootstrapped_at_unix_ms: record.as_ref().map(|r| r.at).unwrap_or_default(),
            bootstrapped_principal: record
                .as_ref()
                .map(|r| r.principal_id.clone())
                .unwrap_or_default(),
            bootstrapped_fingerprint: record
                .as_ref()
                .map(|r| r.fingerprint.clone())
                .unwrap_or_default(),
            principals: principals as u64,
            keys: keys as u64,
            // The boot window (`crate::readiness`). Answered here rather than
            // on `Admin.Health` because this is the one call a server nobody
            // holds a key for can answer, and a boot script is exactly that
            // caller.
            // TWO facts, and the second one is new. The boot window is this
            // process's start-up; the listener is a socket. A twin closes no
            // window and binds no reachable git port, so before the listener
            // was consulted this field answered `true` for a box whose :2222
            // was answering ECONNREFUSED — measured on 10.13.8.101, 2026-09-20.
            serving_git: crate::readiness::is_serving_git(self.git_listener),
            readiness: crate::readiness::detail_with(self.git_listener),
            build: gunnar_common::BUILD_REF.to_owned(),
            role: if self.twin_role || self.stores.is_twin() { "twin" } else { "primary" }.to_owned(),
            // A RECHARGED main (the installer's re-admit) or a HELD one (the boot
            // check, R-7b) says what it awaits (the restore lane reads it).
            recharge_from: awaited_twin(&self.stores),
            restoring: crate::twin::is_restoring(self.stores.root()),
            log_head_seq: self.stores.txlog().head_seq(),
            // What a restoring box holds of its next entry: where the next stream resumes it.
            restore_partial: if crate::twin::is_restoring(self.stores.root()) { crate::twin::intake::partial(self.stores.root()) } else { None },
            // restore-after-snapshot: this box stages a twin's base across streams, and says how
            // much of one it holds while it is restoring.
            restore_snapshot_resumable: true,
            restore_snapshot: if crate::twin::is_restoring(self.stores.root()) {
                crate::twin::snapshot::held_snapshot(self.stores.root()).map(|h| (h.id, h.items, h.bytes, h.whole))
            } else {
                None
            },
        })
    }

    fn enroll_first_identity(
        &self,
        name: &str,
        openssh_public_key: &str,
    ) -> ControlResult<gunnar_grpc::Enrolled> {
        // R-7b: a box the boot check found with its data lost (a twin can give it
        // back) takes no first admin while it is held.
        #[cfg(feature = "replication")]
        if let Some(twin) = crate::repair::held(&self.stores) {
            return Err(ControlError::FailedPrecondition(crate::repair::held_refusal(&twin)));
        }
        let enrolled = self
            .stores
            .auth()
            .enroll_first_user(name, openssh_public_key)
            .map_err(enrolment_error)?;
        // The account namespace, after the door is shut. Deliberately NOT
        // inside the identity CAS: it lives in the catalog, a different
        // document, and one write cannot span both. The ordering is what makes
        // that safe — the security boundary (the record) has already landed, so
        // the worst a failure here can do is leave a gunnar-admin whose account
        // namespace has to be created by hand, never a second open window.
        //
        // Idempotent: `AlreadyExists` on a namespace this principal already
        // intrinsically owns is not a failure of enrolment.
        if let Err(err) = self
            .stores
            .catalog()
            .create_namespace(&enrolled.record.account)
        {
            tracing::warn!(
                account = %enrolled.record.account,
                %err,
                "the first user was enrolled and the enrolment window is closed, but its account \
                 namespace could not be created. The user is admin of it by rule and can create \
                 it themselves with Repos.CreateNamespace."
            );
        }
        // ── the bootstrap admin's client certificate ────────────────────────
        //
        // Minted AFTER the CAS, so the security boundary is already shut when
        // this runs and a failure here cannot reopen it — the same ordering
        // argument as the namespace above. Server-generated key, deliberately:
        // there is no authenticated channel yet to carry a CSR, and this is the
        // one exchange in the server's life where handing a private key over
        // the wire is the honest trade. The server retains no copy of the key.
        let (client_cert_pem, client_key_pem, issuer_cert_pem) = match self.stores.pki() {
            Ok(pki) => match pki.issuer() {
                Ok(Some(issuer)) => {
                    match pki.issue_with_server_key(
                        &enrolled.principal.id,
                        gunnar_core::DEFAULT_LEAF_DAYS,
                    ) {
                        Ok(issued) => {
                            if let Err(err) = self.stores.auth().register_certificate(
                                &enrolled.principal.id,
                                &issued.cert_der,
                                None,
                            ) {
                                tracing::warn!(
                                    principal = %enrolled.principal.id,
                                    %err,
                                    "the bootstrap certificate was minted but could not be \
                                     registered; it is returned anyway and gunnar-admin can \
                                     register it with `gunnar key add`"
                                );
                            }
                            (
                                issued.cert_pem,
                                issued.key_pem.unwrap_or_default(),
                                issuer.cert_pem,
                            )
                        }
                        Err(err) => {
                            tracing::warn!(
                                principal = %enrolled.principal.id,
                                %err,
                                "no bootstrap certificate: the issuer refused to mint"
                            );
                            (String::new(), String::new(), String::new())
                        }
                    }
                }
                Ok(None) => (String::new(), String::new(), String::new()),
                Err(err) => {
                    tracing::warn!(%err, "no bootstrap certificate: the PKI document could not \
                                          be read");
                    (String::new(), String::new(), String::new())
                }
            },
            Err(_) => (String::new(), String::new(), String::new()),
        };
        Ok(gunnar_grpc::Enrolled {
            principal: principal_out(&enrolled.principal),
            key: key_out(&enrolled.key),
            account: enrolled.record.account,
            bootstrapped_at_unix_ms: enrolled.record.at,
            client_cert_pem,
            client_key_pem,
            issuer_cert_pem,
        })
    }
}

/// A read fault on the identity table. **Never a denial and never a state.**
fn unavailable(err: gunnar_core::Error) -> ControlError {
    ControlError::Unavailable(format!("the identity table could not be read: {err}"))
}

/// The refusals of the enrolment window, mapped so a caller can tell them apart
/// from a malformed request.
/// **The twin this box awaits** (`Bootstrap.Status.recharge_from`): the installer's
/// re-admit ([`crate::pairing::recharge_awaited`]), else the boot check's hold
/// ([`crate::repair::held`]); empty on every other box.
fn awaited_twin(stores: &ServerStores) -> String {
    #[cfg(feature = "wg-client")]
    if let Some(twin) = crate::pairing::recharge_awaited(stores) {
        return twin;
    }
    #[cfg(feature = "replication")]
    if let Some(twin) = crate::repair::held(stores) {
        return twin;
    }
    let _ = stores;
    String::new()
}

fn enrolment_error(err: gunnar_core::Error) -> ControlError {
    match err {
        // The door is shut. FAILED_PRECONDITION, because the request was well
        // formed and the *server's state* is what refuses it.
        e @ (gunnar_core::Error::AlreadyBootstrapped { .. }
        | gunnar_core::Error::AlreadyProvisioned { .. }) => {
            ControlError::FailedPrecondition(e.to_string())
        }
        // A bad name or a key that is not an authorized_keys line.
        e @ (gunnar_core::Error::InvalidPath { .. }
        | gunnar_core::Error::ReservedPrincipalId(_)
        | gunnar_core::Error::Key(_)) => ControlError::InvalidArgument(e.to_string()),
        // Storage. Not "the door is shut", which is what a caller would read a
        // FAILED_PRECONDITION as, and not OK, which would be the disaster.
        other => ControlError::Unavailable(other.to_string()),
    }
}

impl CoreControlPlane {
    /// ★ **The estate's operator, made on its first claim** — the one writer
    /// behind `Accounts.ClaimOperator` and behind the primary's own claim when
    /// the installer feeds `operator_name` ([`crate::fed_principals::install`]).
    ///
    /// `fed` is the installer's name for the operator and wins; `asked` is the
    /// caller's, used only when nothing was fed (`gunnar_grpc::seam::operator_name`).
    ///
    /// * A PERSON already under that id or name is the answer, unchanged but
    ///   for two upserts that make it what an operator is: its account
    ///   namespace exists, and it is gunnar-admin.
    /// * Anything else under it — a machine, a group — is refused by name: an
    ///   estate's parts are never its operator.
    /// * Otherwise the principal is created, KEYLESS (the console's credential
    ///   for the person is its first key, which owes nobody an attestation; the
    ///   person's own SSH keys come after and are vouched for by it), with its
    ///   account namespace — and **a namespace of that name that already exists
    ///   with no owner is ADOPTED** rather than refused. MEASURED on test2
    ///   2026-10-04: a first push with the installer's admin key
    ///   (`rickard/t2-scratch`) conjured `rickard`, and `AddPrincipal` refused
    ///   the operator's own account from then on — the first admin's passkey
    ///   bound to nothing. Adoption is safe exactly here: the namespace has no
    ///   principal of its id (this call is creating it), only a server Admin can
    ///   ask, and that Admin could already delete the namespace or grant it.
    pub fn claim_operator_named(
        &self,
        fed: Option<&str>,
        asked: &str,
    ) -> ControlResult<gunnar_grpc::OperatorClaim> {
        let (name, named_by) = gunnar_grpc::seam::operator_name(fed, asked)?;
        let auth = self.stores.auth();
        let held = match auth.principal(name).map_err(internal)? {
            Some(p) => Some(p),
            None => auth.principal_by_name(name).map_err(internal)?,
        };
        if let Some(p) = held {
            if p.kind != PrincipalKind::User {
                return Err(ControlError::FailedPrecondition(format!(
                    "the operator's name {name:?} is held by principal {:?}, which is not a person \
                     ({:?}); an estate's machines are never its operator",
                    p.id, p.kind
                )));
            }
            let adopted_namespace = false;
            if self.stores.catalog().namespace(&p.id).map_err(internal)?.is_none() {
                self.stores.catalog().create_namespace(&p.id).map_err(internal)?;
            }
            self.grant(&p.id, "", "", GrantLevel::Admin)?;
            return Ok(gunnar_grpc::OperatorClaim {
                principal: principal_out(&p),
                created: false,
                adopted_namespace,
                named_by,
            });
        }
        let principal =
            gunnar_core::Principal::new(name, name, PrincipalKind::User).map_err(internal)?;
        let created = auth.add_principal(principal).map_err(internal)?;
        let adopted_namespace = match self.stores.catalog().create_namespace(&created.id) {
            Ok(_) => false,
            Err(gunnar_core::Error::NamespaceExists(_)) => true,
            Err(err) => {
                let _ = auth.remove_principal(&created.id);
                return Err(internal(err));
            }
        };
        if let Err(err) = self.grant(&created.id, "", "", GrantLevel::Admin) {
            // Not left half-made: an operator that is not the estate's admin is
            // not the one that was asked for, and the next claim makes it whole.
            let _ = auth.remove_principal(&created.id);
            return Err(err);
        }
        self.stores.mirror_identity();
        tracing::warn!(
            target: "gunnar::audit",
            event = "operator.claimed",
            operator = %created.id,
            adopted_namespace,
            named_by,
            "the estate's operator was created: a person, keyless, gunnar-admin, with its account \
             namespace{}",
            if adopted_namespace {
                " — the namespace already existed with no owner (a first push conjured it) and is \
                 now the operator's account"
            } else {
                ""
            }
        );
        Ok(gunnar_grpc::OperatorClaim {
            principal: principal_out(&created),
            created: true,
            adopted_namespace,
            named_by,
        })
    }
}

/// The owner's enterprise list on the real stores (`gunnar_grpc::enterprise::EnterprisePlane`).
mod enterprise_plane;

impl ControlPlane for CoreControlPlane {
    fn enterprise(&self) -> Option<&dyn gunnar_grpc::enterprise::EnterprisePlane> {
        Some(self)
    }

    // ── namespaces ─────────────────────────────────────────────────────────

    fn create_namespace(&self, name: &str, _description: &str) -> ControlResult<Namespace> {
        // An EMPLOYEE's id is never a namespace: a namespace named after a
        // principal makes that principal its admin (`owns_account`), and an
        // employee is admin of nothing (`AuthTable::enroll_employee`).
        if self.stores.auth().employer_of(name).map_err(internal)?.is_some() {
            return Err(ControlError::AlreadyExists(format!(
                "{name} is an employee's id, and an employee holds no account of its own"
            )));
        }
        let namespace = self
            .stores
            .catalog()
            .create_namespace(name)
            .map_err(internal)?;
        Ok(self.namespace_out(namespace, 0))
    }

    fn list_namespaces(&self) -> ControlResult<Vec<Namespace>> {
        let mut employees: std::collections::BTreeMap<String, u32> = Default::default();
        for principal in self.stores.auth().principals().map_err(internal)? {
            if let Some(account) = self.stores.auth().employer_of(&principal.id).map_err(internal)? {
                *employees.entry(account).or_default() += 1;
            }
        }
        Ok(self
            .stores
            .catalog()
            .namespaces()
            .map_err(internal)?
            .into_iter()
            .map(|ns| {
                let count = employees.get(&ns.name).copied().unwrap_or(0);
                self.namespace_out(ns, count)
            })
            .collect())
    }

    /// One catalog probe, not the listing the trait's default walks: this is
    /// asked by the account settings and the outsider's view of a namespace.
    fn namespace(&self, name: &str) -> ControlResult<Option<Namespace>> {
        let Some(ns) = self.stores.catalog().namespace(name).map_err(internal)? else {
            return Ok(None);
        };
        let count = self.employee_count(name)?;
        Ok(Some(self.namespace_out(ns, count)))
    }

    fn namespace_for_outsider(&self, principal_id: &str, name: &str) -> ControlResult<Option<Namespace>> {
        // The gate, both directions, before the setting — the same walk
        // `AuthTable::may` makes (an ancestor's gate closes a nested account).
        let auth = self.stores.auth();
        if auth.gate_covering(principal_id).map_err(internal)?.is_some()
            || auth.gate_covering(name).map_err(internal)?.is_some()
        {
            return Ok(None);
        }
        self.namespace(name)
    }

    fn set_namespace_settings(
        &self,
        name: &str,
        public: Option<bool>,
        events_public: Option<bool>,
    ) -> ControlResult<Namespace> {
        let catalog = self.stores.catalog();
        let mut ns = catalog
            .namespace(name)
            .map_err(internal)?
            .ok_or_else(|| ControlError::NotFound(format!("namespace {name}")))?;
        if let Some(public) = public {
            ns = catalog.set_namespace_public(name, public).map_err(internal)?;
        }
        if let Some(events_public) = events_public {
            ns = catalog
                .set_namespace_events_public(name, events_public)
                .map_err(internal)?;
        }
        let count = self.employee_count(name)?;
        Ok(self.namespace_out(ns, count))
    }

    fn delete_namespace(&self, name: &str, delete_repos: bool) -> ControlResult<u32> {
        // A CLAN's namespace goes with the clan (`Clans.Dissolve`), never on
        // its own: a clan left without its namespace would be a name nobody
        // could make anything in, and the namespace's repositories are the
        // clan's to dissolve, not one admin grant's to delete.
        if self.stores.auth().is_clan(name).map_err(internal)? {
            return Err(ControlError::FailedPrecondition(format!(
                "namespace {name} is clan {name}'s: it goes when the clan's admin dissolves the clan"
            )));
        }
        let gone = self
            .stores
            .catalog()
            .delete_namespace(name, delete_repos)
            .map_err(internal)?;
        // **The flow half of deleting a tenant.** The activity ledger keeps
        // four hundred days per namespace INCLUDING which key fingerprints
        // pushed, and a tenant that is gone must not leave a record of who
        // worked on it. Deliberately after the catalog delete: if that refused
        // — a non-empty namespace without `delete_repos` — nothing has been
        // deleted and the series must stay.
        //
        // A failure here is logged and not returned: the namespace IS gone, and
        // reporting the delete as failed would send an operator to re-run it
        // against a name that no longer exists.
        if let Err(err) = self.stores.flow().forget(name) {
            tracing::warn!(
                target: "gunnar::store",
                event = "flow.forget_failed",
                namespace = %name,
                %err,
                "the namespace was deleted but its activity series could not be removed"
            );
        }
        Ok(gone.len() as u32)
    }

    // ── repositories ───────────────────────────────────────────────────────

    fn create_repo(&self, spec: ProtoNewRepo) -> ControlResult<Repo> {
        let path = Self::repo_ref(&spec.path)?;
        // **The disk, before the row.** A repository created on a full disk is
        // a catalog row whose store cannot be materialised, which is the
        // "listed but git says it does not exist" shape `ServerStores::create_repo`
        // exists to prevent — refused here, by the gate the front doors share,
        // with the line a refused push prints.
        if let Some(line) = self.headroom.as_ref().and_then(|gate| gate.refusal()) {
            return Err(ControlError::ResourceExhausted(line));
        }
        let mut new = gunnar_core::NewRepo::new(path).visibility(visibility_in(spec.visibility)?);
        if spec.hash_kind != gunnar_proto::HashKind::Unspecified {
            new = new.hash_kind(match spec.hash_kind {
                gunnar_proto::HashKind::Sha1 => HashKind::Sha1,
                _ => HashKind::Sha256,
            });
        }
        if !spec.default_branch.is_empty() {
            new = new.default_branch(spec.default_branch.clone());
        }
        // The catalog entry and the on-disk repository are created together
        // and transactionally — `ServerStores::create_repo` looks at the disk
        // first (a store already standing at the name is refused BY NAME
        // unless `adopt`), writes the row, makes the store, and rolls the row
        // back if the store fails. Creating one without the other is the
        // shape that produces "it is listed but git says it does not exist";
        // adopting a stranger's directory is the shape that resurrected a
        // deleted repository on 2026-08-30.
        let repo = self
            .stores
            .create_repo(new, spec.adopt)
            .map_err(|err| create_error(&err, &spec.path))?;
        Ok(repo_out(&repo))
    }

    fn write_first_commit(&self, path: &RepoPath, readme: &str) -> ControlResult<String> {
        let (repo, store) = self.open(path)?;
        let kind = match repo.hash_kind {
            HashKind::Sha1 => gix_hash::Kind::Sha1,
            _ => gix_hash::Kind::Sha256,
        };
        let when = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
        let (pack, commit) = crate::first_commit::first_commit_pack(kind, "README.md", readme.as_bytes(), "Welcome", when)
            .map_err(ControlError::InvalidArgument)?;
        store
            .serve()
            .put(&pack, &[gunnar_store::git_storage_trait::RefUpdate::set(repo.default_branch.clone(), commit.clone())])
            .map_err(|err| ControlError::Internal(format!("writing the first commit of {path}: {err:#}")))?;
        Ok(commit)
    }

    /// The front doors' plan chain (`ServerStores::plan_gates`), asked as a
    /// push-to-create asks it: the verdict on a write (a suspended or retained
    /// plan: `FailedPrecondition`), then the cap (`ResourceExhausted`). A gate
    /// that does not bind machines is not asked for one.
    fn create_room(&self, namespace: &str, machine: bool) -> ControlResult<()> {
        use gunnar_ssh::{PlanAction, PlanVerdict};
        for gate in self.stores.plan_gates().iter().filter(|gate| !machine || gate.applies_to_machine()) {
            if let PlanVerdict::Refuse(line) = gate.verdict(namespace, PlanAction::Write) {
                return Err(ControlError::FailedPrecondition(line));
            }
            if let PlanVerdict::Refuse(line) = gate.pack_quota(namespace) {
                return Err(ControlError::ResourceExhausted(line));
            }
        }
        Ok(())
    }

    fn get_repo(&self, path: &RepoPath) -> ControlResult<Repo> {
        let repo_ref = Self::repo_ref(path)?;
        self.stores
            .catalog()
            .get(&repo_ref)
            .map_err(internal)?
            .as_ref()
            .map(repo_out)
            .ok_or_else(|| ControlError::NotFound(format!("repository {path}")))
    }

    fn list_repos(&self, namespace: Option<&str>) -> ControlResult<Vec<Repo>> {
        Ok(self
            .stores
            .catalog()
            .list(namespace)
            .map_err(internal)?
            .iter()
            .map(repo_out)
            .collect())
    }

    /// **Delete: a dated tombstone by default, a reclaim when asked.**
    ///
    /// Two facts had to be held at once here, and they pull in opposite
    /// directions:
    ///
    /// * **The reclaim**: `repo delete` must reclaim the disk. Before it, the
    ///   catalog row went and the objects stayed — 25 GB of a kernel push left
    ///   on the appliance with its indexer still running, invisible because
    ///   nothing listed it.
    /// * **Measured**: the bytes are gone in ~2 seconds (181 GiB to 33 MiB
    ///   measured) and a mirror does not help, because the delete replicates.
    ///   The failure a paying customer is most likely to cause is deleting
    ///   their own repository.
    ///
    /// A tombstone answers both, and only because it is **dated and listed**:
    /// the bytes are held on purpose with a deadline written at the instant of
    /// the delete, [`ServerStores::sweep_expired_tombstones`] reclaims them
    /// when it passes, and `Repos.ListDeleted` / `Admin.StorageInfo` report
    /// them so they are never the invisible 25 GB again. **They still count
    /// against the account** — see [`Self::storage_info`].
    fn delete_repo(
        &self,
        path: &RepoPath,
        options: gunnar_grpc::seam::DeleteOptions,
    ) -> ControlResult<gunnar_grpc::seam::DeleteOutcome> {
        let repo_ref = Self::repo_ref(path)?;
        // The row is read BEFORE it is removed: the tombstone records what the
        // repository was, and an undelete that guessed the hash kind would
        // reopen the resurrection the reclaim rules closed from the other side.
        let was = self.stores.catalog().get(&repo_ref).map_err(internal)?;
        // **An ORPHAN is a delete to finish, not a not-found** (2026-08-30). A
        // store on disk with no row and no tombstone is what an old
        // catalog-only delete left, and on the appliance 2026-08-30 it was ~25-39
        // GB at `alice/linux` that `delete` answered with `NoSuchRepo` after
        // the access check had already refused everybody. `--purge` is
        // honoured — the bytes are what the operator asked for and the row is
        // already gone — and a SOFT delete is refused by name, because a
        // tombstone with no row promises an undelete the server cannot honour.
        let orphan = was.is_none() && self.stores.is_orphan(&repo_ref).unwrap_or(false);
        if orphan && !options.purge {
            return Err(ControlError::FailedPrecondition(
                crate::stores::ServerStores::orphan_soft_delete_refusal(&repo_ref),
            ));
        }
        // A name that is not in the catalog but is TOMBSTONED (a previous
        // delete could not reclaim its store) is a delete to retry, not a
        // not-found: the row is already gone, the reclaim is what is owed.
        match self.stores.catalog().delete(&repo_ref) {
            Ok(_) => {}
            Err(gunnar_core::Error::NoSuchRepo(_))
                if orphan || self.stores.is_tombstoned(&repo_ref).unwrap_or(false) => {}
            Err(err) => return Err(internal(err)),
        }
        if options.purge {
            let (before, after) = self.stores.purge_repo(&repo_ref).map_err(|err| {
                ControlError::Internal(format!("removing the repository's directory: {err:#}"))
            })?;
            return Ok(gunnar_grpc::seam::DeleteOutcome::Purged {
                bytes_reclaimed: before.saturating_sub(after),
            });
        }
        let retention = std::time::Duration::from_secs(
            u64::from(
                options
                    .retention_days
                    .unwrap_or(crate::stores::DEFAULT_DELETE_RETENTION_DAYS),
            ) * 86_400,
        );
        let record = self
            .stores
            .soft_delete(&repo_ref, was.as_ref(), &options.principal_id, retention)
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))?;
        let bytes_kept = self
            .stores
            .repo_dir(&repo_ref)
            .map(|dir| crate::stores::dir_bytes(&dir))
            .unwrap_or(0);
        Ok(gunnar_grpc::seam::DeleteOutcome::Tombstoned {
            purge_after_unix_ms: record.purge_after_unix_ms.unwrap_or_default(),
            bytes_kept,
        })
    }

    /// **Undelete: the row back first, the tombstone off second.**
    ///
    /// That order is not tidiness. A crash between the two leaves a repository
    /// that is catalogued *and* still fenced off, which an operator can fix
    /// with a second `undelete`; the other order leaves a name with no
    /// tombstone and no row, which the next `repo create` would adopt — and
    /// adopting a store a create did not make is exactly the 2026-08-30
    /// resurrection.
    fn undelete_repo(&self, path: &RepoPath) -> ControlResult<Repo> {
        let repo_ref = Self::repo_ref(path)?;
        if self
            .stores
            .catalog()
            .get(&repo_ref)
            .map_err(internal)?
            .is_some()
        {
            return Err(ControlError::AlreadyExists(format!(
                "{path} is in the catalog already; it is not deleted"
            )));
        }
        let spec = self
            .stores
            .undelete_spec(&repo_ref)
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))?;
        // `adopt`: the store on disk is the one this repository always had.
        // This is the second of the two cases where adopting is right rather
        // than a resurrection (the first is `archive-in`), and it is right
        // because the tombstone says so and carries the hash kind the adopt
        // path checks the store's marker against.
        let repo = self
            .stores
            .create_repo(spec, true)
            .map_err(|err| ControlError::Internal(format!("restoring {path}: {err:#}")))?;
        self.stores
            .clear_tombstone(&repo_ref)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        Ok(repo_out(&repo))
    }

    fn purge_repo(&self, path: &RepoPath) -> ControlResult<u64> {
        let repo_ref = Self::repo_ref(path)?;
        if self
            .stores
            .catalog()
            .get(&repo_ref)
            .map_err(internal)?
            .is_some()
        {
            return Err(ControlError::FailedPrecondition(format!(
                "{path} is a LIVE repository, not a deleted one. `repo delete {path} --purge` \
                 deletes and reclaims it in one step; purge alone only ends a retention window."
            )));
        }
        let tombstone = self
            .stores
            .tombstone_of(&repo_ref)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        if tombstone.is_none() {
            return Err(ControlError::NotFound(format!(
                "{path} is neither catalogued nor tombstoned; there is nothing to purge"
            )));
        }
        let (before, after) = self
            .stores
            .purge_repo(&repo_ref)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        Ok(before.saturating_sub(after))
    }

    /// **`Repos.Gc` — the console's door onto the maintenance the CLI has
    /// always had.**
    ///
    /// The whole body is a resolve and a call: the maintenance itself is
    /// [`crate::admin::gc_one`], the same function `gunnar gc` runs, so there
    /// is one writer and not a second implementation to drift (one implementation).
    ///
    /// Unlike [`Self::purge_repo`] this one demands the repository be **live**.
    /// A tombstoned store is on its way out and sealing it would spend the I/O
    /// of a compaction on bytes a sweep is about to unlink; that is `Purge`'s
    /// job, and saying so by name is better than maintaining a corpse.
    fn gc_repo(&self, path: &RepoPath) -> ControlResult<gunnar_grpc::seam::GcJob> {
        let repo_ref = Self::repo_ref(path)?;
        // **The existence check is here and the resolve is in the runner**, and
        // that is not a duplicate. This one refuses a name that was never a
        // repository *now*, so a typo comes back as NOT_FOUND on the request
        // that made it rather than as a FAILED job somebody has to go and read;
        // the runner's is what happens when a repository that WAS live is gone
        // by the time its turn comes, minutes later.
        if self
            .stores
            .catalog()
            .get(&repo_ref)
            .map_err(internal)?
            .is_none()
        {
            return Err(ControlError::NotFound(format!(
                "{path} is not a live repository; nothing to gc"
            )));
        }
        Ok(gc_job_out(path, self.gc.enqueue(&repo_ref.to_string())))
    }

    fn gc_status(&self, path: &RepoPath) -> ControlResult<Option<gunnar_grpc::seam::GcJob>> {
        let repo_ref = Self::repo_ref(path)?;
        Ok(self
            .gc
            .status(&repo_ref.to_string())
            .map(|job| gc_job_out(path, job)))
    }

    // ── accounts: the gate, and the per-user hard purge ────────────────────

    fn gate_account(
        &self,
        account: &str,
        actor: &str,
        note: &str,
    ) -> ControlResult<(gunnar_grpc::seam::AccountGate, bool)> {
        // Read before write, so `was_already_gated` reports what was there
        // rather than what this call put there. Not atomic with the write, and
        // it does not need to be: the field is a courtesy to a console, and the
        // worst a lost race costs is a console saying "you locked this" about a
        // lockout that arrived a millisecond earlier. The *lockout* is atomic,
        // because `AuthTable::gate` is one compare-and-swap.
        let before = self
            .stores
            .auth()
            .gate_covering(account)
            .map_err(internal)?
            .is_some();
        let gate = self
            .stores
            .auth()
            .gate(gunnar_core::AccountGate::administrative(account, actor, note))
            .map_err(gate_error)?;
        tracing::warn!(
            target: "gunnar::audit",
            event = "account.gated",
            account = %account,
            actor = %actor,
            note = %note,
            already = before,
            "an account was locked out: every level, both doors, until it is ungated"
        );
        Ok((gate_out(gate), before))
    }

    fn ungate_account(
        &self,
        account: &str,
    ) -> ControlResult<Option<gunnar_grpc::seam::AccountGate>> {
        let lifted = self
            .stores
            .auth()
            .lift_gate(account)
            .map_err(internal)?
            .map(gate_out);
        if let Some(gate) = &lifted {
            tracing::warn!(
                target: "gunnar::audit",
                event = "account.ungated",
                account = %account,
                held_by = %gate.holder,
                "an account lockout was lifted"
            );
        }
        Ok(lifted)
    }

    fn account_gates(&self) -> ControlResult<Vec<gunnar_grpc::seam::AccountGate>> {
        Ok(self
            .stores
            .auth()
            .gates()
            .map_err(internal)?
            .into_iter()
            .map(gate_out)
            .collect())
    }

    /// **Gate first, enqueue second — and read the gate BACK.**
    ///
    /// The order is the whole guarantee: by the time this returns the account
    /// is shut, so there is no window in which a purge has been accepted and
    /// the user can still push into the account it is about to walk.
    ///
    /// The gate is then read back out of the table rather than the one just
    /// written being returned, and that is not belt-and-braces — it is the only
    /// correct answer in two cases this call cannot distinguish up front:
    ///
    /// * the account was **already** under an administrative gate. The lease is
    ///   not written over it (`gate_for_purge` refuses to downgrade), so the
    ///   gate in force is somebody else's and the job will not lift it.
    /// * the account already had a purge **queued or running**. The queue
    ///   returns that job instead of this one, so the lease that will be
    ///   released is the *other* job's, and returning this call's freshly
    ///   minted id would name a lockout nothing is going to lift.
    fn purge_account(
        &self,
        account: &str,
        options: gunnar_grpc::seam::PurgeAccountOptions,
    ) -> ControlResult<(gunnar_grpc::seam::PurgeJob, gunnar_grpc::seam::AccountGate)> {
        let account = account.trim();
        if account.is_empty() {
            return Err(ControlError::InvalidArgument(
                "an account purge needs an account name".into(),
            ));
        }
        // **A machine's account is never purged** (owner ruling g-nonpay 2026-09-29:
        // "machine principals ... are never touched"). Only a person's account holds a
        // customer's data; a machine, a deploy key or a group is the estate itself —
        // the twin, the billing principal, a CI bot — and emptying it is never the
        // answer to a question about money. Refused before the lockout: nothing is
        // locked and nothing is queued.
        if let Some(p) = self.stores.auth().principal(account).map_err(internal)? {
            if p.kind != gunnar_core::PrincipalKind::User {
                return Err(ControlError::FailedPrecondition(format!(
                    "{account} is a machine principal ({:?}), not a person: a machine's account is never \
                     purged. Remove the principal itself if it is really to go.",
                    p.kind
                )));
            }
        }
        let job_id = self.purge.next_job_id();
        // **The lockout, before anything else.** A failure here is a refusal
        // and nothing is enqueued: a purge that could not lock the account is
        // a purge that would race every reader in it, and running it anyway
        // would be worse than not running it.
        self.gate_for_purge(account, &job_id, &options)?;

        let order = crate::purge_queue::PurgeOrder::new(account, &job_id, &options.reason)
            .by(&options.principal_id)
            .removing_principal(options.remove_principal)
            .expecting_empty(options.expect_empty);
        let job = self.purge.enqueue(order);

        let gate = self
            .stores
            .auth()
            .gate_covering(account)
            .map_err(internal)?
            .map(gate_out)
            // The account is gated — this call just gated it — so an absence
            // here means the row went between the write and the read, which is
            // an operator ungating an account mid-request. Reported as the
            // fact it is rather than as a gate that is not there.
            .unwrap_or_else(|| gunnar_grpc::seam::AccountGate {
                account: account.to_owned(),
                reason: gunnar_grpc::seam::GateReason::Purge,
                holder: job_id.clone(),
                actor: options.principal_id.clone(),
                note: "the lockout was lifted between being taken and being read back".into(),
                at_unix_ms: gunnar_core::now_ms(),
                expires_unix_ms: 0,
            });
        Ok((purge_job_out(job), gate))
    }

    fn purge_account_status(
        &self,
        account: &str,
    ) -> ControlResult<(
        Option<gunnar_grpc::seam::PurgeJob>,
        Option<gunnar_grpc::seam::AccountGate>,
    )> {
        let job = self.purge.status(account).map(purge_job_out);
        let gate = self
            .stores
            .auth()
            .gate_covering(account)
            .map_err(internal)?
            .map(gate_out);
        Ok((job, gate))
    }

    fn list_deleted(
        &self,
        namespace: Option<&str>,
    ) -> ControlResult<Vec<gunnar_grpc::seam::DeletedRepoRow>> {
        Ok(self
            .stores
            .tombstones()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?
            .into_iter()
            .filter(|row| namespace.is_none_or(|want| row.path.namespace() == want))
            .map(|row| gunnar_grpc::seam::DeletedRepoRow {
                path: RepoPath {
                    namespace: row.path.namespace().to_owned(),
                    repo: row.path.name().to_owned(),
                },
                deleted_at_unix_ms: row.tombstone.deleted_at_unix_ms,
                purge_after_unix_ms: row.tombstone.purge_after_unix_ms.unwrap_or_default(),
                principal_id: row.tombstone.principal_id,
                bytes: row.bytes,
            })
            .collect())
    }

    /// **The store directories with no catalog row and no tombstone.**
    ///
    /// It walks the disk rather than asking the catalog — the same reason
    /// [`Self::list_deleted`] does, one step further: a tombstone at least
    /// exists as a file, and an orphan is defined by the absence of *every*
    /// record. On the appliance 2026-08-30 that absence made ~25-39 GB at
    /// `alice/linux` unreachable by `delete`, `purge`, `undelete`, the sweep
    /// AND `list-deleted`, while `create` refused the name because the bytes
    /// were there.
    fn list_orphans(
        &self,
        namespace: Option<&str>,
    ) -> ControlResult<Vec<gunnar_grpc::seam::OrphanRow>> {
        Ok(self
            .stores
            .orphans()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?
            .into_iter()
            .filter(|row| namespace.is_none_or(|want| row.path.namespace() == want))
            .map(|row| gunnar_grpc::seam::OrphanRow {
                path: RepoPath {
                    namespace: row.path.namespace().to_owned(),
                    repo: row.path.name().to_owned(),
                },
                dir: row.dir.display().to_string(),
                bytes: row.bytes,
                hash_marker: row.hash_marker.unwrap_or_default(),
                modified_unix_ms: row.modified_unix_ms,
                failed_reclaim: row.failed_reclaim.unwrap_or_default(),
            })
            .collect())
    }

    /// **Reclaim an orphan.** `FailedPrecondition` when it is not one, because
    /// "this is a live repository" is a fact the caller can act on and not an
    /// internal fault.
    fn reclaim_orphan(&self, path: &RepoPath) -> ControlResult<u64> {
        let repo_ref = Self::repo_ref(path)?;
        self.stores
            .reclaim_orphan(&repo_ref)
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))
    }

    fn index_progress(&self) -> ControlResult<Vec<gunnar_grpc::seam::IndexProgressRow>> {
        Ok(self
            .stores
            .engine()
            .index_progress()
            .into_iter()
            .filter_map(|(dir, s)| {
                let (namespace, name) = self.stores.repo_of_dir(&dir)?;
                Some(gunnar_grpc::seam::IndexProgressRow {
                    namespace,
                    name,
                    pack_id: s.pack_id,
                    objects_done: s.objects_done,
                    objects_total: s.objects_total,
                    bytes_done: s.bytes_done,
                    bytes_total: s.bytes_total,
                    phase: if s.active {
                        s.phase.to_string()
                    } else {
                        "idle".to_string()
                    },
                    started_at_unix_ms: s.started_at_ms as i64,
                    resumed: s.resumed,
                    reinflations: s.reinflations,
                    pauses: s.pauses,
                })
            })
            .filter(|r| r.phase != "idle")
            .collect())
    }

    fn set_default_branch(&self, path: &RepoPath, default_branch: &str) -> ControlResult<Repo> {
        let repo_ref = Self::repo_ref(path)?;
        let repo = self
            .stores
            .catalog()
            .set_default_branch(&repo_ref, default_branch)
            .map_err(internal)?;
        // The catalog is the authority; the repository's `HEAD` is a projection
        // of it and does not move on its own. Without this line the call
        // answers with the new branch and `repo get` reads it back, while the
        // reference advertisement — which reads `HEAD`, not the catalog — keeps
        // naming the old one. That was the whole of the 2026-08-06 defect: a
        // `master` donor pushed cleanly into a repository nobody could clone,
        // and `set-default-branch` looked like it had fixed it.
        self.stores.repoint_head(&repo).map_err(|err| {
            ControlError::Internal(format!("pointing HEAD at the new default branch: {err:#}"))
        })?;
        Ok(repo_out(&repo))
    }

    fn set_visibility(
        &self,
        path: &RepoPath,
        visibility: gunnar_proto::Visibility,
    ) -> ControlResult<Repo> {
        if visibility == gunnar_proto::Visibility::Unspecified {
            return Err(ControlError::InvalidArgument(
                "visibility unspecified".into(),
            ));
        }
        let repo_ref = Self::repo_ref(path)?;
        self.stores
            .catalog()
            .set_visibility(&repo_ref, visibility_in(visibility)?)
            .map(|repo| repo_out(&repo))
            .map_err(internal)
    }

    /// **A member's ONE encryption key** (CRYPT-YUBI 2026-10-26): a repository's ring is
    /// wrapped to the person's encryption public key, never to an SSH key. Empty when they
    /// have none yet.
    fn recipient_keys(&self, principal_id: &str) -> ControlResult<Vec<gunnar_proto::RecipientKey>> {
        let public = self.stores.encryption_keys().public_of(principal_id).map_err(key_refusal)?;
        Ok(public
            .into_iter()
            .map(|public| gunnar_proto::RecipientKey {
                fingerprint: gunnar_core::auth::fingerprint_of_blob(public.as_bytes()).to_string(),
                algo: if public.starts_with("age1pq1") { gunnar_core::auth::PQ_RECIPIENT_ALGO.to_owned() } else { "X25519".to_owned() },
                openssh: public,
            })
            .collect())
    }

    fn encryption_key(&self, principal_id: &str) -> ControlResult<gunnar_proto::GetEncryptionKeyResponse> {
        Ok(encryption_key_out(self.stores.encryption_keys().get(principal_id).map_err(key_refusal)?))
    }

    fn create_encryption_key(
        &self,
        principal_id: &str,
        public_key: &str,
        first: gunnar_proto::UnlockMethod,
    ) -> ControlResult<gunnar_proto::GetEncryptionKeyResponse> {
        let first = method_in(first)?;
        let key = self.stores.encryption_keys().create(principal_id, public_key, first, gunnar_core::now_ms().max(0) as u64).map_err(key_refusal)?;
        Ok(encryption_key_out(Some(key)))
    }

    fn add_unlock_method(&self, principal_id: &str, method: gunnar_proto::UnlockMethod) -> ControlResult<gunnar_proto::GetEncryptionKeyResponse> {
        let method = method_in(method)?;
        let key = self.stores.encryption_keys().add_method(principal_id, method, gunnar_core::now_ms().max(0) as u64).map_err(key_refusal)?;
        Ok(encryption_key_out(Some(key)))
    }

    fn remove_unlock_method(&self, principal_id: &str, id: &str) -> ControlResult<gunnar_proto::GetEncryptionKeyResponse> {
        let key = self.stores.encryption_keys().remove_method(principal_id, id).map_err(key_refusal)?;
        Ok(encryption_key_out(Some(key)))
    }

    fn set_encrypted(&self, path: &RepoPath, encrypted: bool) -> ControlResult<Repo> {
        let repo_ref = Self::repo_ref(path)?;
        self.stores
            .catalog()
            .set_encrypted(&repo_ref, encrypted)
            .map(|repo| repo_out(&repo))
            .map_err(internal)
    }

    /// **`Repos.ArchiveOut`: the same bytes `gunnar repo archive-out` writes,
    /// into a sink the control plane owns** — so a cron on another machine can
    /// pull a backup off a box that has no shell.
    ///
    /// It does **not** go through [`Self::open`]. An archive is three files
    /// read out of a directory; taking the handle cache and the store's lock
    /// for it would make a backup contend with serving, and the whole reason
    /// there is no `freeze` verb is that it does not have to. The pack is
    /// append-only and fsynced below the cut, so what is read is durable and
    /// what arrives after the cut belongs to the next one.
    #[cfg(feature = "engine-znippy")]
    fn archive_out(
        &self,
        path: &RepoPath,
        from_generation: u64,
        sink: &mut dyn std::io::Write,
    ) -> ControlResult<gunnar_grpc::seam::ArchiveCut> {
        let repo_ref = Self::repo_ref(path)?;
        let dir = self
            .stores
            .repo_dir(&repo_ref)
            .map_err(|err| ControlError::Internal(format!("resolving {path}: {err:#}")))?;
        if !dir.is_dir() {
            return Err(ControlError::NotFound(format!(
                "{path} has nothing on disk at {}",
                dir.display()
            )));
        }
        let receipt =
            crate::storage::znippy_engine::archive_out_to(&dir, &mut { sink }, from_generation)
                .map_err(archive_error)?;
        // **The second bytes-out counting point, and the only one outside the
        // git transport.** `Repos.ArchiveOut` streams a repository's archive
        // over gRPC and never touches `transport::serve_blocking`, so its bytes
        // are in neither `ServerMetrics::bytes_out` nor — before this line —
        // any tenant's meter. A replica pulling a hundred gigabytes would have
        // read as a silent namespace.
        //
        // It counts as a FETCH: a caller asked for objects and objects were
        // served, which is what `fetches` means. The principal is not in scope
        // at this seam — the gRPC caller's identity stops at the service layer —
        // so this transfer moves bytes in nobody's name, which is a smaller
        // untruth than attributing it to whoever pushed last.
        self.stores.flow().record(
            &path.namespace,
            gunnar_core::now_ms(),
            &gunnar_core::Transfer {
                bytes_out: receipt.bytes_out,
                fetched: true,
                ..gunnar_core::Transfer::default()
            },
        );
        Ok(gunnar_grpc::seam::ArchiveCut {
            from_generation: receipt.from_generation,
            to_generation: receipt.to_generation,
            bytes_out: receipt.bytes_out,
            file_sha256: receipt.file_sha256,
        })
    }

    // ── refs and objects ───────────────────────────────────────────────────

    fn list_refs(
        &self,
        path: &RepoPath,
        prefix: &str,
        peel_them: bool,
    ) -> ControlResult<Vec<RefTarget>> {
        let (_, store) = self.open(path)?;
        let git = store.serve();
        // **One `refs()` call is one snapshot.** The prefix is filtered here
        // rather than pushed into the store because `GitOps::refs` takes no
        // filter — it hands back the ref namespace, and narrowing it is the
        // caller's. See `gunnar_wire::refs`.
        let snapshot = RefSnapshot::read(git).map_err(wire_error)?;
        let mut out = Vec::new();
        for row in snapshot.with_prefix(Some(prefix)) {
            out.push(ref_target_out(
                git,
                store.hash_kind(),
                &snapshot,
                row,
                peel_them,
            )?);
        }
        Ok(out)
    }

    fn get_ref(
        &self,
        path: &RepoPath,
        ref_name: &str,
        peel_them: bool,
    ) -> ControlResult<RefTarget> {
        let (_, store) = self.open(path)?;
        let git = store.serve();
        // `FullName::new` was the validator and it died with `RefStore`; the
        // rules live in `gunnar_store::refname` now, one authority for the
        // whole tree. It is still checked here rather than trusted: this is a
        // caller's string, and `refname::validate` is a path-traversal boundary
        // wherever a name can become a lookup.
        gunnar_store::refname::validate(ref_name)
            .map_err(|err| ControlError::InvalidArgument(err.to_string()))?;
        let snapshot = RefSnapshot::read(git).map_err(wire_error)?;
        // `refname::validate` admits exactly `HEAD` and `refs/…`, and `HEAD` is
        // **not** one of the rows (the `GitServe` HEAD ruling) — so asking for it in the snapshot
        // would answer `NotFound` for a reference every repository has. The
        // accessor pair is where it comes from; its target still resolves
        // against the snapshot, so both branches answer out of one snapshot.
        let head_row;
        let row = if ref_name == gunnar_store::HEAD {
            head_row = git
                .head()
                .map_err(store_error)?
                .ok_or_else(|| ControlError::NotFound(format!("{ref_name} in {path}")))?;
            &head_row
        } else {
            snapshot
                .get(ref_name)
                .ok_or_else(|| ControlError::NotFound(format!("{ref_name} in {path}")))?
        };
        ref_target_out(git, store.hash_kind(), &snapshot, row, peel_them)
    }

    fn log(
        &self,
        path: &RepoPath,
        start: &str,
        limit: u32,
        touching: &str,
    ) -> ControlResult<Vec<Commit>> {
        self.log_walk(path, LogStart::One(start), limit, touching)
    }

    /// Every branch and tag tip, and `HEAD`, walked as one history: the
    /// History page's "all branches" view (owner order 2026-10-18), so a
    /// commit that lives only on a side branch is drawn too.
    fn log_all_refs(
        &self,
        path: &RepoPath,
        limit: u32,
        touching: &str,
    ) -> ControlResult<Vec<Commit>> {
        self.log_walk(path, LogStart::AllRefs, limit, touching)
    }

    fn create_pull(
        &self,
        path: &RepoPath,
        author: &str,
        title: &str,
        description: &str,
        source_ref: &str,
        target_ref: &str,
    ) -> ControlResult<PullRequest> {
        for (what, name) in [("source_ref", source_ref), ("target_ref", target_ref)] {
            if !name.starts_with("refs/heads/") {
                return Err(ControlError::InvalidArgument(format!(
                    "{what} must be a full branch name under refs/heads/, got {name:?}: a pull \
                     request merges branches, and a short name stored today is an ambiguity \
                     resolved differently tomorrow"
                )));
            }
        }
        if source_ref == target_ref {
            return Err(ControlError::InvalidArgument(
                "a branch cannot be merged into itself".to_owned(),
            ));
        }
        if title.trim().is_empty() {
            return Err(ControlError::InvalidArgument(
                "a title is required".to_owned(),
            ));
        }
        let repo_ref = Self::repo_ref(path)?;
        let (_, store) = self.open(path)?;
        let git = store.serve();
        let snapshot = RefSnapshot::read(git).map_err(wire_error)?;
        let source = snapshot
            .resolve(source_ref)
            .map_err(wire_error)?
            .ok_or_else(|| ControlError::NotFound(format!("{source_ref} in {path}")))?;
        snapshot
            .resolve(target_ref)
            .map_err(wire_error)?
            .ok_or_else(|| ControlError::NotFound(format!("{target_ref} in {path}")))?;
        let record = self
            .pulls()?
            .create(
                &repo_ref.to_string(),
                author,
                title,
                description,
                source_ref,
                target_ref,
                &source.to_string(),
            )
            .map_err(internal)?;
        Ok(pull_out(path, record))
    }

    fn list_pulls(&self, path: &RepoPath, state: i32) -> ControlResult<Vec<PullRequest>> {
        let repo_ref = Self::repo_ref(path)?;
        // Existence check: a list for a repository that is not there is
        // NotFound, never an empty success.
        self.get_repo(path)?;
        let filter = match PullRequestState::try_from(state) {
            Ok(PullRequestState::Unspecified) | Err(_) => None,
            Ok(PullRequestState::Open) => Some(gunnar_core::PullState::Open),
            Ok(PullRequestState::Merged) => Some(gunnar_core::PullState::Merged),
            Ok(PullRequestState::Closed) => Some(gunnar_core::PullState::Closed),
        };
        Ok(self
            .pulls()?
            .list(&repo_ref.to_string(), filter)
            .map_err(internal)?
            .into_iter()
            .map(|record| pull_out(path, record))
            .collect())
    }

    fn get_pull(&self, path: &RepoPath, number: u64) -> ControlResult<PullRequest> {
        let repo_ref = Self::repo_ref(path)?;
        self.get_repo(path)?;
        self.pulls()?
            .get(&repo_ref.to_string(), number)
            .map_err(internal)?
            .map(|record| pull_out(path, record))
            .ok_or_else(|| ControlError::NotFound(format!("pull request #{number} in {path}")))
    }

    fn close_pull(&self, path: &RepoPath, number: u64) -> ControlResult<PullRequest> {
        let repo_ref = Self::repo_ref(path)?;
        self.get_repo(path)?;
        match self
            .pulls()?
            .close(&repo_ref.to_string(), number)
            .map_err(internal)?
        {
            gunnar_core::PullTransition::Done(record) => Ok(pull_out(path, record)),
            gunnar_core::PullTransition::NotFound => Err(ControlError::NotFound(format!(
                "pull request #{number} in {path}"
            ))),
            gunnar_core::PullTransition::NotOpen(state) => Err(ControlError::FailedPrecondition(
                format!("pull request #{number} is already {state:?}, not open"),
            )),
        }
    }

    /// FAST-FORWARD ONLY, and every step is ordered so a failure leaves the
    /// truth on disk: the ancestry is decided by the same
    /// [`gunnar_policy::ancestry::is_descendant_of`] branch protection trusts
    /// (fail-closed: inconclusive is a refusal, never an allow), the ref moves
    /// through the store's own compare-and-swap — the primitive receive-pack
    /// uses, so this is not a second ref-write path — and the record is marked
    /// merged only AFTER the ref has moved.
    fn merge_pull(
        &self,
        path: &RepoPath,
        number: u64,
        principal_id: &str,
    ) -> ControlResult<(PullRequest, MergedRef)> {
        let repo_ref = Self::repo_ref(path)?;
        let key = repo_ref.to_string();
        let pulls = self.pulls()?;
        let record = pulls
            .get(&key, number)
            .map_err(internal)?
            .ok_or_else(|| ControlError::NotFound(format!("pull request #{number} in {path}")))?;
        if record.state != gunnar_core::PullState::Open {
            return Err(ControlError::FailedPrecondition(format!(
                "pull request #{number} is already {:?}, not open",
                record.state
            )));
        }

        let (repo_record, store) = self.open(path)?;
        let git = store.serve();
        let snapshot = RefSnapshot::read(git).map_err(wire_error)?;
        let source = snapshot
            .resolve(&record.source_ref)
            .map_err(wire_error)?
            .ok_or_else(|| {
                ControlError::FailedPrecondition(format!(
                    "the source branch {} is gone; nothing to merge",
                    record.source_ref
                ))
            })?;
        let target = snapshot
            .resolve(&record.target_ref)
            .map_err(wire_error)?
            .ok_or_else(|| {
                ControlError::FailedPrecondition(format!(
                    "the target branch {} is gone",
                    record.target_ref
                ))
            })?;

        // ── THE REVIEW GATE ────────────────────────────────────────────────
        //
        // A verified approval must name the commit this is about to move to.
        //
        // `source` and not `record.source_oid`: the record's oid is the tip at
        // CREATION and the branch may have advanced since. The approval names
        // what was reviewed, so if the branch moved after the review, no
        // approval names the new tip and this refuses — which is the whole
        // point. A force-push after a review does not inherit the review, and
        // the refusal says which commit was actually approved so the reviewer
        // can be asked again.
        //
        // Verified, not merely present: `review_state` re-checks every approval
        // against the ACL key table right now, so an approval by a key that has
        // since been revoked stops counting the moment the key does.
        let head = source.to_string();
        // Read once: `review_state` needs the SIGNED events to re-check each
        // approval, and the fold needs the unsigned halves of the same list.
        let signed = self.forge_events()?;
        let events: Vec<gunnar_core::ForgeEvent> = signed
            .iter()
            .filter(|s| s.event.repo == key)
            .map(|s| s.event.clone())
            .collect();
        let review = gunnar_core::forge::fold(number, &events);
        let approved = self.review_state(&key, &review, &signed)?;
        let ok = approved
            .approvals
            .iter()
            .any(|a| a.verified && a.commit == head);
        if !ok {
            let named: Vec<String> = approved
                .approvals
                .iter()
                .map(|a| {
                    format!(
                        "{} → {} [{}]",
                        a.actor,
                        &a.commit[..12.min(a.commit.len())],
                        a.verdict
                    )
                })
                .collect();
            return Err(ControlError::FailedPrecondition(format!(
                "no verified approval names {}, the commit {} is at. gunnar does not merge on \
                 an approval of something else: an approval names the commit it approved, so a \
                 branch that moved after the review has not been reviewed.{}",
                &head[..12.min(head.len())],
                record.source_ref,
                if named.is_empty() {
                    " Nobody has approved this pull request.".to_owned()
                } else {
                    format!(" What is approved: {}", named.join(", "))
                }
            )));
        }

        // ── THE REVIEW POLICY ──────────────────────────────────────────────
        //
        // Who may count, and how many — from the SAME policy document branch
        // protection lives in, on the rules covering the TARGET ref. The gate
        // above asked "is there a verified approval of this tip"; these two
        // fields ask "whose, and how many", and they are policy rather than
        // fact, which is why they live in a `ProtectionRule` an administrator
        // wrote and not in this function's opinion.
        //
        // Distinct by construction: the fold keys approvals by actor, so a
        // principal who approves twice holds ONE entry, and this count can
        // never be inflated by pressing the button again.
        let policy = self.policy_of(&repo_record)?;
        let rules: Vec<&gunnar_policy::ProtectionRule> = policy
            .protection
            .iter()
            .filter(|rule| rule.pattern.matches_ref(&record.target_ref))
            .collect();
        let forbid_self = rules.iter().any(|rule| rule.forbid_self_approval);
        let required = rules
            .iter()
            .map(|rule| rule.required_approvals)
            .max()
            .unwrap_or(0)
            .max(1) as usize;
        let approvers: Vec<&str> = approved
            .approvals
            .iter()
            .filter(|a| a.verified && a.commit == head)
            .map(|a| a.actor.as_str())
            .collect();
        let counted: Vec<&str> = approvers
            .iter()
            .copied()
            .filter(|actor| !(forbid_self && *actor == record.author))
            .collect();
        if forbid_self && counted.is_empty() && !approvers.is_empty() {
            return Err(ControlError::FailedPrecondition(format!(
                "the protection on {} forbids self-approval, and the only verified approval \
                 of {} is the author's own ({}). An author's sign-off on their own work is \
                 not a review; somebody else has to look at it.",
                record.target_ref,
                &head[..12.min(head.len())],
                record.author
            )));
        }
        if counted.len() < required {
            return Err(ControlError::FailedPrecondition(format!(
                "the protection on {} requires {required} distinct verified approvals of {} \
                 and there {} ({}). Approvals by the same principal count once{}.",
                record.target_ref,
                &head[..12.min(head.len())],
                if counted.len() == 1 {
                    "is 1".to_owned()
                } else {
                    format!("are {}", counted.len())
                },
                if counted.is_empty() {
                    "nobody".to_owned()
                } else {
                    counted.join(", ")
                },
                if forbid_self {
                    ", and the author's own does not count here"
                } else {
                    ""
                }
            )));
        }

        // ── BRANCH PROTECTION, the same gate the push path runs ────────────
        //
        // GUN-004. This function read the policy document, took
        // `forbid_self_approval` and `required_approvals` out of it, and then
        // wrote the ref. `allowed_principals` and `require_signature` live in
        // the same `ProtectionRule` and were evaluated only in
        // `gates::protection` — which the merge path never went through. A
        // contributor with `Level::Write` on a repository in somebody else's
        // namespace could move a ref an administrator had explicitly protected,
        // while the push path refused them correctly: the protection LOOKED
        // like it worked, and the side door was open. The structural cause was
        // that the caller's identity never crossed the seam, which it now does.
        //
        // `BranchProtectionGate::check`, not `PolicyEngine::evaluate`: a merge
        // is not a push. It has no pack to measure, no push options to read and
        // no reference name the client chose, so `LimitsGate`,
        // `PushOptionsGate` and `RefNameGate` would each be deciding about
        // something that is not in front of them.
        if source != target {
            let principal = self
                .stores
                .auth()
                .principal(principal_id)
                .map_err(internal)?
                .ok_or_else(|| {
                    // The caller authenticated and passed a grant check to get
                    // here, so this is a table that changed underneath the
                    // request. Refuse; a merge attributed to nobody is worse
                    // than a merge that did not happen.
                    ControlError::FailedPrecondition(format!(
                        "the principal {principal_id} is no longer in the identity table; \
                         refusing to move a protected reference for an identity that \
                         cannot be resolved"
                    ))
                })?;
            let gate = gunnar_policy::BranchProtectionGate::new(policy.protection.clone());
            let repo_id = gunnar_policy::RepoId::new(&path.namespace, &path.repo);
            let policy_principal = gunnar_policy::Principal {
                id: principal.id.clone(),
                name: principal.name.clone(),
                kind: crate::transport::policy_principal_kind(principal.kind),
            };
            // What this ref move ADDS. A merge carries no pack, so the pack's
            // new-object set — every other gate's answer to "what did this
            // introduce" — is empty here, and an empty set makes
            // `require_signature` pass by having nothing to look at. The
            // honest set is the range `target..source`; see
            // `ancestry::commits_between`.
            let introduced = gunnar_policy::ancestry::commits_between(
                git,
                &source,
                &target,
                gunnar_policy::ancestry::DEFAULT_ANCESTRY_BUDGET,
            )
            .map_err(|err| {
                ControlError::FailedPrecondition(format!(
                    "the commits this merge would add could not be enumerated ({err}); \
                     refusing rather than running branch protection over an empty set"
                ))
            })?;
            let updates = [gunnar_policy::RefUpdate::from_wire(
                record.target_ref.clone(),
                target,
                source,
            )];
            let keys = crate::transport::key_directory(&self.stores);
            let ctx = gunnar_policy::PushContext::new(
                &policy_principal,
                &repo_id,
                &updates,
                &introduced,
                git,
                &keys,
            );
            match gunnar_policy::Gate::check(&gate, &ctx) {
                Ok(gunnar_policy::Verdict::Allow) => {}
                Ok(verdict) => {
                    return Err(ControlError::FailedPrecondition(format!(
                        "branch protection refuses this merge: {}",
                        verdict.reason().unwrap_or_default()
                    )));
                }
                // A gate that could not decide refuses, exactly as it does on
                // the push path.
                Err(err) => {
                    return Err(ControlError::FailedPrecondition(format!(
                        "branch protection could not decide this merge ({err}); refusing rather \
                         than guessing"
                    )));
                }
            }
        }

        if source != target {
            match gunnar_policy::ancestry::is_descendant_of(
                git,
                &source,
                &target,
                gunnar_policy::ancestry::DEFAULT_ANCESTRY_BUDGET,
            ) {
                Ok(true) => {}
                Ok(false) => {
                    return Err(ControlError::FailedPrecondition(format!(
                        "not a fast-forward: {} does not descend from {}. gunnar has no merge \
                         engine yet — rebase or merge locally, push the result, and merge again",
                        record.source_ref, record.target_ref
                    )));
                }
                // Inconclusive is a refusal, never an allow — the same
                // judgement BranchProtectionGate makes.
                Err(err) => {
                    return Err(ControlError::FailedPrecondition(format!(
                        "the ancestry walk could not be completed ({err}); refusing rather than \
                         guessing"
                    )));
                }
            }
            git.update_ref(
                &record.target_ref,
                Some(target.as_bytes()),
                Some(source.as_bytes()),
            )
            .map_err(|err| {
                ControlError::FailedPrecondition(format!(
                    "the target ref moved while merging ({err}); nothing was written — retry \
                     against the new tip"
                ))
            })?;
        }
        // source == target is "already up to date": nothing to write, and the
        // record honestly says the merge oid is the tip both already share.

        let merged = match pulls
            .mark_merged(&key, number, &source.to_string())
            .map_err(internal)?
        {
            gunnar_core::PullTransition::Done(record) => record,
            // The ref HAS moved; a racing close between our CAS and this write
            // must be reported loudly, not papered over.
            other => {
                return Err(ControlError::Internal(format!(
                    "the ref moved to {source} but the record could not be marked merged \
                     ({other:?}); the repository is correct, the record is not"
                )));
            }
        };
        Ok((
            pull_out(path, merged),
            MergedRef {
                ref_name: record.target_ref.clone(),
                old_oid: target.to_string(),
                new_oid: source.to_string(),
            },
        ))
    }

    fn read_object(
        &self,
        path: &RepoPath,
        oid: &str,
        max_bytes: u64,
    ) -> ControlResult<ReadObjectResponse> {
        let (_, store) = self.open(path)?;
        let git = store.serve();
        let id = gix_hash::ObjectId::from_hex(oid.as_bytes())
            .map_err(|err| ControlError::InvalidArgument(format!("{oid}: {err}")))?;

        // ── the object ceiling, contract half, now complete ────────────────
        //
        // `header()` costs no inflate — `gix-odb` answers kind and size out of
        // the index — so the size is known before any allocation, and both
        // refusals happen HERE rather than after the object is materialised.
        //
        // Two ceilings, and they are different in kind. See their constants.
        if let Some((_, object_bytes)) = git.header(id.as_bytes()).map_err(store_error)? {
            // The OBJECT ceiling first, and the order is deliberate: an object
            // over it cannot be served at any `max_bytes`, so saying so
            // immediately is better than sending the caller off to retry with a
            // prefix that will be refused for a second reason.
            if self.max_object_bytes != 0 && object_bytes > self.max_object_bytes {
                return Err(ControlError::ResourceExhausted(format!(
                    "object {oid} is {object_bytes} bytes, over this server's {}-byte ceiling \
                     for reading an object. Reading any part of it costs the whole object in \
                     memory, because a prefix of a delta-encoded object needs its entire base \
                     chain, so no max_bytes makes this request cheaper.",
                    self.max_object_bytes
                )));
            }
            // The RESPONSE ceiling second: this one costs nobody anything, and
            // `max_bytes` is the way past it.
            let response_bytes = if max_bytes == 0 {
                object_bytes
            } else {
                object_bytes.min(max_bytes)
            };
            if response_bytes > MAX_RESPONSE_BYTES {
                return Err(ControlError::ResourceExhausted(format!(
                    "object {oid} is {object_bytes} bytes and the response would be \
                     {response_bytes}, over the {MAX_RESPONSE_BYTES}-byte limit a gRPC client \
                     can receive by default. Ask for a prefix with max_bytes."
                )));
            }
        }

        // The half with no contract change: the object is inflated once
        // and then **moved** into the response, where it used to be copied out
        // of `buf` a second time by `to_vec()`. On a one-gigabyte blob that
        // second copy was another gigabyte, for nothing.
        //
        // `GitServe::read` returns the inflated bytes owned, so the move is the
        // signature now rather than a borrow that had to be ended first — the
        // `{ … }` block this replaced existed only to drop a `Data<'a>` tied to
        // the caller's buffer.
        let Some((kind, mut buf)) = git.read(id.as_bytes()).map_err(store_error)? else {
            return Err(ControlError::NotFound(format!("object {oid} in {path}")));
        };
        let size = buf.len() as u64;

        // The first inflation is still whole-object — `GitServe` has no bounded
        // read and for a delta-encoded object cannot honestly grow one — but it
        // is now BOUNDED, by `max_object_bytes` above. A caller asking for one
        // byte of a one-gigabyte blob is refused rather than served at the cost
        // of a gigabyte.
        let truncated = max_bytes != 0 && size > max_bytes;
        if truncated {
            buf.truncate(max_bytes as usize);
        }
        Ok(ReadObjectResponse {
            oid: id.to_string(),
            kind: object_kind_out(kind)? as i32,
            size,
            data: buf,
            truncated,
        })
    }

    /// **`Refs.ReadLfsObject`, served out of the repository's own LFS store.**
    ///
    /// The same store the SSH adapter and the HTTP batch API serve
    /// (`gunnar_lfs::FsLfsStore` under `<git_dir>/lfs`), opened the same way
    /// `transport::open_lfs_store` opens it, so there is one place an object
    /// lives and one answer to where it is.
    ///
    /// # Whole object or nothing, and the ceiling that decides
    ///
    /// `read_object` truncates a git blob past `max_bytes`, because a prefix of
    /// a file is still a file's beginning. This does not: the caller asked for
    /// a PDF, and half a PDF is not a smaller PDF. So the SIZE decides before
    /// a byte is read — `size_of` costs a `stat`, not an open — and an object
    /// over the ceiling is refused with its size in the message, which is what
    /// lets the caller go to `git lfs` instead.
    ///
    /// The ceiling is the caller's `max_bytes`, lowered to
    /// [`MAX_RESPONSE_BYTES`] because that is what a gRPC client can receive by
    /// default. Nothing here allocates from a number the client sent: the
    /// allocation is the object's own size, after that size has been refused
    /// or accepted.
    ///
    /// # A ranged read (2026-10-15)
    ///
    /// With `range`, the same ceiling bounds a RANGE instead of the object, so
    /// a caller with no `git lfs` — a console handing a browser a 6 MB README
    /// picture — reads any object a range at a time, and one that needs only
    /// a picture's header reads only that. The store seeks (`open_at`), so a
    /// range deep into a large object does not read what lies before it. Still
    /// never a silent prefix: a range ends early only at the object's end,
    /// which `offset` + the length against `size` says.
    fn read_lfs_object(
        &self,
        path: &RepoPath,
        oid: &str,
        max_bytes: u64,
        range: Option<(u64, u64)>,
    ) -> ControlResult<ReadLfsObjectResponse> {
        let (_, store) = self.open(path)?;
        let id = gunnar_lfs::Oid::parse(oid)
            .map_err(|err| ControlError::InvalidArgument(format!("{oid}: {err}")))?;
        // The trait the store's two readers live on; `gunnar-lfs` keeps the
        // wire adapters and the backend apart, and this is the backend half.
        use gunnar_lfs::LfsStore as _;

        let lfs = gunnar_lfs::FsLfsStore::open_or_init(store.git_dir()).map_err(|err| {
            ControlError::Internal(format!("opening the repository's LFS store: {err}"))
        })?;

        let ceiling = match max_bytes {
            0 => MAX_RESPONSE_BYTES,
            n => n.min(MAX_RESPONSE_BYTES),
        };
        let size = lfs
            .size_of(&id)
            .map_err(|err| ControlError::Internal(format!("reading the LFS store: {err}")))?
            .ok_or_else(|| ControlError::NotFound(format!("LFS object {oid} in {path}")))?;

        // **A ranged read** (`offset`/`length` not both 0): the ceiling bounds
        // the RANGE, so an object of any size is read a range at a time. An
        // offset at or past the end is refused by name rather than answered
        // empty, and a length over the ceiling is refused rather than cut — a
        // caller never gets fewer bytes than it asked for unless the object's
        // end is the reason.
        if let Some((offset, length)) = range {
            if offset > size || (offset == size && size > 0) {
                return Err(ControlError::InvalidArgument(format!(
                    "offset {offset} is past the end of LFS object {oid}, which is {size} bytes"
                )));
            }
            if length > ceiling {
                return Err(ControlError::ResourceExhausted(format!(
                    "a range of {length} bytes of LFS object {oid} is over the {ceiling}-byte ceiling \
                     for this request; ask for {ceiling} bytes or fewer at a time"
                )));
            }
            let want = if length == 0 { ceiling } else { length }.min(size - offset);
            let object = lfs
                .open_at(&id, offset)
                .map_err(|err| ControlError::Internal(format!("opening LFS object {oid}: {err}")))?
                .ok_or_else(|| ControlError::NotFound(format!("LFS object {oid} in {path}")))?;
            let mut data = Vec::with_capacity(want as usize);
            let mut reader = std::io::Read::take(object.reader, want);
            std::io::Read::read_to_end(&mut reader, &mut data)
                .map_err(|err| ControlError::Internal(format!("reading LFS object {oid}: {err}")))?;
            if (data.len() as u64) < want {
                return Err(ControlError::Internal(format!(
                    "LFS object {oid} ended {} bytes into a {want}-byte range at {offset}",
                    data.len()
                )));
            }
            return Ok(ReadLfsObjectResponse { oid: oid.to_owned(), size: object.size, data, offset });
        }

        if size > ceiling {
            return Err(ControlError::ResourceExhausted(format!(
                "LFS object {oid} is {size} bytes, over the {ceiling}-byte ceiling for this \
                 request. An LFS object is served whole or not at all — a prefix of one is not a \
                 smaller file — so no max_bytes makes this request smaller. `git lfs` streams it, \
                 and a ranged read (offset/length) reads it a range at a time."
            )));
        }

        let object = lfs
            .open(&id)
            .map_err(|err| ControlError::Internal(format!("opening LFS object {oid}: {err}")))?
            .ok_or_else(|| ControlError::NotFound(format!("LFS object {oid} in {path}")))?;
        // `size_of` and `open` are two calls on a store an upload can commit
        // to in between, so the length is taken from the object that was
        // actually opened and the read is bounded by it rather than by the
        // earlier answer.
        if object.size > ceiling {
            return Err(ControlError::ResourceExhausted(format!(
                "LFS object {oid} is {} bytes, over the {ceiling}-byte ceiling for this request",
                object.size
            )));
        }
        let mut data = Vec::with_capacity(object.size as usize);
        let mut reader = std::io::Read::take(object.reader, object.size);
        std::io::Read::read_to_end(&mut reader, &mut data)
            .map_err(|err| ControlError::Internal(format!("reading LFS object {oid}: {err}")))?;

        Ok(ReadLfsObjectResponse {
            oid: oid.to_owned(),
            size: data.len() as u64,
            data,
            offset: 0,
        })
    }

    /// **`Refs.Diff`, served** (`crate::diff`).
    ///
    /// It used to answer `Unimplemented` — *"the server has no tree-diff
    /// engine; gix's blob-diff is client-side porcelain and an S crate must not
    /// link it"*. The constraint was right and the conclusion was not: a tree
    /// diff needs `GitServe::read` and nothing else, so it costs no crate and
    /// the appliance can serve one. `crate::diff` says what it computes exactly
    /// and what it deliberately does not (rename detection).
    fn diff(
        &self,
        path: &RepoPath,
        from: &str,
        to: &str,
        path_prefixes: &[String],
    ) -> ControlResult<Vec<FileChange>> {
        // The repository is opened first so a bad path is still a NotFound
        // rather than an argument error, which would hide a typo.
        let (_repo, store) = self.open(path)?;
        let git = store.serve();
        let hash = store.hash_kind();

        // An empty side is the empty tree, which is what makes "everything this
        // commit added" expressible without a magic oid: `from: ""` diffs
        // against nothing.
        let resolve = |spec: &str| -> ControlResult<Option<gix_hash::ObjectId>> {
            if spec.is_empty() {
                return Ok(None);
            }
            Ok(Some(self.tree_of(git, hash, path, spec)?))
        };
        let old = resolve(from)?;
        let new = resolve(to)?;

        crate::diff::compare(git, hash, old, new, path_prefixes).map_err(|err| match err {
            // A tree-ish that names an object this repository does not hold is
            // the caller's mistake, not a fault: `NotFound`, with the id.
            crate::diff::DiffError::Missing(oid) => {
                ControlError::NotFound(format!("object {oid} in {path}"))
            }
            crate::diff::DiffError::WrongKind { .. } => {
                ControlError::InvalidArgument(err.to_string())
            }
            crate::diff::DiffError::Corrupt { .. } | crate::diff::DiffError::Backend(_) => {
                ControlError::Internal(err.to_string())
            }
        })
    }

    // ── identity and access ────────────────────────────────────────────────

    fn add_principal(
        &self,
        id: &str,
        name: &str,
        kind: gunnar_proto::PrincipalKind,
    ) -> ControlResult<Principal> {
        // gunnar-core's principals carry an id chosen by the caller, not a
        // minted one: grants name it, so a generated id would make every grant
        // in a config file unwritable until after the principal existed.
        //
        // The id and the name are two arguments on purpose (2026-09-12). Until
        // then this line read `Principal::new(name, name, …)`, which twinned
        // the account slug with the display name; every rename was a
        // re-identification and every console had to pin "the name I saw".
        // The service hands the name as the id when the caller set none, so
        // every caller from before keeps exactly what it had.
        let principal = gunnar_core::Principal::new(id, name, principal_kind_in(kind))
            .map_err(internal)?;
        let created = self
            .stores
            .auth()
            .add_principal(principal)
            .map(|p| principal_out(&p))
            .map_err(internal)?;
        // ── the account, created WITH the user ─────────────────────────────
        //
        // A principal is intrinsically admin of the namespace named after its
        // ID (`gunnar_core::AuthTable::owns_account`), which is the `<account>`
        // in `<host>/<account>/<repo>`. That rule reads no table, so it can
        // only be sound if the two names cannot be claimed independently — and
        // this is the half that makes them one claim: creating the principal
        // creates the namespace, and a namespace that already exists makes the
        // whole call fail, principal and all.
        //
        // Rolled back on failure rather than left half-made. A principal with
        // somebody else's namespace as its account is exactly the state the
        // intrinsic rule must never be able to reach.
        if let Err(err) = self.stores.catalog().create_namespace(id) {
            let _ = self.stores.auth().remove_principal(id);
            return Err(ControlError::AlreadyExists(format!(
                "cannot create the account namespace \"{id}\" for this user: {err}. A user's \
                 account is the namespace named after their id and cannot be somebody else's; \
                 the principal was not created."
            )));
        }
        // The metadata mirror's identity half, off the stripe. After the write,
        // best effort, never the reason a verb fails: see
        // `ServerStores::mirror_identity`.
        self.stores.mirror_identity();
        Ok(created)
    }

    fn enroll_employee(
        &self,
        account: &str,
        ask: &gunnar_grpc::EmployeeAsk,
    ) -> ControlResult<gunnar_grpc::EmployeeAnswer> {
        if self.stores.catalog().namespace(account).map_err(internal)?.is_none() {
            return Err(ControlError::NotFound(format!("account {account}")));
        }
        // A clan is no account: employees are a person's account's (clans,
        // 2026-10-05), and a clan's members are accounts of their own.
        if self.stores.auth().is_clan(account).map_err(internal)? {
            return Err(ControlError::FailedPrecondition(format!(
                "{account} is a clan, not an account: employees are enrolled by an account's admin, \
                 and a clan's members are accounts that join it"
            )));
        }
        let principal = if ask.seats == 0 {
            // An id that names a namespace would make the employee that
            // namespace's admin by name (`owns_account`). Refused, as the
            // account a principal is born with would refuse it.
            if self.stores.catalog().namespace(&ask.id).map_err(internal)?.is_some() {
                return Err(ControlError::AlreadyExists(format!(
                    "namespace {} exists, so an employee may not be called that",
                    ask.id
                )));
            }
            Some(
                gunnar_core::Principal::new(&ask.id, &ask.name, gunnar_core::PrincipalKind::User)
                    .map_err(internal)?,
            )
        } else {
            None
        };
        let room = gunnar_core::RoomAsk {
            room_bytes: ask.room_bytes,
            seats: ask.seats,
            from_seat: ask.from_seat,
            cap: ask.cap,
            stored: ask.stored,
            order: ask.order.clone(),
            dry_run: ask.dry_run,
        };
        let answer = match self.stores.auth().enroll_with_room(account, principal, &room) {
            Ok(answer) => answer,
            // Short is an ANSWER at the seam (nothing was written); the
            // service says it in the one sentence every plane shares.
            Err(gunnar_core::Error::RoomShort { need, unused, short, .. }) => {
                let (seats, seats_open) =
                    self.stores.auth().seats_of(account).map_err(internal)?;
                return Ok(gunnar_grpc::EmployeeAnswer {
                    principal: None,
                    room_bytes: ask.room_bytes,
                    seats,
                    seats_open,
                    need_bytes: need,
                    unused_bytes: Some(unused),
                    shortfall_bytes: short,
                    unchanged: true,
                });
            }
            Err(gunnar_core::Error::PrincipalExists(id)) => {
                return Err(ControlError::AlreadyExists(format!(
                    "principal {id} already exists, and an existing principal can never become an \
                     employee"
                )))
            }
            Err(err @ gunnar_core::Error::NoOpenSeat(_)) => {
                return Err(ControlError::FailedPrecondition(err.to_string()))
            }
            Err(err @ gunnar_core::Error::NameExists { .. }) => {
                return Err(ControlError::AlreadyExists(err.to_string()))
            }
            Err(err @ gunnar_core::Error::InvalidInput { .. }) => {
                return Err(ControlError::InvalidArgument(err.to_string()))
            }
            Err(other) => return Err(internal(other)),
        };
        if !answer.unchanged {
            self.stores.mirror_identity();
        }
        Ok(gunnar_grpc::EmployeeAnswer {
            principal: answer.principal.as_ref().map(principal_out),
            room_bytes: answer.room_bytes,
            seats: answer.seats,
            seats_open: answer.seats_open,
            need_bytes: answer.need_bytes,
            unused_bytes: answer.unused_bytes,
            shortfall_bytes: answer.shortfall_bytes,
            unchanged: answer.unchanged,
        })
    }

    fn seats(&self, account: &str) -> ControlResult<(u32, u32)> {
        self.stores.auth().seats_of(account).map_err(internal)
    }

    fn clans(&self) -> Option<&dyn gunnar_grpc::clans::ClanPlane> {
        Some(self)
    }

    fn has_employees(&self, account: &str) -> ControlResult<bool> {
        self.stores.auth().is_enterprise(account).map_err(internal)
    }

    fn employees(&self, account: &str) -> ControlResult<Vec<Principal>> {
        Ok(self
            .stores
            .auth()
            .employees_of(account)
            .map_err(internal)?
            .iter()
            .map(principal_out)
            .collect())
    }

    fn principal_by_name(&self, name: &str) -> ControlResult<Option<Principal>> {
        Ok(self
            .stores
            .auth()
            .principal_by_name(name)
            .map_err(internal)?
            .as_ref()
            .map(principal_out))
    }

    /// The fed name is read where the installer left it — the last join reply,
    /// `<data>/pairing/joined.toml` — so it holds across restarts and needs no
    /// second record. A build without the pairing loop was fed nothing.
    /// ★ **The operator's first invite**, kept in the identity table beside
    /// every other invite (the twin replicates it): the break-glass token's
    /// hash as `operator-bootstrap` for the operator's first passkey, no
    /// server grant. Spent — and a leftover one withdrawn — once the operator
    /// holds a passkey; otherwise recorded, or renewed for another
    /// `OPERATOR_INVITE_TTL_MS` when the same hash is pending. Two updates
    /// (withdraw, then create), each its own: a crash between them leaves no
    /// invite, and the next feed records it again.
    fn operator_bootstrap_invite(
        &self,
        operator: &str,
        secret_sha256: &str,
        now_unix_ms: i64,
        ttl_ms: i64,
    ) -> ControlResult<gunnar_grpc::BootstrapInvite> {
        use gunnar_grpc::seam::OPERATOR_INVITE_ID;
        let hash = gunnar_grpc::seam::bootstrap_hash(secret_sha256)?;
        let ttl_ms = gunnar_grpc::seam::bootstrap_ttl(ttl_ms)?;
        let auth = self.stores.auth();
        if !auth.web_credentials(Some(operator)).map_err(internal)?.is_empty() {
            if auth.revoke_invite(OPERATOR_INVITE_ID).map_err(internal)?.is_some() {
                self.stores.mirror_identity();
            }
            return Ok(gunnar_grpc::BootstrapInvite::Spent);
        }
        let renewed = auth
            .invites()
            .map_err(internal)?
            .iter()
            .any(|row| row.id == OPERATOR_INVITE_ID && row.secret_hash == hash && row.principal_id == operator);
        auth.revoke_invite(OPERATOR_INVITE_ID).map_err(internal)?;
        auth.create_invite(gunnar_core::Invite {
            id: OPERATOR_INVITE_ID.to_owned(),
            principal_id: operator.to_owned(),
            secret_hash: hash,
            created_by: "installer".to_owned(),
            created: now_unix_ms,
            expires: now_unix_ms + ttl_ms,
            note: "the operator's first passkey: the installer's first invite".to_owned(),
            server_level: None,
        })
        .map_err(internal)?;
        self.stores.mirror_identity();
        if !renewed {
            tracing::warn!(
                target: "gunnar::audit",
                event = "operator.bootstrap_invite",
                operator,
                ttl_days = ttl_ms / 86_400_000,
                "the installer's first invite (its hash) is recorded for the operator: his first passkey registers on his account, by gunnar's word"
            );
        }
        Ok(if renewed { gunnar_grpc::BootstrapInvite::Renewed } else { gunnar_grpc::BootstrapInvite::Recorded })
    }

    fn claim_operator(&self, asked: &str) -> ControlResult<gunnar_grpc::OperatorClaim> {
        #[cfg(feature = "wg-client")]
        let fed = crate::fed_principals::fed_operator(self.stores.root());
        #[cfg(not(feature = "wg-client"))]
        let fed: Option<String> = None;
        self.claim_operator_named(fed.as_deref(), asked)
    }

    fn rename_principal(&self, principal_id: &str, name: &str) -> ControlResult<Principal> {
        // The label alone. The namespace is the id's and does not move; nothing
        // keyed on the id is touched, and `AuthTable::rename_principal` says so
        // in its tests.
        let renamed = self
            .stores
            .auth()
            .rename_principal(principal_id, name)
            .map(|p| principal_out(&p))
            .map_err(internal)?;
        self.stores.mirror_identity();
        Ok(renamed)
    }

    fn list_principals(&self) -> ControlResult<Vec<Principal>> {
        Ok(self
            .stores
            .auth()
            .principals()
            .map_err(internal)?
            .iter()
            .map(principal_out)
            .collect())
    }

    fn principal_activity(
        &self,
    ) -> ControlResult<std::collections::BTreeMap<String, gunnar_grpc::PrincipalSeen>> {
        Ok(self
            .stores
            .activity()
            .all()
            .into_iter()
            .map(|(id, seen)| {
                (
                    id,
                    gunnar_grpc::PrincipalSeen {
                        last_sign_in_unix_ms: seen.signed_in,
                        last_operation_unix_ms: seen.operated,
                    },
                )
            })
            .collect())
    }

    fn holds_server_grant(&self, principal_id: &str) -> ControlResult<bool> {
        self.stores.auth().holds_server_grant(principal_id).map_err(internal)
    }

    fn add_credential(
        &self,
        principal_id: &str,
        credential_id: &[u8],
        public_key: &[u8],
        label: &str,
        sign_count: u32,
    ) -> ControlResult<gunnar_proto::WebCredential> {
        let stored = self
            .stores
            .auth()
            .add_web_credential(gunnar_core::WebCredential {
                id: gunnar_grpc::webauthn::b64url(credential_id),
                principal_id: principal_id.to_owned(),
                label: label.to_owned(),
                public_key_hex: hex::encode(public_key),
                sign_count,
                created: gunnar_core::now_ms(),
                last_used: None,
                sessions: Vec::new(),
            })
            .map_err(internal)?;
        web_credential_out(&stored)
    }

    fn credentials(&self, principal_id: Option<&str>) -> ControlResult<Vec<gunnar_proto::WebCredential>> {
        self.stores
            .auth()
            .web_credentials(principal_id)
            .map_err(internal)?
            .iter()
            .map(web_credential_out)
            .collect()
    }

    fn credential(&self, credential_id: &[u8]) -> ControlResult<Option<gunnar_grpc::StoredCredential>> {
        let Some(row) = self
            .stores
            .auth()
            .web_credential(&gunnar_grpc::webauthn::b64url(credential_id))
            .map_err(internal)?
        else {
            return Ok(None);
        };
        let public_key = hex::decode(&row.public_key_hex).map_err(|err| {
            ControlError::Internal(format!("web credential {} holds a key that is not hex: {err}", row.id))
        })?;
        Ok(Some(gunnar_grpc::StoredCredential {
            credential: web_credential_out(&row)?,
            public_key,
        }))
    }

    fn revoke_credential(&self, credential_id: &[u8]) -> ControlResult<Option<gunnar_proto::WebCredential>> {
        let removed = self
            .stores
            .auth()
            .revoke_web_credential(&gunnar_grpc::webauthn::b64url(credential_id))
            .map_err(internal)?;
        // Its session keys went with it.
        self.stores.mirror_identity();
        removed.as_ref().map(web_credential_out).transpose()
    }

    fn rename_credential(
        &self,
        credential_id: &[u8],
        label: &str,
    ) -> ControlResult<Option<gunnar_proto::WebCredential>> {
        self.stores
            .auth()
            .rename_web_credential(&gunnar_grpc::webauthn::b64url(credential_id), label)
            .map_err(internal)?
            .as_ref()
            .map(web_credential_out)
            .transpose()
    }

    fn create_invite(&self, invite: gunnar_grpc::NewInvite) -> ControlResult<gunnar_proto::Invite> {
        // A32-23: the identity table itself never stores an Admin-level invite, whoever asks.
        if invite.server_level == gunnar_proto::GrantLevel::Admin {
            return Err(ControlError::InvalidArgument(gunnar_grpc::service::access::NO_ADMIN_BY_INVITE.to_owned()));
        }
        let stored = self
            .stores
            .auth()
            .create_invite(gunnar_core::Invite {
                id: invite.id,
                principal_id: invite.principal_id,
                secret_hash: invite.secret_hash,
                created_by: invite.created_by,
                created: invite.created_at_unix_ms,
                expires: invite.expires_at_unix_ms,
                note: invite.note,
                server_level: level_in_opt(invite.server_level),
            })
            .map_err(internal)?;
        Ok(invite_out(&stored))
    }

    fn invites(&self) -> ControlResult<Vec<gunnar_proto::Invite>> {
        Ok(self
            .stores
            .auth()
            .invites()
            .map_err(internal)?
            .iter()
            .map(invite_out)
            .collect())
    }

    fn revoke_invite(&self, id: &str) -> ControlResult<Option<gunnar_proto::Invite>> {
        Ok(self
            .stores
            .auth()
            .revoke_invite(id)
            .map_err(internal)?
            .as_ref()
            .map(invite_out))
    }

    fn check_invite(&self, secret_hash: &str, now_unix_ms: i64) -> ControlResult<gunnar_grpc::InviteCheck> {
        Ok(match self.stores.auth().check_invite(secret_hash, now_unix_ms).map_err(internal)? {
            gunnar_core::InviteStanding::Valid(invite) => gunnar_grpc::InviteCheck::Valid(invite_out(&invite)),
            gunnar_core::InviteStanding::Used(_) => gunnar_grpc::InviteCheck::Used,
            gunnar_core::InviteStanding::Expired(_) => gunnar_grpc::InviteCheck::Expired,
            gunnar_core::InviteStanding::Unknown => gunnar_grpc::InviteCheck::Unknown,
        })
    }

    fn employer_of(&self, principal_id: &str) -> ControlResult<Option<String>> {
        self.stores.auth().employer_of(principal_id).map_err(internal)
    }

    fn sso(&self) -> Option<&dyn gunnar_grpc::sso::plane::SsoPlane> {
        Some(self)
    }

    fn web_login(&self, commit: gunnar_grpc::WebLoginCommit) -> ControlResult<gunnar_grpc::WebLoginOutcome> {
        let (principal, credential, key) = self
            .stores
            .auth()
            .web_login(
                &gunnar_grpc::webauthn::b64url(&commit.credential_id),
                commit.sign_count,
                commit.now_unix_ms,
                &commit.session_openssh,
                commit.expires_at_unix_ms,
            )
            .map_err(internal)?;
        self.stores.mirror_identity();
        // A console session was issued: the person's last sign-in (2026-10-21).
        self.stores.activity().signed_in(&principal.id, commit.now_unix_ms);
        Ok(gunnar_grpc::WebLoginOutcome {
            principal: principal_out(&principal),
            credential: web_credential_out(&credential)?,
            fingerprint: key.fingerprint_sha256,
        })
    }

    fn web_register(&self, registration: gunnar_grpc::WebRegistration) -> ControlResult<gunnar_grpc::WebRegistered> {
        let (credential, principal, level) = self
            .stores
            .auth()
            .register_web_credential(
                registration.invite_secret_hash.as_deref(),
                registration.principal_id.as_deref(),
                gunnar_core::WebCredential {
                    id: gunnar_grpc::webauthn::b64url(&registration.credential_id),
                    principal_id: String::new(),
                    label: registration.label,
                    public_key_hex: hex::encode(&registration.public_key),
                    sign_count: registration.sign_count,
                    created: registration.now_unix_ms,
                    last_used: None,
                    sessions: Vec::new(),
                },
                registration.now_unix_ms,
            )
            .map_err(internal)?;
        Ok(gunnar_grpc::WebRegistered {
            credential: web_credential_out(&credential)?,
            principal: principal_out(&principal),
            server_level: level.map(level_out).unwrap_or(GrantLevel::Unspecified),
        })
    }

    fn approve_machine_enrolment(
        &self,
        approval: gunnar_grpc::MachineApproval,
    ) -> ControlResult<gunnar_grpc::MachineApproved> {
        let step_up = approval
            .step_up
            .as_ref()
            .map(|(id, count)| (gunnar_grpc::webauthn::b64url(id), *count));
        let (principal, credential, created) = self
            .stores
            .auth()
            .approve_machine_credential(
                &approval.machine,
                level_in(approval.server_level)?,
                gunnar_core::WebCredential {
                    id: gunnar_grpc::webauthn::b64url(&approval.credential_id),
                    principal_id: String::new(),
                    label: approval.label,
                    public_key_hex: hex::encode(&approval.public_key),
                    sign_count: approval.sign_count,
                    created: approval.now_unix_ms,
                    last_used: None,
                    sessions: Vec::new(),
                },
                step_up.as_ref().map(|(id, count)| (id.as_str(), *count)),
                approval.now_unix_ms,
            )
            .map_err(internal)?;
        self.stores.mirror_identity();
        Ok(gunnar_grpc::MachineApproved {
            principal: principal_out(&principal),
            credential: web_credential_out(&credential)?,
            created,
        })
    }

    fn remove_principal(&self, principal_id: &str) -> ControlResult<(u32, u32)> {
        let before_keys = self.stores.auth().keys().map_err(internal)?.len();
        let before_grants = self.stores.auth().grants(None).map_err(internal)?.len();
        self.stores
            .auth()
            .remove_principal(principal_id)
            .map_err(internal)?;
        let after_keys = self.stores.auth().keys().map_err(internal)?.len();
        let after_grants = self.stores.auth().grants(None).map_err(internal)?.len();
        self.stores.mirror_identity();
        Ok((
            before_keys.saturating_sub(after_keys) as u32,
            before_grants.saturating_sub(after_grants) as u32,
        ))
    }

    fn add_key(
        &self,
        principal_id: &str,
        openssh_public_key: &str,
        _comment: &str,
        expires_at_unix_ms: Option<i64>,
        caller: &str,
        attestation: Option<gunnar_proto::SignedKeyAttestation>,
    ) -> ControlResult<PublicKey> {
        // The fingerprint the attestation must name is derived HERE from the
        // key line, never taken from the client: an attestation over a
        // fingerprint the client chose would attest to nothing the SSH listener
        // will ever match. Parsed once more inside `register_key`; that is one
        // parse of one line on a verb that runs when a person gets a machine.
        // An `age1pq1…` line is a quantum-safe encryption key (crypt-pq),
        // fingerprinted over its key bytes; anything else must be SSH.
        let adding = match gunnar_core::auth::pq_recipient_fingerprint(openssh_public_key) {
            Some(fingerprint) => fingerprint,
            None => gunnar_core::Fingerprint::of_key(
                &gunnar_core::auth::parse_public_key(openssh_public_key).map_err(internal)?,
            ),
        };
        let holders = self
            .stores
            .auth()
            .attesting_keys_of(principal_id)
            .map_err(internal)?;
        // **The key it already holds is already there** (L1, release-3 recharge): a restored
        // main holds the twin's key from the log, and the pairing door enrols it again. That
        // is no new key, so no attestation is owed — ALREADY_EXISTS, which callers tolerate.
        if holders.iter().any(|k| k.fingerprint == adding.as_str()) {
            return Err(ControlError::AlreadyExists(format!("principal {principal_id} already holds key {}", adding.as_str())));
        }
        let requirement = gunnar_core::key_attestation::Requirement::of(principal_id, caller, holders);
        let attestation = attestation.map(from_proto_attestation).transpose()?;
        gunnar_core::key_attestation::check(
            &requirement,
            principal_id,
            adding.as_str(),
            attestation.as_ref(),
        )
        .map_err(|problem| match problem {
            // Required and absent: the request is well formed and the table
            // says "not without their word" — a precondition, with the
            // command that satisfies it in the message.
            gunnar_core::AttestationProblem::Missing { .. } => {
                ControlError::FailedPrecondition(problem.to_string())
            }
            // Present and wrong: the caller's argument.
            _ => ControlError::InvalidArgument(problem.to_string()),
        })?;
        let registered = self
            .stores
            .auth()
            .register_key(
                principal_id,
                openssh_public_key,
                expires_at_unix_ms.map(|ms| ms as UnixMillis),
            )
            .map(|key| key_out(&key))
            .map_err(internal)?;
        self.stores.mirror_identity();
        Ok(registered)
    }

    fn revoke_key(&self, fingerprint: &str) -> ControlResult<()> {
        let parsed = gunnar_core::Fingerprint::parse(fingerprint)
            .map_err(|err| ControlError::InvalidArgument(err.to_string()))?;
        let revoked = self.stores.auth().revoke_key(&parsed).map_err(internal)?;
        self.stores.mirror_identity();
        match revoked {
            Some(_) => Ok(()),
            None => Err(ControlError::NotFound(format!("key {fingerprint}"))),
        }
    }

    fn list_keys(&self, principal_id: Option<&str>) -> ControlResult<Vec<PublicKey>> {
        let keys = match principal_id {
            Some(id) => self.stores.auth().keys_of(id).map_err(internal)?,
            None => self.stores.auth().keys().map_err(internal)?,
        };
        Ok(keys.iter().map(key_out).collect())
    }

    fn grant(
        &self,
        principal_id: &str,
        namespace: &str,
        repo: &str,
        level: GrantLevel,
    ) -> ControlResult<gunnar_proto::Grant> {
        let scope = scope_in(namespace, repo)?;
        let grant = Grant {
            principal: principal_id.to_owned(),
            scope,
            level: level_in(level)?,
        };
        self.stores
            .auth()
            .grant(grant)
            .map(|g| grant_out(&g))
            .map_err(internal)
    }

    fn revoke(&self, principal_id: &str, namespace: &str, repo: &str) -> ControlResult<()> {
        let scope = scope_in(namespace, repo)?;
        match self
            .stores
            .auth()
            .revoke_grant(principal_id, &scope)
            .map_err(internal)?
        {
            true => Ok(()),
            false => Err(ControlError::NotFound(format!(
                "grant for {principal_id} on {scope}"
            ))),
        }
    }

    fn list_grants(
        &self,
        principal_id: Option<&str>,
        namespace: Option<&str>,
        repo: Option<&str>,
    ) -> ControlResult<Vec<gunnar_proto::Grant>> {
        Ok(self
            .stores
            .auth()
            .grants(principal_id)
            .map_err(internal)?
            .iter()
            .map(grant_out)
            .filter(|g| namespace.is_none_or(|want| want == g.namespace))
            .filter(|g| repo.is_none_or(|want| want == g.repo))
            .collect())
    }

    // ── groups (punkt 9) ───────────────────────────────────────────────────

    fn add_group_member(
        &self,
        group_id: &str,
        member_id: &str,
        signed: gunnar_proto::SignedMembershipEvent,
    ) -> ControlResult<u64> {
        let signed = self.verify_membership_event(
            signed,
            group_id,
            member_id,
            gunnar_core::MembershipAction::Add,
        )?;
        // Apply to the live table first: if the typecheck (group exists and is
        // a group, member exists) fails, nothing is signed into the log. A
        // membership event in the log names a change that was actually made.
        self.stores
            .auth()
            .add_to_group(group_id, member_id)
            .map_err(internal)?;
        self.append_membership_event(&signed)
    }

    fn remove_group_member(
        &self,
        group_id: &str,
        member_id: &str,
        signed: gunnar_proto::SignedMembershipEvent,
    ) -> ControlResult<(bool, u64)> {
        let signed = self.verify_membership_event(
            signed,
            group_id,
            member_id,
            gunnar_core::MembershipAction::Remove,
        )?;
        let was_member = self
            .stores
            .auth()
            .remove_from_group(group_id, member_id)
            .map_err(internal)?;
        // Recorded even when it was a no-op: the attempt to remove is evidence
        // too, and a reader folding the log sees a remove of a non-member leave
        // the set unchanged, exactly as `remove_from_group` did.
        let index = self.append_membership_event(&signed)?;
        Ok((was_member, index))
    }

    fn membership_events(
        &self,
        group_id: Option<&str>,
    ) -> ControlResult<Vec<gunnar_proto::SignedMembershipEvent>> {
        Ok(self
            .membership_log_events()?
            .into_iter()
            .filter(|signed| group_id.is_none_or(|g| signed.event.group == g))
            .map(to_proto_membership)
            .collect())
    }

    fn list_group_members(&self, group_id: &str) -> ControlResult<Vec<Principal>> {
        // The group must exist and be a group, so "no members" and "no such
        // group" cannot be confused into the same empty list.
        let auth = self.stores.auth();
        match auth.principal(group_id).map_err(internal)? {
            Some(p) if p.kind == PrincipalKind::Group => {}
            Some(_) => {
                return Err(ControlError::InvalidArgument(format!(
                    "principal \"{group_id}\" is not a group"
                )))
            }
            None => return Err(ControlError::NotFound(format!("group {group_id}"))),
        }
        // Membership is stored by member id; resolve each to a full principal so
        // a UI can show names and kinds, not bare ids.
        let mut members = Vec::new();
        for id in auth.members_of(group_id).map_err(internal)? {
            if let Some(p) = auth.principal(&id).map_err(internal)? {
                members.push(principal_out(&p));
            }
        }
        Ok(members)
    }

    // ── policy ─────────────────────────────────────────────────────────────

    fn get_protection(
        &self,
        path: &RepoPath,
        ref_pattern: Option<&str>,
    ) -> ControlResult<Vec<BranchProtection>> {
        let (repo, _) = self.open(path)?;
        let config = self.policy_of(&repo)?;
        Ok(config
            .protection
            .iter()
            .filter(|rule| ref_pattern.is_none_or(|want| rule.pattern.as_str() == want))
            .map(protection_out)
            .collect())
    }

    /// **Write one protection rule**, replacing any rule with the same pattern.
    ///
    /// Two things this deliberately does not do, both of them places where the
    /// proto and `gunnar_policy::ProtectionRule` do not line up. Getting either
    /// wrong silently is how an operator ends up with a policy they did not
    /// write:
    ///
    /// * **The per-pattern byte and object limits are refused, not dropped.**
    ///   `BranchProtection` carries `max_object_bytes` and
    ///   `max_objects_per_push` per rule; `gunnar-policy`'s `LimitPolicy` is
    ///   **repository-wide**. Storing a per-rule number into a repository-wide
    ///   limit would apply it to references the caller never named, and
    ///   ignoring it would report success for a limit that is not enforced.
    ///   Both are worse than saying so.
    /// * **`allow_create` and `ancestry_budget` survive a round trip.** They
    ///   have no proto field, so a rule written over gRPC would otherwise reset
    ///   whatever a `gunnar-policy.json` had set — an edit through the console
    ///   quietly widening a rule it did not display. The existing rule is read
    ///   first and only the fields the proto carries are overwritten.
    fn set_protection(
        &self,
        path: &RepoPath,
        protection: BranchProtection,
    ) -> ControlResult<BranchProtection> {
        let (repo, _) = self.open(path)?;
        if protection.max_object_bytes != 0 || protection.max_objects_per_push != 0 {
            return Err(ControlError::InvalidArgument(
                "max_object_bytes and max_objects_per_push are per-rule in the protocol and \
                 repository-wide in this server's policy engine, so a value here would apply to \
                 references this rule does not name. Leave them 0 and set the repository's \
                 limits in its policy document."
                    .to_owned(),
            ));
        }
        let pattern = gunnar_policy::RefPattern::new(protection.ref_pattern.clone())
            .map_err(|err| ControlError::InvalidArgument(err.to_string()))?;

        let mut config = self.policy_of(&repo)?;
        // Start from the rule that is there, so the two fields the proto cannot
        // express keep their values.
        let mut rule = config
            .protection
            .iter()
            .find(|rule| rule.pattern == pattern)
            .cloned()
            .unwrap_or_else(|| {
                gunnar_policy::ProtectionRule::protect(pattern.as_str())
                    .expect("the pattern was compiled one line above")
            });
        rule.pattern = pattern;
        rule.allow_force_push = protection.allow_force_push;
        rule.allow_delete = protection.allow_delete;
        rule.require_signature = protection.require_signature;
        // Empty in the proto means "anybody"; `None` means the same in the
        // policy. A `Some(vec![])` would mean **nobody may push**, which is a
        // very different rule to arrive at by accident.
        rule.allowed_principals = if protection.allowed_principal_ids.is_empty() {
            None
        } else {
            Some(protection.allowed_principal_ids.clone())
        };
        rule.forbid_self_approval = protection.forbid_self_approval;
        rule.required_approvals = protection.required_approvals;

        config
            .protection
            .retain(|other| other.pattern != rule.pattern);
        config.protection.push(rule.clone());
        self.store_policy(&repo, &config)?;
        Ok(protection_out(&rule))
    }

    fn delete_protection(&self, path: &RepoPath, ref_pattern: &str) -> ControlResult<()> {
        let (repo, _) = self.open(path)?;
        let mut config = self.policy_of(&repo)?;
        let before = config.protection.len();
        config
            .protection
            .retain(|rule| rule.pattern.as_str() != ref_pattern);
        if config.protection.len() == before {
            return Err(ControlError::NotFound(format!(
                "no protection rule for {ref_pattern} in {path}"
            )));
        }
        self.store_policy(&repo, &config)
    }

    fn get_ref_name_policy(&self, path: &RepoPath) -> ControlResult<RefNamePolicy> {
        let (repo, _) = self.open(path)?;
        let config = self.policy_of(&repo)?;
        Ok(ref_name_policy_out(&config.ref_names))
    }

    fn set_ref_name_policy(
        &self,
        path: &RepoPath,
        policy: RefNamePolicy,
    ) -> ControlResult<RefNamePolicy> {
        let (repo, _) = self.open(path)?;
        let compiled = gunnar_policy::RefNamePolicy::new(
            policy.allow_patterns.clone(),
            policy.deny_patterns.clone(),
        )
        .map_err(|err| ControlError::InvalidArgument(err.to_string()))?;
        let mut config = self.policy_of(&repo)?;
        config.ref_names = compiled.clone();
        self.store_policy(&repo, &config)?;
        Ok(ref_name_policy_out(&compiled))
    }

    // ── forge (roadmap phase 1) ────────────────────────────────────────────
    //
    // **Real**, over the same append-only log `gunnar forge` writes. There is
    // one forge log per server and the events carry their repository, so the
    // gRPC surface and the CLI are two doors onto one file rather than two
    // stores that can disagree (one implementation).

    fn forge_append(&self, event: gunnar_proto::SignedForgeEvent) -> ControlResult<u64> {
        let signed = from_proto_event(event)?;

        // **The signature is checked before anything is written.** A review log
        // that took an event it could not verify would be a log of claims, and
        // the point of the whole design is that it is a log of evidence. The
        // key must already be in the ACL table for the same reason: a signature
        // by a key gunnar does not know is not something a later reader could
        // check at all.
        let key = self
            .stores
            .auth()
            .signing_keys()
            .map_err(|err| ControlError::Unavailable(format!("{err:#}")))?
            .into_iter()
            .find(|row| row.fingerprint_sha256 == signed.key_fingerprint)
            .ok_or_else(|| {
                ControlError::InvalidArgument(format!(
                    "{} is not registered on this server, so nobody reading this event later \
                     could check its signature",
                    signed.key_fingerprint
                ))
            })?;
        // **The key must be the claimed actor's own.** The signature proves
        // which key spoke; the table's `principal_id` says whose voice that
        // is, and an event attributed to one principal signed by another's
        // key is a claim filed in somebody else's name — exactly what the
        // service layer's actor==caller check refuses, re-checked here at the
        // seam because this door can also be reached without a connection.
        if key.principal_id != signed.event.actor {
            return Err(ControlError::InvalidArgument(format!(
                "this event is attributed to {:?} and is signed by {}, which is {:?}'s key; \
                 an approval is the actor's own word, so it must carry the actor's own \
                 signature",
                signed.event.actor, signed.key_fingerprint, key.principal_id
            )));
        }
        let public = gunnar_core::ssh_key::PublicKey::from_openssh(&key.openssh)
            .map_err(|err| ControlError::Internal(format!("stored key is unreadable: {err}")))?;
        gunnar_core::forge::verify_event(&signed, &public)
            .map_err(|problem| ControlError::InvalidArgument(format!("{problem}")))?;

        // **The subject must exist and be open**, and which subject that is
        // depends on the kind. A review event names a pull request the record
        // owns; an issue event names an issue THIS log owns. Both refuse an
        // event on something merged, closed or never opened — evidence about
        // nothing — but they ask different authorities, so they branch here.
        let (namespace, name) = signed.event.repo.split_once('/').ok_or_else(|| {
            ControlError::InvalidArgument(format!(
                "`repo` must be `<namespace>/<repo>`, got {:?}",
                signed.event.repo
            ))
        })?;
        let path = RepoPath::new(namespace, name);
        match &signed.event.event {
            // An opening creates the issue and so has no precondition: there is
            // nothing yet to be open. Its number is the fold's to assign.
            gunnar_core::Event::IssueOpened { .. } => {}
            // A comment or close names an issue by number. The issue is folded
            // from this same log — there is no record behind it — so the check
            // is against the fold rather than `get_pull`.
            gunnar_core::Event::IssueCommented { .. } | gunnar_core::Event::IssueClosed { .. } => {
                let repo_events: Vec<gunnar_core::ForgeEvent> = self
                    .forge_events()?
                    .into_iter()
                    .filter(|e| e.event.repo == signed.event.repo)
                    .map(|e| e.event)
                    .collect();
                match gunnar_core::forge::fold_issue(signed.event.pull, &repo_events) {
                    None => {
                        return Err(ControlError::FailedPrecondition(format!(
                            "no issue #{} in {}: nobody has opened one, so an event on it is \
                             evidence about nothing",
                            signed.event.pull, signed.event.repo
                        )));
                    }
                    Some(issue) if !issue.open => {
                        return Err(ControlError::FailedPrecondition(format!(
                            "issue #{} in {} is closed; an event on it cannot change what has \
                             already happened",
                            signed.event.pull, signed.event.repo
                        )));
                    }
                    Some(_) => {}
                }
            }
            // A review event names a pull request, whose record is the authority
            // for whether it exists and is open.
            gunnar_core::Event::Commented { .. }
            | gunnar_core::Event::Approved { .. }
            | gunnar_core::Event::Rejected { .. } => {
                let record = self.get_pull(&path, signed.event.pull)?;
                if record.state != gunnar_proto::PullRequestState::Open as i32 {
                    return Err(ControlError::FailedPrecondition(format!(
                        "pull request #{} in {} is not open; a review event cannot change what \
                         has already happened",
                        signed.event.pull, signed.event.repo
                    )));
                }
            }
        }

        let log = self.stores.forge_log();
        let mut line = serde_json::to_string(&signed)
            .map_err(|err| ControlError::Internal(format!("encoding the event: {err}")))?;
        line.push('\n');
        let _framed = gunnar_core::txlog::sink::append_line(log.records_path(), line.trim_end_matches('\n'))
            .map_err(|err| ControlError::Unavailable(format!("framing the line in the transaction log: {err}")))?;
        use std::io::Write as _;
        let mut file = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(log.records_path())
            .map_err(|err| ControlError::Unavailable(format!("opening the forge log: {err}")))?;
        file.write_all(line.as_bytes()).map_err(|err| {
            ControlError::Unavailable(format!("appending to the forge log: {err}"))
        })?;
        // The index it landed at, counted after the write so it names this
        // event and not the one before it.
        let count = self
            .stores
            .forge_log()
            .lines_of()
            .map_err(|err| ControlError::Unavailable(format!("{err:#}")))?
            .len() as u64;
        Ok(count.saturating_sub(1))
    }

    fn forge_review(
        &self,
        repo: &str,
        pull: u64,
    ) -> ControlResult<(
        gunnar_proto::ReviewState,
        Vec<gunnar_proto::SignedForgeEvent>,
    )> {
        let all = self.forge_events()?;
        let mine: Vec<gunnar_core::ForgeEvent> = all
            .iter()
            .filter(|signed| signed.event.repo == repo)
            .map(|signed| signed.event.clone())
            .collect();
        let state = gunnar_core::forge::fold(pull, &mine);
        let events = all
            .iter()
            .filter(|signed| signed.event.repo == repo && signed.event.pull == pull)
            .cloned()
            .map(to_proto_event)
            .collect();
        Ok((self.review_state(repo, &state, &all)?, events))
    }

    fn forge_reviews(&self, repo: &str) -> ControlResult<Vec<gunnar_proto::ReviewState>> {
        let all = self.forge_events()?;
        let mine: Vec<gunnar_core::ForgeEvent> = all
            .iter()
            .filter(|signed| signed.event.repo == repo)
            .map(|signed| signed.event.clone())
            .collect();
        let mut numbers: Vec<u64> = mine.iter().map(|event| event.pull).collect();
        numbers.sort_unstable();
        numbers.dedup();
        let mut out = Vec::new();
        for pull in numbers {
            let state = gunnar_core::forge::fold(pull, &mine);
            out.push(self.review_state(repo, &state, &all)?);
        }
        Ok(out)
    }

    fn forge_issue(
        &self,
        repo: &str,
        number: u64,
    ) -> ControlResult<Option<(gunnar_proto::IssueState, Vec<gunnar_proto::SignedForgeEvent>)>> {
        let all = self.forge_events()?;
        let mine: Vec<gunnar_core::ForgeEvent> = all
            .iter()
            .filter(|signed| signed.event.repo == repo)
            .map(|signed| signed.event.clone())
            .collect();
        let Some(issue) = gunnar_core::forge::fold_issue(number, &mine) else {
            return Ok(None);
        };
        // The whole thread, in log order: the opening, every comment, and the
        // close. An `IssueOpened` carries `pull == 0`, so it is matched by
        // position — the Nth opening is issue N — while comments and closes name
        // their number directly, exactly as the fold reads them.
        let mut opened_seen = 0u64;
        let events = all
            .iter()
            .filter(|signed| {
                if signed.event.repo != repo {
                    return false;
                }
                match &signed.event.event {
                    gunnar_core::Event::IssueOpened { .. } => {
                        opened_seen += 1;
                        opened_seen == number
                    }
                    gunnar_core::Event::IssueCommented { .. }
                    | gunnar_core::Event::IssueClosed { .. } => signed.event.pull == number,
                    _ => false,
                }
            })
            .cloned()
            .map(to_proto_event)
            .collect();
        Ok(Some((issue_state(repo, &issue), events)))
    }

    fn forge_issues(&self, repo: &str) -> ControlResult<Vec<gunnar_proto::IssueState>> {
        let mine: Vec<gunnar_core::ForgeEvent> = self
            .forge_events()?
            .into_iter()
            .filter(|signed| signed.event.repo == repo)
            .map(|signed| signed.event)
            .collect();
        Ok(gunnar_core::forge::fold_issues(&mine)
            .iter()
            .map(|issue| issue_state(repo, issue))
            .collect())
    }

    // ── admin ──────────────────────────────────────────────────────────────

    /// **The two numbers an operator is surprised by if nobody reports them.**
    ///
    /// Tombstoned bytes, because a customer who deletes a repository and sees
    /// no change in their usage will call the bill wrong; and replication,
    /// because every configured standby on this project received NOTHING from
    /// `e31ab8f4` until 2026-08-30 and the only thing that said so was a log
    /// line nobody was tailing.
    fn stats_extras(&self) -> ControlResult<gunnar_grpc::seam::StatsExtras> {
        let tombstones = self.stores.tombstones().unwrap_or_default();
        let report = self.replication.report();
        // The tenants row, off the same slot the band reads (one implementation). A build
        // without `metered`, or a metered one with no slot, counts nothing.
        #[allow(unused_mut)]
        let mut tenants = crate::dashboard::TenantCounts::default();
        #[cfg(feature = "metered")]
        if let Some(slot) = &self.entitlement {
            tenants = slot.counts();
        }
        Ok(gunnar_grpc::seam::StatsExtras {
            tombstoned_repos: tombstones.len() as u64,
            tombstoned_bytes: tombstones.iter().map(|row| row.bytes).sum(),
            replication_configured: report.configured,
            replication_enqueued: report.enqueued,
            replication_synced: report.synced,
            replication_failed: report.failed,
            replication_bus_gaps: report.bus_gaps,
            replication_refs_total: report.refs.total,
            replication_refs_unmirrored: report.refs.unmirrored,
            standbys: report
                .standbys
                .into_iter()
                .map(|row| gunnar_proto::StandbyStatus {
                    // The word the console badge prints, decided once here
                    // (one implementation) rather than re-derived from the booleans by
                    // every surface that draws a standby.
                    verdict: row.verdict().word().to_owned(),
                    name: row.name,
                    remote: row.remote,
                    pending: row.pending,
                    consecutive_failures: row.consecutive_failures,
                    last_error: row.last_error,
                    last_success_unix_ms: row.last_success_unix_ms,
                    needs_full_resync: row.needs_full_resync,
                    stale: row.stale,
                })
                .collect(),
            tenants_paid: tenants.paid,
            tenants_grace: tenants.grace,
            tenants_suspended: tenants.suspended,
        })
    }

    fn counts(&self) -> ControlResult<ControlCounts> {
        let (namespaces, repos) = self.stores.catalog().counts().map_err(internal)?;
        let (principals, keys, grants) = self.stores.auth().counts().map_err(internal)?;
        Ok(ControlCounts {
            namespaces: namespaces as u64,
            repos: repos as u64,
            principals: principals as u64,
            keys: keys as u64,
            grants: grants as u64,
        })
    }

    fn verify_chain(
        &self,
        request: &gunnar_proto::VerifyChainRequest,
    ) -> ControlResult<gunnar_proto::VerifyChainResponse> {
        // The SAME walk `gunnar verify` runs (one implementation): `crate::verify` is the
        // one implementation, and this method is a projection of its `Chain`
        // onto the wire. No verdict is computed here.
        let target = match request.target.as_str() {
            "" => None,
            spec => Some(spec),
        };
        let chain = if !request.artifact_sha256.is_empty() {
            crate::verify::verify_artifact(&self.stores, self, &request.artifact_sha256, target)
        } else {
            let Some(repo) = &request.repo else {
                return Err(ControlError::InvalidArgument(
                    "name a repository, or an artifact_sha256 to start from".to_owned(),
                ));
            };
            let rev = match request.rev.as_str() {
                "" => "HEAD",
                rev => rev,
            };
            crate::verify::verify(&self.stores, self, repo, rev, target)
        }
        // A walk that cannot START is a refusal with the reason — a missing
        // repository, a rev that names nothing, a malformed target. It is
        // never an empty chain: six grey rows would render as "merely
        // incomplete", which is a pass a console reader would believe.
        .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))?;
        Ok(chain.to_proto())
    }

    fn blame(
        &self,
        path: &RepoPath,
        rev: &str,
        file: &str,
    ) -> ControlResult<gunnar_proto::BlameResponse> {
        // The SAME walk `gunnar blame` runs (one implementation): `crate::blame::blame` is
        // the one implementation, routed here through the store handle the
        // running server already holds (`&self.stores`) — never a fresh
        // `ServerStores::open`, which would fight the server's exclusive lock.
        // That is the whole of it: down the verb takes the lock and cannot
        // run while a `serve` holds it; here it runs against the open store.
        let rev = if rev.is_empty() { "HEAD" } else { rev };
        let rows = crate::blame::blame(&self.stores, self, path, rev, file)
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))?;
        Ok(gunnar_proto::BlameResponse {
            lines: rows
                .into_iter()
                .map(|row| gunnar_proto::BlameLine {
                    commit: row.commit.to_hex().to_string(),
                    author: row.author,
                    line: row.line,
                })
                .collect(),
        })
    }

    fn search(
        &self,
        path: &RepoPath,
        rev: &str,
        pattern: &str,
        max_file_bytes: u64,
        max_matches: u32,
    ) -> ControlResult<gunnar_proto::SearchResponse> {
        // As `blame` above: one implementation (`crate::search::search`),
        // walked live against the running server's open store. A zero ceiling
        // means the module's default rather than "no files" / "no matches".
        let rev = if rev.is_empty() { "HEAD" } else { rev };
        let defaults = crate::search::Limits::default();
        let limits = crate::search::Limits {
            max_file_bytes: if max_file_bytes == 0 {
                defaults.max_file_bytes
            } else {
                max_file_bytes
            },
            max_matches: if max_matches == 0 {
                defaults.max_matches
            } else {
                max_matches as usize
            },
        };
        let hits = crate::search::search(&self.stores, self, path, rev, pattern, limits)
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))?;
        Ok(gunnar_proto::SearchResponse {
            matches: hits
                .into_iter()
                .map(|hit| gunnar_proto::SearchMatch {
                    path: hit.path,
                    line_number: hit.line_number as u32,
                    line: hit.line,
                })
                .collect(),
        })
    }

    /// **The PKI document, read** (`Admin.IssuerInfo`) — the ONE
    /// implementation, and the same document `gunnar issuer show` prints.
    ///
    /// Through [`ServerStores::pki_readonly`] and never `pki()`: the handle
    /// this opens installs a secret store that refuses every call, so the
    /// capability to sign is absent from the value rather than absent from
    /// whoever remembered not to call `create` on it. A future edit of this
    /// body cannot mint with it.
    ///
    /// An unreadable document is [`ControlError::Unavailable`] and not an
    /// empty answer, for the reason that error exists: "this box has no
    /// issuer" and "I could not find out" are different facts, and the first
    /// one invites an operator to mint over a CA their whole fleet pins.
    fn issuer_info(&self) -> ControlResult<gunnar_proto::IssuerInfoResponse> {
        let pki = self.stores.pki_readonly().map_err(|err| {
            ControlError::Unavailable(format!("the PKI document could not be opened: {err:#}"))
        })?;
        // The SAME reader `gunnar issuer show` prints from (one
        // implementation): there is no second assembly of this answer, so the
        // wire and the disk cannot describe one document differently.
        crate::admin::issuer_document(&pki).map_err(|err| {
            ControlError::Unavailable(format!("the PKI document could not be read: {err:#}"))
        })
    }

    fn setting(&self, name: &str) -> ControlResult<Option<Vec<u8>>> {
        self.stores.settings().get(name).map_err(internal)
    }

    fn set_setting(&self, name: &str, value: &[u8]) -> ControlResult<Option<Vec<u8>>> {
        self.stores.settings().set(name, value).map_err(internal)
    }

    /// **The audit chain, read as a shape** (`Admin.AuditTrail`, lane T11).
    ///
    /// Opened fresh from [`ServerStores::audit_path`] rather than reaching for
    /// the live `AuditChain` the gate holds: the gate's copy carries an
    /// in-memory tip and would answer from it, and the question being asked is
    /// about the FILE — whether it still holds what gunnar wrote. So this
    /// re-reads and re-verifies, which is also what makes `verified: false`
    /// mean something.
    ///
    /// A chain that will not open is **not** an error: it is `present: false`
    /// with `why`, because "this box has no durable trail" is exactly the
    /// answer an operator needs from a box whose disk filled or whose trail
    /// somebody has edited, and turning it into a failed RPC would hide it.
    /// The one thing never done here is to answer an empty chain, which would
    /// read as "nothing has happened" instead of "I hold no record".
    fn audit_trail(&self, at_seq: u64) -> ControlResult<gunnar_proto::AuditTrailResponse> {
        let path = self.stores.audit_path();
        // Whether the trail is replicated is a property of this BOX, not of
        // the open: a twin and a box mid-restore originate nothing and keep a
        // per-box trail, and on a primary this is false only when the server
        // already shouted about it at start-up.
        let replicated = !self.stores.is_twin()
            && !crate::twin::is_restoring(self.stores.root())
            && gunnar_core::txlog::sink::log_for(&path)
                .is_some_and(|(_, rel)| rel == gunnar_core::txlog::AUDIT_REL);
        let mut out = gunnar_proto::AuditTrailResponse {
            present: false,
            entries: 0,
            tip: String::new(),
            verified: false,
            replicated,
            hash_at_seq: String::new(),
            why: String::new(),
            tip_seq: 0,
        };
        let chain = match gunnar_core::AuditChain::open(&path) {
            Ok(chain) => chain,
            Err(err) => {
                out.why = format!("{err}");
                return Ok(out);
            }
        };
        let entries = match chain.entries() {
            Ok(entries) => entries,
            Err(err) => {
                out.why = format!("{err}");
                return Ok(out);
            }
        };
        out.present = true;
        out.entries = entries.len() as u64;
        if let Some(last) = entries.last() {
            out.tip.clone_from(&last.hash);
            // Reported, not computed from the count: see the proto comment.
            out.tip_seq = last.seq;
        }
        match chain.verify() {
            Ok(_) => out.verified = true,
            Err(err) => out.why = format!("{err}"),
        }
        if at_seq != 0 {
            // `seq` is dense from 0, so the entry with this seq is at this
            // index — but it is LOOKED UP by `seq` rather than indexed, because
            // a chain that has been cut is exactly the case this is asked in
            // and an index would answer confidently with the wrong entry.
            match entries.iter().find(|e| e.seq == at_seq) {
                Some(e) => out.hash_at_seq = e.hash.clone(),
                None => {
                    let sep = if out.why.is_empty() { "" } else { "; " };
                    out.why = format!(
                        "{}{sep}this trail holds no entry at seq {at_seq} (it holds {} entries)",
                        out.why,
                        entries.len()
                    );
                }
            }
        }
        Ok(out)
    }

    fn storage_info(&self, path: Option<&RepoPath>) -> ControlResult<StorageInfoResponse> {
        let repos = match path {
            Some(path) => vec![self.open(path)?.0],
            None => self.stores.catalog().list(None).map_err(internal)?,
        };
        let mut total_hot = 0u64;
        let mut total_explode = 0u64;
        let mut total_budget = 0u64;
        // One registry walk for every open store, rather than one per
        // repository: `Admin.StorageInfo` over a server with a thousand
        // repositories is already an unbounded recursive `stat` walk
        // (`control_plane_starvation`), and adding a per-repository lookup
        // inside that loop would make it two.
        let bands: std::collections::HashMap<std::path::PathBuf, crate::storage::ExplodeBand> =
            self.stores.engine().explode_use().into_iter().collect();
        let mut out = Vec::new();
        for repo in repos {
            let store = self.stores.repo_store(&repo).map_err(|err| {
                ControlError::Internal(format!("opening the repository's stores: {err:#}"))
            })?;
            let (loose, _objects_dir) = object_dir_stats(store.git_dir());
            // `hot_bytes` was `object_dir_stats`'s byte count until 2026-09-04
            // — a walk of `<git_dir>/objects`, which the znippy engine does not
            // have (its store is `<git_dir>/gunnar-git.znippy/`), so every
            // appliance repository reported 0 hot bytes. It is now the same
            // per-file walk `Usage.Read` bills from (`repo_bytes`, one implementation):
            // the whole directory minus LFS, which is what the proto comment
            // on `RepoStorage.hot_bytes` always said it was.
            let bytes = repo_bytes(store.git_dir()).hot();
            let refs = store.serve().refs().map_err(store_error)?.len() as u64;
            total_hot += bytes;
            // A repository nobody has opened has no band to report, and zero is
            // the truth of that: the cache is per open store and an unopened
            // one is holding nothing this process can name.
            let band = bands.get(store.git_dir()).copied().unwrap_or_default();
            total_explode += band.used();
            total_budget += band.budget;
            out.push(RepoStorage {
                repo: Some(RepoPath::new(&repo.namespace, &repo.name)),
                hash_kind: hash_kind(repo.hash_kind) as i32,
                loose_object_count: loose,
                hot_bytes: bytes,
                // **Not a measurement.** The znippy engine keeps ONE archive
                // per repository (counted in `hot_bytes` with the rest of the
                // directory) and has no cold tier; the two fields stay 0 and
                // `cold_measured: false` says the 0 is not a reading, so a
                // console shows N/A rather than "0 B" (owner, 2026-09-28).
                cold_bytes: 0,
                cold_object_count: 0,
                cold_measured: false,
                last_repack_at_unix_ms: 0,
                ref_count: refs,
                explode_bytes: band.used(),
                explode_budget_bytes: band.budget,
                explode_evicted_bytes: band.evicted_bytes,
            });
        }
        // The backend strings report what THIS process is running, not a plan
        // and not what it could have been built with. There is no "none" arm
        // any more: `gunnar-server` refuses to compile without an engine, so
        // the engine-free binary that used to answer here cannot be built.
        //
        // Both strings come off the same `Engine`, because one engine answers
        // for objects *and* refs — they were two strings when they were two
        // backends, and reporting two different ones now would be a shape the
        // storage contract no longer has.
        let engine = self.stores.engine();
        let (object_backend, ref_backend) =
            (engine.describe(), engine.describe());
        // **Tombstoned bytes are reported here or nowhere.** They are in
        // none of the `repos` rows above, because a tombstoned repository has
        // no catalog row — which is exactly how the measured 25 GB stayed
        // invisible. They are still on the disk and still on the account.
        let tombstones = self.stores.tombstones().unwrap_or_default();
        let total_tombstoned_bytes = tombstones.iter().map(|row| row.bytes).sum();
        let tombstoned = tombstones
            .into_iter()
            .map(|row| gunnar_proto::TombstonedRepo {
                repo: Some(RepoPath {
                    namespace: row.path.namespace().to_owned(),
                    repo: row.path.name().to_owned(),
                }),
                bytes: row.bytes,
                deleted_at_unix_ms: row.tombstone.deleted_at_unix_ms,
                purge_after_unix_ms: row.tombstone.purge_after_unix_ms.unwrap_or_default(),
            })
            .collect();
        Ok(StorageInfoResponse {
            object_backend,
            ref_backend,
            // The same engine, in parts (name, description, source repository).
            engine: Some(engine.report()),
            total_hot_bytes: total_hot,
            // Not a measurement; see `cold_measured` on each row.
            total_cold_bytes: 0,
            cold_measured: false,
            repos: out,
            total_explode_bytes: total_explode,
            total_explode_budget_bytes: total_budget,
            total_tombstoned_bytes,
            tombstoned,
            // **The storage reality of the machine.** The appliance has no
            // shell, so this call is the only way anyone ever sees which disks
            // became `/data`, what was rejected and why, or whether the
            // metadata mirror is genuinely on another spindle.
            reality: Some(self.stores.storage_reality()),
        })
    }

    /// **"If a tenant's cap rose to N bytes, could you serve it?"** —
    /// `Admin.Capacity`, the question monetize must ask before it buys a disk.
    ///
    /// Three measurements, none of them new (one implementation):
    ///
    /// * the bytes are the disk gate's own `statvfs` — the SAME one a push is
    ///   refused under, so the capacity a seller is quoted and the floor a
    ///   push dies at cannot disagree;
    /// * what the tenant already holds is [`Self::usage`]'s `pack_bytes` —
    ///   the meter `caps["pack_bytes"]` caps, so the delta is computed against
    ///   the number the quota is actually about;
    /// * whether the set can grow is the header band's `/proc/mounts` + md
    ///   sysfs read;
    /// * the box's cores and RAM — product scope, the ceilings a seller may
    ///   sell up to — are [`crate::capacity::MachineFacts::measure`]: the
    ///   `available_parallelism` the budgets use and the band's
    ///   `/proc/meminfo`, absent (never 0) when unreadable.
    ///
    /// [`crate::capacity::answer`] decides over them, and is pure so that the
    /// SEALED arm can be driven on a developer box where gunnar is never PID 1.
    ///
    /// **No gate wired is `Unimplemented`, not a default floor.** A plane
    /// built without [`Self::with_headroom`] does not know the `--disk-floor`
    /// in force, and quoting a seller against a floor this server is not
    /// enforcing is worse than declining to answer.
    fn capacity(
        &self,
        request: &gunnar_proto::CapacityRequest,
    ) -> ControlResult<gunnar_proto::CapacityResponse> {
        let Some(gate) = self.headroom.as_ref() else {
            return Err(ControlError::Unimplemented(
                "Admin.Capacity (no disk-headroom gate is wired on this control plane, so the \
                 --disk-floor in force is unknown and no quote can be made against it)",
            ));
        };
        // A named namespace must EXIST. `usage` is NotFound for one the
        // catalog does not hold, and that error is propagated rather than
        // swallowed into "it holds nothing": quoting a raise against the wrong
        // tenant's zero is how a seller oversells.
        let held_bytes = if request.namespace.is_empty() {
            0
        } else {
            self.usage(Some(&request.namespace))?
                .first()
                .map(|row| row.pack_bytes)
                .unwrap_or(0)
        };
        let root = gate.root().to_path_buf();
        let mut answer = crate::capacity::answer(&crate::capacity::Question {
            room: gate.headroom().map_err(|err| err.to_string()),
            floor_spec: gate.floor().to_string(),
            requested_bytes: request.requested_bytes,
            held_bytes,
            namespace: request.namespace.clone(),
            growth: crate::capacity::GrowthFacts::measure(&root),
            machine: crate::capacity::MachineFacts::measure(),
            root: root.clone(),
        });
        // Every disk, only when asked: a seller's quote never pays for the
        // mount-table walk (`CapacityRequest.disks`).
        if request.disks {
            let slow = self.stores.slow();
            let serialdat = std::path::PathBuf::from(slow.serialdat());
            let mut disks = crate::capacity::measure_disks(&root, Some(&serialdat), gate.floor());
            // What is on /serialdat, thing by thing — only the paths that
            // actually live under it (a directory configured elsewhere is not
            // this mount's).
            let log = slow.path_of(crate::slow::LOG_DIR);
            let known: Vec<(&str, std::path::PathBuf)> = [
                ("metadata copy", slow.path_of(crate::slow::META_DIR)),
                ("crash record", slow.path_of(crate::slow::CRASH_DIR)),
                ("audit trail", log.join("audit-chain.jsonl")),
                ("logs", log),
                ("grow journal", serialdat.join("grow-journal")),
                ("repository mirror", serialdat.join(crate::slow::REPOS_DIR)),
            ]
            .into_iter()
            .filter(|(_, path)| path.starts_with(&serialdat))
            .collect();
            let used = disks
                .mounts
                .iter()
                .find(|m| m.labels.iter().any(|l| l == "serialdat") && m.measured)
                .map(|m| m.used_bytes);
            if disks.mounts.iter().any(|m| m.labels.iter().any(|l| l == "serialdat")) {
                disks.serialdat = crate::capacity::serialdat_breakdown(&known, used);
            }
            answer.disks = Some(disks);
        }
        Ok(answer)
    }

    // ── the runtime data-set growth (`crate::grow`) ─────────────────────

    fn grow_start(
        &self,
        request: &gunnar_proto::GrowStartRequest,
    ) -> ControlResult<gunnar_proto::GrowStatusResponse> {
        self.grow_machine()?
            .start(request)
            .map_err(ControlError::FailedPrecondition)
    }

    fn grow_status(&self) -> ControlResult<gunnar_proto::GrowStatusResponse> {
        match &self.grow {
            Some(grow) => Ok(grow.status()),
            // No machine wired: the seam's honest default, never Unimplemented
            // — see the trait's note on why the credential-free status must
            // always answer.
            None => Ok(gunnar_proto::GrowStatusResponse {
                phase: "idle".to_owned(),
                engine_present: false,
                serving: true,
                server_unix_ms: gunnar_grpc::bus::now_unix_ms(),
                detail: "this control plane has no runtime growth wired in".to_owned(),
                hotplug: crate::dashboard::probe::pci_hotplug().present,
                journal: gunnar_grpc::grow_journal::Summary::measure().map(|s| s.to_wire()),
                ..Default::default()
            }),
        }
    }

    fn grow_resume(&self, give_up: bool) -> ControlResult<gunnar_proto::GrowStatusResponse> {
        self.grow_machine()?
            .resume(give_up)
            .map_err(ControlError::FailedPrecondition)
    }

    /// **The meters, per namespace.** See `usage.proto` for what each counts
    /// and [`repo_bytes`] for the one walk that attributes a directory.
    ///
    /// Reads the DISK, not the open handles: `Admin.StorageInfo` opens every
    /// repository it reports (`repo_store`) to ask for its ref count, which
    /// on a server with a thousand repositories is a thousand store opens for
    /// one bill. A bill needs bytes, and bytes are on the disk whether or not
    /// the store is open — so this walks `repo_dir` and opens nothing. The one
    /// meter that IS about open handles (`objects`) reads the engine's live
    /// registry, which is a few `len()` calls and no disk.
    ///
    /// Tombstones are charged to the namespace the tombstone names, off the
    /// same walk `Admin.StorageInfo` and `Admin.Stats` use — a deleted
    /// repository's bytes are on the account until the purge, and a bill that
    /// forgot them would be the one an operator cannot explain.
    fn usage(&self, namespace: Option<&str>) -> ControlResult<Vec<gunnar_proto::NamespaceUsage>> {
        // A box growing its own data set has /data unmounted for the remount: its repositories'
        // sizes are not readable until it is back — a named, retryable refusal the caller waits
        // on, never `Internal: … the repository root does not resolve` (round 4 fresh UpCloud
        // mockup: a 502 at the console mid-growth). As `log_fetch` says it.
        self.usage_readable()?;
        // **One namespace: its own repositories and its own tombstones, walked
        // now** (2026-10-06). This used to list the WHOLE catalog and walk the
        // WHOLE repository root for tombstones on every call, so a poller
        // reading N tenants one by one did O(N²) work (load test: ~25–30 s of
        // 1.4 cores on main per 300 s at 1,000 tenants). The usage ledger's
        // index answers which repositories are the namespace's; the walk is
        // the same `repo_bytes`, so the answer is the same exact reading.
        if let Some(name) = namespace {
            let measured_at_unix_ms = gunnar_core::now_ms();
            let Some((held, _)) = self.stores.usage_ledger().exact(&self.stores, name).map_err(internal)? else {
                return Err(ControlError::NotFound(format!(
                    "namespace {name} is not in the catalog"
                )));
            };
            let objects = self.open_objects_of(name);
            return Ok(vec![self.usage_row(name, &held, objects, measured_at_unix_ms)]);
        }
        self.usage_all()
    }

    /// **One namespace's repositories with what each stores** — the same
    /// per-repository walk [`Self::usage`] sums, row by row (see the seam).
    fn repo_usage(&self, namespace: &str) -> ControlResult<Vec<gunnar_proto::RepoStored>> {
        let Some((_, repos)) = self.stores.usage_ledger().exact(&self.stores, namespace).map_err(internal)? else {
            return Err(ControlError::NotFound(format!(
                "namespace {namespace} is not in the catalog"
            )));
        };
        let open_objects: std::collections::HashMap<std::path::PathBuf, u64> =
            self.stores.engine().open_object_counts().into_iter().collect();
        // Sorted by repository name: the ledger keeps them in a BTreeMap.
        Ok(repos
            .into_iter()
            .map(|(name, bytes, dir)| gunnar_proto::RepoStored {
                repo: Some(gunnar_proto::RepoPath::new(namespace, &name)),
                stored_bytes: bytes.pack,
                cache_bytes: bytes.cache,
                lfs_bytes: bytes.lfs,
                objects: dir.and_then(|d| open_objects.get(&d).copied()).unwrap_or(0),
            })
            .collect())
    }

    /// **One page of every namespace's meters, out of the usage ledger**
    /// (`UsageBatch.ReadMany`, 2026-10-06) — re-measuring only what changed
    /// since the ledger last looked, and with a cursor answering only the
    /// namespaces whose row moved. See `crate::usage_ledger`.
    fn usage_page(
        &self,
        page_token: &str,
        page_size: usize,
        changed_since: &str,
    ) -> ControlResult<gunnar_proto::ReadManyUsageResponse> {
        self.usage_readable()?;
        let now = gunnar_core::now_ms();
        let ledger = self.stores.usage_ledger();
        let (cursor, after) = gunnar_grpc::seam::usage_page_token::decode(page_token);
        // The cursor is taken BEFORE the settle, on the first page, and carried
        // in the token by every later one: a change during the read is answered
        // again next time rather than lost.
        let cursor = if cursor.is_empty() { ledger.cursor_now(now) } else { cursor };
        let (rows, more, changed_only) = ledger
            .page(&self.stores, &after, page_size, changed_since, now)
            .map_err(internal)?;
        let next_page_token = match (more, rows.last()) {
            (true, Some((last, _))) => gunnar_grpc::seam::usage_page_token::encode(&cursor, last),
            _ => String::new(),
        };
        let usages = rows
            .iter()
            .map(|(name, held)| self.usage_row(name, held, held.objects, now))
            .collect();
        Ok(gunnar_proto::ReadManyUsageResponse {
            usages,
            next_page_token,
            cursor,
            changed_only,
            as_of_unix_ms: now,
        })
    }

    /// **The flow series** (`Usage.Activity`) — see the seam for the contract.
    ///
    /// The window is resolved HERE and not in the handler, because this is the
    /// half that knows what this server keeps: `0` for `since` means the whole
    /// kept window, `0` for `until` means now, and both ends are clamped to
    /// whole UTC days. A window that runs backwards returns nothing rather than
    /// an error — it is an empty question, and an empty answer is what it
    /// deserves.
    ///
    /// A named namespace must EXIST, for [`ControlPlane::usage`]'s reason:
    /// answering "no activity" for a namespace that is not in the catalog would
    /// let a typo read as a silent tenant, which is the one conclusion this
    /// whole ledger exists to make reliable.
    ///
    /// **Today is flushed before it is read.** The live slot holds today, the
    /// store holds a copy taken at the last tick, and a series that read only
    /// the store would end a minute in the past. Rather than fold the live slot
    /// into the answer — a second arithmetic on top of the flush's — the flush
    /// is simply run, which is a copy and cannot double a count.
    fn activity(
        &self,
        namespace: &str,
        since_unix_ms: i64,
        until_unix_ms: i64,
    ) -> ControlResult<(Vec<gunnar_proto::DayActivity>, i64)> {
        if self
            .stores
            .catalog()
            .namespace(namespace)
            .map_err(internal)?
            .is_none()
        {
            return Err(ControlError::NotFound(format!(
                "namespace {namespace} is not in the catalog"
            )));
        }
        let now = gunnar_core::now_ms();
        let flow = self.stores.flow();
        if let Err(err) = flow.flush(now) {
            // Not fatal: the store still holds everything up to the last tick,
            // and a read that refused because a write failed would be worse
            // than a read that is a minute stale and says nothing about it.
            tracing::warn!(
                target: "gunnar::store",
                event = "flow.flush_failed",
                %err,
                "could not flush the flow ledger before an Activity read; the series is as of \
                 the last successful flush"
            );
        }
        let today = gunnar_core::day_of(now);
        let from = if since_unix_ms == 0 {
            today - gunnar_core::RETENTION_DAYS
        } else {
            gunnar_core::day_of(since_unix_ms)
        }
        .max(today - gunnar_core::RETENTION_DAYS);
        let to = if until_unix_ms == 0 {
            today
        } else {
            gunnar_core::day_of(until_unix_ms)
        }
        .min(today);
        if from > to {
            return Ok((Vec::new(), gunnar_core::RETENTION_DAYS));
        }
        let days = flow
            .store()
            .series(namespace, from, to)
            .map_err(internal)?
            .into_iter()
            .map(|(day, row)| day_activity(day, &row))
            .collect();
        Ok((days, gunnar_core::RETENTION_DAYS))
    }

    /// **The admission plan** (`Usage.AdmitPlan`) — see the seam for the
    /// contract. A read for the admin view and the tenant, never on the
    /// admission path: the policy is asked exactly as the gate asks it, with
    /// the usage the gate would plan with, once per kind of work this server
    /// admits (`request` stands for ls-remote and gc).
    fn admit_plan(&self, namespace: &str) -> ControlResult<gunnar_proto::AdmitPlanResponse> {
        use gunnar_ssh::edda_admit::{Consumer, Work};
        use gunnar_ssh::governor::OpClass;
        if self
            .stores
            .catalog()
            .namespace(namespace)
            .map_err(internal)?
            .is_none()
        {
            return Err(ControlError::NotFound(format!(
                "namespace {namespace} is not in the catalog"
            )));
        }
        let Some(gate) = &self.admission else {
            return Err(ControlError::Unimplemented("Usage.AdmitPlan"));
        };
        let policy = gate.admit_policy();
        let usage = gate.admit_usage(&*policy, namespace);
        let limit = policy.limit();
        let who = Consumer::Namespace(namespace.to_owned());
        let estimates = policy.estimates();
        let kinds = [OpClass::Clone, OpClass::Fetch, OpClass::Push, OpClass::LsRemote]
            .into_iter()
            .map(|class| {
                let kind = gunnar_ssh::admission::work_kind(class);
                let plan = policy.plan(&Work::new(kind, None), &who, &usage);
                gunnar_proto::AdmitPlanKind {
                    kind: kind.name().to_owned(),
                    admit_class: plan.class.name().to_owned(),
                    why: plan.why,
                    estimate_bytes: plan.estimate.usage_bytes(),
                    estimate_cpu_ms: plan.estimate.cpu_ms,
                    samples: estimates
                        .iter()
                        .find(|row| row.kind == kind)
                        .map_or(0, |row| row.samples),
                }
            })
            .collect();
        Ok(gunnar_proto::AdmitPlanResponse {
            policy: policy.policy().to_owned(),
            window_days: usage.window_days,
            used_bytes: usage.bytes,
            limit_bytes: limit.map(|l| l.bytes),
            budget_left_bytes: limit.map(|l| l.bytes.saturating_sub(usage.bytes)),
            kinds,
        })
    }

    // ── the metered appliance: `Entitlement` ────────────────────────────────

    #[cfg(feature = "metered")]
    fn entitlement_get(
        &self,
        namespace: &str,
    ) -> ControlResult<Option<gunnar_proto::EntitlementFact>> {
        self.entitlement()?
            .get(namespace)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))
    }

    #[cfg(feature = "metered")]
    fn entitlement_list(&self) -> ControlResult<Vec<gunnar_proto::EntitlementFact>> {
        self.entitlement()?
            .list()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))
    }

    #[cfg(feature = "metered")]
    fn entitlement_refused_at_boot(&self) -> ControlResult<Option<gunnar_proto::RefusedAtBoot>> {
        Ok(self.entitlement()?.refusal())
    }

    /// The refusals, by kind: a forged fact is `PermissionDenied` (the caller
    /// held the admin grant and still may not move a plan without monetize's
    /// signature), a malformed one `InvalidArgument`, and one this box could
    /// not record `FailedPrecondition` — verified, and still not enforced,
    /// because a plan the log does not show is not a plan.
    #[cfg(feature = "metered")]
    fn entitlement_set(
        &self,
        fact: gunnar_proto::EntitlementFact,
    ) -> ControlResult<(gunnar_proto::EntitlementState, u64)> {
        use crate::entitlement::SetRefused;
        let (state, seq) = self.entitlement()?.set(fact).map_err(|err| match err {
            SetRefused::Forged { .. } => ControlError::PermissionDenied(err.to_string()),
            // **`PermissionDenied` and not `FailedPrecondition`, deliberately.**
            // monetize's poller treats a refusal as final and stops retrying
            // that fact, and that is the right answer here: a fact this box has
            // moved past will never become acceptable, so retrying it for ever
            // would be a hot loop against a decision that is not going to
            // change. It is the same code as a forged fact because it is the
            // same sentence — this caller may not move this plan with this
            // fact — and the words say which of the two it was.
            SetRefused::Replayed { .. } | SetRefused::Unstamped { .. } | SetRefused::Behind { .. } => ControlError::PermissionDenied(err.to_string()),
            SetRefused::Malformed(_) => ControlError::InvalidArgument(err.to_string()),
            SetRefused::NotRecorded { .. } => ControlError::FailedPrecondition(err.to_string()),
            SetRefused::NoKey { .. } => ControlError::FailedPrecondition(err.to_string()),
        })?;
        Ok((crate::entitlement::state_to_proto(state), seq))
    }

    // ── the metered appliance: `Billing` ────────────────────────────────────
    //
    // The key is read out of the sealed secret store on every call rather than
    // cached on this struct. Both verbs are human-paced — one is an operator
    // reading a string to paste into a configuration, the other is a customer
    // clicking renew — so a redb read and an OpenSSH parse are free at this
    // rate, and a cached key is a copy that has to be invalidated the day the
    // key is rolled. `ServerStores::actor_ticket_key` mints on first use, so
    // the FIRST of these calls on a fresh appliance is what brings the key into
    // existence; nothing has to run at boot for this to work.

    #[cfg(feature = "metered")]
    fn actor_ticket_public_key_hex(&self) -> ControlResult<String> {
        Ok(self
            .stores
            .actor_ticket_key()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?
            .public_key_hex()
            .to_owned())
    }

    #[cfg(feature = "metered")]
    fn actor_ticket_sign(&self, message: &[u8]) -> ControlResult<[u8; 64]> {
        Ok(self
            .stores
            .actor_ticket_key()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?
            .sign(message))
    }

    // The named sealed slot (2026-10-09): stored through the sealed, logged
    // secret store; a twin or a box being restored refuses the write as every
    // logged write is refused there.
    #[cfg(feature = "metered")]
    fn sealed_get(&self, name: &str) -> ControlResult<Option<(String, Vec<u8>)>> {
        self.stores.sealed_slot_get(name).map_err(|err| ControlError::Internal(format!("{err:#}")))
    }

    #[cfg(feature = "metered")]
    fn sealed_put(&self, name: &str, owner: &str, value: &[u8]) -> ControlResult<bool> {
        self.stores.sealed_slot_put(name, owner, value).map_err(|err| ControlError::Unavailable(format!("{err:#}")))
    }

    // ── mirror ─────────────────────────────────────────────────────────────

    /// **Register an upstream.** Bookkeeping only — no fetch happens here.
    ///
    /// `create_repo` is honoured before the registration, because a mirror of a
    /// repository that does not exist is a registration nothing can ever act
    /// on. Without the flag the repository must already be there, and a missing
    /// one is `NotFound` rather than a silently created empty one.
    fn mirror_add(
        &self,
        path: &RepoPath,
        remote_url: &str,
        prune: bool,
        create_repo: bool,
    ) -> ControlResult<MirrorConfig> {
        if remote_url.trim().is_empty() {
            return Err(ControlError::InvalidArgument(
                "a mirror needs a remote URL".to_owned(),
            ));
        }
        // **The destination, before it is written down.** `Mirror.Add` reaches
        // every enrolled principal — `owns_account` makes a caller intrinsically
        // Admin in its own namespace — so without this the verb is an
        // arbitrary outbound request from the server's network position,
        // authorised by having a key. See `mirror_fetch::check_destination`.
        // Refused at REGISTRATION rather than only on the first sync, so the
        // operator's mistake and the attacker's are both answered on the call
        // that made them.
        crate::mirror_fetch::classify(remote_url).map_err(ControlError::InvalidArgument)?;
        crate::mirror_fetch::check_destination(remote_url, self.stores.root())
            .map_err(ControlError::InvalidArgument)?;
        let repo_ref = Self::repo_ref(path)?;
        // **The repository is NOT created here** (owner order 2026-10-18).
        // Its object format and its default branch are the upstream's, and
        // only the upstream can say them: an ssh upstream is never asked here,
        // and a private one answers nothing before its credential is set — so
        // creating it now meant a guess (sha256, `main`) that a sha1 upstream
        // could never be fetched into, and an empty private repository left
        // behind by every import that failed. The registration says the
        // repository is to come, and the first sync that reaches the upstream
        // creates it (`mirror_fetch::sync_once`).
        let creates = create_repo && self.get_repo(path).is_err();
        if creates {
            // The disk, refused now by the gate `Repos.Create` asks, rather
            // than on a job minutes later.
            if let Some(line) = self.headroom.as_ref().and_then(|gate| gate.refusal()) {
                return Err(ControlError::ResourceExhausted(line));
            }
            if self.stores.catalog().namespace(path.namespace.as_str()).map_err(internal)?.is_none() {
                return Err(ControlError::NotFound(format!("namespace {}", path.namespace)));
            }
        } else {
            // Opened rather than merely catalogued: a registration against a
            // repository whose store cannot be opened would look fine and fail
            // on the first sync.
            self.open(path)?;
        }
        let mut record = gunnar_core::MirrorRecord::new(
            &repo_ref,
            remote_url,
            prune,
            gunnar_grpc::bus::now_unix_ms(),
        );
        record.creates_repo = creates;
        let stored = self
            .stores
            .mirrors()
            .set(&repo_ref, record)
            .map_err(internal)?;
        Ok(mirror_out(&stored))
    }

    /// **The one verb that genuinely needs the client half**, and the only one
    /// still refused.
    ///
    /// The original refusal covered all four: *"mirroring runs over
    /// gunnar-client (nornir-git ls-remote + fetch), which an S crate must
    /// never link (the dependency budget)"*. That is true of a sync and of nothing else — adding,
    /// listing and removing a registration are a document write, a document
    /// read and a document delete. Narrowing the gap to the verb that has it is
    /// the difference between "mirroring is unimplemented" and "this build
    /// cannot fetch".
    /// **Enqueue one sync, and return without syncing.**
    ///
    /// The refusal this replaced covered all four verbs and then just this
    /// one: *"mirroring runs over gunnar-client (nornir-git ls-remote + fetch),
    /// which an S crate must never link (the dependency budget)"*. That was true while the only
    /// fetch client in the constellation needed `gix`, a `.git` directory and a
    /// worktree — none of which exist on an appliance running as PID 1 over
    /// znippy. `gunnar_wire::fetch_pack` is a fetch client with none of those
    /// requirements, over the same `BufRead`/`Write` pair `upload_pack`
    /// already answers on, so the gap is closed rather than narrowed again.
    ///
    /// **Registration first**, so an unregistered repository is `NotFound` by
    /// name and not a job that fails four minutes later — two very different
    /// things to tell an operator, and only one of them is their mistake.
    ///
    /// The upstream and `prune` are read HERE and carried on the order, because
    /// they are what the caller asked about; the credential is read on the
    /// worker (see [`CoreControlPlane::mirror_queue`]) because it is a secret
    /// and an order is `Debug`.
    fn mirror_sync(&self, path: &RepoPath) -> ControlResult<MirrorConfig> {
        let record = self.mirror_record(path)?;
        let repo_ref = Self::repo_ref(path)?;
        // Refused at the DOOR rather than on the queue: a remote gunnar cannot
        // dial is the caller's mistake and it is knowable now, and a job that
        // sat QUEUED and then failed on the shape of a URL is a console button
        // that went down for nothing.
        crate::mirror_fetch::classify(&record.remote_url).map_err(ControlError::InvalidArgument)?;
        // Same door, same reason: a registration that predates the destination
        // rule must not become a dial by being clicked.
        crate::mirror_fetch::check_destination(&record.remote_url, self.stores.root())
            .map_err(ControlError::InvalidArgument)?;
        let job = self.mirror.enqueue(crate::mirror_queue::MirrorOrder {
            path: repo_ref.key(),
            upstream: record.remote_url.clone(),
            prune: record.prune,
        });
        let mut out = mirror_out(&record);
        out.job = Some(mirror_job_out(path, job));
        Ok(out)
    }

    /// **Seal the credential first, then record its kind.**
    ///
    /// That order is the correctness argument. A document that claims a
    /// credential the secret store does not hold makes every later sync fail
    /// with "no credential stored" against an operator who can see one listed;
    /// a sealed value with no document pointing at it is unreachable and
    /// harmless. So the value is written before the fact, and forgotten after
    /// it.
    ///
    /// The value never comes back out of this function. `mirror_out` has no
    /// field for it, `MirrorConfig` has no field for it, and the two error
    /// paths below quote the repository and the kind and nothing else.
    fn mirror_set_credential(
        &self,
        path: &RepoPath,
        kind: gunnar_proto::MirrorCredentialKind,
        secret: &str,
        username: &str,
    ) -> ControlResult<MirrorConfig> {
        gunnar_grpc::seam::credential_arguments(kind, secret)?;
        self.mirror_record(path)?;
        let repo_ref = Self::repo_ref(path)?;

        let kind = credential_kind_in(kind);
        let secrets = self.stores.secrets().map_err(|err| {
            ControlError::Internal(format!("the sealed secret store is not available: {err:#}"))
        })?;
        let key = gunnar_core::credential_secret_key(&repo_ref);
        let stored = if kind.is_set() {
            gunnar_store::SecretStore::put(&secrets, &key, secret.as_bytes())
        } else {
            gunnar_store::SecretStore::delete(&secrets, &key)
        };
        stored.map_err(|err| {
            // `{err}` and not the value: this string reaches a client.
            ControlError::Internal(format!(
                "the mirror credential for {path} could not be sealed: {err}"
            ))
        })?;

        let record = self
            .stores
            .mirrors()
            .set_credential(&repo_ref, kind, username)
            .map_err(internal)?
            .ok_or_else(|| ControlError::NotFound(format!("no mirror registered for {path}")))?;
        Ok(mirror_out(&record))
    }

    fn mirror_status(
        &self,
        namespace: Option<&str>,
        path: Option<&RepoPath>,
    ) -> ControlResult<Vec<MirrorConfig>> {
        let all = self.stores.mirrors().all().map_err(internal)?;
        Ok(all
            .iter()
            .filter(|record| match path {
                Some(want) => record.repo == format!("{}/{}", want.namespace, want.repo),
                None => true,
            })
            .filter(|record| match namespace {
                Some(want) => record
                    .repo
                    .split_once('/')
                    .is_some_and(|(ns, _)| ns == want),
                None => true,
            })
            .map(|record| {
                let mut out = mirror_out(record);
                // **The job belongs on the listing**, which is what makes
                // `Mirror.Status` the poll a console uses: state, queue
                // position, progress, error and report, in the `GcStatus`
                // shape. A separate `MirrorSyncStatus` verb would have been a
                // second door onto one fact.
                out.job = out
                    .repo
                    .as_ref()
                    .zip(self.mirror.status(&record.repo))
                    .map(|(path, job)| mirror_job_out(path, job));
                // **A failure outlives its job** (import-big, 2026-10-26). The
                // queue forgets a job at a restart and after its retention, and
                // the registration's `last_error` does not: when the queue holds
                // nothing, the last failure is shown as the FAILED job it was,
                // so the repository page and the mirrors list say why an import
                // is empty instead of "idle".
                if out.job.is_none() && !record.last_error.is_empty() {
                    out.job = out.repo.clone().map(|path| gunnar_proto::MirrorJob {
                        job_id: String::new(),
                        path: Some(path),
                        state: gunnar_proto::MirrorJobState::Failed as i32,
                        error: record.last_error.clone(),
                        ..Default::default()
                    });
                }
                out
            })
            .collect())
    }

    /// **Un-register an upstream, and forget its credential with it.**
    ///
    /// The registration goes first and the sealed value second, and the order
    /// is the correctness argument — the mirror image of
    /// [`Self::mirror_set_credential`]'s. That function writes the value before
    /// the document so a document can never claim a credential the store does
    /// not hold; this one removes the document before the value for the same
    /// reason read backwards. A sealed secret with no document pointing at it
    /// is unreachable and harmless; a document with no secret makes every later
    /// sync fail with "no credential stored" against an operator who can see
    /// one listed. So the failure mode of a crash between the two lines is the
    /// harmless one, and the `NotFound` path deletes nothing.
    ///
    /// Before 2026-09-11 the value was simply left behind: `Mirror.Remove` took
    /// the document away and the ssh private key or forge token stayed in the
    /// sealed store for the life of the box, with nothing on the control plane
    /// naming it or able to name it — un-listable, un-rotatable, and still
    /// decryptable by anything that reaches the KEK. An operator who removes a
    /// mirror because its credential leaked has been told the credential is
    /// gone.
    fn mirror_remove(&self, path: &RepoPath) -> ControlResult<()> {
        self.mirror_record(path)?;
        let repo_ref = Self::repo_ref(path)?;
        if !self.stores.mirrors().remove(&repo_ref).map_err(internal)? {
            return Err(ControlError::NotFound(format!(
                "no mirror registered for {path}"
            )));
        }
        let secrets = self.stores.secrets().map_err(|err| {
            ControlError::Internal(format!("the sealed secret store is not available: {err:#}"))
        })?;
        gunnar_store::SecretStore::delete(&secrets, &gunnar_core::credential_secret_key(&repo_ref))
            .map_err(|err| {
                // `{err}` and not the value: this string reaches a client. The
                // registration IS gone by now, so this says exactly that rather
                // than reading as "nothing happened".
                ControlError::Internal(format!(
                    "the registration for {path} was removed and its sealed credential could \
                     not be deleted: {err}. The secret is still on this box; remove it before \
                     trusting that it is gone."
                ))
            })?;
        Ok(())
    }

    // ── replication: the three verbs the appliance is configured with ──────

    #[cfg(feature = "replication")]
    fn replication_set(
        &self,
        target: gunnar_proto::ReplicationTarget,
    ) -> ControlResult<gunnar_proto::ReplicationStatusResponse> {
        let slot = self.replication_slot()?;
        let mut target = crate::replication_wire::target_from_proto(target)?;
        // **The key the appliance pushes with, minted ON THE BOX.**
        //
        // An operator who names no identity is not asking for the client key
        // ladder — on an image with no home directory that ladder finds nothing
        // and every push fails on authentication forever. They are asking for
        // "use this box's own key", and there was no way to put one there. So
        // the server mints one, keeps the private half, and hands back the
        // public line for them to authorise on the standby. See
        // `replication_wire::REPLICATION_KEY`.
        let minted_public = if target.identity.is_none() {
            let (path, public) = crate::replication_wire::ensure_identity(self.stores.root())?;
            target.identity = Some(path);
            Some(public)
        } else {
            None
        };
        // The public-only requirements that depend on the key, now that there
        // IS one. Checked here rather than in `target_from_proto` because that
        // runs before the mint — and refusing a target for the absence of a key
        // this function is about to create is how the browse replica's own
        // documented one-liner became unrunnable on an appliance.
        crate::replication_wire::require_public_only_identity(&target)?;
        let mut config = slot
            .config()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        // `set_target` REPLACES by name. That is what makes the verb
        // idempotent, and idempotent is what an operator on a flaky link needs:
        // a retried `SetReplication` must not leave two standbys behind.
        config.set_target(target);
        slot.apply(config)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        let mut out = self.replication_snapshot(false)?;
        out.identity_public_key = minted_public.unwrap_or_default();
        Ok(out)
    }

    #[cfg(feature = "replication")]
    fn replication_remove(
        &self,
        name: &str,
    ) -> ControlResult<gunnar_proto::ReplicationStatusResponse> {
        let slot = self.replication_slot()?;
        let mut config = slot
            .config()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        if !config.remove_target(name) {
            // NotFound and not a silent success. "I removed the standby" about a
            // standby that was never there reads identically to "I removed the
            // standby" about the one you meant, and the difference is whether
            // your data is still going somewhere.
            return Err(ControlError::NotFound(format!(
                "no replication target named {name:?}"
            )));
        }
        slot.apply(config)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        self.replication_snapshot(false)
    }

    // ── The transaction log: what the twin fetches ──────────────────────────

    fn is_group_member(&self, principal_id: &str, group: &str) -> ControlResult<bool> {
        self.stores
            .auth()
            .groups_of(principal_id)
            .map(|groups| groups.iter().any(|g| g == group))
            .map_err(|err| ControlError::Unavailable(format!("reading group membership: {err}")))
    }

    fn become_twin(&self, primary: &str) -> ControlResult<String> {
        let key = crate::twin::become_twin(&self.stores, primary)
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))?;
        // Following starts now, not at the next boot: the key is enrolled on
        // the primary next, and the loop retries until it is.
        crate::twin::start_follower(Arc::clone(&self.stores));
        Ok(key)
    }

    #[cfg(feature = "wg-client")]
    fn assign_tunnel_address(&self, address: &str) -> ControlResult<gunnar_proto::AssignTunnelAddressResponse> {
        let window_open = self
            .stores
            .auth()
            .bootstrap_window_open()
            .map_err(|err| ControlError::Unavailable(format!("reading the bootstrap window: {err}")))?;
        crate::appliance::tunnel_address_answer(self.stores.root(), address, window_open)
    }

    #[cfg(feature = "wg-client")]
    fn set_tunnel_address(&self, address: &str) -> ControlResult<gunnar_proto::AssignTunnelAddressResponse> {
        // `Admin.SetTunnelAddress`: the service already held the caller to
        // server-wide Admin, which is what the open window stands in for on
        // the unauthenticated door.
        crate::appliance::tunnel_address_answer(self.stores.root(), address, true)
    }

    fn twin_csr(&self) -> ControlResult<String> {
        crate::twin_tls::request(self.stores.root()).map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))
    }

    fn install_twin_certificate(&self, cert_pem: &str, ca_pem: &str, replication_port: u16, replication_host: &str) -> ControlResult<i64> {
        let host = (!replication_host.is_empty()).then_some(replication_host);
        crate::twin_tls::install_at(self.stores.root(), cert_pem, ca_pem, replication_port, host)
            .map(|expiry| expiry.days_left)
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))
    }

    fn issue_twin_certificate(&self, principal: &str, csr_pem: &str) -> ControlResult<(String, String, u16, String)> {
        crate::twin_tls::issue_for_twin(&self.stores, principal, csr_pem)
            .map(|(cert, ca, port)| (cert, ca, port, crate::twin_tls::replication_host(self.stores.root()).unwrap_or_default()))
            .map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))
    }

    fn twin_git_listener_needs_restart(&self) -> bool {
        crate::twin::git_listener_needs_restart(&self.stores)
    }

    fn restore_begin(&self, owner: &str) -> ControlResult<u64> {
        crate::twin::restore_begin_by(&self.stores, owner).map_err(|err| {
            // Somebody else's restore is a NO to a known caller, not a box in the wrong state.
            if err.downcast_ref::<crate::twin::RestoreNotYours>().is_some() {
                ControlError::PermissionDenied(format!("{err:#}"))
            } else {
                ControlError::FailedPrecondition(format!("{err:#}"))
            }
        })
    }

    /// The keys handed in by `serve` (`--restore-pubkey`), then the admin-grade keys the
    /// installer's door fed this box ([`crate::fed_principals::restore_keys_at`]). Read on
    /// every call: a feed that arrives while the box runs counts from the next stream on.
    fn restore_keys(&self) -> ControlResult<Vec<String>> {
        #[allow(unused_mut)]
        let mut keys = self.restore_keys.clone();
        #[cfg(feature = "wg-client")]
        keys.extend(crate::fed_principals::restore_keys_at(self.stores.root()).map_err(ControlError::Unavailable)?);
        keys.sort();
        keys.dedup();
        Ok(keys)
    }

    fn restore_room(&self, announced_bytes: u64) -> ControlResult<()> {
        crate::twin::room_for_restore(self.stores.root(), announced_bytes).map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))
    }

    /// **The server's intake** (restore-large-entry, 2026-10-07): an entry larger than one piece
    /// is staged on this box's disk as it arrives and survives the stream ending inside it
    /// ([`crate::twin::intake`]).
    fn restore_intake<'a>(&'a self, owner: &str) -> ControlResult<Option<Box<dyn gunnar_grpc::RestoreIntake + 'a>>> {
        match crate::twin::intake::Intake::open(&self.stores, owner) {
            Ok(Some(intake)) => Ok(Some(Box::new(intake))),
            Ok(None) => Ok(None),
            // Somebody else's restore is a NO to a known caller, not a box in the wrong state.
            Err(err) if err.downcast_ref::<crate::twin::RestoreNotYours>().is_some() => Err(ControlError::PermissionDenied(format!("{err:#}"))),
            Err(err) => Err(ControlError::FailedPrecondition(format!("{err:#}"))),
        }
    }

    fn restore_apply(&self, entry: gunnar_proto::LogEntry) -> ControlResult<bool> {
        let e = gunnar_core::txlog::Entry { seq: entry.seq, kind: entry.kind as u16, meta: entry.meta, blob: entry.blob };
        match crate::twin::restore_apply(&self.stores, &e) {
            Ok(crate::twin::Applied::Lost(_)) => Ok(true),
            Ok(_) => Ok(false),
            Err(err) => Err(ControlError::Internal(format!("restoring seq {}: {err:#}", e.seq))),
        }
    }

    fn restore_finish(&self, announced_head: u64, log_id_of_source: &str) -> ControlResult<u64> {
        let head = crate::twin::restore_finish_streamed(&self.stores, announced_head, log_id_of_source).map_err(|err| ControlError::FailedPrecondition(format!("{err:#}")))?;
        // c-no-restart: the restored box restarts ITSELF (the appliance's PID 1).
        crate::twin::restart_after_restore();
        Ok(head)
    }

    fn snapshot_stream(&self, sink: &mut dyn FnMut(gunnar_proto::LogChunk) -> ControlResult<()>) -> ControlResult<u64> {
        self.snapshot_stream_from(0, 0, "", sink)
    }

    /// **A snapshot from item `from_item`, byte `from_offset` on** (restore-after-snapshot,
    /// 2026-10-07): a twin's kept base, every piece with its item, offset, the item's crc on its
    /// last and the base's id ([`crate::twin::snapshot::serve_from`]); a primary's own snapshot,
    /// a new cut each time, with none. A base that changed is `[snapshot-changed]`.
    fn snapshot_stream_from(&self, from_item: u64, from_offset: u64, expect_id: &str, sink: &mut dyn FnMut(gunnar_proto::LogChunk) -> ControlResult<()>) -> ControlResult<u64> {
        // The one copy a piece takes: out of the producer's buffer into the wire message.
        let mut pieces = |p: crate::twin::snapshot::Piece<'_>, pos: Option<crate::twin::snapshot::PiecePos<'_>>| -> anyhow::Result<()> {
            sink(gunnar_proto::LogChunk {
                seq: 0,
                kind: u32::from(p.kind),
                meta: p.meta.to_vec(),
                blob_len: p.blob_len,
                blob: p.blob.to_vec(),
                last: p.last,
                restore_head: 0,
                restore_bytes: 0,
                log_id: String::new(),
                offset: pos.map(|q| q.offset),
                entry_crc: pos.and_then(|q| q.crc),
                snapshot_item: pos.map(|q| q.item),
                snapshot_id: pos.map(|q| q.id.to_owned()).unwrap_or_default(),
            })
            .map_err(|err| anyhow::anyhow!("{err}"))
        };
        crate::twin::snapshot::serve_from(&self.stores, from_item, from_offset, expect_id, &mut pieces).map_err(|err| match err.downcast_ref::<crate::twin::snapshot::SnapshotChanged>() {
            Some(changed) => ControlError::FailedPrecondition(changed.to_string()),
            None => ControlError::Internal(format!("producing a snapshot: {err:#}")),
        })
    }

    fn log_retain(&self, from: u64) -> ControlResult<gunnar_proto::LogHeadResponse> {
        let log = self.stores.txlog();
        if log.is_follower() {
            return Err(ControlError::FailedPrecondition("retention: a twin's log is the primary's numbers; retain on the primary".into()));
        }
        let from = if from == 0 { log.head_seq() + 1 } else { from };
        let first = log.retain_from(from).map_err(|err| ControlError::Unavailable(format!("retaining the transaction log from {from}: {err}")))?;
        tracing::warn!(target: gunnar_core::observe::TARGET_TWIN, from, first, head = log.head_seq(), "the transaction log now retains from {first}; a twin behind it takes a snapshot");
        self.log_head()
    }

    fn log_layout(&self) -> ControlResult<Vec<(u64, u64, u64)>> {
        let log = self.stores.txlog();
        if log.is_follower() {
            return Err(ControlError::FailedPrecondition("retention: a twin's log is the primary's numbers; retain on the primary".into()));
        }
        Ok(log.layout())
    }

    fn data_volume(&self) -> Option<(u64, u64)> {
        // While the set is released for a growth, statvfs of the data root reads the box's
        // root filesystem: no number is better than that one.
        if self.stores.txlog().is_released() {
            return None;
        }
        let vfs = rustix::fs::statvfs(self.stores.root()).ok()?;
        let total = vfs.f_blocks.saturating_mul(vfs.f_frsize);
        let free = vfs.f_bfree.saturating_mul(vfs.f_frsize);
        (total > 0).then(|| (total, total.saturating_sub(free)))
    }

    fn twin_owed_read(&self) -> ControlResult<Vec<u8>> {
        match std::fs::read(self.stores.root().join(crate::twin::TWIN_OWED_FILE)) {
            Ok(b) => Ok(b),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
            Err(e) => Err(ControlError::Unavailable(format!("reading {}: {e}", crate::twin::TWIN_OWED_FILE))),
        }
    }

    fn twin_owed_write(&self, bytes: &[u8]) -> ControlResult<()> {
        if self.stores.txlog().is_released() {
            return Err(ControlError::Unavailable("the data set is released for a growth; twin-owed.json is written after the remount".into()));
        }
        // Per box, never a transaction: what a primary owes its twins is not the twins' to hold.
        crate::durable::write_atomic_unframed(self.stores.root(), crate::twin::TWIN_OWED_FILE, bytes).map_err(|e| ControlError::Unavailable(format!("writing {}: {e:#}", crate::twin::TWIN_OWED_FILE)))
    }

    fn restore_snapshot_chunk(&self, chunk: &gunnar_proto::LogChunk) -> ControlResult<Option<u64>> {
        let kind = u16::try_from(chunk.kind).map_err(|_| ControlError::InvalidArgument(format!("snapshot piece of kind {}", chunk.kind)))?;
        let piece = crate::twin::snapshot::Piece { kind, meta: &chunk.meta, blob_len: chunk.blob_len, blob: &chunk.blob, last: chunk.last };
        crate::twin::snapshot::restore_piece(&self.stores, piece).map_err(|err| ControlError::Internal(format!("installing the snapshot: {err:#}")))
    }

    fn health_alarms(&self) -> Vec<gunnar_proto::HealthAlarm> {
        #[allow(unused_mut)]
        let mut alarms = Vec::new();
        // A box stuck mid-restore serves reads and refuses every write: say so on the wire.
        if !self.stores.is_twin() && crate::twin::is_restoring(self.stores.root()) {
            alarms.push(gunnar_proto::HealthAlarm {
                event: "twin.restoring_at_open".into(),
                count: 1,
                since_unix_ms: 0,
                detail: "this box is MID-RESTORE: it originates no transactions and refuses every \
                         control-plane write until a restore finishes — resend the twin's log"
                    .into(),
            });
        }
        // An old main fenced off by a newer generation of its log (stinky row 18): it serves
        // reads and refuses every write, and must say so rather than look like a broken box.
        if !self.stores.is_twin() {
            if let Some(why) = crate::twin::fenced_why(self.stores.root()) {
                alarms.push(gunnar_proto::HealthAlarm { event: "twin.fenced_by_generation".into(), count: 1, since_unix_ms: 0, detail: why });
            }
        }
        // ★ twin-resync-space (2026-10-06): a twin that gave its stale copy up to make room for
        // a full resync holds NO copy until it lands — main is the only one meanwhile.
        if self.stores.is_twin() {
            if let Some(d) = crate::twin::snapshot::dropped(self.stores.root()) {
                let too_small = crate::twin::snapshot::too_small_total(self.stores.root())
                    .map(|t| format!(" The resync did not fit even then: this twin's volume ({t} bytes) must be grown to at least main's data set before it is tried again ({}).", gunnar_grpc::TWIN_TOO_SMALL))
                    .unwrap_or_default();
                alarms.push(gunnar_proto::HealthAlarm {
                    event: "twin.resync_without_copy".into(),
                    count: 1,
                    since_unix_ms: d.at_unix_ms,
                    detail: format!("{}.{too_small}", d.sentence()),
                });
            }
        }
        // The log's size over its cap (2026-09-22): a warning, never a deletion. A twin's log is
        // its primary's numbers and is trimmed there, so only a box that originates one is told.
        if !self.stores.is_twin() {
            let (total, _) = crate::twin::volume_bytes(self.stores.root());
            match crate::twin::txlog_alarm_cap(std::env::var(crate::twin::TXLOG_ALARM_ENV).ok().as_deref(), total) {
                Ok(Some((cap, how))) => alarms.extend(crate::twin::txlog_size_alarm(self.stores.txlog().bytes(), cap, &how)),
                Ok(None) => {}
                Err(why) => alarms.push(gunnar_proto::HealthAlarm { event: crate::twin::TXLOG_SIZE_ALARM.into(), count: 1, since_unix_ms: 0, detail: why }),
            }
        }
        #[cfg(feature = "metered")]
        if let Some(a) = self.entitlement.as_ref().and_then(|slot| slot.alarm()) {
            alarms.push(a);
        }
        // The growth's own alarm (DEFECT D, 2026-09-29): /data kept unmounted past the growth's
        // bound (`grow.unmounted_too_long`), or a set that could not be mounted back (`grow.fatal`).
        if let Some(a) = self.grow.as_ref().and_then(|g| g.alarm()) {
            alarms.push(a);
        }
        // The installer's feed (`crate::feed`): a medium value the door contradicted, or a
        // fed monetize key that waits for a restart.
        alarms.extend(crate::feed::alarms());
        alarms
    }

    fn is_twin(&self) -> bool {
        self.stores.is_twin()
    }

    fn log_follows(&self) -> bool {
        self.stores.is_twin() || self.stores.txlog().is_follower()
    }

    fn topology_facts(&self) -> gunnar_grpc::topology::Facts {
        crate::topology::facts(self.stores.root())
    }

    fn maintenance_reasons(&self) -> Vec<String> {
        #[allow(unused_mut)]
        let mut why = Vec::new();
        #[cfg(feature = "metered")]
        if self.entitlement.as_ref().is_some_and(|slot| slot.maintenance()) {
            why.push(crate::entitlement::KEY_MISMATCH_ALARM.to_string());
        }
        why
    }

    fn primary_heartbeat(&self, silent_after_ms: u64) -> Option<gunnar_proto::PrimaryHeartbeat> {
        let cfg = crate::twin::TwinConfig::load(self.stores.root()).ok().flatten()?;
        // The follower's OWN word and reason travel with the numbers (X2): a
        // twin that cannot start, or whose every poll fails, records both, and
        // this is the only door that reads them out to anybody.
        let st = crate::twin::status(self.stores.root());
        let (last, primary_head, applied) = match &st {
            Some(s) => (s.last_answer_unix_ms, s.primary_head_seq, s.applied_seq),
            None => (0, 0, self.stores.txlog().head_seq()),
        };
        let own = st.as_ref().map(|s| (s.state.to_string(), s.why.clone()));
        Some(gunnar_grpc::heartbeat::primary_view(
            &cfg.primary,
            last,
            primary_head,
            applied,
            crate::twin::now_ms(),
            silent_after_ms,
            own.as_ref().map(|(a, b)| (a.as_str(), b.as_str())),
        ))
    }

    fn log_head(&self) -> ControlResult<gunnar_proto::LogHeadResponse> {
        self.log_head_signed("")
    }

    fn log_head_signed(&self, nonce: &str) -> ControlResult<gunnar_proto::LogHeadResponse> {
        // **A twin's poll in the restore window is refused by name** (T17, 2026-09-21; T15's
        // TD8). Mid-replay (`txlog-restoring`) or finished and owed its restart
        // (`txlog-reseal`), this process holds the fresh box's KEK while the replayed host key
        // is sealed under the dead primary's; the re-seal that reconciles them runs on the next
        // open. Answering would mean an UNSIGNED answer a pinned twin refuses, and a
        // `cannot read its host key … wrong key-encrypting key` WARN that reads like a broken
        // box (MEASURED under KVM, 0.4 s after "Restore finished"). The box is not yet the
        // primary it will be, and says exactly that; the twin records it as its `why` and polls
        // again. Only a nonce asks for proof of identity — an unnonced LogHead (an operator,
        // `twin replay`) still gets the numbers.
        if !nonce.trim().is_empty() {
            let root = self.stores.root();
            if crate::twin::is_restoring(root) {
                return Err(ControlError::Unavailable(
                    "this box is being restored from a twin and is not a primary yet: it answers a twin's poll \
                     once the replay has finished and the box has restarted"
                        .to_owned(),
                ));
            }
            if crate::twin::reseal_pending(root) {
                return Err(ControlError::Unavailable(
                    "this box finished a restore and must restart before it answers a twin: its host key is \
                     sealed under the key-encrypting key the restart re-seals, so until then it cannot prove \
                     which box it is"
                        .to_owned(),
                ));
            }
        }
        let mut head = crate::twin::own_head(&self.stores);
        // **Prove which box answered** (2026-09-21, lane T4). Signed last, over
        // the nonce the caller just minted plus the identity and the numbers
        // above, so a recorded answer cannot be replayed at the next poll and
        // the numbers cannot be edited in flight. No nonce = not a twin's poll,
        // and then there is nothing to be fresh about and nothing is signed.
        //
        // The generation (stinky row 18, 2026-10-10) is signed with them: a
        // primary names which restore of its log it is, a twin the highest its
        // primary has been. A fence that cannot be read is refused by name, never
        // answered as 0 — a twin would take that for an old main.
        let root = self.stores.root();
        let generation = if crate::twin::is_twin_root(root) {
            crate::twin::pinned_generation(root)
        } else {
            crate::twin::log_generation(root)
        };
        head.generation = generation.map_err(|err| ControlError::Internal(format!("this box's log generation: {err:#}")))?;
        let (key, sig) =
            crate::twin::sign_head_answer(&self.stores, nonce, &head.log_id, head.first_seq, head.head_seq, head.generation);
        head.answer_key = key;
        head.answer_sig = sig;
        Ok(head)
    }

    fn fence_by_generation(&self, proof: &gunnar_proto::GenerationProof) -> ControlResult<()> {
        crate::twin::fence_by_proof(&self.stores, proof)
            .map(drop)
            .map_err(|err| ControlError::Internal(format!("fencing this box off as an old generation of its log: {err:#}")))
    }

    fn log_fetch(
        &self,
        from: u64,
        to: u64,
        max_bytes: u64,
    ) -> ControlResult<Vec<gunnar_proto::LogEntry>> {
        let log = self.readable_log()?;
        let entries = crate::twin::fetch_range(log, from, to, max_bytes).map_err(log_read_refusal)?;
        Ok(entries
            .into_iter()
            .map(|e| gunnar_proto::LogEntry {
                seq: e.seq,
                kind: e.kind as u32,
                meta: e.meta,
                blob: e.blob,
            })
            .collect())
    }

    /// **`Mirror.LogFetch` off the segments, a piece at a time** (twin-streaming, 2026-10-06):
    /// the refusals now, as the call's status; then [`crate::twin::stream_range`] — the payload
    /// crc of every entry checked before its last piece leaves — through [`ChunkOut`] onto the
    /// wire. What this box holds of an entry is one piece, whatever its size.
    fn log_fetch_stream(&self, from: u64, to: u64, max_bytes: u64) -> ControlResult<gunnar_grpc::seam::LogFetchProducer> {
        self.log_fetch_stream_at(from, 0, to, max_bytes)
    }

    /// [`Self::log_fetch_stream`] with the first entry from byte `from_offset` on
    /// (restore-large-entry, 2026-10-07): [`crate::twin::stream_range_at`].
    fn log_fetch_stream_at(&self, from: u64, from_offset: u64, to: u64, max_bytes: u64) -> ControlResult<gunnar_grpc::seam::LogFetchProducer> {
        let log = self.readable_log()?;
        crate::twin::check_range(log, from, to).map_err(log_read_refusal)?;
        let stores = Arc::clone(&self.stores);
        Ok(Box::new(move |sink| {
            let mut out = ChunkOut { sink, open: None };
            crate::twin::stream_range_at(stores.txlog(), from, from_offset, to, max_bytes, &mut out).map(drop).map_err(|err| {
                let err = match err.downcast::<ControlError>() {
                    Ok(said) => return said,
                    Err(other) => other,
                };
                match err.downcast::<gunnar_core::txlog::Error>() {
                    Ok(e) => log_read_refusal(e),
                    Err(other) => ControlError::Internal(format!("transaction log: {other:#}")),
                }
            })
        }))
    }

    #[cfg(feature = "replication")]
    fn replication_status(
        &self,
        include_refs: bool,
    ) -> ControlResult<gunnar_proto::ReplicationStatusResponse> {
        self.replication_slot()?;
        self.replication_snapshot(include_refs)
    }

    /// **The replication watermark** (`Mirror.FlushReplication`,
    /// `DATA-SET-GROWTH-FLOW.md` §2.2, G2, T11): step 0 of the runtime
    /// growth, and the proof — as far as replication can give one — that the
    /// twin is caught up before `/data` is unmounted.
    ///
    /// The flush half of `replication_abdicate`, alone: optionally enqueue
    /// every repository (`resync`, the only way a repository nobody pushed
    /// since the twin existed reaches it), then wait — bounded — for every
    /// standby's queue to drain. No freeze, no demote. The tuple it answers
    /// is §2.2's conjunction, measured at the end of the wait, and `verdict`
    /// says in words what it proves and what §2.1 says it cannot.
    #[cfg(feature = "replication")]
    fn replication_flush(
        &self,
        request: &gunnar_proto::FlushReplicationRequest,
    ) -> ControlResult<gunnar_proto::FlushReplicationResponse> {
        let slot = self.replication_slot()?;
        let began = gunnar_grpc::bus::now_unix_ms();
        let started = std::time::Instant::now();
        let ceiling = if request.timeout_secs == 0 { abdicate_flush_secs() } else { u64::from(request.timeout_secs) };
        let Some(replicator) = slot.replicator() else {
            return Err(ControlError::FailedPrecondition(
                "no replicator is running on this box (no standby configured, or this box is not a primary); there is nothing to flush and nothing to prove".to_owned(),
            ));
        };
        if request.resync {
            replicator
                .resync_scoped(None, None, &[])
                .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        }
        let deadline = started + std::time::Duration::from_secs(ceiling);
        loop {
            let drained = replicator.status().iter().all(|s| s.pending == 0);
            if drained || std::time::Instant::now() >= deadline {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(100));
        }
        let status = replicator.status();
        let counters = replicator.counters();
        let pending: u64 = status.iter().map(|s| s.pending as u64).sum();
        let needs_full_resync = status.iter().any(|s| s.needs_full_resync);
        let last_success = status
            .iter()
            .map(|s| s.last_success_unix_ms.unwrap_or(0))
            .min()
            .unwrap_or(0);
        let in_flight = self.admission.as_ref().map(|a| a.in_flight()).unwrap_or(0);
        let catalog_repos = self
            .stores
            .catalog()
            .counts()
            .map(|(_, repos)| repos as u64)
            .unwrap_or(0);
        let standbys = self.replication_snapshot(false)?.standbys;
        let caught_up = in_flight == 0
            && !status.is_empty()
            && pending == 0
            && !needs_full_resync
            && status.iter().all(|s| s.last_success_unix_ms.is_some_and(|t| t >= began) || s.pending == 0 && s.last_success_unix_ms.is_some());
        let verdict = if status.is_empty() {
            "no standby is configured: nothing was flushed and nothing is proven".to_owned()
        } else if caught_up {
            format!(
                "CAUGHT UP as far as replication can prove: {} standby(s), nothing pending, no full-resync hole, {} transfer(s) in flight, {} bus gap(s) since boot{}. What this does NOT prove (DATA-SET-GROWTH-FLOW.md §2.1): refs outside heads/tags, LFS objects, the control database, visibility, tombstones, and — unless `resync` ran once since the twin existed — repositories nobody pushed since",
                status.len(),
                in_flight,
                counters.bus_gaps,
                if request.resync { " (every catalog repository was enqueued)" } else { "" }
            )
        } else {
            let names: Vec<String> = status
                .iter()
                .filter(|s| s.pending > 0 || s.needs_full_resync)
                .map(|s| format!("{} (pending {}{})", s.name, s.pending, if s.needs_full_resync { ", needs full resync" } else { "" }))
                .collect();
            format!(
                "NOT caught up after {} s: {} transfer(s) in flight, {} repository(ies) pending [{}]{}; the growth must not unmount the set on this",
                started.elapsed().as_secs(),
                in_flight,
                pending,
                names.join(", "),
                if needs_full_resync { " — a standby has a hole retrying will not close: run `replication resync`" } else { "" }
            )
        };
        tracing::info!(
            target: "gunnar::replication",
            event = "replication.flush",
            caught_up,
            in_flight,
            pending,
            bus_gaps = counters.bus_gaps,
            needs_full_resync,
            waited_ms = started.elapsed().as_millis() as u64,
            "{verdict}"
        );
        Ok(gunnar_proto::FlushReplicationResponse {
            caught_up,
            in_flight,
            pending,
            bus_gaps: counters.bus_gaps,
            needs_full_resync,
            last_success_unix_ms: last_success,
            flushed_at_unix_ms: began,
            waited_ms: started.elapsed().as_millis() as u64,
            standbys,
            catalog_repos,
            verdict,
        })
    }

    /// **Demote: clear EVERY replication target in one write.** The failover
    /// primitive — see the `Mirror.DemoteReplication` proto comment for the
    /// split-brain it closes. A recovered old-primary still lists the box that
    /// is now the new primary, and its replicator force-clobbers the new
    /// primary's post-failover writes; demoting it drops that whole roster so it
    /// can be re-added as the new primary's standby instead.
    ///
    /// Idempotent, and never `NotFound`: unlike `replication_remove`, which
    /// names one standby and must distinguish "removed the one you meant" from
    /// "removed one that was never there", demote clears the lot — a box with no
    /// targets is a perfectly good thing to demote and comes back `Ok` with zero
    /// cleared, because "make sure I am not a primary" must not fail on a box
    /// that already is not one.
    #[cfg(feature = "replication")]
    fn replication_demote(&self) -> ControlResult<gunnar_proto::ReplicationStatusResponse> {
        let slot = self.replication_slot()?;
        let mut config = slot
            .config()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        config.clear_targets();
        slot.apply(config)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        self.replication_snapshot(false)
    }

    /// **Set this box's role**: a writable `Primary`, or a read-only `Standby`.
    ///
    /// The one writer. It persists the role into `replication.json` (so it
    /// survives the reboot after a power cut) AND flips the shared
    /// write-gate the SSH/HTTP front doors read — both from
    /// [`ReplicationSlot::apply`], which is the single place the two are kept in
    /// step (one implementation). `PRIMARY` is the **takeover flip** a promoted standby runs;
    /// `STANDBY` is how a box is deliberately made read-only. Idempotent: setting
    /// the role a box already holds writes the same file and the same flag.
    #[cfg(feature = "replication")]
    fn replication_set_role(
        &self,
        role: gunnar_proto::ReplicationRole,
    ) -> ControlResult<gunnar_proto::ReplicationStatusResponse> {
        let slot = self.replication_slot()?;
        let mut config = slot
            .config()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        let wanted = crate::mirror::Role::from_proto(role);
        // **A browse replica cannot be promoted** (the browse replica). Not by an
        // operator's `SetRole PRIMARY`, not by `abdicate --promote`, not by the
        // passive heartbeat: the box holds only public repositories and serves
        // strangers; as a primary it would be a git host with half the data
        // and an open door. The only way out is `STANDBY`, which narrows what
        // the box serves and keeps it frozen — from there an operator may
        // promote, and by then they have said so twice.
        if config.role.is_browse() && wanted == crate::mirror::Role::Primary {
            return Err(ControlError::FailedPrecondition(
                "this box is a browse replica; it cannot be promoted to primary. It holds only \
                 public repositories and serves anonymous reads — first `gunnar control \
                 replication demote` it to a plain standby, then promote that"
                    .into(),
            ));
        }
        config.role = wanted;
        slot.apply(config)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        self.replication_snapshot(false)
    }

    /// **Abdicate: the master steps down cleanly, in order.** The voluntary
    /// counterpart to the crash [`Self::replication_demote`] covers, and the
    /// order is the whole difference between a hand-off and a crash:
    ///
    /// 1. **FREEZE** — role → `Standby`, so this box stops taking client writes
    ///    before the flush begins. This closes the residual race `demote` alone
    ///    left open (a client pushing to the box in the window before it is
    ///    demoted): once frozen, there is no such write to lose.
    /// 2. **FLUSH** — resync every standby and wait, with a ceiling, for the
    ///    queues to drain, so the standby has everything that was pending. The
    ///    wait is best-effort: a standby that is down must not wedge the
    ///    abdication forever — the roster still clears below, and a recovered
    ///    standby replays from this box's history when it is re-added the other
    ///    way round.
    /// 3. **DEMOTE** — clear the roster (reusing the same `clear_targets`
    ///    primitive), so the abdicated box can never later clobber the new
    ///    primary.
    ///
    /// It does NOT promote the standby: naming a new primary is the operator's
    /// decision, run as abdication's last act (`SetRole(PRIMARY)` on the
    /// standby — the CLI's `--promote`), never a default this box picks.
    #[cfg(feature = "replication")]
    fn replication_abdicate(&self) -> ControlResult<gunnar_proto::ReplicationStatusResponse> {
        let slot = self.replication_slot()?;

        // 1. FREEZE. role -> Standby, targets untouched (the replicator stays up
        //    for the flush below).
        let mut config = slot
            .config()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        config.role = crate::mirror::Role::Standby;
        slot.apply(config)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;

        // 2. FLUSH. Enqueue every repository for every standby, then wait for
        //    the queues to empty, bounded so a dead standby cannot hang the
        //    hand-off. The workers run on the git runtime, so they make progress
        //    while this admin thread sleeps.
        if let Some(replicator) = slot.replicator() {
            replicator
                .resync_scoped(None, None, &[])
                .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
            let deadline =
                std::time::Instant::now() + std::time::Duration::from_secs(abdicate_flush_secs());
            loop {
                let drained = replicator.status().iter().all(|s| s.pending == 0);
                if drained || std::time::Instant::now() >= deadline {
                    break;
                }
                std::thread::sleep(std::time::Duration::from_millis(100));
            }
        }

        // 3. DEMOTE. Clear the roster so this box can never clobber the new
        //    primary. Re-read: the flush did not change the config, but reading
        //    it back keeps this the same load-modify-apply the other verbs use.
        let mut config = slot
            .config()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        config.clear_targets();
        slot.apply(config)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
        self.replication_snapshot(false)
    }

    /// **The backfill verb.** See `mirror::Replicator::resync_scoped` for the
    /// gap it closes and why enqueueing is the whole of it.
    ///
    /// Three refusals, each of which would otherwise be a silent nothing:
    ///
    /// * a server with a **configuration but no running replicator** — a target
    ///   is on disk and nothing is draining its queue — is `Unavailable` and not
    ///   an `Ok` with zero queued, because the two read identically and only one
    ///   of them makes a second copy;
    /// * a **standby name that is not configured** is `NotFound`, the same rule
    ///   `replication_remove` already applies;
    /// * a **repository this server does not have** is `NotFound` rather than a
    ///   resync of nothing, because the ordinary way to get there is a typo.
    #[cfg(feature = "replication")]
    fn replication_resync(
        &self,
        name: &str,
        repo: Option<&gunnar_proto::RepoPath>,
        except: &[gunnar_proto::RepoPath],
    ) -> ControlResult<gunnar_proto::ResyncReplicationResponse> {
        let slot = self.replication_slot()?;
        let Some(replicator) = slot.replicator() else {
            return Err(ControlError::Unavailable(format!(
                "no replicator is running, so nothing would drain a backfill queue. \
                 `replication.json` holds {} target(s); the server has not started them.",
                slot.config().map(|c| c.targets.len()).unwrap_or(0)
            )));
        };
        let only = match repo {
            None => None,
            Some(path) => Some(Self::repo_ref(path)?),
        };
        let except = except
            .iter()
            .map(Self::repo_ref)
            .collect::<ControlResult<Vec<_>>>()?;
        let reports = replicator
            .resync_scoped(Some(name), only.as_ref(), &except)
            .map_err(|err| ControlError::NotFound(format!("{err:#}")))?;
        Ok(gunnar_proto::ResyncReplicationResponse {
            standbys: reports
                .into_iter()
                .map(|r| gunnar_proto::ResyncStandby {
                    standby: r.standby,
                    in_scope: r.in_scope,
                    queued: r.queued,
                    already_pending: r.already_pending,
                    refused: r.refused,
                    sha1_repos: r.sha1_repos,
                    excluded: r.excluded,
                })
                .collect(),
            status: Some(self.replication_snapshot(false)?),
        })
    }

    // ── outbound webhooks ──────────────────────────────────────────────────

    #[cfg(feature = "webhooks")]
    fn webhook_add(
        &self,
        request: gunnar_proto::AddWebhookRequest,
    ) -> ControlResult<gunnar_proto::WebhookListResponse> {
        let slot = self.webhook_slot()?;
        let endpoint = crate::webhook::Endpoint {
            name: request.name,
            url: request.url,
            kinds: request.kinds,
            namespace: request.namespace,
            repo: request.repo,
            // An empty secret is "no HMAC", not a secret that is the empty
            // string — so it maps to None and `has_secret` reads false.
            secret: Some(request.secret).filter(|s| !s.is_empty()),
            added_at_unix_ms: gunnar_grpc::bus::now_unix_ms(),
        };
        // `add` validates the URL and the kind names, so a typo is refused here
        // (InvalidArgument) rather than silently delivering nowhere.
        slot.add(endpoint)
            .map_err(|err| ControlError::InvalidArgument(format!("{err:#}")))
    }

    #[cfg(feature = "webhooks")]
    fn webhook_list(&self) -> ControlResult<gunnar_proto::WebhookListResponse> {
        self.webhook_slot()?
            .list_response()
            .map_err(|err| ControlError::Internal(format!("{err:#}")))
    }

    #[cfg(feature = "webhooks")]
    fn webhook_remove(
        &self,
        name: &str,
    ) -> ControlResult<gunnar_proto::WebhookListResponse> {
        let slot = self.webhook_slot()?;
        slot.remove(name)
            .map_err(|err| ControlError::Internal(format!("{err:#}")))?
            // NotFound and not a silent success: "removed the endpoint" about
            // one that was never there reads identically to removing the one you
            // meant, and the difference is whether events are still being sent.
            .ok_or_else(|| ControlError::NotFound(format!("no webhook endpoint named {name:?}")))
    }
}

/// The largest `Refs.ReadObject` response, and it is **not** a number somebody
/// picked.
///
/// # Measured off the transport, not chosen
///
/// `tonic 0.13.1`'s `DEFAULT_MAX_RECV_MESSAGE_SIZE` is `4 * 1024 * 1024`
/// (`tonic/src/codec/mod.rs:100`; the send default beside it is `usize::MAX`).
/// gunnar overrides neither. So a response larger than this **cannot be
/// received by a client using the generated stub's defaults** — it fails on the
/// client with a length error after the server has already paid for it. Refusing
/// it before inflating turns an expensive failure into a cheap one; it does not
/// turn a working request into a refusal, which is the objection that kept this
/// entry open.
///
/// The refusal is on the size of the **response**, not of the object, so
/// `max_bytes` still works: asking for a 1 KiB prefix of a 1 GiB blob is
/// answered exactly as before.
///
/// # What this alone does NOT fix
///
/// The server still inflates the whole object to produce that prefix, because
/// `ObjectStore` has no bounded read and cannot honestly grow one — a prefix of
/// a delta-encoded object needs its whole base chain (the investigation is in
/// the object-ceiling record, checked against `gix-odb 0.83.0`). Bounding *that* needs a
/// ceiling on the **object**, which is [`DEFAULT_MAX_OBJECT_BYTES`] below.
const MAX_RESPONSE_BYTES: u64 = 4 * 1024 * 1024;

/// The memory this deployment is willing to spend on `Refs.ReadObject`
/// inflations, in total, across every control-plane worker at once.
///
/// 512 MiB. The control plane is an administrative surface — a handful of
/// operators and a UI — sharing a box with the thing that actually matters, the
/// git serving path. Half a gigabyte is a rounding error against a forge host's
/// memory and is far more than object *inspection* has any business using; the
/// number that would need defending is a larger one, not this.
const READ_OBJECT_MEMORY_BUDGET: u64 = 512 * 1024 * 1024;

/// The most control-plane workers that can be inflating at once.
///
/// `read_object` runs **synchronously** on a control-plane worker (the split gave
/// the control plane its own runtime and deliberately did not add
/// `spawn_blocking`), so the number of concurrent inflations is the number of
/// those workers, and further callers queue rather than allocate.
/// [`control_plane_workers`](crate::serve::control_plane_workers) is
/// `cores / 4` clamped to `4..=8` (the handler workers, R5.1-G), so **8** is its ceiling on any machine.
///
/// The clamp's upper bound is used rather than the live count on purpose: a
/// default derived from `available_parallelism()` would make this RPC refuse
/// different requests on a laptop and on the forge host, which is precisely the
/// class of difference that is not found until production.
///
/// **This bound moves** if these methods are ever wrapped in `spawn_blocking` —
/// which `gunnar-grpc/src/seam.rs` still asks for, and the admission record says
/// the gRPC router still has no `ConcurrencyLimitLayer`. On that day the
/// denominator becomes unbounded and this constant is where to start.
const MAX_CONCURRENT_INFLATES: u64 = 8;

/// **The object ceiling** `Refs.ReadObject` refuses above — 64 MiB.
///
/// ```text
///   ceiling  =  memory budget for this RPC  ÷  concurrent inflates
///            =  512 MiB                     ÷  8
///            =  64 MiB          (a 512 MiB worst case, which is the budget)
/// ```
///
/// # This one really does refuse a request that works today
///
/// [`MAX_RESPONSE_BYTES`] costs nobody anything — it declines to build a response
/// no client could receive. This is different: asking for a 1 KiB prefix of a
/// 100 MiB blob is a request the server can answer today and will now refuse,
/// because answering it means materialising 100 MiB to hand back a kilobyte, and
/// eight of those concurrently is 800 MiB out of the git path's memory on an
/// unauthenticated RPC.
///
/// 64 MiB is chosen against what git itself does rather than out of the air: a
/// blob that large is already outside what belongs in a pack — it is what
/// `gunnar-lfs` exists for — and this is an *inspection* surface, not the clone
/// path, which is untouched by this and streams. The refusal names the object's
/// size, so a caller learns the fact rather than a limit.
///
/// A deployment that disagrees sets its own with
/// [`CoreControlPlane::with_max_object_bytes`], including `0` for no ceiling.
const DEFAULT_MAX_OBJECT_BYTES: u64 = READ_OBJECT_MEMORY_BUDGET / MAX_CONCURRENT_INFLATES;

// `PROTECTION_GAP` stood here, and it read:
//
//   > Policy.*: gunnar-core has no store for branch protection or ref-name
//   > policy … Serving this over gRPC needs a policy document in the catalog
//
// There is one — `gunnar_core::PolicyStore`, at `refs/gunnar/policy` — and
// every `Policy.*` verb below is served from it. The constant outlived the
// refusal it explained: `cargo check` called it `never used` while
// `gunnar-ui/docs/coverage.md` was still quoting it to render six console
// panels as disabled. A dead string that a doc still believes is worse than no
// string, so it is gone rather than left as a comment with a name.

// `MIRROR_GAP` stood here too, and it read:
//
//   > Mirror.*: mirroring runs over gunnar-client (nornir-git ls-remote +
//   > fetch), which an S crate must never link (the dependency budget). Use `gunnar mirror` on a
//   > normal-OS host instead
//
// It had already been narrowed from all four verbs to the one that genuinely
// needed a fetch client. That client exists in-tree now —
// `gunnar_wire::fetch_pack`, no gix, no `.git` directory, no worktree, over the
// same `BufRead`/`Write` pair `upload_pack` answers on — so `Mirror.Sync` is
// served rather than refused and the string is gone for the reason
// `PROTECTION_GAP`'s is: a dead refusal a doc still quotes is worse than no
// refusal. `gunnar-cli/tests/policy_mirror.rs` mentions it by name; that is
// prose about the history, and this paragraph is what it now describes.

impl CoreControlPlane {
    /// `Usage.*` is not readable while the data set is unmounted for a growth.
    fn usage_readable(&self) -> ControlResult<()> {
        if self.stores.txlog().is_released() || crate::twin::maintenance::is_held(self.stores.root()) {
            return Err(ControlError::Unavailable(format!(
                "{} this box's data set is being grown (unmounted): its usage is read again after the remount — ask again",
                gunnar_grpc::PRIMARY_GROWING
            )));
        }
        Ok(())
    }

    /// The indexed objects of `namespace`'s OPEN stores, now.
    fn open_objects_of(&self, namespace: &str) -> u64 {
        let prefix = self.stores.repos_root().canonicalize().unwrap_or_else(|_| self.stores.repos_root().to_path_buf()).join(namespace);
        self.stores
            .engine()
            .open_object_counts()
            .into_iter()
            .filter(|(dir, _)| dir.parent() == Some(prefix.as_path()))
            .map(|(_, n)| n)
            .sum()
    }

    /// **One `NamespaceUsage` row**: what the ledger holds, the open objects,
    /// and the FLOW half off the flow ledger's live atomics.
    fn usage_row(
        &self,
        name: &str,
        held: &crate::usage_ledger::Held,
        objects: u64,
        measured_at_unix_ms: i64,
    ) -> gunnar_proto::NamespaceUsage {
        let mut row = gunnar_proto::NamespaceUsage {
            namespace: name.to_owned(),
            measured_at_unix_ms,
            pack_bytes: held.bytes.pack,
            cache_bytes: held.bytes.cache,
            lfs_bytes: held.bytes.lfs,
            tombstoned_bytes: held.tombstoned_bytes,
            repos: held.repos,
            objects,
            ..Default::default()
        };
        fill_flow(&mut row, self.stores.flow(), name, measured_at_unix_ms);
        row
    }

    /// **Every namespace, walked now** (`Usage.ReadAll`): the full recount —
    /// one catalog list, one tombstone walk, every repository's directory. The
    /// reading the usage ledger must always agree with.
    fn usage_all(&self) -> ControlResult<Vec<gunnar_proto::NamespaceUsage>> {
        let catalog = self.stores.catalog();
        let namespaces: Vec<String> = catalog
            .namespaces()
            .map_err(internal)?
            .into_iter()
            .map(|ns| ns.name)
            .collect();
        let repos = catalog.list(None).map_err(internal)?;
        let tombstones = self.stores.tombstones().unwrap_or_default();
        let open_objects: std::collections::HashMap<std::path::PathBuf, u64> =
            self.stores.engine().open_object_counts().into_iter().collect();
        let flow = self.stores.flow();
        let measured_at_unix_ms = gunnar_core::now_ms();
        let mut by_ns: std::collections::HashMap<&str, Vec<&gunnar_core::Repo>> = std::collections::HashMap::new();
        for repo in &repos {
            by_ns.entry(repo.namespace.as_str()).or_default().push(repo);
        }
        let mut out = Vec::with_capacity(namespaces.len());
        for name in namespaces {
            let mut row = gunnar_proto::NamespaceUsage {
                namespace: name.clone(),
                measured_at_unix_ms,
                ..Default::default()
            };
            for repo in by_ns.get(name.as_str()).map(Vec::as_slice).unwrap_or(&[]) {
                let path = RepoRef::new(&repo.namespace, &repo.name).map_err(|err| {
                    ControlError::Internal(format!("a catalogued repository has an illegal path: {err}"))
                })?;
                let dir = self
                    .stores
                    .repo_dir(&path)
                    .map_err(|err| ControlError::Internal(format!("{err:#}")))?;
                let bytes = repo_bytes(&dir);
                row.repos += 1;
                row.pack_bytes += bytes.pack;
                row.cache_bytes += bytes.cache;
                row.lfs_bytes += bytes.lfs;
                row.objects += open_objects.get(&dir).copied().unwrap_or(0);
            }
            row.tombstoned_bytes = tombstones
                .iter()
                .filter(|t| t.path.namespace() == name)
                .map(|t| t.bytes)
                .sum();
            fill_flow(&mut row, flow, &name, measured_at_unix_ms);
            out.push(row);
        }
        Ok(out)
    }
}

/// ── the FLOW half of a usage row ────────────────────────────────────────────
///
/// Everything else in a row is what the namespace HOLDS, and it reads the same
/// for a tenant who pushed this morning and a tenant who last touched this box
/// in March. These seven are what MOVED, read off the flow ledger's live
/// atomics — no walk, no disk, one hash lookup — so that a console showing a
/// usage row can tell a working customer from a silent one without a second
/// call.
///
/// A namespace nothing has moved through today has zeroes here, and for a flow
/// meter a zero is a fact: a transfer either occurred or it did not.
/// `last_push_unix_ms` and `last_fetch_unix_ms` are the exception and look back
/// over the WHOLE kept window, because "how long has this tenant been quiet" is
/// the question they exist for.
fn fill_flow(row: &mut gunnar_proto::NamespaceUsage, flow: &gunnar_core::FlowLedger, name: &str, now_unix_ms: i64) {
    let glance = flow.glance(name, now_unix_ms);
    row.bytes_in_today = glance.today.bytes_in;
    row.bytes_out_today = glance.today.bytes_out;
    row.pushes_today = glance.today.pushes;
    row.fetches_today = glance.today.fetches;
    row.refused_today = glance.today.refused();
    row.last_push_unix_ms = glance.last_push_unix_ms;
    row.last_fetch_unix_ms = glance.last_fetch_unix_ms;
}

/// Loose object count and total bytes under `objects/`.
///
/// Walked rather than estimated: `Admin.StorageInfo` exists so an operator can
/// see what is actually on the disk, and a number that came from a guess would
/// be worse than no number.
fn object_dir_stats(git_dir: &std::path::Path) -> (u64, u64) {
    fn walk(dir: &std::path::Path, loose: &mut u64, bytes: &mut u64, in_loose_shard: bool) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            let name = entry.file_name();
            let name = name.to_string_lossy();
            if kind.is_dir() {
                // A loose-object shard is two hex characters.
                let shard = name.len() == 2 && name.chars().all(|c| c.is_ascii_hexdigit());
                walk(&entry.path(), loose, bytes, shard);
            } else if kind.is_file() {
                if in_loose_shard {
                    *loose += 1;
                }
                if let Ok(meta) = entry.metadata() {
                    *bytes += meta.len();
                }
            }
        }
    }
    let mut loose = 0;
    let mut bytes = 0;
    walk(&git_dir.join("objects"), &mut loose, &mut bytes, false);
    (loose, bytes)
}

/// **One repository's bytes, attributed per file.** The one walk both
/// `Admin.StorageInfo` and `Usage.Read` are summed from (one implementation), so the two
/// cannot disagree about what a directory weighs.
///
/// The classification is by file name and is engine-neutral on purpose:
///
/// | file | meter |
/// |---|---|
/// | `<git_dir>/lfs/**` | `lfs` |
/// | `…/objects.exploded*` (znippy's eager and lazy pools) | `cache` |
/// | everything else — `objects.pack` + journal, `objects.index` (the persisted oid index, 2026-09-04), `objects.tail`, `objects.graph`, `refs.log`, `OBJECT_FORMAT`; gix's `objects/**` and refs (`objects.ordinal` is gone as of 2026-09-04 — the index's oid column is the ordinal space; a stale one is deleted at open) | `pack` |
///
/// `pack` is therefore "the hot tier minus the exploded cache" exactly as
/// `usage.proto` promises — it includes the derived index files, which are
/// re-derivable, because that is the contract monetize's own client-side sum
/// reaches and two definitions of one bill is the thing to avoid. The file
/// list is written in `usage.proto`'s header; a new file the engine grows lands
/// in `pack` until somebody names it, which errs on the side of the operator
/// seeing it rather than not.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RepoBytes {
    /// The truth and its indexes: everything that is neither cache nor LFS.
    pub pack: u64,
    /// znippy's exploded read cache, as it is on the disk right now.
    pub cache: u64,
    /// LFS objects, committed and in flight.
    pub lfs: u64,
}

impl RepoBytes {
    /// The whole directory minus LFS: what `RepoStorage.hot_bytes` reports.
    pub fn hot(&self) -> u64 {
        self.pack + self.cache
    }
}

/// See [`RepoBytes`].
pub fn repo_bytes(git_dir: &std::path::Path) -> RepoBytes {
    fn walk(dir: &std::path::Path, acc: &mut RepoBytes) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let Ok(meta) = entry.metadata() else {
                continue;
            };
            if meta.is_dir() {
                walk(&entry.path(), acc);
            } else if entry
                .file_name()
                .to_string_lossy()
                .starts_with("objects.exploded")
            {
                acc.cache += meta.len();
            } else {
                acc.pack += meta.len();
            }
        }
    }
    let mut acc = RepoBytes::default();
    let Ok(entries) = std::fs::read_dir(git_dir) else {
        return acc;
    };
    for entry in entries.flatten() {
        let Ok(meta) = entry.metadata() else {
            continue;
        };
        if meta.is_dir() && entry.file_name() == gunnar_lfs::fs_store::LFS_DIR {
            acc.lfs += crate::stores::dir_bytes(&entry.path());
        } else if meta.is_dir() {
            walk(&entry.path(), &mut acc);
        } else {
            acc.pack += meta.len();
        }
    }
    acc
}

// ───────────────────────────────────────────────────────────────────────────
// ACL identity: the gRPC gate's two questions, answered by `AuthTable`
// ───────────────────────────────────────────────────────────────────────────

/// **The one place gRPC identity is decided, and it decides nothing itself.**
///
/// `gunnar-grpc` closed the allow-all authentication hole with SSH-key-derived
/// identity: a caller signs a single-use challenge with a key that is already
/// in the ACL key table, and the gate asks the control plane two questions:
/// *whose key is this*, and *may they*. Both are delegated here, and both land
/// on [`AuthTable`]:
///
/// | question | answered by |
/// |---|---|
/// | whose key is this | [`AuthTable::principal_by_fingerprint`] (expiry included) |
/// | may they | [`AuthTable::may_server`] / [`AuthTable::may_namespace`] / [`AuthTable::may`] |
///
/// So gRPC and SSH share one identity table and **one** ACL. Revoking a key
/// over gRPC revokes it for git in the same instant, and there is no second
/// grant decision that could drift from the first — one implementation,
/// because two disagreeing security checks have cost this design once already.
impl gunnar_grpc::Identity for CoreControlPlane {
    /// The installer's feed, as `crate::fed_principals::note_fed` left it: the
    /// keys this primary will enrol and has not yet.
    fn awaiting_enrolment(&self, fingerprint: &str) -> Option<String> {
        self.stores.awaiting_enrolment(fingerprint)
    }

    fn registered_key(
        &self,
        fingerprint: &str,
    ) -> ControlResult<Option<gunnar_grpc::RegisteredKey>> {
        // A malformed fingerprint is "no such key", not an error: the string
        // came off a public port and refusing to parse it loudly would make
        // this an oracle for what a well-formed fingerprint looks like.
        let Ok(parsed) = gunnar_core::Fingerprint::parse(fingerprint) else {
            return Ok(None);
        };
        // `principal_by_fingerprint` is the SSH listener's own lookup; it
        // already refuses an expired key and a key whose principal is gone.
        let Some(principal) = self
            .stores
            .auth()
            .principal_by_fingerprint(&parsed)
            .map_err(internal)?
        else {
            return Ok(None);
        };
        let key = self
            .stores
            .auth()
            .keys_of(&principal.id)
            .map_err(internal)?
            .into_iter()
            .find(|key| key.fingerprint_sha256 == fingerprint);
        let machine = principal.kind == gunnar_core::PrincipalKind::Machine;
        Ok(key.map(|key| gunnar_grpc::RegisteredKey {
            principal_id: principal.id,
            machine,
            // The `authorized_keys` line the key was registered from. The gate
            // verifies the sshsig against it and re-derives the fingerprint
            // from it, so a wrong row here cannot become a wrong identity.
            openssh: key.openssh,
        }))
    }

    /// The X.509 half of the **same** table `registered_key` reads.
    ///
    /// `gunnar control bootstrap` has minted client certificates and registered
    /// them under `algo: "x509"` since the certificate-identity plan's first-boot
    /// half landed; until the listener grew mTLS there was nothing that could
    /// look one up, so those registrations were inert. This is the lookup, and it
    /// is deliberately the
    /// same three steps `registered_key` takes — hash, principal, key row — so
    /// that revoking a certificate over gRPC revokes it for the handshake in
    /// the same instant, out of one table (one implementation).
    ///
    /// No `openssh` line comes back and none is wanted: the handshake already
    /// proved possession, so there is no second signature to check. See
    /// [`gunnar_grpc::CertificateIdentity`].
    fn registered_certificate(
        &self,
        der: &[u8],
    ) -> ControlResult<Option<gunnar_grpc::CertificateIdentity>> {
        // The one place that decides what bytes a certificate credential is.
        // `gunnar-grpc` hands the DER across the seam rather than a
        // fingerprint precisely so this stays the only spelling of it.
        let fingerprint = gunnar_core::auth::fingerprint_of_certificate(der);
        let Some(principal) = self
            .stores
            .auth()
            .principal_by_fingerprint(&fingerprint)
            .map_err(internal)?
        else {
            return Ok(None);
        };
        // `principal_by_fingerprint` already refuses an expired key and a key
        // whose principal is gone. The row is re-read so that a fingerprint
        // that resolves to a principal but has no key row — a state only a
        // corrupted table can be in — is "no identity" rather than an
        // identity with no credential behind it.
        let registered = self
            .stores
            .auth()
            .keys_of(&principal.id)
            .map_err(internal)?
            .into_iter()
            .any(|key| key.fingerprint_sha256 == fingerprint.to_string());
        if !registered {
            return Ok(None);
        }
        Ok(Some(gunnar_grpc::CertificateIdentity {
            principal_id: principal.id,
            fingerprint: fingerprint.to_string(),
        }))
    }

    /// f-principal-reach: what `fed_principals::install` narrowed a `billing`
    /// principal to, from the data root.
    fn narrowed_methods(&self, principal_id: &str) -> ControlResult<Option<Vec<String>>> {
        // ★ The estate's repair principal is narrowed by its NAME, on every box and in every
        // build (main rebuild, owner 2026-10-12): never admin, whatever it was granted.
        if principal_id == gunnar_grpc::REPAIR_PRINCIPAL {
            return Ok(Some(gunnar_grpc::REPAIR_METHODS.iter().map(|m| m.to_string()).collect()));
        }
        // The narrowing is written by the fed principals (the `wg-client` build,
        // the appliance's); a build without them narrows nobody.
        #[cfg(feature = "wg-client")]
        return crate::fed_principals::narrowed_of(self.stores.root(), principal_id).map_err(ControlError::Internal);
        #[cfg(not(feature = "wg-client"))]
        {
            let _ = principal_id;
            Ok(None)
        }
    }

    fn may(
        &self,
        principal_id: &str,
        access: &gunnar_grpc::Access,
        level: gunnar_proto::GrantLevel,
    ) -> ControlResult<bool> {
        let level = level_in(level)?;
        let auth = self.stores.auth();
        match access {
            gunnar_grpc::Access::Server => auth.may_server(principal_id, level).map_err(internal),
            gunnar_grpc::Access::Namespace(namespace) => auth
                .may_namespace(principal_id, namespace, level)
                .map_err(internal),
            gunnar_grpc::Access::Repo(path) => {
                let repo_ref = Self::repo_ref(path)?;
                // A grant on a repository that does not exist means nothing.
                // Answering `true` here would let a caller probe the ACL for
                // repositories it cannot see.
                let Some(repo) = self.stores.catalog().get(&repo_ref).map_err(internal)? else {
                    return Ok(false);
                };
                auth.may(principal_id, &repo, level).map_err(internal)
            }
        }
    }

    /// One read of the catalog and one of the identity table for the whole
    /// listing (round 5.3.1); a row that does not exist is `false`, as `may`.
    fn may_each_repo(
        &self,
        principal_id: &str,
        paths: &[RepoPath],
        level: gunnar_proto::GrantLevel,
    ) -> ControlResult<Vec<bool>> {
        let level = level_in(level)?;
        let refs = paths.iter().map(Self::repo_ref).collect::<ControlResult<Vec<_>>>()?;
        let rows = self.stores.catalog().get_many(&refs).map_err(internal)?;
        let known: Vec<gunnar_core::model::Repo> = rows.iter().flatten().cloned().collect();
        let mut answers = self.stores.auth().may_each(principal_id, &known, level).map_err(internal)?.into_iter();
        Ok(rows.iter().map(|row| row.is_some() && answers.next().unwrap_or(false)).collect())
    }
}

// ───────────────────────────────────────────────────────────────────────────
// Policy: the proto shape and the engine shape
// ───────────────────────────────────────────────────────────────────────────

/// One `gunnar_policy::ProtectionRule`, as the protocol spells it.
///
/// The two limit fields come back **0**, which the proto documents as "no
/// limit", and that is the truth about a *per-rule* limit: this engine has
/// none. The repository-wide ceilings live in the policy document's `limits`
/// and are reported by nothing on this service — see `set_protection` for why
/// writing them here is refused rather than approximated.
fn protection_out(rule: &gunnar_policy::ProtectionRule) -> BranchProtection {
    BranchProtection {
        ref_pattern: rule.pattern.as_str().to_owned(),
        allow_force_push: rule.allow_force_push,
        allow_delete: rule.allow_delete,
        require_signature: rule.require_signature,
        // `None` — "anybody" — is the empty list, which is what the proto
        // means by empty. The round trip is stable in both directions.
        allowed_principal_ids: rule.allowed_principals.clone().unwrap_or_default(),
        max_object_bytes: 0,
        max_objects_per_push: 0,
        forbid_self_approval: rule.forbid_self_approval,
        required_approvals: rule.required_approvals,
    }
}

fn ref_name_policy_out(policy: &gunnar_policy::RefNamePolicy) -> RefNamePolicy {
    RefNamePolicy {
        allow_patterns: policy.allow.iter().map(|p| p.as_str().to_owned()).collect(),
        deny_patterns: policy.deny.iter().map(|p| p.as_str().to_owned()).collect(),
    }
}

/// One `gunnar_core::MirrorRecord`, as the protocol spells it.
///
/// The state is **derived from the record's own facts**, not stored beside
/// them: `SYNCING` is a live condition and nothing here runs a sync, so a
/// stored `SYNCING` could only ever be a lie left behind by a crash. What the
/// record can honestly report is `FAILED` when the last attempt left an error
/// and `IDLE` otherwise — and a registration nobody has synced is `IDLE`, which
/// is what it is.
fn mirror_out(record: &gunnar_core::MirrorRecord) -> MirrorConfig {
    let (namespace, repo) = record
        .repo
        .split_once('/')
        .unwrap_or((record.repo.as_str(), ""));
    MirrorConfig {
        repo: Some(RepoPath::new(namespace, repo)),
        remote_url: record.remote_url.clone(),
        prune: record.prune,
        state: if record.last_error.is_empty() {
            gunnar_proto::MirrorState::Idle as i32
        } else {
            gunnar_proto::MirrorState::Failed as i32
        },
        added_at_unix_ms: record.added_at_unix_ms,
        last_sync_at_unix_ms: record.last_sync_at_unix_ms,
        last_error: record.last_error.clone(),
        sync_count: record.sync_count,
        // **The kind, and never the value.** `WebhookEndpoint.has_secret`'s
        // rule, one step wider because there are two kinds here and picking the
        // wrong one is a refusal an operator has to be able to see coming.
        credential: credential_kind_out(record.credential) as i32,
        credential_username: record.credential_username.clone(),
        // Filled in by the caller that holds the queue; a bare record does not
        // know whether a job exists for it.
        job: None,
        repo_pending: record.creates_repo,
        lfs_not_copied: record.lfs_detected,
    }
}

/// The proto's credential kind onto the store's.
fn credential_kind_in(kind: gunnar_proto::MirrorCredentialKind) -> gunnar_core::MirrorCredentialKind {
    match kind {
        gunnar_proto::MirrorCredentialKind::Unspecified => gunnar_core::MirrorCredentialKind::None,
        gunnar_proto::MirrorCredentialKind::SshKey => gunnar_core::MirrorCredentialKind::SshKey,
        gunnar_proto::MirrorCredentialKind::Token => gunnar_core::MirrorCredentialKind::Token,
    }
}

/// The store's credential kind onto the proto's.
fn credential_kind_out(kind: gunnar_core::MirrorCredentialKind) -> gunnar_proto::MirrorCredentialKind {
    match kind {
        gunnar_core::MirrorCredentialKind::None => gunnar_proto::MirrorCredentialKind::Unspecified,
        gunnar_core::MirrorCredentialKind::SshKey => gunnar_proto::MirrorCredentialKind::SshKey,
        gunnar_core::MirrorCredentialKind::Token => gunnar_proto::MirrorCredentialKind::Token,
    }
}

/// **Unseal the credential a sync dials with, or say there is none.**
///
/// The document is the authority on WHETHER there is one and the secret store
/// on WHAT it is, and a disagreement between them is reported rather than
/// smoothed over: a record that claims a credential whose sealed value is gone
/// would otherwise dial anonymously and be refused by the upstream, which sends
/// an operator to rotate a key that is not the problem.
///
/// The returned [`crate::mirror_fetch::Credential`] is deliberately not
/// `Debug`, so nothing downstream can format it by accident.
fn read_credential(
    stores: &Arc<ServerStores>,
    repo: &gunnar_core::RepoRef,
) -> Result<crate::mirror_fetch::Credential, String> {
    let record = stores
        .mirrors()
        .get(repo)
        .map_err(|err| format!("reading the mirror registration for {}: {err:#}", repo.key()))?
        .ok_or_else(|| format!("no mirror is registered for {} any more", repo.key()))?;
    if !record.credential.is_set() {
        return Ok(crate::mirror_fetch::Credential::None);
    }
    let secrets = stores
        .secrets()
        .map_err(|err| format!("the sealed secret store is not available: {err:#}"))?;
    let key = gunnar_core::credential_secret_key(repo);
    let sealed = gunnar_store::SecretStore::get(&secrets, &key)
        // `{err}` and not `{err:#}`: this string lands on a job a console
        // renders, and a chain from the secret store is where a value could
        // ride out.
        .map_err(|err| format!("the mirror credential for {} could not be read: {err}", repo.key()))?
        .ok_or_else(|| {
            format!(
                "{} is registered as having {}, and the sealed value is not in the secret \
                 store. Set it again with `Mirror.SetCredential`; dialling anonymously \
                 instead would be refused by the upstream and read as a bad key.",
                repo.key(),
                record.credential.name()
            )
        })?;
    Ok(match record.credential {
        gunnar_core::MirrorCredentialKind::SshKey => {
            crate::mirror_fetch::Credential::SshKey(sealed)
        }
        gunnar_core::MirrorCredentialKind::Token => crate::mirror_fetch::Credential::Token {
            username: record.credential_username.clone(),
            secret: String::from_utf8(sealed).map_err(|_| {
                format!(
                    "the token stored for {} is not utf-8, so it cannot be an HTTP header value",
                    repo.key()
                )
            })?,
        },
        gunnar_core::MirrorCredentialKind::None => crate::mirror_fetch::Credential::None,
    })
}

/// **One line in the namespace's account audit log** about a mirror sync, and
/// the same on the `gunnar::audit` target (a namespace with no account, a
/// community box, has the target only).
fn audit_line(stores: &ServerStores, repo: &gunnar_core::RepoRef, kind: &str, detail: &str, refused: bool) {
    tracing::info!(
        target: gunnar_grpc::AUDIT_TARGET,
        event = kind,
        repo = %repo.key(),
        detail,
        "mirror"
    );
    let Ok(Some(account)) = stores.auth().account_of_namespace(repo.namespace()) else { return };
    let event = gunnar_core::account_audit::AccountEvent {
        kind,
        actor: "",
        actor_role: "system",
        target: &repo.key(),
        detail,
        outcome: if refused {
            gunnar_core::account_audit::Outcome::Refused
        } else {
            gunnar_core::account_audit::Outcome::Ok
        },
    };
    if let Err(err) = stores.account_audit().append(&account, event, gunnar_core::now_ms()) {
        tracing::warn!(target: "gunnar::git", repo = %repo.key(), %err, "a mirror sync's audit line was not written");
    }
}

/// **How a sync ended, audited**: an import's (a first sync's) outcome always,
/// a later sync's only when it failed — a mirror polled every few minutes
/// would otherwise fill the log with "nothing new".
fn audit_mirror_outcome(
    stores: &ServerStores,
    repo: &gunnar_core::RepoRef,
    order: &crate::mirror_queue::MirrorOrder,
    first: bool,
    error: Option<&str>,
    report: &crate::job_queue::Reporter<crate::mirror_queue::Mirror>,
) {
    let upstream = crate::mirror_fetch::scrub(&order.upstream);
    match (first, error) {
        (true, None) => {
            let refs = report.snapshot().map(|job| job.report.updates.len()).unwrap_or_default();
            audit_line(stores, repo, "mirror.import.done", &format!("imported {refs} reference(s) from {upstream}"), false);
        }
        (true, Some(why)) => audit_line(stores, repo, "mirror.import.failed", &format!("from {upstream}: {why}"), true),
        (false, Some(why)) => audit_line(stores, repo, "mirror.sync.failed", &format!("from {upstream}: {why}"), true),
        (false, None) => {}
    }
}

/// **The one place a [`crate::mirror_queue::MirrorJob`] becomes a wire job.**
///
/// `gc_job_out`'s twin, and shaped after it deliberately: three status RPCs
/// render the same queue fields, so a console reads a gc, a purge and a mirror
/// with one renderer.
///
/// `path` is threaded in rather than re-parsed out of the job's own key — it is
/// the request's own path, already validated, and re-parsing it here would be a
/// second resolver that could disagree with the first (one implementation).
fn mirror_job_out(
    path: &RepoPath,
    job: crate::mirror_queue::MirrorJob,
) -> gunnar_proto::MirrorJob {
    // The mirror's own half, taken out whole before the queue's half is: the
    // update list is owned and has to be MOVED onto the wire, and a job's
    // `Deref` only ever lends its report.
    let report = job.report;
    let report_refused = report.refused;
    let (progress_done, progress_total) = job.progress.unwrap_or((0, 0));
    gunnar_proto::MirrorJob {
        job_id: job.job_id,
        path: Some(path.clone()),
        state: match job.state {
            crate::mirror_queue::MirrorState::Queued => {
                gunnar_proto::MirrorJobState::Queued as i32
            }
            crate::mirror_queue::MirrorState::Running => {
                gunnar_proto::MirrorJobState::Running as i32
            }
            crate::mirror_queue::MirrorState::Done => gunnar_proto::MirrorJobState::Done as i32,
            crate::mirror_queue::MirrorState::Failed => {
                gunnar_proto::MirrorJobState::Failed as i32
            }
        },
        queue_position: job.queue_position,
        // **`has_progress` first.** A job that has not reached the packfile
        // header has no denominator, and `0/0` would be a progress bar
        // claiming zero per cent instead of admitting it does not know yet.
        has_progress: job.progress.is_some(),
        progress_done,
        progress_total,
        objects: report.objects,
        bytes: report.bytes,
        updates: report
            .updates
            .into_iter()
            .map(|(ref_name, old_oid, new_oid)| gunnar_proto::RefUpdate {
                ref_name,
                old_oid,
                new_oid,
            })
            .collect(),
        error: job.error.unwrap_or_default(),
        enqueued_at_unix_ms: job.enqueued_at_unix_ms,
        started_at_unix_ms: job.started_at_unix_ms,
        finished_at_unix_ms: job.finished_at_unix_ms,
        // Only a FAILED job carries the plan's refusal; a later success of
        // the same registration starts a new job with a fresh report.
        refused_reason: match (job.state, report_refused) {
            (crate::mirror_queue::MirrorState::Failed, crate::mirror_queue::Refusal::Plan) => {
                gunnar_proto::MirrorRefusal::Plan as i32
            }
            (crate::mirror_queue::MirrorState::Failed, crate::mirror_queue::Refusal::PackCap) => {
                gunnar_proto::MirrorRefusal::PackCap as i32
            }
            _ => gunnar_proto::MirrorRefusal::Unspecified as i32,
        },
    }
}

// ── the forge event, across the wire ───────────────────────────────────────
//
// Two functions and no derive, because the wire shape and the signed shape are
// deliberately different things: the signed shape is what `sshsig` covers and
// may never change to suit a transport, and the wire shape is a `oneof` because
// protobuf has no sum type otherwise. Keeping the conversion explicit is what
// makes a change to either one a compile error rather than a silent re-encoding
// that breaks every stored signature.

/// The wire form of a signed membership event.
fn to_proto_membership(
    signed: gunnar_core::SignedMembershipEvent,
) -> gunnar_proto::SignedMembershipEvent {
    gunnar_proto::SignedMembershipEvent {
        event: Some(gunnar_proto::MembershipEvent {
            group: signed.event.group,
            member: signed.event.member,
            action: proto_action(signed.event.action) as i32,
            actor: signed.event.actor,
            at_unix_ms: signed.event.at_unix_ms,
        }),
        key_fingerprint: signed.key_fingerprint,
        signature: signed.signature,
    }
}

/// The signed core form of a wire key attestation. An absent `attestation` is
/// refused rather than defaulted, for the reason `from_proto_membership` gives.
fn from_proto_attestation(
    wire: gunnar_proto::SignedKeyAttestation,
) -> ControlResult<gunnar_core::SignedKeyAttestation> {
    let attestation = wire
        .attestation
        .ok_or_else(|| ControlError::InvalidArgument("`attestation.attestation` is required".to_owned()))?;
    Ok(gunnar_core::SignedKeyAttestation {
        attestation: gunnar_core::KeyAttestation {
            principal_id: attestation.principal_id,
            fingerprint: attestation.fingerprint,
            at_unix_ms: attestation.at_unix_ms,
        },
        key_fingerprint: wire.key_fingerprint,
        signature: wire.signature,
    })
}

/// The signed core form of a wire membership event.
///
/// An absent `event` or an `UNSPECIFIED` action is refused rather than
/// defaulted: proto3 makes every field optional, and a membership change with
/// no action is not a thing that happened.
fn from_proto_membership(
    wire: gunnar_proto::SignedMembershipEvent,
) -> ControlResult<gunnar_core::SignedMembershipEvent> {
    let event = wire
        .event
        .ok_or_else(|| ControlError::InvalidArgument("`event` is required".to_owned()))?;
    let action = match gunnar_proto::MembershipAction::try_from(event.action) {
        Ok(gunnar_proto::MembershipAction::Add) => gunnar_core::MembershipAction::Add,
        Ok(gunnar_proto::MembershipAction::Remove) => gunnar_core::MembershipAction::Remove,
        _ => {
            return Err(ControlError::InvalidArgument(
                "`event.action` must be ADD or REMOVE".to_owned(),
            ))
        }
    };
    Ok(gunnar_core::SignedMembershipEvent {
        event: gunnar_core::MembershipEvent {
            group: event.group,
            member: event.member,
            action,
            actor: event.actor,
            at_unix_ms: event.at_unix_ms,
        },
        key_fingerprint: wire.key_fingerprint,
        signature: wire.signature,
    })
}

/// The wire enum for a core [`gunnar_core::MembershipAction`].
fn proto_action(action: gunnar_core::MembershipAction) -> gunnar_proto::MembershipAction {
    match action {
        gunnar_core::MembershipAction::Add => gunnar_proto::MembershipAction::Add,
        gunnar_core::MembershipAction::Remove => gunnar_proto::MembershipAction::Remove,
    }
}

/// The wire form of a signed event.
fn to_proto_event(signed: gunnar_core::SignedEvent) -> gunnar_proto::SignedForgeEvent {
    use gunnar_proto::forge_event::Kind;

    let kind = match signed.event.event {
        gunnar_core::Event::Commented {
            body,
            path,
            line,
            blob_oid,
        } => Kind::Commented(gunnar_proto::Commented {
            body,
            path,
            line,
            blob_oid,
        }),
        gunnar_core::Event::Approved { commit } => {
            Kind::Approved(gunnar_proto::Approved { commit })
        }
        gunnar_core::Event::Rejected { commit, reason } => {
            Kind::Rejected(gunnar_proto::Rejected { commit, reason })
        }
        gunnar_core::Event::IssueOpened { title, body } => {
            Kind::IssueOpened(gunnar_proto::IssueOpened { title, body })
        }
        gunnar_core::Event::IssueCommented { body } => {
            Kind::IssueCommented(gunnar_proto::IssueCommented { body })
        }
        gunnar_core::Event::IssueClosed { reason } => {
            Kind::IssueClosed(gunnar_proto::IssueClosed { reason })
        }
    };
    gunnar_proto::SignedForgeEvent {
        event: Some(gunnar_proto::ForgeEvent {
            repo: signed.event.repo,
            pull: signed.event.pull,
            actor: signed.event.actor,
            at_unix_ms: signed.event.at_unix_ms,
            kind: Some(kind),
        }),
        key_fingerprint: signed.key_fingerprint,
        signature: signed.signature,
    }
}

/// A folded [`gunnar_core::forge::Issue`], as the wire carries it.
///
/// Unlike a review, this IS the whole state — title, body, open — because there
/// is no record behind an issue for a reader to ask instead. The signatures on
/// the events are what make it evidence; the fold is what makes it a state.
fn issue_state(repo: &str, issue: &gunnar_core::forge::Issue) -> gunnar_proto::IssueState {
    gunnar_proto::IssueState {
        repo: repo.to_owned(),
        number: issue.number,
        title: issue.title.clone(),
        body: issue.body.clone(),
        author: issue.author.clone(),
        open: issue.open,
        comments: issue.comments as u64,
        opened_at_unix_ms: issue.opened_at_unix_ms,
    }
}

/// The signed form of a wire event.
///
/// An absent `kind` is refused rather than defaulted: proto3 makes every field
/// optional, and a `ForgeEvent` with no kind is not a thing that happened.
fn from_proto_event(
    wire: gunnar_proto::SignedForgeEvent,
) -> ControlResult<gunnar_core::SignedEvent> {
    use gunnar_proto::forge_event::Kind;

    let event = wire
        .event
        .ok_or_else(|| ControlError::InvalidArgument("`event` is required".to_owned()))?;
    let kind = event
        .kind
        .ok_or_else(|| ControlError::InvalidArgument("`event.kind` is required".to_owned()))?;
    let inner = match kind {
        Kind::Commented(it) => gunnar_core::Event::Commented {
            body: it.body,
            path: it.path,
            line: it.line,
            blob_oid: it.blob_oid,
        },
        Kind::Approved(it) => gunnar_core::Event::Approved { commit: it.commit },
        Kind::Rejected(it) => gunnar_core::Event::Rejected {
            commit: it.commit,
            reason: it.reason,
        },
        Kind::IssueOpened(it) => gunnar_core::Event::IssueOpened {
            title: it.title,
            body: it.body,
        },
        Kind::IssueCommented(it) => gunnar_core::Event::IssueCommented { body: it.body },
        Kind::IssueClosed(it) => gunnar_core::Event::IssueClosed { reason: it.reason },
    };
    Ok(gunnar_core::SignedEvent {
        event: gunnar_core::ForgeEvent {
            repo: event.repo,
            pull: event.pull,
            actor: event.actor,
            at_unix_ms: event.at_unix_ms,
            event: inner,
        },
        key_fingerprint: wire.key_fingerprint,
        signature: wire.signature,
    })
}
#[cfg(test)]
mod tests {
    use super::*;

    /// ★ **A box being RESTORED answers a write UNAVAILABLE, never INTERNAL** (r5.1, integration
    /// dev run 3: the front certifying the twin against a main being restored read "the primary
    /// would not enrol gunnar-twin: the membership: Internal: internal error" for minutes — a bug
    /// to anyone reading the log, and to the guest). Its log follows the twin's until the restore
    /// is whole, so every write is refused: said as "try again", which a generated client retries.
    #[test]
    fn a_write_on_a_restoring_box_is_unavailable_not_internal() {
        let td = tempfile::tempdir().unwrap();
        let stores = crate::stores::ServerStores::open(td.path()).unwrap();
        stores.txlog().set_follower(true);
        let p = gunnar_core::Principal::new("alice", "alice", gunnar_core::PrincipalKind::User).unwrap();
        let err = stores.auth().add_principal(p).map_err(internal).expect_err("a follower log takes no write");
        assert!(matches!(err, ControlError::Unavailable(_)), "{err:?}");
        assert!(err.to_string().contains("restor"), "{err}");
    }

    /// **`INTERNAL` must be refused by name, never widened.**
    ///
    /// The regression this locks down was real: `visibility_in` aliased
    /// `INTERNAL` onto `Public` from before 2026-08-03, when public still meant
    /// "any authenticated principal". After that the alias silently PUBLISHED
    /// repositories whose creator asked for the narrower thing, and the
    /// console's visibility picker walked straight into it (2026-08-19).
    /// The green arms are the identity-value guard: without them a
    /// `visibility_in` that refuses everything would pass the red arm too.
    #[test]
    fn internal_is_refused_by_name_and_the_two_real_visibilities_pass() {
        let err = visibility_in(gunnar_proto::Visibility::Internal)
            .expect_err("INTERNAL has no implementation and must be refused");
        let text = err.to_string();
        assert!(
            text.contains("internal") && text.contains("private"),
            "the refusal must name the value and the real choices: {text}"
        );
        assert_eq!(
            visibility_in(gunnar_proto::Visibility::Public).expect("public is real"),
            Visibility::Public
        );
        assert_eq!(
            visibility_in(gunnar_proto::Visibility::Private).expect("private is real"),
            Visibility::Private
        );
        // Unspecified still lands on the only safe default.
        assert_eq!(
            visibility_in(gunnar_proto::Visibility::Unspecified).expect("unspecified defaults"),
            Visibility::Private
        );
    }

    /// **The abdication flush ceiling is env-tunable, but only UPWARD-sane.**
    ///
    /// The flush is a poll (drained-or-deadline); the ceiling only bounds how
    /// long a slow standby is given before the roster clears. A loaded rig may
    /// need more than the 30 s default, so `GUNNAR_ABDICATE_FLUSH_SECS` raises
    /// it — but a garbage or zero value must NOT collapse it to something that
    /// truncates the flush before a single job drains. The identity-value guard
    /// here is the default-path assert: without it a resolver that ignored the
    /// override entirely (always returning 30) would still pass the "bad input
    /// falls back" arms, so the `120 -> 120` arm is what proves the override is
    /// actually read.
    #[cfg(feature = "replication")]
    #[test]
    fn abdicate_flush_ceiling_honours_a_sane_override_and_rejects_the_rest() {
        // A real, larger ceiling for a loaded box is taken verbatim.
        assert_eq!(resolve_flush_secs(Some("120")), 120, "a positive override must win");
        assert_eq!(resolve_flush_secs(Some("  90 ")), 90, "surrounding whitespace is trimmed");
        // The default when nothing is set — and it must NOT equal the override
        // above, or the test could not tell a read override from a dead one.
        assert_eq!(resolve_flush_secs(None), ABDICATE_FLUSH_SECS);
        assert_ne!(ABDICATE_FLUSH_SECS, 120, "default must differ from the override arm");
        // Every wrong shape falls back to the safe default, never to 0.
        assert_eq!(resolve_flush_secs(Some("")), ABDICATE_FLUSH_SECS, "blank falls back");
        assert_eq!(resolve_flush_secs(Some("nope")), ABDICATE_FLUSH_SECS, "non-numeric falls back");
        assert_eq!(resolve_flush_secs(Some("0")), ABDICATE_FLUSH_SECS, "zero would truncate — refused");
        assert_eq!(resolve_flush_secs(Some("-5")), ABDICATE_FLUSH_SECS, "negative does not parse as u64");
    }
}

/// An encryption-key refusal as the control plane says it (CRYPT-YUBI).
fn key_refusal(r: gunnar_core::encryption_key::KeyRefusal) -> ControlError {
    use gunnar_core::encryption_key::KeyRefusal as R;
    match r {
        R::AlreadyHasKey(s) | R::MethodHeld(s) => ControlError::AlreadyExists(s),
        R::NoSuchMethod(s) => ControlError::NotFound(s),
        R::NoKey(s) => ControlError::FailedPrecondition(s),
        R::LastMethod(s) => ControlError::FailedPrecondition(s),
        R::Invalid(s) => ControlError::InvalidArgument(s),
        R::Store(e) => internal(e),
    }
}


fn method_in(m: gunnar_proto::UnlockMethod) -> ControlResult<gunnar_core::encryption_key::UnlockMethod> {
    Ok(gunnar_core::encryption_key::UnlockMethod {
        id: String::new(),
        kind: gunnar_core::encryption_key::MethodKind::parse(&m.kind).map_err(key_refusal)?,
        label: m.label.trim().to_owned(),
        method_ref: m.method_ref.trim().to_owned(),
        rp_id: m.rp_id.trim().to_owned(),
        wrap: m.wrap,
        added_ms: 0,
    })
}

fn encryption_key_out(key: Option<gunnar_core::encryption_key::EncryptionKey>) -> gunnar_proto::GetEncryptionKeyResponse {
    match key {
        None => gunnar_proto::GetEncryptionKeyResponse::default(),
        Some(k) => gunnar_proto::GetEncryptionKeyResponse {
            exists: true,
            public_key: k.public_key,
            methods: k
                .methods
                .into_iter()
                .map(|m| gunnar_proto::UnlockMethod {
                    id: m.id,
                    kind: m.kind.word().to_owned(),
                    label: m.label,
                    method_ref: m.method_ref,
                    rp_id: m.rp_id,
                    wrap: m.wrap,
                    added_ms: m.added_ms,
                })
                .collect(),
        },
    }
}