offline-protocol 0.21.0

Main protocol engine for the Offline Protocol SDK
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
//! Group messaging — MLS-encrypted, transport-agnostic group operations.
//!
//! This module implements group creation, member invite/remove/leave,
//! encrypted message fan-out, commit distribution, and pending commit
//! buffering for out-of-order delivery.
//!
//! Groups are transport-agnostic: messages route through whichever transport
//! DORS selects (BLE, WiFi Direct, or Internet). When Internet is available
//! and a relay server supports it, the protocol can send a single relay
//! broadcast instead of O(N) per-member fan-out.

use crate::protocol::{
    base64_decode, base64_encode, internal_prefixes, GroupMemberRemovedPayload,
    InternalMessageResult, OfflineProtocol, RichPayloadV1, RichSendExtras, RICH_PAYLOAD_V1,
};
use crate::{Error, Event, Result};
use chrono::{DateTime, Utc};
use offline_protocol_core::{
    ContentType, ForwardInfo, MediaMetadata, Message, MessageId, MessagePriority,
};
use offline_protocol_mls::GroupRole;
use offline_protocol_transport::TransportType;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::{Duration as StdDuration, Instant};
use tracing::{debug, error, info, warn};

/// TTL for group message dedup entries (5 minutes).
pub(super) const GROUP_MESSAGE_DEDUP_TTL_SECS: u64 = 300;
/// Maximum number of group message dedup entries before forced cleanup.
pub(super) const MAX_GROUP_MESSAGE_DEDUP_ENTRIES: usize = 10_000;
/// Maximum allowed base64-encoded payload size for incoming group messages (1 MB).
pub(crate) const MAX_BASE64_PAYLOAD_SIZE: usize = 1_048_576;
/// How long an outstanding relay group registration waits for its
/// `__GROUP_CREATED__` answer before the correlation entry is expired. The
/// relay answers within a round trip, so this is generous slack; what it
/// bounds is the *forged-ack acceptance window* against a relay that never
/// answers (prefix-unaware echo relay, legacy server).
pub(super) const RELAY_REGISTER_ACK_TIMEOUT_SECS: i64 = 30;
/// Registration sends per connection before giving up on relay sync for a
/// group. An unanswered registration is re-sent on expiry (the frame may
/// have been lost); past this budget the group simply stays unsynced and
/// sends take the always-correct per-member fan-out path. Reset by the
/// internet 0→1 re-sync, which re-registers from scratch.
pub(super) const RELAY_REGISTER_MAX_ATTEMPTS: u32 = 3;
/// How long a relay group broadcast waits for its settled `GroupMessageSent`
/// delivery report before being re-sent. The relay emits the report only
/// after its whole fan-out settles, which is bounded by its 45 s wall-clock
/// budget (`GROUP_FANOUT_DEADLINE_SECS` relay-side) plus a possible wait for
/// a relay-wide fan-out slot — so this sits above that budget, not above a
/// round trip. An entry older than this is presumed lost with its frame or
/// connection, not merely slow.
pub(super) const RELAY_BROADCAST_REPORT_TIMEOUT_SECS: i64 = 60;
/// Broadcast sends per logical group message (initial send plus re-sends on
/// report timeout) before the sender stops trusting the broadcast path and
/// falls back to per-member fan-out for the whole roster. Re-sent broadcasts
/// are safe: the relay echoes the client-supplied `message_id`, so receiver
/// dedup and the relay's push dedup both hold across attempts.
pub(super) const RELAY_BROADCAST_MAX_ATTEMPTS: u32 = 3;
/// Upper bound on broadcasts awaiting a delivery report at once. Each entry
/// holds a full ciphertext copy and lives for up to
/// `RELAY_BROADCAST_REPORT_TIMEOUT_SECS * RELAY_BROADCAST_MAX_ATTEMPTS`, so
/// against a relay that accepts broadcasts but never reports, an app sending
/// steadily would otherwise grow the tracker without limit. At the cap the
/// oldest entry is downgraded to per-member fan-out, which needs no report
/// to be correct — the bound costs uplink, never delivery.
pub(super) const MAX_RELAY_BROADCAST_PENDING: usize = 64;
/// Relay capability token gating the group broadcast path: the v2 settled
/// delivery contract (client `message_id` accept/echo, group push fallback,
/// the settled `GroupMessageSent` delivery report, `forward_info`
/// passthrough) plus — what v3 adds — an address-aware relay group path:
/// members are named in the identifier space the roster was registered in
/// (this SDK registers the MLS roster, i.e. `off1…` addresses), fan-out and
/// push resolve those names to accounts relay-side, and group sender
/// attribution carries the sender's declared address. The relay advertises
/// it (with the granular `group_*` tokens it aggregates) in its
/// `Authenticated` answer; the bridge injects the list via
/// `set_relay_capabilities` before reporting the transport up.
///
/// A `group_delivery_v2` relay deliberately fails this gate. Against its
/// username-keyed group path, a post-addressing broadcast is worse than
/// useless: the relay cannot resolve address-registered members to
/// connections (the broadcast reaches nobody it was registered for), its
/// report names members in username space (the roster set-difference
/// re-issues to the whole roster), and any copy it does deliver arrives
/// attributed by username — failing the SEC-M1 wire-sender/credential match
/// and burning the ciphertext on a copy that is then rejected. Failing the
/// gate keeps every group send on the per-member fan-out path, which post-#27
/// relays route and attribute correctly by address.
pub(crate) const RELAY_CAP_GROUP_DELIVERY_V3: &str = "group_delivery_v3";
/// Upper bound on stored relay capability tokens, and on the byte length of
/// each token. The list is wire-supplied by the relay — bounded so a hostile
/// or broken relay cannot grow resident memory with it.
pub(super) const MAX_RELAY_CAPABILITIES: usize = 64;
/// See [`MAX_RELAY_CAPABILITIES`].
pub(super) const MAX_RELAY_CAPABILITY_TOKEN_BYTES: usize = 128;
/// Maximum number of buffered out-of-order commits per group.
pub(super) const MAX_PENDING_COMMITS_PER_GROUP: usize = 8;
/// TTL for buffered pending commits. Must be at least
/// `GROUP_MESSAGE_DEDUP_TTL_SECS`: the commit's message ID is already in the
/// dedup table, so the buffered copy is its only path to processing — a
/// shorter TTL would open a window where the buffer has given up while the
/// dedup entry still rejects every redelivery, losing the commit for good.
/// Matching the dedup TTL means that by the time the buffer expires, a
/// sender-side redelivery can be accepted fresh.
pub(super) const PENDING_COMMIT_TTL_SECS: u64 = GROUP_MESSAGE_DEDUP_TTL_SECS;
/// Global cap on buffered pending commits across all groups.
pub(super) const MAX_PENDING_COMMITS_TOTAL: usize = 64;
/// Global cap on buffered commit payload bytes across all groups (4 MiB).
pub(super) const MAX_PENDING_COMMIT_TOTAL_BYTES: usize = 4 * 1024 * 1024;
/// Global cap on distinct group IDs holding buffered pending commits.
pub(super) const MAX_PENDING_COMMIT_GROUPS: usize = 16;
/// Maximum number of buffered out-of-order group application messages per group.
pub(super) const MAX_PENDING_GROUP_MESSAGES_PER_GROUP: usize = 16;
/// TTL for buffered out-of-order group application messages. Must be at
/// least `GROUP_MESSAGE_DEDUP_TTL_SECS` — same reasoning as
/// `PENDING_COMMIT_TTL_SECS`: the buffered copy is the message's only path
/// to delivery while its dedup entry blocks redelivery.
pub(super) const PENDING_GROUP_MESSAGE_TTL_SECS: u64 = GROUP_MESSAGE_DEDUP_TTL_SECS;
/// Global cap on buffered group application messages across all groups.
pub(super) const MAX_PENDING_GROUP_MESSAGES_TOTAL: usize = 256;
/// Global cap on buffered group application ciphertext bytes (base64 length)
/// across all groups (8 MiB).
pub(super) const MAX_PENDING_GROUP_MESSAGE_TOTAL_BYTES: usize = 8 * 1024 * 1024;
/// Global cap on distinct group IDs holding buffered group application
/// messages. Bounds the width of a one-entry-per-fabricated-group spread
/// flood and the map-key memory it retains (group IDs are wire-supplied,
/// up to `GroupId::MAX_LEN` bytes each).
pub(super) const MAX_PENDING_GROUP_MESSAGE_GROUPS: usize = 32;
/// Timeout before the next eligible member re-elects itself for a leave
/// remove-commit when the original elected remover fails (30 seconds).
pub(super) const LEAVE_ELECTION_TIMEOUT_SECS: u64 = 30;
/// Delay after detecting a potential epoch fork before the leader issues a
/// resync commit (30 seconds — gives time for buffered commits to drain and
/// delayed commits to arrive, reducing false positive fork detections).
pub(super) const EPOCH_FORK_RESOLUTION_DELAY_SECS: u64 = 30;
/// Maximum number of tracked epoch fork states to prevent unbounded growth.
pub(super) const MAX_EPOCH_FORK_ENTRIES: usize = 32;
/// Maximum number of tracked pending leave elections to prevent unbounded growth.
pub(super) const MAX_PENDING_LEAVE_ELECTIONS: usize = 64;
/// Maximum lifetime for a leave election before it is abandoned (5 minutes).
/// After this, the election is cleaned up regardless of whether the member
/// was removed — prevents infinite retry loops when all candidates fail.
pub(super) const LEAVE_ELECTION_MAX_LIFETIME_SECS: u64 = 300;
/// Minimum cooldown between re-election attempts for the same leave election
/// to prevent spamming MLS operations on every process tick (5 seconds).
pub(super) const LEAVE_ELECTION_ATTEMPT_COOLDOWN_SECS: u64 = 5;
/// Minimum interval between `GroupUnauthorizedMembershipChange` reports for
/// the same (group, committer) pair (5 minutes). Divergent role metadata —
/// e.g. two members auto-promoting different admins — re-fires the judgment
/// on every commit from the "wrong" admin until Stage 2 adds reconciliation;
/// without a window that is an unbounded stream of security events and log
/// lines for one underlying condition. Roster events still carry
/// `authorized: Some(false)` on every occurrence.
pub(super) const UNAUTHORIZED_REPORT_SUPPRESS_SECS: u64 = 300;
/// Maximum number of tracked (group, committer) report timestamps to prevent
/// unbounded growth (both key halves are wire-influenced strings).
pub(super) const MAX_UNAUTHORIZED_REPORT_ENTRIES: usize = 256;

/// Correlation state for one in-flight relay group registration.
#[derive(Debug, Clone)]
pub(crate) struct RelayRegisterPending {
    /// When the outstanding `__GRP_RELAY_REG__` frame was (last) sent;
    /// entries older than [`RELAY_REGISTER_ACK_TIMEOUT_SECS`] are expired
    /// on the process tick.
    pub(crate) armed_at: DateTime<Utc>,
    /// Registration sends on this connection, counted against
    /// [`RELAY_REGISTER_MAX_ATTEMPTS`].
    pub(crate) attempts: u32,
}

/// Correlation state for one in-flight relay group broadcast awaiting its
/// settled `GroupMessageSent` delivery report.
///
/// Keyed (in `GroupMeshState::relay_broadcast_pending`) by the logical group
/// message id carried in the broadcast payload and echoed back by a v2
/// relay. Holds everything needed to (a) re-send the broadcast under the
/// same logical id when the report is lost, and (b) rebuild per-member
/// `__GRP_MLS_MSG__` copies for members the report names as missed or does
/// not name at all (the relay's roster can be a strict subset of the MLS
/// roster).
#[derive(Debug, Clone)]
pub(crate) struct RelayBroadcastPending {
    /// Group the broadcast belongs to.
    pub(crate) group_id: String,
    /// Base64-encoded MLS application ciphertext, reused verbatim for
    /// broadcast re-sends and per-member backstop copies (MLS application
    /// ciphertext is recipient-independent within a group).
    pub(crate) ciphertext_b64: String,
    /// MLS epoch at which the message was encrypted (informational).
    pub(crate) epoch: u64,
    /// Optional reply-to message id.
    pub(crate) reply_to: Option<String>,
    /// Hop-visible forward attribution; `None` when sealed into the
    /// ciphertext as rich extras.
    pub(crate) forward_info: Option<ForwardInfo>,
    /// Priority of the original send, inherited by backstop copies.
    pub(crate) priority: MessagePriority,
    /// When the outstanding broadcast frame was (last) sent; entries older
    /// than [`RELAY_BROADCAST_REPORT_TIMEOUT_SECS`] are re-sent or downgraded
    /// on the process tick.
    pub(crate) armed_at: DateTime<Utc>,
    /// Broadcast sends for this logical message, counted against
    /// [`RELAY_BROADCAST_MAX_ATTEMPTS`].
    pub(crate) attempts: u32,
}

/// Which gate refused a leaf, for the `GroupLeafIdentityUnproven` rate-limit
/// key.
///
/// Part of the key for the same reason `unauthorized_change_reports` carries
/// its `enforced` flag: the two are different signals with different urgency,
/// and neither may suppress the other's first report inside one window. A
/// declined invite is a stranger's group you never joined; a refused commit
/// accuses a member of a group you are already in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum UnprovenLeafSite {
    /// A group invite declined because its ratchet tree carried the leaf.
    WelcomeDeclined,
    /// A membership commit refused because it would have installed the leaf.
    CommitRefused,
    /// A roster read skipped the leaf because it was already seated in local
    /// group state.
    ///
    /// The odd one out, and the reason it needs its own site: the other two
    /// refuse a frame *arriving*, so nothing is installed and there is a
    /// delivering peer to name. This one reports a leaf that is already in the
    /// tree, holding live group secrets — the wire gates cannot have admitted
    /// it, so it arrived by a direct write to the install-scoped provider store
    /// or by a build predating those gates. There is no delivering peer, so the
    /// report is attributed to this device (see
    /// [`OfflineProtocol::report_unproven_leaf`]), and the remedy it implies is
    /// different too: abandon the group rather than evict a member, because the
    /// leaf can already read everything sent to it.
    RosterEntry,
}

/// Claims a rate-limit window for `key`, returning whether the caller should
/// report.
///
/// Shared by the two security reporters so their suppression, map bounding and
/// eviction order cannot drift apart. Bounds the map by dropping lapsed windows
/// first and only then evicting the oldest live entry — the longest-suppressed
/// one, which is the safe direction to lose.
fn claim_report_window<K: Eq + std::hash::Hash + Clone>(
    reports: &mut HashMap<K, Instant>,
    key: K,
) -> bool {
    let now = Instant::now();
    let suppressed = reports.get(&key).is_some_and(|last| {
        now.duration_since(*last).as_secs() < UNAUTHORIZED_REPORT_SUPPRESS_SECS
    });
    if suppressed {
        return false;
    }

    if reports.len() >= MAX_UNAUTHORIZED_REPORT_ENTRIES {
        reports.retain(|_, last| {
            now.duration_since(*last).as_secs() < UNAUTHORIZED_REPORT_SUPPRESS_SECS
        });
    }
    if reports.len() >= MAX_UNAUTHORIZED_REPORT_ENTRIES {
        if let Some(oldest) = reports
            .iter()
            .min_by_key(|(_, t)| **t)
            .map(|(k, _)| k.clone())
        {
            reports.remove(&oldest);
        }
    }
    reports.insert(key, now);
    true
}

/// Bundled state for group messaging.
///
/// Groups together the cached member lists, dedup table, pending commit
/// buffer, and relay sync tracking so that `OfflineProtocol` doesn't carry
/// these as individual fields.
#[derive(Default)]
pub(crate) struct GroupMeshState {
    /// Cached group membership lists for fan-out without holding MLS lock.
    /// Maps group_id -> list of member user IDs.
    pub(crate) members: HashMap<String, Vec<String>>,

    /// Deduplication cache for group messages received via multiple paths.
    /// Key: message ID, Value: when first seen.
    pub(crate) message_dedup: HashMap<String, Instant>,

    /// Buffer for out-of-order MLS commits that failed to decrypt.
    /// Maps group_id -> deque of pending commits awaiting retry.
    /// When a commit succeeds for a group, buffered commits are drained and retried.
    pub(crate) pending_commits: HashMap<String, VecDeque<PendingCommit>>,

    /// Buffer for group application messages that failed MLS decryption
    /// because local group state lagged the sender's (Welcome not yet
    /// processed, or epoch behind). Drained after a successful Welcome join
    /// or commit for the group. Maps group_id -> deque of pending messages.
    pub(crate) pending_group_messages: HashMap<String, VecDeque<PendingGroupMessage>>,

    /// Group IDs that have been successfully registered with the relay server.
    /// Cleared when Internet transport disconnects so that groups are re-synced
    /// when connectivity returns.
    pub(crate) relay_synced: HashSet<String>,

    /// Group IDs with a relay registration in flight (a `__GRP_RELAY_REG__`
    /// frame enqueued, no relay answer yet). The `__GROUP_CREATED__` ack only
    /// sets `relay_synced` for groups in this map: the relay forwards peer
    /// message content verbatim, so without this correlation any peer that
    /// knows a group id could forge the ack over the internet path and route
    /// our broadcasts into a relay that never registered the group. Cleared
    /// per group on ack, group-scoped `__GROUP_ERROR__`, leave/removal, and
    /// wholesale when the Internet transport drops (the answer can never
    /// arrive). Entries a relay never answers are expired on the process
    /// tick ([`RELAY_REGISTER_ACK_TIMEOUT_SECS`]) and re-registered up to
    /// [`RELAY_REGISTER_MAX_ATTEMPTS`] times — a relay that never acks
    /// (prefix-unaware echo relay, legacy server) must not leave the
    /// acceptance window armed indefinitely for a forged ack to claim.
    pub(crate) relay_register_pending: HashMap<String, RelayRegisterPending>,

    /// Capability tokens the connected relay advertised in its
    /// `Authenticated` answer, injected by the platform bridge via
    /// `set_relay_capabilities` *before* it reports the Internet transport
    /// up — the false→true flush must already see them. Empty for relays
    /// that predate the advertisement. Cleared when Internet drops: a
    /// reconnect may land on a different relay.
    pub(crate) relay_capabilities: HashSet<String>,

    /// In-flight relay group broadcasts awaiting their settled
    /// `GroupMessageSent` delivery report, keyed by logical group message
    /// id. Settled by `handle_relay_group_delivery_report` (which re-sends
    /// per-member copies to members the relay did not reach), re-sent on
    /// report timeout, and downgraded to full per-member fan-out when the
    /// attempt budget is exhausted or the Internet transport drops (the
    /// report can never arrive on a dead connection).
    pub(crate) relay_broadcast_pending: HashMap<String, RelayBroadcastPending>,

    /// Whether Internet transport was available on the last `process()` tick.
    /// Used for edge-detection: sync groups on 0→1 transition, clear on 1→0.
    pub(crate) internet_was_available: bool,

    /// Pending leave elections awaiting a remove-commit from the elected member.
    /// Key: (group_id, leaving_member_id) — uses a tuple to avoid ambiguity
    /// from string concatenation when IDs contain separator characters.
    pub(crate) pending_leave_elections: HashMap<(String, String), PendingLeaveElection>,

    /// Suspected epoch forks awaiting resolution. Key: group_id.
    pub(crate) epoch_forks: HashMap<String, EpochForkState>,

    /// When an unauthorized membership change by (group_id, committer,
    /// enforced) was last reported, for rate-limiting the security event —
    /// see [`UNAUTHORIZED_REPORT_SUPPRESS_SECS`]. Bounded by
    /// [`MAX_UNAUTHORIZED_REPORT_ENTRIES`] with oldest-entry eviction.
    ///
    /// The `enforced` flag is part of the key on purpose: an applied change
    /// and a refused one are different signals with different urgency (the
    /// refusal doubles as a partition alarm), so neither may suppress the
    /// other's first report inside one window.
    pub(crate) unauthorized_change_reports: HashMap<(String, String, bool), Instant>,

    /// When an unproven-leaf refusal by (group_id, delivering peer, site) was
    /// last reported, for rate-limiting `GroupLeafIdentityUnproven` — same
    /// window and same bound as [`Self::unauthorized_change_reports`], kept
    /// separate so neither signal can suppress the other's first report.
    ///
    /// Needed because the commit half of this report is driven by an
    /// authenticated group member: refusals are permanent and cheap, so an
    /// insider can produce one per frame, and an unthrottled event channel
    /// buries the signal in its own repetition.
    ///
    /// [`UnprovenLeafSite`] is part of the key for the same reason
    /// `unauthorized_change_reports` keys on `enforced`: a declined invite must
    /// not swallow the first refused *commit*, which is the more urgent signal
    /// of the two. Relying on the two never colliding — today they cannot,
    /// because `handle_group_mls_welcome` returns early for a group already
    /// joined — would hide that guarantee in a different function.
    pub(crate) unproven_leaf_reports: HashMap<(String, String, UnprovenLeafSite), Instant>,
}

/// Outcome of attempting to process an MLS Commit.
enum CommitOutcome {
    /// Successfully processed; contains the group ID.
    Success(String),
    /// MLS decryption failed transiently (e.g., out-of-order delivery);
    /// the commit may succeed after a prior commit advances the epoch.
    /// Contains the group ID for buffering.
    Retriable(String),
    /// Permanently failed (parse error, bad ciphertext, MLS unavailable);
    /// should not be retried.
    Rejected,
}

/// Verdict from [`OfflineProtocol::judge_membership_change`] for one commit's
/// applied membership delta.
pub(crate) struct MembershipJudgment {
    /// Whether the authenticated committer is a known admin of the group.
    /// Gates trust in the commit-payload metadata (role, rich attestation).
    pub(crate) sender_is_admin: bool,
    /// Whether the change as a whole was authorized: an admin committed it
    /// *and* the commit's own framing agrees with the delta it produced.
    pub(crate) authorized: bool,
}

/// Outcome of attempting to decrypt a group application message.
enum GroupDecryptOutcome {
    /// Decrypted application data.
    Plaintext(Vec<u8>),
    /// MLS consumed a Commit or Proposal that arrived via the message
    /// channel (e.g., due to reordering) — not application data.
    NonApplication,
    /// Wire sender does not match the MLS-authenticated sender (SEC-M1).
    SecurityRejected,
    /// Local group state lags the sender's (no group yet, or epoch behind);
    /// the message may decrypt after a Welcome or commit lands, so it is
    /// worth buffering for deferred retry.
    Retriable,
    /// No local group state AND the payload is not MLS wire framing at
    /// all — this is not a welcome-racing ciphertext. On the mesh path
    /// that means garbage (dropped); on the relay path it means a legacy
    /// relay-only group message whose plaintext happens to be valid
    /// base64, which must be emitted raw rather than buffered and lost.
    NotMlsCiphertext,
    /// A commit riding the application channel was refused before merging by
    /// `GroupConfig::enforce_admin_commits`.
    ///
    /// This variant is why enforcement lives in the MLS layer rather than in
    /// the commit handler: a commit ciphertext wrapped in an ordinary
    /// `__GRP_MLS_MSG__` frame reaches `merge_staged_commit` through *this*
    /// path, which otherwise treats it as benign reordering
    /// ([`Self::NonApplication`]). Enforcing only on the commit-framed path
    /// would leave that reframing as a bypass.
    ///
    /// Permanent, like the commit-path rejection: the same ciphertext can
    /// never become authorized, so it must not be buffered and retried.
    PolicyRejected {
        /// The MLS-authenticated committer whose commit was refused.
        committer: String,
        /// User ids the refused commit would have added, sorted.
        added: Vec<String>,
        /// User ids the refused commit would have removed, sorted.
        removed: Vec<String>,
    },
    /// Permanently failed; not worth retrying.
    Failed,
}

// --- Group (mesh/MLS) payloads ---

/// Options for `OfflineProtocol::send_group_message_with`: priority and
/// reply threading (as on `send_group_message`), plus the rich media fields.
///
/// The rich fields (`content_type`, `media_metadata` — including any
/// cloud-media `encryption_key`/`iv` secrets) only ever travel inside the
/// MLS-sealed `__RICH_V1__` body of the group ciphertext, and only when
/// *every* other group member advertised `rich_versions` support (one
/// ciphertext serves the whole group, so one legacy or unknown-capability
/// member forces the drop). Otherwise they are silently dropped — never
/// sent cleartext — and the message degrades to what `send_group_message`
/// sends.
#[derive(Debug, Clone, Default)]
pub struct GroupSendOptions {
    /// Message priority (defaults to Medium).
    pub priority: Option<MessagePriority>,
    /// ID of the message this is replying to.
    pub reply_to_msg: Option<String>,
    /// Content-type rendering hint (text, image, video, ...), delivered
    /// sealed-only. Must not be [`ContentType::FileChunk`].
    pub content_type: Option<ContentType>,
    /// Rich media metadata (cloud attachments — including the
    /// `encryption_key`/`iv` secrets), delivered sealed-only.
    pub media_metadata: Option<MediaMetadata>,
}

/// Snapshot of whether a rich group send right now would seal its extras,
/// from `OfflineProtocol::group_rich_readiness`. Point-in-time and
/// advisory: capability knowledge changes with key-package exchanges,
/// attested adds, and restarts, and the send path re-evaluates the gate
/// itself — this exists so apps can warn before sending (e.g. gray out the
/// attachment button) instead of learning from `GroupRichExtrasDropped`
/// after the drop.
#[derive(Debug, Clone)]
pub struct GroupRichReadiness {
    /// True when every other member is known rich-capable and the local
    /// kill switch is on — rich extras would seal.
    pub ready: bool,
    /// Members not known to parse the sealed rich payload (unknown and
    /// known-non-support are indistinguishable). Empty when `ready`, and
    /// also empty when only the local kill switch blocks sealing.
    pub unknown_members: Vec<String>,
}

/// Relay-side registration state of a group, from
/// `OfflineProtocol::group_relay_sync_state`. Point-in-time: transitions
/// are surfaced as `GroupRelaySyncChanged` events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelaySyncState {
    /// The relay positively acknowledged the group's registration on the
    /// current connection — relay-dependent server commands for the group
    /// (invite links, server-side fan-out) can be issued.
    Synced,
    /// A registration was sent and its acknowledgment is outstanding.
    /// The SDK re-sends on a timer and gives up after a bounded number of
    /// attempts (`GroupRelaySyncChanged { reason: "ack_timeout" }`).
    Pending,
    /// No registration is in flight — the group is unknown locally, the
    /// Internet transport is down, relay grouping is disabled, or a prior
    /// attempt was answered with an error / timed out.
    Unsynced,
}

/// Payload for MLS-encrypted group messages sent via mesh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct GroupMlsMessagePayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// Base64-encoded MLS ciphertext.
    pub(crate) ciphertext: String,
    /// MLS epoch at which the message was encrypted.
    pub(crate) epoch: u64,
    /// Optional reply-to message ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) reply_to: Option<String>,
    /// Optional forwarding attribution (present when message was forwarded).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) forward_info: Option<offline_protocol_core::ForwardInfo>,
    /// Logical id of the group message this frame carries, present when the
    /// frame re-issues a relay broadcast (the delivery-report backstop or
    /// the lost-report fallback). Lets the receiver emit the same app-facing
    /// message id every member sees for this logical message, and absorb a
    /// cross-path duplicate when the relay's own copy also arrived. Absent
    /// on the ordinary per-member fan-out path, where the envelope id is
    /// the only id. Unauthenticated at parse time — the receiver never
    /// *marks* it as seen before the ciphertext MLS-decrypts (see
    /// `handle_group_mls_msg_via`), so a non-member cannot poison the id to
    /// suppress a message it could not itself have sent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) message_id: Option<String>,
}

/// Payload for MLS Welcome messages (group invites) sent via mesh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct GroupMlsWelcomePayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// Human-readable group name.
    pub(crate) group_name: Option<String>,
    /// Base64-encoded MLS Welcome data.
    pub(crate) welcome_data: String,
    /// Current member list (user IDs) at the time of invite.
    pub(crate) member_list: Vec<String>,
    /// Role assignments: user_id -> role.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub(crate) member_roles: HashMap<String, GroupRole>,
    /// Rich-payload versions the inviter attests per existing member
    /// (additive; absent from old SDKs), so the joiner can seal rich extras
    /// toward members it never directly exchanged key packages with.
    /// Entries only appear for members the inviter knows capable — absence
    /// means "no information", never a downgrade. Recipient-side trust
    /// bounds: entries are ignored for user ids outside the joined MLS
    /// roster, and a later direct key-package exchange with a member
    /// overrides its attested entry.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub(crate) member_rich: HashMap<String, Vec<u8>>,
    /// The group creator the inviter has on record (additive; absent from
    /// old SDKs and from inviters whose own metadata never learned it).
    ///
    /// Without this, a joiner's metadata is materialized by `set_member_role`
    /// via `GroupMetadata::new(None)`, leaving `created_by` permanently
    /// `None` — so `check_is_admin`'s creator fallback is dead code for
    /// every joiner, and a group whose role snapshot arrived incomplete
    /// resolves to deny-by-default. Propagating it makes the fallback
    /// reachable.
    ///
    /// Trust bounds mirror [`Self::member_roles`]: this is the inviter's
    /// unauthenticated claim, adopted only when the joiner has no creator on
    /// record (first write wins, see `MlsManager::set_group_creator`), and
    /// deliberately **not** bounded to the joined MLS roster — the creator of
    /// record may have already left the group. It feeds only the admin
    /// *fallback* used for send-side gating and the authorization report; it
    /// is never consulted by receive-side commit enforcement, which fails
    /// open on an unknown admin set rather than trusting a single claim.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) created_by: Option<String>,
}

/// Type of group membership commit operation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub(crate) enum GroupCommitType {
    /// A member was added to the group.
    Add,
    /// A member was removed from the group.
    Remove,
    /// A key update commit (epoch advancement without membership change).
    /// Used for epoch fork resolution.
    KeyUpdate,
}

/// Payload for MLS Commit messages (membership changes) sent via mesh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct GroupMlsCommitPayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// Type of commit operation.
    pub(crate) commit_type: GroupCommitType,
    /// Base64-encoded MLS commit ciphertext.
    pub(crate) ciphertext: String,
    /// MLS epoch at which the commit was created.
    pub(crate) epoch: u64,
    /// User ID of the affected member (added or removed).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) affected_member: Option<String>,
    /// Role assigned to the affected member (for Add commits).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) role: Option<GroupRole>,
    /// Rich-payload versions the inviter attests for the added member
    /// (additive; absent from old SDKs or when the inviter has no
    /// knowledge), so existing members — who never exchange key packages
    /// with the newcomer — can keep sealing rich extras. Recipient-side
    /// trust bounds mirror `role`: honored only for the member the MLS
    /// state delta actually added and only from an admin sender, and a
    /// later direct key-package exchange overrides it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) affected_member_rich: Option<Vec<u8>>,
}

/// Payload for group leave notifications sent via mesh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct GroupMlsLeavePayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// User ID of the leaving member.
    pub(crate) leaving_member: String,
}

/// Payload for group role change notifications sent via mesh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct GroupRoleChangePayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// User ID of the member whose role changed.
    pub(crate) target_user_id: String,
    /// New role.
    pub(crate) new_role: GroupRole,
    /// User ID of who changed the role.
    pub(crate) changed_by: String,
}

/// Payload for group rename notifications sent via mesh.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct GroupRenamePayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// New human-readable group name.
    pub(crate) new_name: String,
    /// User ID of who renamed the group.
    pub(crate) renamed_by: String,
}

// --- Relay optimization payloads ---

/// Payload for registering/updating a group with the relay server.
///
/// Sent as a `__GRP_RELAY_REG__`-prefixed internal message to the user's
/// own ID via Internet transport. The relay server does NOT intercept the
/// prefix — a prefix-unaware relay just echoes the self-addressed frame
/// back. It is the platform bridge translator (the relay adapter) that
/// recognizes the frame via `internet_control_op` and replaces it with a
/// relay-native `CreateGroup` plus admin-gated member deltas, so the relay
/// learns the group → member mapping for server-side fan-out of future
/// `__GRP_RELAY_BCAST__` messages. A transport without such an adapter
/// leaves the group unsynced (per-member fan-out) — see
/// `try_relay_register_group`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct RelayGroupRegistrationPayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// Human-readable group name (for display/search on relay).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub(crate) group_name: Option<String>,
    /// Current member user IDs.
    pub(crate) members: Vec<String>,
    /// Whether the registering user is a group admin, when locally
    /// determinable. The bridge translator uses this to skip the
    /// `AddGroupMember`/`RemoveGroupMember` deltas a non-admin would be
    /// denied (the relay restricts membership mutation to admins) — the
    /// denial would otherwise arrive as a group-scoped `GroupError` that
    /// revokes `relay_synced` and surfaces as an app-visible error on every
    /// reconnect. Absent means unknown: the bridge falls back to
    /// send-and-learn.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) is_admin: Option<bool>,
}

/// Payload for a relay-broadcast of an MLS-encrypted group message.
///
/// Sent as a `__GRP_RELAY_BCAST__`-prefixed internal message to the user's
/// own ID via Internet transport. The relay server does NOT intercept the
/// prefix; the platform bridge translator replaces the frame with a
/// relay-native `SendGroupMessage`, and the relay's fan-out arrives at each
/// member as a `__GROUP_MSG__` frame injected by *their* bridge. This path
/// is only taken once the relay has positively acknowledged the group's
/// registration (`relay_synced`) — on any other relay the frame would be
/// echoed back and the content silently lost.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct RelayGroupBroadcastPayload {
    /// MLS group identifier.
    pub(crate) group_id: String,
    /// Base64-encoded MLS ciphertext.
    pub(crate) ciphertext: String,
    /// MLS epoch at which the message was encrypted.
    pub(crate) epoch: u64,
    /// Optional reply-to message ID.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) reply_to: Option<String>,
    /// Optional forwarding attribution (present when message was forwarded).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) forward_info: Option<offline_protocol_core::ForwardInfo>,
    /// Logical message id for this group message, stable across broadcast
    /// re-sends of the same logical message. The bridge translator stamps it
    /// onto the relay `SendGroupMessage` frame; a v2 relay echoes it to
    /// every member (receiver dedup), keys its push dedup by it, and names
    /// it in the settled `GroupMessageSent` delivery report (sender
    /// correlation). `default` only so old captured frames in tests still
    /// deserialize — production frames always carry it.
    #[serde(default)]
    pub(crate) message_id: String,
}

/// A relay `GroupMessageSent` settled delivery report, forwarded verbatim
/// (as the raw server frame JSON) by the platform bridge into
/// `handle_relay_group_delivery_report`. Field names follow the relay wire
/// contract; the enclosing `type` tag and `timestamp` are ignored. All
/// three member lists default to empty so a v1 relay's bare receipt (no
/// lists) still parses — it settles the entry with everyone unreached,
/// which per-member re-issue then covers.
///
/// Member-name namespace: a `group_delivery_v3` relay names members by the
/// identifiers the roster was registered under — for this SDK, the MLS
/// roster's `off1…` addresses — which is what makes the set difference in
/// `handle_relay_group_delivery_report` meaningful. A v2 relay names
/// members by relay-account *username*, a namespace that never intersects
/// the address roster; the subtraction then removes nothing and the whole
/// roster is re-issued per-member. That degradation is the fail-safe, not
/// the contract — the broadcast gate requires v3 precisely so reports in
/// the wrong namespace only ever arrive from relays this SDK no longer
/// broadcasts through (e.g. a capability set that changed mid-flight).
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RelayGroupDeliveryReport {
    /// Group the report is for.
    pub(crate) group_id: String,
    /// The logical message id, echoed from the broadcast frame.
    pub(crate) message_id: String,
    /// Members whose relay socket write was confirmed (a server-side
    /// write-ack, not an application-level delivery ACK).
    #[serde(default)]
    pub(crate) delivered: Vec<String>,
    /// Members unreachable over a socket who took a device push.
    #[serde(default)]
    pub(crate) pushed: Vec<String>,
    /// Members the relay reached neither way.
    #[serde(default)]
    pub(crate) missed: Vec<RelayGroupDeliveryMiss>,
}

/// One recipient a relay group fan-out could not reach.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct RelayGroupDeliveryMiss {
    /// The member's identifier as the relay knows it. Wire field name is
    /// `username` for relay-contract stability, but under `group_delivery_v3`
    /// the value is the registered member id (an `off1…` address for this
    /// SDK); only v2 relays put an account username here (see the namespace
    /// note on [`RelayGroupDeliveryReport`]).
    pub(crate) username: String,
    /// Stable machine-readable code (`offline_no_push`,
    /// `connection_lost_no_push`, `undeliverable`, `already_pushed`,
    /// `too_large_for_push`, `fanout_deadline`, …). Treated as opaque —
    /// logged, never matched on — so new relay codes cannot break parsing.
    #[serde(default)]
    pub(crate) reason: String,
}

/// A commit that arrived out-of-order and is waiting to be processed.
///
/// In mesh networks, messages can arrive out of order. If a Commit arrives
/// before a prior Commit, MLS decryption will fail. We buffer it here and
/// retry after successfully processing a later commit for the same group.
#[derive(Debug, Clone)]
pub(crate) struct PendingCommit {
    /// The original sender of this commit.
    pub(crate) sender: String,
    /// The original message ID (already recorded in the dedup table).
    /// Released when the buffered copy is dropped undelivered by cap
    /// eviction, so a redelivery is accepted fresh instead of being
    /// rejected as a replay of a copy that no longer exists anywhere.
    pub(crate) message_id: String,
    /// The raw JSON data (after prefix strip) for replay.
    pub(crate) data: String,
    /// When this pending commit was first buffered.
    pub(crate) buffered_at: Instant,
    /// Number of times this commit has been retried and still failed.
    /// A commit that expires with `retry_count > 0` is a strong signal
    /// of epoch mismatch (true fork), not just slow delivery.
    pub(crate) retry_count: u32,
}

/// A group application message that arrived before local MLS state could
/// decrypt it (Welcome not yet processed, or epoch behind the sender's).
///
/// The Welcome and the first group message are sent back-to-back and can
/// arrive out of order across transports. The ciphertext is buffered at
/// first arrival — the message-ID dedup table keeps rejecting redeliveries,
/// so this buffered copy is the message's only path to delivery.
#[derive(Debug, Clone)]
pub(crate) struct PendingGroupMessage {
    /// The original wire sender of this message.
    pub(crate) sender: String,
    /// The original message ID (already recorded in the dedup table).
    pub(crate) message_id: String,
    /// Logical group message id carried in the frame's payload, when the
    /// frame re-issued a relay broadcast (`GroupMlsMessagePayload::message_id`).
    /// On delivery the drain emits this id, so every member sees the same
    /// app-facing id whichever path reached them; the deferred delivery ACK
    /// is keyed on `message_id` regardless, since that is the envelope the
    /// sender's ack_manager awaits. A rival copy of the same logical message
    /// cannot double-deliver: whichever copy decrypts first spends the
    /// ratchet generation, and the drain drops any later copy of an id it
    /// already delivered. `None` on the ordinary fan-out and relay paths.
    pub(crate) logical_id: Option<String>,
    /// Base64-encoded MLS application ciphertext.
    pub(crate) ciphertext_b64: String,
    /// Relay-provided timestamp; `None` for mesh messages (stamped at emit).
    pub(crate) timestamp: Option<String>,
    /// Optional ID of the message this one replies to.
    pub(crate) reply_to: Option<String>,
    /// Optional forwarding attribution.
    pub(crate) forward_info: Option<offline_protocol_core::ForwardInfo>,
    /// When this message was first buffered.
    pub(crate) buffered_at: Instant,
    /// Transport the frame arrived on, recorded so the drain can send the
    /// deferred delivery ACK directly on it once the message finally decrypts
    /// (see the deferred-ACK atom in CLAUDE.md). `None` for the relay path
    /// (the relay sender is not ACK-gated) and for transport-less test enqueue
    /// — in both cases the drain ACK is a correct no-op.
    pub(crate) received_via: Option<TransportType>,
}

/// Tracks a leave election where we're waiting for the elected remover to
/// issue a remove-commit. If the timeout expires and the member is still
/// in the group, the next eligible member re-elects itself.
#[derive(Debug, Clone)]
pub(crate) struct PendingLeaveElection {
    /// Group the leave is for.
    pub(crate) group_id: String,
    /// User ID of the member who is leaving.
    pub(crate) leaving_member: String,
    /// When we received the leave notification.
    pub(crate) received_at: Instant,
    /// When we last attempted to issue a remove-commit for this election.
    /// Used as a cooldown to prevent spamming MLS operations on every
    /// process tick when the current candidate fails repeatedly.
    pub(crate) last_attempt_at: Option<Instant>,
}

/// Tracks a suspected epoch fork for a group.
///
/// An epoch fork occurs when two members issue concurrent commits at the
/// same epoch (e.g., two admins adding different members simultaneously).
/// Members who accepted commit A are on one branch, those who accepted
/// commit B are on another. Detected when buffered commits expire without
/// resolution.
#[derive(Debug, Clone)]
pub(crate) struct EpochForkState {
    /// Group with the suspected fork.
    pub(crate) group_id: String,
    /// Our local epoch when the fork was detected, or `None` if MLS was unavailable.
    pub(crate) local_epoch: Option<u64>,
    /// When the fork was first suspected.
    pub(crate) detected_at: Instant,
    /// Whether the leader has already attempted resolution.
    pub(crate) resolution_attempted: bool,
}

/// Global limits enforced by [`enforce_global_buffer_bound`], grouped so the
/// three same-typed caps cannot be transposed at a call site.
struct GlobalBufferCaps {
    /// Maximum distinct group IDs in the buffer map.
    max_groups: usize,
    /// Maximum buffered entries across all groups.
    max_entries: usize,
    /// Maximum buffered payload bytes across all groups.
    max_bytes: usize,
}

const PENDING_COMMIT_CAPS: GlobalBufferCaps = GlobalBufferCaps {
    max_groups: MAX_PENDING_COMMIT_GROUPS,
    max_entries: MAX_PENDING_COMMITS_TOTAL,
    max_bytes: MAX_PENDING_COMMIT_TOTAL_BYTES,
};

const PENDING_GROUP_MESSAGE_CAPS: GlobalBufferCaps = GlobalBufferCaps {
    max_groups: MAX_PENDING_GROUP_MESSAGE_GROUPS,
    max_entries: MAX_PENDING_GROUP_MESSAGES_TOTAL,
    max_bytes: MAX_PENDING_GROUP_MESSAGE_TOTAL_BYTES,
};

/// Enforces a global bound — entry count, payload bytes, and distinct group
/// count — across all per-group pending buffers, evicting until an incoming
/// entry of `incoming_bytes` for `incoming_group` fits. Returns the entries
/// evicted to make room so callers can release per-entry state (e.g. the
/// replay-dedup ID that would otherwise keep rejecting a redelivery of the
/// evicted message), or `None` (evicting nothing) when the incoming entry
/// alone exceeds the byte budget — the caller must drop it. Without that
/// guard a single oversized entry would purge every buffered entry across
/// all groups and then land anyway, blowing the cap it was meant to respect.
///
/// Group IDs on these buffers come straight off the wire, and the buffered
/// case (`GroupNotFound`) is precisely the pre-join, unauthenticated one —
/// per-group caps alone leave total retention open-ended across
/// attacker-chosen group IDs.
///
/// Freeing a *group slot* (admitting a new group ID at the group cap)
/// evicts the single largest per-group buffer wholesale: emptying some
/// group is the only way to free a slot, and doing it one entry at a time
/// would round-robin across level-sized buffers — purging nearly every
/// buffered entry map-wide before any single group emptied. Evicting one
/// group as a unit bounds the damage at one per-group buffer and
/// preferentially removes a concentrated flood over honest few-entry
/// groups.
///
/// Entry/byte pressure then evicts the oldest entry of the *largest*
/// remaining buffer (tie-broken by age), so a flood that concentrates in a
/// few group IDs is evicted before honest welcome-race entries, which are
/// few per group. A flood that instead spreads one entry per fabricated
/// group ID levels the buffer sizes and degrades eviction to
/// globally-oldest; the group cap bounds how wide such a spread can reach
/// (and the map-key memory it retains), but within it a sustained spread
/// flood can still push out an honest entry. Callers mitigate that by
/// releasing the evicted entry's dedup ID, turning the loss into a
/// redelivery retry instead of a permanent one — full protection would
/// need sender-level accounting, which none of these pre-join paths have.
fn enforce_global_buffer_bound<T>(
    map: &mut HashMap<String, VecDeque<T>>,
    incoming_group: &str,
    caps: &GlobalBufferCaps,
    incoming_bytes: usize,
    entry_bytes: impl Fn(&T) -> usize,
    buffered_at: impl Fn(&T) -> Instant,
) -> Option<Vec<T>> {
    if incoming_bytes > caps.max_bytes {
        return None;
    }
    let (mut entries, mut bytes) = map
        .values()
        .flat_map(|buf| buf.iter())
        .fold((0usize, 0usize), |(n, b), e| (n + 1, b + entry_bytes(e)));
    // Each deque is in arrival order, so its front is its oldest entry.
    // Rank groups by (buffer length, entry age): largest buffer first,
    // oldest front entry breaking ties.
    let pick_victim = |map: &HashMap<String, VecDeque<T>>| {
        map.iter()
            .filter_map(|(gid, buf)| {
                buf.front()
                    .map(|e| ((buf.len(), std::cmp::Reverse(buffered_at(e))), gid))
            })
            .max_by_key(|(rank, _)| *rank)
            .map(|(_, gid)| gid.clone())
    };
    let mut all_evicted = Vec::new();
    while map.len() >= caps.max_groups && !map.contains_key(incoming_group) {
        let Some(victim_group) = pick_victim(map) else {
            break;
        };
        warn!(
            group_id = %victim_group,
            "Pending buffers at group capacity, evicting largest group buffer wholesale"
        );
        if let Some(buf) = map.remove(&victim_group) {
            entries -= buf.len();
            bytes -= buf.iter().map(&entry_bytes).sum::<usize>();
            all_evicted.extend(buf);
        }
    }
    while entries >= caps.max_entries || bytes + incoming_bytes > caps.max_bytes {
        let Some(victim_group) = pick_victim(map) else {
            break;
        };
        warn!(
            group_id = %victim_group,
            "Pending buffer at global capacity, evicting oldest entry of largest group buffer"
        );
        if let Some(buf) = map.get_mut(&victim_group) {
            if let Some(evicted) = buf.pop_front() {
                entries -= 1;
                bytes -= entry_bytes(&evicted);
                all_evicted.push(evicted);
            }
            if buf.is_empty() {
                map.remove(&victim_group);
            }
        }
    }
    Some(all_evicted)
}

impl OfflineProtocol {
    /// Transport-less convenience wrapper over [`Self::handle_group_mls_msg_via`],
    /// used only by tests; production always knows the arrival transport.
    #[cfg(test)]
    pub(crate) fn handle_group_mls_msg(
        &mut self,
        message: &Message,
        sender: &str,
        data: &str,
    ) -> InternalMessageResult {
        self.handle_group_mls_msg_via(message, sender, data, None)
    }

    /// Handles an incoming MLS-encrypted group message, with the transport the
    /// frame arrived on.
    ///
    /// Returns [`InternalMessageResult::SecurityRejected`] when the wire
    /// sender does not match the MLS-authenticated sender (SEC-M1), so the
    /// caller suppresses the delivery ACK exactly like the `__MLS_ENC__`
    /// path; a genuine crypto/parse failure consumes the message.
    ///
    /// Deferred-ACK atom (mesh-group analog of the DM/media fix, PR #223): a
    /// message buffered because local group state is not ready yet returns
    /// [`InternalMessageResult::Deferred`], so the receive loop skips the
    /// delivery ACK and unmarks the transport-level dedup — keeping the
    /// sender's per-member `ack_manager` retransmitting until the message is
    /// actually delivered on drain (`drain_pending_group_messages` sends the
    /// deferred ACK on `received_via`). Without this the buffered-but-ACKed
    /// copy could be evicted/expired before a commit drained it and be lost,
    /// even though the group-level `release_replay_protection` already clears
    /// dedup on drop. The group-level `message_dedup` stays marked across the
    /// pending lifetime (replay-amplification defense + authoritative
    /// double-delivery guard), so — unlike the DM path — the drain does not
    /// re-mark the transport dedup.
    pub(crate) fn handle_group_mls_msg_via(
        &mut self,
        message: &Message,
        sender: &str,
        data: &str,
        arrival_transport: Option<TransportType>,
    ) -> InternalMessageResult {
        let payload = match serde_json::from_str::<GroupMlsMessagePayload>(data) {
            Ok(p) => p,
            Err(_) => {
                warn!(sender = %sender, "Failed to parse GroupMlsMessage payload");
                return InternalMessageResult::Consumed;
            }
        };

        // Dedup check using the unique message ID. When the payload carries a
        // logical id (a re-issued relay broadcast), the same logical message
        // may already have arrived via the relay path under that id — check
        // both keys so a cross-path duplicate is absorbed here instead of
        // burning an MLS decrypt on a ciphertext whose ratchet generation was
        // already consumed (which would classify Retriable and buffer noise).
        let dedup_key = message.id.as_str().to_string();
        let logical_key = payload.message_id.clone();
        let seen = self.group_mesh.message_dedup.contains_key(&dedup_key)
            || logical_key
                .as_deref()
                .is_some_and(|l| self.group_mesh.message_dedup.contains_key(l));
        if seen {
            // Already seen. If the buffered copy is still awaiting decryption,
            // this is a sender retransmit of an undelivered message: defer (no
            // ACK) so the sender keeps retrying until we actually deliver on
            // drain. Returning before decrypt also preserves the
            // replay-amplification defense (one MLS crypto op per id). If the
            // id is not buffered, it was already delivered (a dropped-and-
            // released id would not be in the dedup table at all), so treat it
            // as a normal duplicate and re-ACK to let the sender stop.
            let pending = self.is_group_message_pending(&payload.group_id, &dedup_key)
                || logical_key
                    .as_deref()
                    .is_some_and(|l| self.is_group_message_pending(&payload.group_id, l));
            if pending {
                debug!(
                    group_id = %payload.group_id,
                    msg_id = %dedup_key,
                    "Duplicate of a still-pending group message, deferring ACK"
                );
                return InternalMessageResult::Deferred;
            }
            debug!(
                group_id = %payload.group_id,
                msg_id = %dedup_key,
                "Duplicate group message, skipping"
            );
            return InternalMessageResult::Consumed;
        }

        // Mark as seen BEFORE attempting decode/decrypt to prevent replay
        // amplification: an adversary replaying the same message (even with a bad
        // epoch) should only trigger one MLS crypto operation. Only the envelope
        // id is marked here — the payload's logical id is unauthenticated wire
        // input until the ciphertext MLS-decrypts, and marking it pre-decrypt
        // would let a non-member poison a logical id to suppress the genuine
        // copy. It is marked below, on successful decrypt only.
        self.group_mesh
            .message_dedup
            .insert(dedup_key, Instant::now());
        if self.group_mesh.message_dedup.len() > MAX_GROUP_MESSAGE_DEDUP_ENTRIES {
            self.cleanup_group_message_dedup();
        }

        // Size guard before base64 decode
        let ciphertext_bytes = match base64_decode(&payload.ciphertext) {
            Ok(bytes) => bytes,
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "Failed to decode group message ciphertext");
                return InternalMessageResult::Consumed;
            }
        };

        match self.decrypt_group_application(&payload.group_id, ciphertext_bytes, sender) {
            GroupDecryptOutcome::Plaintext(plaintext) => {
                let Ok(text) = String::from_utf8(plaintext) else {
                    warn!(
                        group_id = %payload.group_id,
                        "Decrypted group payload is not valid UTF-8, dropping"
                    );
                    return InternalMessageResult::Consumed;
                };
                // Decryption authenticated the sender as a group member, so
                // the payload's logical id (if any) can now be trusted: mark
                // it delivered so the relay path's copy of the same logical
                // message dedups against this one, and emit it as the
                // app-facing id so every member sees the same id for this
                // logical message regardless of arrival path.
                let msg_id = logical_key.unwrap_or_else(|| message.id.as_str().to_string());
                if msg_id != message.id.as_str() {
                    self.group_mesh
                        .message_dedup
                        .insert(msg_id.clone(), Instant::now());
                }
                let timestamp = chrono::Utc::now().to_rfc3339();
                info!(group_id = %payload.group_id, "Decrypted mesh group message");
                let (content, media_metadata, content_type, forward_info_event) =
                    Self::restore_group_rich(text, payload.forward_info, sender);
                self.emit_event(Event::group_message_received(
                    payload.group_id,
                    sender.to_string(),
                    content,
                    timestamp,
                    msg_id,
                    payload.reply_to,
                    forward_info_event,
                    media_metadata,
                    content_type,
                ));
                InternalMessageResult::Consumed
            }
            GroupDecryptOutcome::SecurityRejected => InternalMessageResult::SecurityRejected,
            GroupDecryptOutcome::Retriable => {
                let group_id = payload.group_id.clone();
                self.buffer_pending_group_message(
                    &group_id,
                    PendingGroupMessage {
                        sender: sender.to_string(),
                        message_id: message.id.as_str().to_string(),
                        logical_id: logical_key,
                        ciphertext_b64: payload.ciphertext,
                        timestamp: None,
                        reply_to: payload.reply_to,
                        forward_info: payload.forward_info,
                        buffered_at: Instant::now(),
                        received_via: arrival_transport,
                    },
                );
                // Buffered, not delivered: defer the ACK so the sender keeps
                // retransmitting until the drain surfaces it. The drain then
                // ACKs directly on `arrival_transport`.
                InternalMessageResult::Deferred
            }
            GroupDecryptOutcome::NonApplication => {
                // MLS consumed a commit or proposal riding the application
                // channel — group state may have advanced, which can unblock
                // buffered commits and messages exactly like a commit-channel
                // success.
                self.drain_pending_commits(&payload.group_id);
                self.drain_pending_group_messages(&payload.group_id);
                InternalMessageResult::Consumed
            }
            GroupDecryptOutcome::PolicyRejected {
                committer,
                added,
                removed,
            } => {
                // A commit reframed onto the application channel, refused by
                // enforcement before merging. Consume it: the rejection is
                // permanent, so buffering would retry a ciphertext that can
                // never be authorized.
                self.report_unauthorized_membership_change(
                    &payload.group_id,
                    &committer,
                    &added,
                    &removed,
                    "sender_not_admin",
                    true,
                );
                InternalMessageResult::Consumed
            }
            // The mesh channel carries MLS ciphertext by protocol, so a
            // payload that is not MLS framing is garbage, not legacy content.
            GroupDecryptOutcome::NotMlsCiphertext | GroupDecryptOutcome::Failed => {
                InternalMessageResult::Consumed
            }
        }
    }

    /// Decrypts a group application ciphertext, classifying the failure
    /// modes shared by the mesh (`handle_group_mls_msg`), relay
    /// (`handle_relay_group_message_with_mls`), and deferred-retry
    /// (`drain_pending_group_messages`) inbound paths.
    fn decrypt_group_application(
        &self,
        group_id: &str,
        ciphertext: Vec<u8>,
        sender: &str,
    ) -> GroupDecryptOutcome {
        let mls_guard = match self.read_mls_guard() {
            Ok(guard) => guard,
            Err(e) => {
                warn!(group_id = %group_id, error = %e, "MLS unavailable, dropping group message");
                return GroupDecryptOutcome::Failed;
            }
        };
        let gid = match offline_protocol_mls::GroupId::new(group_id) {
            Ok(gid) => gid,
            Err(e) => {
                warn!(group_id = %group_id, error = %e, "Dropping group message with invalid group id");
                return GroupDecryptOutcome::Failed;
            }
        };
        // The epoch field is not used for decryption — OpenMLS determines
        // the epoch from the ciphertext header itself.
        let encrypted = offline_protocol_mls::EncryptedMessage {
            group_id: gid,
            message_type: offline_protocol_mls::MlsMessageType::Application,
            epoch: 0,
            ciphertext,
            sender_id: sender.to_string(),
            timestamp_ms: chrono::Utc::now().timestamp_millis() as u64,
        };
        match mls_guard.decrypt_from_group(&encrypted, sender) {
            Ok(Some(plaintext)) => GroupDecryptOutcome::Plaintext(plaintext),
            Ok(None) => {
                // Ok(None) means MLS consumed a Commit or Proposal — not application
                // data. This is normal for non-application messages that arrive via the
                // group message channel (e.g., due to message reordering).
                debug!(
                    group_id = %group_id,
                    "MLS returned no plaintext (commit/proposal consumed), not an application message"
                );
                GroupDecryptOutcome::NonApplication
            }
            Err(offline_protocol_mls::MlsError::SenderIdentityMismatch {
                claimed,
                authenticated,
            }) => {
                error!(
                    group_id = %group_id,
                    claimed = %claimed,
                    authenticated = %authenticated,
                    "SECURITY: wire sender does not match MLS-authenticated sender, rejecting group message"
                );
                GroupDecryptOutcome::SecurityRejected
            }
            // The same class as SEC-M1 and the same disposition: a permanent
            // refusal to attribute this frame to anyone. A leaf whose key does
            // not hash to its own credential can never become legitimate, so
            // this must not be buffered — and it must withhold the ACK and
            // unmark the id, which is what `SecurityRejected` already carries.
            Err(e @ offline_protocol_mls::MlsError::LeafAddressMismatch { .. }) => {
                error!(
                    group_id = %group_id,
                    sender = %sender,
                    error = %e,
                    "SECURITY: group leaf does not prove the identity it claims, rejecting group message"
                );
                GroupDecryptOutcome::SecurityRejected
            }
            Err(e @ offline_protocol_mls::MlsError::UnsupportedSender { .. }) => {
                error!(
                    group_id = %group_id,
                    sender = %sender,
                    error = %e,
                    "SECURITY: rejecting a group message from an unsupported sender role"
                );
                GroupDecryptOutcome::SecurityRejected
            }
            Err(offline_protocol_mls::MlsError::CommitNotAuthorized {
                committer,
                added,
                removed,
            }) => GroupDecryptOutcome::PolicyRejected {
                committer,
                added,
                removed,
            },
            Err(e @ offline_protocol_mls::MlsError::GroupNotFound(_)) => {
                // No local group state yet. Only buffer what is actually MLS
                // wire framing — a racing ciphertext parses, legacy relay
                // plaintext that happens to be valid base64 does not.
                // (`Decryption` failures below skip this check: decryption
                // only runs after framing already parsed.)
                if offline_protocol_mls::is_mls_framed(&encrypted.ciphertext) {
                    warn!(
                        group_id = %group_id,
                        error = %e,
                        "Failed to decrypt group message (may be out-of-order, buffering)"
                    );
                    GroupDecryptOutcome::Retriable
                } else {
                    debug!(
                        group_id = %group_id,
                        "Group message payload is not MLS framing and no local group state exists"
                    );
                    GroupDecryptOutcome::NotMlsCiphertext
                }
            }
            Err(
                e @ (offline_protocol_mls::MlsError::Decryption(_)
                | offline_protocol_mls::MlsError::SessionDesync(_)),
            ) => {
                // Epoch-lagged ciphertext — may decrypt once a commit
                // advances local group state. `SessionDesync` is the same
                // epoch-mismatch condition surfaced with a distinct variant for
                // the 1:1 re-key path; on the group path it buffers exactly as
                // `Decryption` always has (the group's own recovery is the
                // commit-driven drain, not a re-key).
                warn!(
                    group_id = %group_id,
                    error = %e,
                    "Failed to decrypt group message (may be out-of-order, buffering)"
                );
                GroupDecryptOutcome::Retriable
            }
            Err(e) => {
                warn!(group_id = %group_id, error = %e, "Failed to decrypt group message");
                GroupDecryptOutcome::Failed
            }
        }
    }

    /// Handles an incoming MLS Welcome message (group invite).
    pub(crate) fn handle_group_mls_welcome(&mut self, message_id: &str, sender: &str, data: &str) {
        let payload = match serde_json::from_str::<GroupMlsWelcomePayload>(data) {
            Ok(p) => p,
            Err(_) => {
                warn!(sender = %sender, "Failed to parse GroupMlsWelcome payload");
                return;
            }
        };

        info!(group_id = %payload.group_id, "Received mesh group Welcome");

        // Dedup check — prevents double-join when the same Welcome arrives via
        // multiple transports nearly simultaneously (TOCTOU race on members cache).
        let dedup_key = message_id.to_string();
        if self.group_mesh.message_dedup.contains_key(&dedup_key) {
            debug!(group_id = %payload.group_id, msg_id = %dedup_key, "Duplicate Welcome message, skipping");
            return;
        }
        self.group_mesh
            .message_dedup
            .insert(dedup_key, Instant::now());
        if self.group_mesh.message_dedup.len() > MAX_GROUP_MESSAGE_DEDUP_ENTRIES {
            self.cleanup_group_message_dedup();
        }

        // Skip duplicate Welcome — we're already a member
        if self.group_mesh.members.contains_key(&payload.group_id) {
            debug!(group_id = %payload.group_id, "Ignoring duplicate Welcome — already a member of this group");
            return;
        }

        let welcome_bytes = match base64_decode(&payload.welcome_data) {
            Ok(bytes) => bytes,
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "Failed to decode welcome data");
                return;
            }
        };

        // Join group via MLS, then update cache
        let mls_guard = match self.read_mls_guard() {
            Ok(guard) => guard,
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "MLS unavailable, dropping group welcome");
                return;
            }
        };
        let gid = match offline_protocol_mls::GroupId::new(&payload.group_id) {
            Ok(gid) => gid,
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "Dropping group welcome with invalid group id");
                return;
            }
        };
        let welcome = offline_protocol_mls::WelcomeMessage {
            group_id: gid.clone(),
            welcome_data: welcome_bytes,
            inviter_id: sender.to_string(),
            group_name: payload.group_name.clone(),
            timestamp_ms: chrono::Utc::now().timestamp_millis() as u64,
        };
        // Collected under the MLS guard, emitted after it drops: `emit_event`
        // takes the shared state, and holding both is the lock order this
        // module avoids everywhere else.
        let mut unproven_leaf_invite = false;
        let join_result = match mls_guard.join_group(&welcome) {
            Ok(group_info) => Some(group_info.members.clone()),
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "Failed to join mesh group");
                // A forged ratchet tree is the one join failure that is an
                // accusation rather than a fault: the inviter built a leaf
                // around an identity they cannot prove. Everything else here
                // (a spent key package, a storage error) is noise, so only
                // this class is surfaced.
                if matches!(
                    e,
                    offline_protocol_mls::MlsError::LeafAddressMismatch { .. }
                        | offline_protocol_mls::MlsError::UnsupportedSender { .. }
                ) {
                    unproven_leaf_invite = true;
                }
                None
            }
        };
        drop(mls_guard);

        if unproven_leaf_invite {
            let group_id = payload.group_id.clone();
            self.report_unproven_leaf(
                &group_id,
                sender,
                UnprovenLeafSite::WelcomeDeclined,
                // Identifier-free for the same reason as the commit site: a
                // `SecurityWarning`'s `reason` is not scrubbed, and the error
                // names the impersonated address. The detail stays in the log.
                "Group invite declined: it carried an identity claim this device could not \
                 verify, so messages in this group could not be reliably attributed"
                    .to_string(),
            );
        }

        if let Some(members) = join_result {
            let group_id = payload.group_id.clone();

            // Record the inviter's rich-capability attestations for members
            // we have never (and may never) directly exchange key packages
            // with — without them every rich send into this group drops its
            // extras. Bounded to the authoritative MLS roster we just
            // joined: entries for non-members are attacker-suppliable dead
            // weight and are ignored. `record_attested_rich` skips self,
            // non-V1 lists, and peers we already know directly.
            for (user_id, versions) in &payload.member_rich {
                if members.contains(user_id) {
                    self.record_attested_rich(user_id, versions);
                }
            }

            self.group_mesh.members.insert(group_id.clone(), members);

            // Store member roles and the creator of record from the welcome
            // payload. The creator is what makes `check_is_admin`'s fallback
            // reachable for a joiner: without it our metadata is materialized
            // by `set_member_role` via `GroupMetadata::new(None)`, so a group
            // whose role snapshot arrived incomplete would resolve to
            // deny-by-default with no way back. Deliberately not bounded to
            // the roster we just joined — the creator of record may already
            // have left. `set_group_creator` is first-write-wins, so a
            // duplicate or later Welcome cannot rewrite it.
            if !payload.member_roles.is_empty() || payload.created_by.is_some() {
                if let Ok(mls_guard) = self.read_mls_guard() {
                    for (user_id, role) in &payload.member_roles {
                        if let Err(e) = mls_guard.set_member_role(&gid, user_id, *role) {
                            warn!(user_id = %user_id, error = %e, "Failed to store member role from welcome");
                        }
                    }
                    if let Some(creator) = &payload.created_by {
                        if let Err(e) = mls_guard.set_group_creator(&gid, creator) {
                            warn!(creator = %creator, error = %e, "Failed to store group creator from welcome");
                        }
                    }
                }
            }

            // Send a fresh key package to the inviter. The inviter consumed our
            // previous key package to create this Welcome, so they need a new one
            // for future group invites. Clear the tracking flag first so the send
            // isn't suppressed as a duplicate.
            self.key_package_sent_to.remove(sender);
            if let Err(e) = self.send_key_package_to(sender, false) {
                debug!(
                    inviter = %sender,
                    error = %e,
                    "Failed to send fresh key package to inviter after Welcome (will retry on discovery)"
                );
            }

            self.emit_event(Event::group_member_added(
                group_id.clone(),
                self.local_id.clone(),
                sender.to_string(),
                payload.group_name.clone(),
                // Not evaluated: this Welcome is what creates our view of the
                // group, so there is no prior role state to judge the inviter
                // against. `Some(true)` here would claim a check that cannot
                // exist on this path.
                None,
            ));

            // A commit or group message can race ahead of its Welcome (they
            // are sent back-to-back and may take different paths); now that
            // the group exists locally, retry anything that was buffered.
            // Commits first — an epoch-advancing commit may be exactly what
            // a buffered message is waiting for.
            self.drain_pending_commits(&group_id);
            self.drain_pending_group_messages(&group_id);
        }
    }

    /// Handles an incoming MLS Commit message (membership change).
    ///
    /// Validates the `affected_member` claim against actual MLS state delta
    /// to prevent forged membership events.
    ///
    /// If decryption fails (e.g., due to out-of-order delivery in a mesh network),
    /// the commit is buffered for deferred retry. When a subsequent commit for the
    /// same group succeeds, buffered commits are drained and retried.
    pub(crate) fn handle_group_mls_commit(&mut self, message_id: &str, sender: &str, data: &str) {
        // Dedup check — prevents processing the same commit twice when it
        // arrives via multiple transports. Without this, the second copy fails
        // at MLS (wrong epoch) and gets buffered as a "retriable" pending
        // commit, wasting space and potentially triggering false fork detection.
        let dedup_key = message_id.to_string();
        if self.group_mesh.message_dedup.contains_key(&dedup_key) {
            debug!(msg_id = %dedup_key, "Duplicate commit message, skipping");
            return;
        }
        self.group_mesh
            .message_dedup
            .insert(dedup_key, Instant::now());
        if self.group_mesh.message_dedup.len() > MAX_GROUP_MESSAGE_DEDUP_ENTRIES {
            self.cleanup_group_message_dedup();
        }

        match self.process_commit_core(sender, data) {
            CommitOutcome::Success(group_id) => {
                self.drain_pending_commits(&group_id);
                // A commit that advanced the epoch may unblock buffered
                // application messages encrypted at the newer epoch.
                self.drain_pending_group_messages(&group_id);
            }
            CommitOutcome::Retriable(group_id) => {
                self.buffer_pending_commit(&group_id, message_id, sender, data);
            }
            CommitOutcome::Rejected => {}
        }
    }

    /// Core commit processing logic. Returns an outcome indicating success,
    /// retriable failure, or permanent rejection.
    ///
    /// Does **not** buffer on failure — callers decide whether to buffer based
    /// on the returned outcome.
    fn process_commit_core(&mut self, sender: &str, data: &str) -> CommitOutcome {
        let payload = match serde_json::from_str::<GroupMlsCommitPayload>(data) {
            Ok(p) => p,
            Err(_) => {
                warn!(sender = %sender, "Failed to parse GroupMlsCommit payload");
                return CommitOutcome::Rejected;
            }
        };

        info!(
            group_id = %payload.group_id,
            commit_type = ?payload.commit_type,
            "Received mesh group Commit"
        );

        if payload.ciphertext.is_empty() {
            warn!(
                group_id = %payload.group_id,
                "Received Commit with empty ciphertext, cannot advance MLS epoch"
            );
            return CommitOutcome::Rejected;
        }

        let ciphertext_bytes = match base64_decode(&payload.ciphertext) {
            Ok(bytes) => bytes,
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "Failed to decode commit ciphertext");
                return CommitOutcome::Rejected;
            }
        };

        let mls_guard = match self.read_mls_guard() {
            Ok(guard) => guard,
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "MLS unavailable, dropping group commit");
                return CommitOutcome::Rejected;
            }
        };

        let gid = match offline_protocol_mls::GroupId::new(&payload.group_id) {
            Ok(gid) => gid,
            Err(e) => {
                warn!(group_id = %payload.group_id, error = %e, "Rejecting group commit with invalid group id");
                return CommitOutcome::Rejected;
            }
        };

        // Capture members before commit for delta validation. `None` marks a
        // failed read: this and the post-commit refresh below are the two
        // inputs to the membership delta, and a transient storage failure
        // (`MlsStorage` is a platform keychain/keystore) silently defaulting
        // to an empty roster would fabricate a full-roster delta — and, with
        // it, a security report naming an innocent committer as having added
        // every member. `Ok(None)` (no local group yet) stays an empty
        // roster: past a successful decrypt it is unreachable anyway.
        //
        // Deliberately MLS-derived, not the `group_mesh.members` cache: relay
        // reconciliation can splice ids into the cache that MLS never
        // admitted, and a cache-derived "before" would report such a phantom
        // as an unauthorized removal on the next real commit.
        let members_before: Option<HashSet<String>> = match mls_guard.get_group_info(&gid) {
            Ok(info) => Some(
                info.map(|i| i.members.into_iter().collect())
                    .unwrap_or_default(),
            ),
            Err(e) => {
                warn!(
                    group_id = %payload.group_id,
                    error = %e,
                    "Failed to read pre-commit roster — this commit's membership delta will not be derived or judged"
                );
                None
            }
        };

        // Process Commit via MLS to advance epoch (single lock acquisition)
        let encrypted = offline_protocol_mls::EncryptedMessage {
            group_id: gid.clone(),
            message_type: offline_protocol_mls::MlsMessageType::Commit,
            epoch: payload.epoch,
            ciphertext: ciphertext_bytes,
            sender_id: sender.to_string(),
            timestamp_ms: chrono::Utc::now().timestamp_millis() as u64,
        };
        let mls_result = mls_guard.decrypt_from_group(&encrypted, sender);
        drop(mls_guard);

        match mls_result {
            Ok(_) => {}
            Err(ref e) => {
                // If this is a Remove commit targeting us, we can't decrypt it
                // because the admin already removed us from the MLS group. But the
                // commit payload metadata tells us we were removed, so handle it
                // gracefully: emit the event, clean up local state, and reject the
                // commit (don't buffer it — it will never succeed).
                //
                // SECURITY: Verify the sender is an admin before trusting the
                // unencrypted commit metadata. Without this check, a non-admin
                // group member could forge a commit with garbage ciphertext and
                // affected_member = victim to force group eviction.
                let self_id = self.local_id.clone();
                if matches!(payload.commit_type, GroupCommitType::Remove)
                    && payload.affected_member.as_deref() == Some(&self_id)
                    && self
                        .check_is_admin(&payload.group_id, sender)
                        .unwrap_or(false)
                {
                    info!(
                        group_id = %payload.group_id,
                        "Received remove-commit targeting us — cleaning up local state"
                    );
                    // Clean up local MLS state
                    if let Ok(mls_guard) = self.read_mls_guard() {
                        let _ = mls_guard.leave_group(&gid);
                    }
                    self.group_mesh.members.remove(&payload.group_id);
                    let was_synced = self.group_mesh.relay_synced.remove(&payload.group_id);
                    let was_pending = self
                        .group_mesh
                        .relay_register_pending
                        .remove(&payload.group_id)
                        .is_some();
                    if was_synced || was_pending {
                        self.emit_event(Event::group_relay_sync_changed(
                            payload.group_id.clone(),
                            false,
                            "removed",
                        ));
                    }
                    self.group_mesh
                        .pending_group_messages
                        .remove(&payload.group_id);
                    // Also drop buffered commits: they can never apply now,
                    // and a stale one retried after a rapid re-invite would
                    // expire with retry_count > 0 and falsely flag an epoch
                    // fork.
                    self.group_mesh.pending_commits.remove(&payload.group_id);
                    self.emit_event(Event::group_member_removed(
                        payload.group_id.clone(),
                        self_id,
                        sender.to_string(),
                        // Reached only through the `check_is_admin` gate above.
                        Some(true),
                    ));
                    return CommitOutcome::Rejected;
                }

                // Enforcement refused this commit before merging (only
                // possible with `GroupConfig::enforce_admin_commits` on).
                // Report it on the same signal the applied case uses, marked
                // `enforced` so the app can tell "this happened, undo it"
                // from "this was blocked and we are now behind the group's
                // epoch". Nothing merged, so no roster event accompanies it.
                if let offline_protocol_mls::MlsError::CommitNotAuthorized {
                    committer,
                    added,
                    removed,
                } = e
                {
                    let (committer, added, removed) =
                        (committer.clone(), added.clone(), removed.clone());
                    self.report_unauthorized_membership_change(
                        &payload.group_id,
                        &committer,
                        &added,
                        &removed,
                        "sender_not_admin",
                        true,
                    );
                    return CommitOutcome::Rejected;
                }

                // Classify MLS errors: permanent failures should not be retried,
                // only failures caused by lagging local group state are worth
                // buffering. GroupNotFound is NOT permanent — a commit can
                // outrun our Welcome (they may take different transports), so
                // it is buffered and retried after the join lands, exactly
                // like application messages. A spoofed sender (SEC-M1) is
                // permanent — retrying the same forged commit can never
                // succeed.
                //
                // The leaf-binding refusals are permanent for the same reason,
                // and getting this wrong is worse here than merely wasteful. A
                // leaf whose key does not hash to its own credential can never
                // start doing so, and an unsupported sender role never becomes
                // supported, so every retry re-runs a full MLS `process_message`
                // on a frame with no reachable success. Worse, a buffered commit
                // that expires with `retry_count > 0` is read as an epoch fork
                // (`drain_pending_commits`), which emits a false
                // `group_epoch_fork_detected` and has the elected leader fan an
                // `update_keys` commit out to the whole group — so one forged
                // commit, from any member, would buy an attacker a group-wide
                // re-key round and a bogus security alarm. Buffering also spends
                // one of `MAX_PENDING_COMMITS_PER_GROUP` slots, evicting
                // legitimate out-of-order commits.
                let is_permanent = matches!(
                    e,
                    offline_protocol_mls::MlsError::Deserialization(_)
                        | offline_protocol_mls::MlsError::InvalidMessage(_)
                        | offline_protocol_mls::MlsError::Storage(_)
                        | offline_protocol_mls::MlsError::SenderIdentityMismatch { .. }
                        | offline_protocol_mls::MlsError::LeafAddressMismatch { .. }
                        | offline_protocol_mls::MlsError::UnsupportedSender { .. }
                );
                if is_permanent {
                    error!(
                        group_id = %payload.group_id,
                        epoch = payload.epoch,
                        error = %e,
                        "Permanently failed to process group commit (not retriable)"
                    );
                    // The commit half of `GroupLeafIdentityUnproven`. This is
                    // the more serious of the two sites the code emits it from:
                    // a Welcome refusal declines an invite from a stranger, but
                    // this accuses a member of a group the user is already in.
                    // `sender` is the peer that delivered the commit and it is
                    // proved — `__GRP_MLS_COMMIT__` is security-gated, so the
                    // sender signed with the key its own address derives from
                    // — while the identity the forged leaf claimed stays in the
                    // diagnostic text.
                    if matches!(
                        e,
                        offline_protocol_mls::MlsError::LeafAddressMismatch { .. }
                            | offline_protocol_mls::MlsError::UnsupportedSender { .. }
                    ) {
                        // Variant-neutral summary: the `UnsupportedSender`
                        // half seats no leaf at all (an `ExternalSenders`
                        // extension, or a non-member sender role), so the
                        // "identity nobody proved" wording would be wrong for
                        // it.
                        //
                        // The error is deliberately NOT interpolated: it names
                        // the impersonated address, and the telemetry scrubber
                        // hashes only `peer_id` on a `SecurityWarning` — it
                        // ships `reason` verbatim. Leaking a third party's
                        // address to a sink running `scrub_ids: true` is the
                        // exact trap the `convergence_diag` detail rule names.
                        // The full error is in the `error!` above.
                        let detail = "Group membership change refused: it carried an identity \
                                      claim this device could not verify, so messages in this \
                                      group could not be reliably attributed"
                            .to_string();
                        let group_id = payload.group_id.clone();
                        self.report_unproven_leaf(
                            &group_id,
                            sender,
                            UnprovenLeafSite::CommitRefused,
                            detail,
                        );
                    }
                    return CommitOutcome::Rejected;
                }
                error!(
                    group_id = %payload.group_id,
                    epoch = payload.epoch,
                    error = %e,
                    "Failed to process group commit (may be out-of-order, buffering)"
                );
                return CommitOutcome::Retriable(payload.group_id);
            }
        }

        // Refresh cache and compute the actual membership delta. Like the
        // pre-commit read above, a failed refresh must not default to an
        // empty roster — so when either read failed, the delta is unknowable
        // and everything derived from it (roster events, the authorization
        // judgment, leave-election cleanup, auto-promotion) is skipped for
        // this commit rather than fabricated. The commit itself has already
        // merged; the member cache and events self-heal on the next
        // successful commit or refresh.
        let members_after: Option<HashSet<String>> = match self
            .refresh_group_members(&payload.group_id)
        {
            Ok(members) => Some(members.into_iter().collect()),
            Err(e) => {
                warn!(
                    group_id = %payload.group_id,
                    error = %e,
                    "Failed to refresh post-commit roster — this commit's membership delta will not be derived or judged"
                );
                None
            }
        };
        let (Some(members_before), Some(members_after)) = (members_before, members_after) else {
            if matches!(payload.commit_type, GroupCommitType::KeyUpdate) {
                self.group_mesh.epoch_forks.remove(&payload.group_id);
            }
            return CommitOutcome::Success(payload.group_id);
        };

        // Sorted so event payloads and log lines are deterministic.
        let mut actual_added: Vec<String> =
            members_after.difference(&members_before).cloned().collect();
        actual_added.sort();
        let mut actual_removed: Vec<String> =
            members_before.difference(&members_after).cloned().collect();
        actual_removed.sort();

        let has_membership_change = !actual_added.is_empty() || !actual_removed.is_empty();

        // Validate claimed affected_member against actual MLS delta. A
        // mismatch means the commit's unencrypted framing disagrees with the
        // authenticated MLS state change it actually produced — forged or
        // replayed metadata.
        let mut claim_matches_delta = true;
        if let Some(claimed) = &payload.affected_member {
            let valid = match payload.commit_type {
                GroupCommitType::Add => actual_added.contains(claimed),
                GroupCommitType::Remove => actual_removed.contains(claimed),
                GroupCommitType::KeyUpdate => true, // No membership change expected
            };
            if !valid && has_membership_change {
                claim_matches_delta = false;
                error!(
                    group_id = %payload.group_id,
                    sender = %sender,
                    claimed = %claimed,
                    actual_added = ?actual_added,
                    actual_removed = ?actual_removed,
                    "SECURITY: Commit affected_member does not match actual MLS state delta — possible forgery"
                );
            }
        }

        // No delta, no judgment: a pure KeyUpdate changes no membership and
        // needs no admin (fork-resolution KeyUpdates are issued by the
        // deterministic leader, who is often not one).
        let judgment = if has_membership_change {
            Some(self.judge_membership_change(
                &payload.group_id,
                sender,
                &actual_added,
                &actual_removed,
                claim_matches_delta,
            ))
        } else {
            None
        };

        // Commit-payload metadata (role, rich attestation) is honored only
        // for the member the MLS delta actually added and only from an
        // admin sender — adds are admin-only, so a non-admin sender means
        // forged metadata on a replayed/crafted frame.
        let metadata_sender_is_admin =
            judgment.as_ref().is_some_and(|j| j.sender_is_admin) && !actual_added.is_empty();
        // What the roster events below carry. `None` never reaches them: an
        // empty delta emits no events.
        let authorized = judgment.map(|j| j.authorized);

        // Emit events based on actual MLS membership changes, not claimed affected_member
        for member in &actual_added {
            // Store the role from the commit payload only for the specific affected member,
            // and only if the sender is an admin (prevents non-admins from injecting elevated roles).
            if let (Some(role), Some(affected)) = (&payload.role, &payload.affected_member) {
                if member == affected {
                    if metadata_sender_is_admin {
                        if let Ok(mls_guard) = self.read_mls_guard() {
                            if let Err(e) = mls_guard.set_member_role(&gid, member, *role) {
                                warn!(user_id = %member, error = %e, "Failed to store member role from commit");
                            }
                        }
                    } else {
                        warn!(
                            sender = %sender,
                            group_id = %payload.group_id,
                            "Ignoring role from commit: sender is not admin"
                        );
                    }
                }
            }
            // Record the inviter's rich-capability attestation for the
            // newcomer — we existing members never exchange key packages
            // with them, and without this one unknown member drops rich
            // extras for the whole group. Same trust bounds as the role
            // above; a later direct exchange overrides it.
            if let (Some(versions), Some(affected)) =
                (&payload.affected_member_rich, &payload.affected_member)
            {
                if member == affected && metadata_sender_is_admin {
                    self.record_attested_rich(member, versions);
                }
            }
            self.emit_event(Event::group_member_added(
                payload.group_id.clone(),
                member.clone(),
                sender.to_string(),
                None,
                authorized,
            ));
        }
        for member in &actual_removed {
            // Clean up role metadata for removed members
            if let Ok(mls_guard) = self.read_mls_guard() {
                if let Err(e) = mls_guard.remove_member_role(&gid, member) {
                    warn!(user_id = %member, error = %e, "Failed to clean up role metadata for removed member");
                }
            }
            self.emit_event(Event::group_member_removed(
                payload.group_id.clone(),
                member.clone(),
                sender.to_string(),
                authorized,
            ));
            // Clear any pending leave election for this member — the remove
            // has been committed successfully.
            self.group_mesh
                .pending_leave_elections
                .remove(&(payload.group_id.clone(), member.to_string()));
        }

        // Auto-promote if removal left zero admins and other members remain
        if !actual_removed.is_empty() {
            let remaining = self
                .group_mesh
                .members
                .get(&payload.group_id)
                .cloned()
                .unwrap_or_default();
            self.auto_promote_if_no_admin(&payload.group_id, &remaining);
        }

        // Only clear fork tracking when a KeyUpdate commit succeeds — these
        // are the resolution commits issued by the leader. Regular Add/Remove
        // commits from the same branch succeeding doesn't prove the fork is
        // resolved; members on the other branch are still diverged.
        if matches!(payload.commit_type, GroupCommitType::KeyUpdate) {
            self.group_mesh.epoch_forks.remove(&payload.group_id);
        }

        CommitOutcome::Success(payload.group_id)
    }

    /// Judges one **applied** membership delta against the local admin
    /// overlay, reporting an unauthorized change (rate-limited) via
    /// `GroupUnauthorizedMembershipChange`.
    ///
    /// This deliberately does **not** gate the membership change. MLS
    /// authorizes membership by MLS membership — RFC 9420 leaves access
    /// control to the application — and by the time the delta exists,
    /// `decrypt_from_group` has already merged the commit, advancing our
    /// epoch irreversibly. The only way to reject would be to refuse the
    /// merge, which forks us permanently from every peer that accepted it
    /// (see `check_epoch_forks`: members left on a forked branch have to be
    /// re-invited by the app, and a fork the local role metadata caused —
    /// it is best-effort and can legitimately lag — would be a partition
    /// with no attacker involved). An unrecoverable partition is a worse
    /// failure than an insider membership change, so the change is applied
    /// and reported truthfully.
    ///
    /// Unlike the commit-metadata gate in `process_commit_core`, this covers
    /// removals too. When receive-side enforcement is enabled
    /// (`GroupConfig::enforce_admin_commits`) the *rejection* happens earlier,
    /// pre-merge in the MLS layer, and never reaches this function — but it
    /// reports through the same [`Self::report_unauthorized_membership_change`]
    /// so both outcomes surface on one signal.
    pub(crate) fn judge_membership_change(
        &mut self,
        group_id: &str,
        sender: &str,
        added: &[String],
        removed: &[String],
        claim_matches_delta: bool,
    ) -> MembershipJudgment {
        let sender_is_admin = self.check_is_admin(group_id, sender).unwrap_or(false);

        // A membership change is authorized only when an admin committed it
        // *and* the commit's own framing agrees with the delta it produced.
        let authorized = sender_is_admin && claim_matches_delta;

        if !authorized {
            let reason = if sender_is_admin {
                "affected_member_mismatch"
            } else {
                "sender_not_admin"
            };
            self.report_unauthorized_membership_change(
                group_id, sender, added, removed, reason, false,
            );
        }

        MembershipJudgment {
            sender_is_admin,
            authorized,
        }
    }

    /// Emits the rate-limited `GroupLeafIdentityUnproven` report.
    ///
    /// Shared by the three group-side sites that find a leaf which does not
    /// derive its own credential: declining a Welcome whose ratchet tree
    /// contains one, refusing a commit that would install one, and a roster read
    /// skipping one already seated in local state.
    ///
    /// `peer` is who the finding is attributed to, and it is not the same kind
    /// of thing in all three. For the two wire sites it is the peer that
    /// delivered the forgery — the inviter or the committing sender — which is
    /// proved, both frames being security-gated against the sender's own
    /// address. For [`UnprovenLeafSite::RosterEntry`] there is no delivering
    /// peer at all: the leaf is already in the tree and no wire gate admitted
    /// it, so the caller passes this device's own id, the same attribution
    /// `RelayAddressDeclarationRefused` uses when the finding is about this
    /// device rather than a peer's behaviour. Apps must therefore read `peer_id`
    /// on this code as "who this concerns", not "who to blame".
    ///
    /// The identity the forged leaf claimed stays in `detail`, which is
    /// diagnostic text.
    ///
    /// Rate-limited per `(group, peer, site)` through the shared
    /// [`claim_report_window`], on the same window and bound as
    /// [`Self::report_unauthorized_membership_change`]. The commit half makes
    /// this necessary rather than tidy: refusals are permanent and cost the
    /// sender nothing, so an authenticated member can emit one per frame and
    /// bury the signal in its own repetition. `site` is in the key so a
    /// declined invite cannot swallow the first refused *commit* — see
    /// [`UnprovenLeafSite`].
    ///
    /// `detail` must stay **identifier-free**: it becomes the event `reason`,
    /// which the telemetry scrubber passes through verbatim while hashing only
    /// `peer_id`. The impersonated address belongs in the log, not here.
    fn report_unproven_leaf(
        &mut self,
        group_id: &str,
        peer: &str,
        site: UnprovenLeafSite,
        detail: String,
    ) -> bool {
        let key = (group_id.to_string(), peer.to_string(), site);
        if !claim_report_window(&mut self.group_mesh.unproven_leaf_reports, key) {
            debug!(
                group_id = %group_id,
                sender = %peer,
                ?site,
                "Suppressing repeated unproven-leaf report within the rate-limit window"
            );
            return false;
        }

        self.emit_event(Event::security_warning(
            peer.to_string(),
            crate::events::SecurityWarningCode::GroupLeafIdentityUnproven,
            detail,
        ));
        true
    }

    /// Emits the rate-limited unauthorized-membership-change report.
    ///
    /// Shared by both outcomes so apps see one signal regardless of
    /// configuration: `enforced == false` means the change was applied and is
    /// reported after the fact (the default), `enforced == true` means the
    /// commit was refused before merging and no membership change occurred.
    ///
    /// Rate-limited per `(group, committer, enforced)` because divergent role
    /// metadata would otherwise re-fire on every commit from the same peer.
    /// `enforced` is part of the key so the two outcomes never suppress each
    /// other: a refusal is a partition alarm — the device stopped merging and
    /// now trails the group's epoch — and losing the first one of those behind
    /// an earlier report-only event would hide the very condition the app is
    /// told to act on. Within one outcome class the window still collapses
    /// repeats, which is what the limit is for. The tracking map is bounded:
    /// lapsed windows are dropped first, then the oldest live entry.
    fn report_unauthorized_membership_change(
        &mut self,
        group_id: &str,
        committer: &str,
        added: &[String],
        removed: &[String],
        reason: &str,
        enforced: bool,
    ) {
        let key = (group_id.to_string(), committer.to_string(), enforced);
        if !claim_report_window(&mut self.group_mesh.unauthorized_change_reports, key) {
            debug!(
                group_id = %group_id,
                sender = %committer,
                reason,
                enforced,
                "Suppressing repeated unauthorized-membership-change report within the rate-limit window"
            );
            return;
        }
        if enforced {
            warn!(
                group_id = %group_id,
                sender = %committer,
                reason,
                added = ?added,
                removed = ?removed,
                "SECURITY: Unauthorized group membership change refused — the commit was not merged, so our epoch now trails members that accepted it"
            );
        } else {
            warn!(
                group_id = %group_id,
                sender = %committer,
                reason,
                added = ?added,
                removed = ?removed,
                "SECURITY: Unauthorized group membership change applied — MLS accepted the commit, but the SDK's admin policy did not authorize it"
            );
        }
        self.emit_event(Event::group_unauthorized_membership_change(
            group_id.to_string(),
            committer.to_string(),
            added.to_vec(),
            removed.to_vec(),
            reason.to_string(),
            enforced,
        ));
    }

    /// Releases every replay-protection record for a buffered entry dropped
    /// undelivered (cap eviction or TTL expiry), so a sender-side redelivery
    /// is accepted fresh instead of being rejected as a replay of a copy
    /// that no longer exists anywhere.
    ///
    /// Two layers must be released. The group-level dedup table rejects
    /// redeliveries inside the group handlers; the transport-level
    /// deduplicator rejects them earlier, at the receive loop — on the mesh
    /// path the envelope ID doubles as the group dedup key, so without this
    /// release a redelivery would be swallowed (and re-ACKed as delivered)
    /// for up to the deduplicator's retention window without ever reaching
    /// the group handlers. Relay-path IDs are relay payload IDs that never
    /// enter the transport deduplicator (the platform bridges mint a fresh
    /// envelope UUID per injected message), so `from_str` fails or the
    /// unmark is a no-op there — both harmless.
    pub(crate) fn release_replay_protection(&mut self, message_id: &str) {
        self.group_mesh.message_dedup.remove(message_id);
        if let Ok(envelope_id) = MessageId::from_str(message_id) {
            self.deduplicator.unmark_seen(&envelope_id);
        }
    }

    /// Buffers a failed commit for deferred retry.
    ///
    /// The commit's message ID is already in the dedup table, so this
    /// buffered copy is its only path to processing — whenever a buffered
    /// commit is dropped unprocessed (cap eviction here, TTL expiry at
    /// drain), its replay protection is released so a redelivery gets a
    /// fresh chance instead of being permanently rejected, mirroring
    /// `buffer_pending_group_message`.
    pub(crate) fn buffer_pending_commit(
        &mut self,
        group_id: &str,
        message_id: &str,
        sender: &str,
        data: &str,
    ) {
        let pending = PendingCommit {
            sender: sender.to_string(),
            message_id: message_id.to_string(),
            data: data.to_string(),
            buffered_at: Instant::now(),
            retry_count: 0,
        };
        let Some(evicted) = enforce_global_buffer_bound(
            &mut self.group_mesh.pending_commits,
            group_id,
            &PENDING_COMMIT_CAPS,
            pending.data.len(),
            |c| c.data.len(),
            |c| c.buffered_at,
        ) else {
            // Only the ciphertext field is size-guarded at decode time; the
            // JSON around it is attacker-sized, so an oversized payload must
            // be dropped rather than allowed to purge the whole buffer.
            warn!(
                group_id = %group_id,
                size = pending.data.len(),
                "Pending commit exceeds the global byte budget, dropping"
            );
            return;
        };
        // An evicted commit was never processed — release its replay
        // protection so a sender-side redelivery is accepted fresh instead
        // of being rejected as a replay of a copy that no longer exists.
        for entry in &evicted {
            self.release_replay_protection(&entry.message_id);
        }
        let displaced = {
            let buf = self
                .group_mesh
                .pending_commits
                .entry(group_id.to_string())
                .or_default();
            let displaced = if buf.len() >= MAX_PENDING_COMMITS_PER_GROUP {
                warn!(
                    group_id = %group_id,
                    "Pending commit buffer full, dropping oldest"
                );
                buf.pop_front()
            } else {
                None
            };
            buf.push_back(pending);
            debug!(
                group_id = %group_id,
                buffered_count = buf.len(),
                "Buffered out-of-order commit for deferred retry"
            );
            displaced
        };
        if let Some(displaced) = displaced {
            self.release_replay_protection(&displaced.message_id);
        }
    }

    /// Drains and retries buffered pending commits for a group after a
    /// successful commit advanced the epoch. Each successful retry triggers
    /// another drain pass (at most `MAX_PENDING_COMMITS_PER_GROUP` iterations).
    ///
    /// Call-site contract: a commit success inside this drain can unblock
    /// buffered application messages, but this function does not drain them —
    /// every caller must follow with `drain_pending_group_messages`.
    ///
    /// Uses `process_commit_core` (not `handle_group_mls_commit`) to avoid
    /// double-buffering: this method owns the retry lifecycle and re-buffers
    /// only via `still_pending`, never through the core processing path.
    pub(crate) fn drain_pending_commits(&mut self, group_id: &str) {
        // Track commits that were retried at least once and still expired —
        // these are strong evidence of epoch mismatch (true fork), not just
        // slow delivery from the mesh network.
        let mut retried_expired_count: usize = 0;

        // Limit iterations to avoid unbounded looping
        for _ in 0..MAX_PENDING_COMMITS_PER_GROUP {
            let pending = match self.group_mesh.pending_commits.get_mut(group_id) {
                Some(buf) if !buf.is_empty() => std::mem::take(buf),
                _ => break,
            };

            let mut any_succeeded = false;
            let mut still_pending = VecDeque::new();

            for entry in pending {
                // Drop expired entries — only count retried ones for fork detection
                if entry.buffered_at.elapsed() > StdDuration::from_secs(PENDING_COMMIT_TTL_SECS) {
                    debug!(
                        group_id = %group_id,
                        retry_count = entry.retry_count,
                        "Dropping expired pending commit"
                    );
                    if entry.retry_count > 0 {
                        retried_expired_count += 1;
                    }
                    // Never processed — release replay protection so a
                    // redelivery is accepted fresh even before the periodic
                    // dedup sweep runs.
                    self.release_replay_protection(&entry.message_id);
                    continue;
                }
                match self.process_commit_core(&entry.sender, &entry.data) {
                    CommitOutcome::Success(_) => {
                        any_succeeded = true;
                    }
                    CommitOutcome::Retriable(_) => {
                        // Still out-of-order — keep for next pass with incremented retry count
                        let mut entry = entry;
                        entry.retry_count += 1;
                        still_pending.push_back(entry);
                    }
                    CommitOutcome::Rejected => {
                        // Permanently bad — drop silently
                    }
                }
            }

            // Re-buffer commits that still failed
            if !still_pending.is_empty() {
                self.group_mesh
                    .pending_commits
                    .entry(group_id.to_string())
                    .or_default()
                    .extend(still_pending);
            }

            if !any_succeeded {
                break;
            }
            // Another commit succeeded — loop again in case it unblocked more
        }

        // Clean up empty entries
        if self
            .group_mesh
            .pending_commits
            .get(group_id)
            .is_none_or(|v| v.is_empty())
        {
            self.group_mesh.pending_commits.remove(group_id);
        }

        // If commits that were retried (and kept failing) expired, this is a
        // strong signal of epoch fork — the commits were valid but for a
        // different epoch branch. Commits that expired without any retries
        // are more likely just slow mesh delivery and are not flagged.
        if retried_expired_count > 0 && !self.group_mesh.epoch_forks.contains_key(group_id) {
            self.flag_potential_epoch_fork(group_id);
        }
    }

    /// Buffers a group application message whose decryption failed because
    /// local group state lagged (Welcome not yet processed / epoch behind).
    ///
    /// The message ID is already in the dedup table, so redeliveries via
    /// other transports are rejected there — this buffered copy is the
    /// message's only path to delivery, via `drain_pending_group_messages`.
    /// Correspondingly, whenever a buffered copy is dropped undelivered
    /// (cap eviction here, TTL expiry at drain), its replay protection is
    /// released so a redelivery gets a fresh chance instead of being
    /// permanently lost.
    pub(crate) fn buffer_pending_group_message(
        &mut self,
        group_id: &str,
        pending: PendingGroupMessage,
    ) {
        let Some(evicted) = enforce_global_buffer_bound(
            &mut self.group_mesh.pending_group_messages,
            group_id,
            &PENDING_GROUP_MESSAGE_CAPS,
            pending.ciphertext_b64.len(),
            |m| m.ciphertext_b64.len(),
            |m| m.buffered_at,
        ) else {
            // Unreachable in practice — the ciphertext passed the 1 MiB
            // base64_decode guard on both inbound paths — but the invariant
            // belongs here, not in the callers.
            warn!(
                group_id = %group_id,
                size = pending.ciphertext_b64.len(),
                "Pending group message exceeds the global byte budget, dropping"
            );
            return;
        };
        // An evicted message was never delivered — release its replay
        // protection so a sender-side redelivery is accepted fresh instead
        // of being rejected as a replay of a copy that no longer exists.
        for entry in &evicted {
            self.release_replay_protection(&entry.message_id);
        }
        let displaced = {
            let buf = self
                .group_mesh
                .pending_group_messages
                .entry(group_id.to_string())
                .or_default();
            let displaced = if buf.len() >= MAX_PENDING_GROUP_MESSAGES_PER_GROUP {
                warn!(
                    group_id = %group_id,
                    "Pending group message buffer full, dropping oldest"
                );
                buf.pop_front()
            } else {
                None
            };
            buf.push_back(pending);
            debug!(
                group_id = %group_id,
                buffered_count = buf.len(),
                "Buffered out-of-order group message for deferred retry"
            );
            displaced
        };
        if let Some(displaced) = displaced {
            self.release_replay_protection(&displaced.message_id);
        }
    }

    /// Whether a message id is currently buffered awaiting decryption for the
    /// given group. Drives the deferred-ACK decision in
    /// [`Self::handle_group_mls_msg_via`]'s duplicate branch: a retransmit of a
    /// still-pending message must be deferred (no ACK), while a duplicate of an
    /// already-delivered one is re-ACKed so the sender can stop.
    /// Matches both the envelope id and (for re-issued broadcast copies) the
    /// logical id, so a cross-path retransmit of a still-pending logical
    /// message is deferred rather than re-ACKed as delivered.
    fn is_group_message_pending(&self, group_id: &str, message_id: &str) -> bool {
        self.group_mesh
            .pending_group_messages
            .get(group_id)
            .is_some_and(|buf| {
                buf.iter().any(|m| {
                    m.message_id == message_id || m.logical_id.as_deref() == Some(message_id)
                })
            })
    }

    /// Sends the deferred delivery ACK for a group message surfaced by the
    /// drain, on the transport it originally arrived on.
    ///
    /// Mirrors the DM `ack_drained_message`: it closes the ACK-latency window
    /// so a sender that exhausts its retry budget before local group state
    /// catches up still learns of delivery, instead of marking a
    /// locally-delivered message undeliverable. `received_via` is `None` for
    /// relay-path entries (the relay sender is not ACK-gated) and transport-less
    /// test enqueue, in which case this is a correct no-op and recovery falls
    /// back to the sender's next resend hitting the duplicate re-ACK path.
    fn ack_drained_group_message(
        &mut self,
        ack_to: &str,
        acked_message_id: &str,
        received_via: Option<TransportType>,
    ) {
        let Some(transport) = received_via else {
            return;
        };
        if let Err(err) = self.send_group_delivery_ack(ack_to, acked_message_id, transport) {
            error!(
                msg_id = %acked_message_id,
                error = %err,
                "Failed to send deferred delivery ACK for drained group message"
            );
        }
    }

    /// Drains buffered group application messages after local MLS state for
    /// the group advanced (successful Welcome join or commit). Messages are
    /// retried in arrival order; entries that still fail retriably are
    /// re-buffered until their TTL expires.
    ///
    /// A buffered entry can turn out to be a commit or proposal riding the
    /// application channel (`NonApplication`): MLS consumes it, so group
    /// state may have advanced mid-drain. When that happens, buffered
    /// commits are drained and another pass runs, since entries re-buffered
    /// earlier in the same pass may now decrypt. Terminates: a pass loops
    /// only after consuming a `NonApplication` entry, which is never
    /// re-buffered, so each looping pass shrinks the buffer.
    ///
    /// Double delivery is impossible by construction rather than by
    /// bookkeeping: MLS consumes a ratchet generation on decrypt, so a copy
    /// of a ciphertext that was already decrypted elsewhere fails here
    /// (`Decryption` → `Retriable`) and never reaches the emit. Reaching the
    /// `Plaintext` branch *proves* this logical message has not been
    /// delivered before. `delivered_here` exists only to stop a second
    /// buffered copy from burning that pointless decrypt within one drain —
    /// see the declaration.
    pub(crate) fn drain_pending_group_messages(&mut self, group_id: &str) {
        // Ids (envelope and logical) this drain has already delivered. Both
        // the mesh re-issue of a relay broadcast and the relay's own copy of
        // it can sit buffered at once while group state lags, and they carry
        // the same ciphertext. Once one is delivered, the other must be
        // dropped without a decrypt attempt: its generation is spent, so MLS
        // would classify it `Retriable` and re-buffer it as noise until its
        // TTL — whose expiry would then call `release_replay_protection` on
        // an id that WAS delivered, re-opening a replay window for it.
        let mut delivered_here: HashSet<String> = HashSet::new();
        loop {
            let pending = match self.group_mesh.pending_group_messages.get_mut(group_id) {
                Some(buf) if !buf.is_empty() => std::mem::take(buf),
                _ => break,
            };

            let mut state_advanced = false;
            let mut still_pending = VecDeque::new();
            for entry in pending {
                // A second buffered copy of something this drain just
                // delivered. Checked before the TTL branch so it can never
                // release replay protection for a delivered id.
                if delivered_here.contains(&entry.message_id)
                    || entry
                        .logical_id
                        .as_deref()
                        .is_some_and(|l| delivered_here.contains(l))
                {
                    debug!(
                        group_id = %group_id,
                        msg_id = %entry.message_id,
                        "Buffered copy of a message this drain already delivered, dropping"
                    );
                    // The frame *is* delivered (as a duplicate), so ACK it or
                    // the sender keeps retransmitting a message we hold.
                    // `received_via` is `None` on the relay path, where the
                    // sender is not ACK-gated — a correct no-op there.
                    self.ack_drained_group_message(
                        &entry.sender,
                        &entry.message_id,
                        entry.received_via,
                    );
                    continue;
                }
                if entry.buffered_at.elapsed()
                    > StdDuration::from_secs(PENDING_GROUP_MESSAGE_TTL_SECS)
                {
                    debug!(
                        group_id = %group_id,
                        msg_id = %entry.message_id,
                        "Dropping expired pending group message"
                    );
                    // Never delivered — release replay protection so a
                    // redelivery is accepted fresh even before the periodic
                    // dedup sweep runs.
                    self.release_replay_protection(&entry.message_id);
                    continue;
                }
                // Validated at buffer time; failure here is defensive only.
                let Ok(ciphertext_bytes) = base64_decode(&entry.ciphertext_b64) else {
                    continue;
                };
                match self.decrypt_group_application(group_id, ciphertext_bytes, &entry.sender) {
                    GroupDecryptOutcome::Plaintext(plaintext) => {
                        let Ok(text) = String::from_utf8(plaintext) else {
                            warn!(
                                group_id = %group_id,
                                "Decrypted group payload is not valid UTF-8, dropping"
                            );
                            continue;
                        };
                        info!(
                            group_id = %group_id,
                            msg_id = %entry.message_id,
                            "Delivered buffered group message after group state caught up"
                        );
                        // Capture the ACK targets before the fields move into
                        // the event: the message is delivered now, so the drain
                        // sends the deferred delivery ACK directly on the
                        // recorded arrival transport instead of waiting for the
                        // sender's next resend. The ACK is always keyed on the
                        // envelope id (`message_id`) — that is what the sender's
                        // ack_manager awaits.
                        let received_via = entry.received_via;
                        let ack_sender = entry.sender.clone();
                        let ack_message_id = entry.message_id.clone();
                        // A re-issued broadcast copy carries the logical id the
                        // whole group knows this message by: emit that id and
                        // mark it delivered, so the relay path's copy of the
                        // same logical message dedups against this one.
                        //
                        // No "already delivered elsewhere?" check is needed
                        // here, and none would be correct: the successful
                        // decrypt above already proves this ciphertext's
                        // ratchet generation was unspent, i.e. that no other
                        // copy was delivered before it. A copy that *was*
                        // beaten to it fails decrypt and lands in `Retriable`,
                        // never here.
                        let emit_id = match entry.logical_id {
                            Some(logical) => {
                                self.group_mesh
                                    .message_dedup
                                    .insert(logical.clone(), Instant::now());
                                logical
                            }
                            None => entry.message_id,
                        };
                        delivered_here.insert(ack_message_id.clone());
                        delivered_here.insert(emit_id.clone());
                        let (content, media_metadata, content_type, forward_info_event) =
                            Self::restore_group_rich(text, entry.forward_info, &entry.sender);
                        let timestamp = entry
                            .timestamp
                            .unwrap_or_else(|| chrono::Utc::now().to_rfc3339());
                        self.emit_event(Event::group_message_received(
                            group_id.to_string(),
                            entry.sender,
                            content,
                            timestamp,
                            emit_id,
                            entry.reply_to,
                            forward_info_event,
                            media_metadata,
                            content_type,
                        ));
                        self.ack_drained_group_message(&ack_sender, &ack_message_id, received_via);
                    }
                    GroupDecryptOutcome::Retriable => {
                        still_pending.push_back(entry);
                    }
                    GroupDecryptOutcome::NonApplication => {
                        state_advanced = true;
                    }
                    GroupDecryptOutcome::PolicyRejected {
                        committer,
                        added,
                        removed,
                    } => {
                        // Dropped, not re-buffered: the refusal is permanent,
                        // so re-queueing would retry it until the entry ages
                        // out and then misreport the expiry as an epoch fork.
                        self.report_unauthorized_membership_change(
                            group_id,
                            &committer,
                            &added,
                            &removed,
                            "sender_not_admin",
                            true,
                        );
                    }
                    GroupDecryptOutcome::SecurityRejected
                    | GroupDecryptOutcome::NotMlsCiphertext
                    | GroupDecryptOutcome::Failed => {
                        // Dropped unprocessed — release replay protection, for
                        // the same reason the arrival path unmarks a rejected
                        // relay copy (see the marking note atop
                        // `handle_relay_group_message_with_mls`) and the TTL
                        // arm above releases an expired one. A relay copy can
                        // outrun its Welcome, so a mis-attributed one is judged
                        // *here* rather than at arrival — and a hostile relay
                        // picks that ordering for free. Left marked, the id
                        // reads as delivered while no longer being pending, so
                        // the per-member re-issue that is this message's own
                        // delivery safety net is absorbed as an
                        // already-delivered duplicate and re-ACKed: delivered
                        // nowhere, sender told otherwise.
                        //
                        // `PolicyRejected` above deliberately does not release:
                        // that refusal is permanent, so a later copy could only
                        // waste work.
                        self.release_replay_protection(&entry.message_id);
                    }
                }
            }

            if !still_pending.is_empty() {
                self.group_mesh
                    .pending_group_messages
                    .entry(group_id.to_string())
                    .or_default()
                    .extend(still_pending);
            }

            if !state_advanced {
                break;
            }
            // The consumed commit may also unblock buffered commit-channel
            // commits; drain them before the next message pass (the pass itself
            // satisfies drain_pending_commits' call-site contract).
            self.drain_pending_commits(group_id);
        }

        // Clean up empty entries
        if self
            .group_mesh
            .pending_group_messages
            .get(group_id)
            .is_none_or(|v| v.is_empty())
        {
            self.group_mesh.pending_group_messages.remove(group_id);
        }
    }

    /// Flags a group as having a potential epoch fork.
    ///
    /// Called when buffered commits expire without resolution, indicating
    /// the group may have diverged due to concurrent commits.
    fn flag_potential_epoch_fork(&mut self, group_id: &str) {
        if self.group_mesh.epoch_forks.len() >= MAX_EPOCH_FORK_ENTRIES {
            // Evict the oldest entry to prevent unbounded growth
            if let Some(oldest_key) = self
                .group_mesh
                .epoch_forks
                .values()
                .min_by_key(|f| f.detected_at)
                .map(|f| f.group_id.clone())
            {
                self.group_mesh.epoch_forks.remove(&oldest_key);
            }
        }

        let local_epoch = self.refresh_group_members(group_id).ok().and_then(|_| {
            let mls_guard = self.read_mls_guard().ok()?;
            let gid = offline_protocol_mls::GroupId::new(group_id).ok()?;
            mls_guard
                .get_group_info(&gid)
                .ok()
                .flatten()
                .map(|i| i.epoch)
        });

        if local_epoch.is_none() {
            warn!(
                group_id = %group_id,
                "Could not read local MLS epoch during fork detection — MLS unavailable or group not found"
            );
        }

        warn!(
            group_id = %group_id,
            local_epoch = ?local_epoch,
            "Potential epoch fork detected — buffered commits expired without resolution"
        );

        self.group_mesh.epoch_forks.insert(
            group_id.to_string(),
            EpochForkState {
                group_id: group_id.to_string(),
                local_epoch,
                detected_at: Instant::now(),
                resolution_attempted: false,
            },
        );

        self.emit_event(Event::group_epoch_fork_detected(
            group_id.to_string(),
            local_epoch,
        ));
    }

    /// Handles an incoming group leave notification.
    ///
    /// After verifying the sender, the lexicographically-first remaining member
    /// (deterministic election) issues an MLS remove-commit to advance the group
    /// epoch and revoke the leaving member's keys. Other members will receive
    /// the commit via `handle_group_mls_commit`.
    ///
    /// # Security limitations
    ///
    /// Leave notifications are **not** MLS-authenticated because a member cannot
    /// issue a self-removal Commit in MLS. The `sender` field comes from the
    /// `Message` envelope which is not cryptographically bound. In an adversarial
    /// mesh environment a relay node could forge a leave notification to force-
    /// remove a legitimate member. Mitigations:
    ///
    /// 1. `sender == leaving_member` check prevents cross-member impersonation
    ///    when the transport layer preserves sender identity.
    /// 2. Membership is verified against the **MLS group state** (authoritative),
    ///    not just the local cache.
    /// 3. The elected remover issues a real MLS Commit that all members verify
    ///    cryptographically.
    ///
    /// For fully adversarial environments, consider requiring admin-only removal
    /// or adding an MLS application-message-signed leave proof.
    pub(crate) fn handle_group_mls_leave(&mut self, message_id: &str, sender: &str, data: &str) {
        let payload = match serde_json::from_str::<GroupMlsLeavePayload>(data) {
            Ok(p) => p,
            Err(_) => {
                warn!(sender = %sender, "Failed to parse GroupMlsLeave payload");
                return;
            }
        };

        // Dedup check — prevents duplicate leave notifications from resetting
        // the election timer or triggering redundant remove-commit attempts.
        let dedup_key = message_id.to_string();
        if self.group_mesh.message_dedup.contains_key(&dedup_key) {
            debug!(
                group_id = %payload.group_id,
                msg_id = %dedup_key,
                "Duplicate leave notification, skipping"
            );
            return;
        }
        self.group_mesh
            .message_dedup
            .insert(dedup_key, Instant::now());
        if self.group_mesh.message_dedup.len() > MAX_GROUP_MESSAGE_DEDUP_ENTRIES {
            self.cleanup_group_message_dedup();
        }

        // Verify sender matches the claimed leaving member to prevent spoofing
        if payload.leaving_member != sender {
            error!(
                sender = %sender,
                claimed = %payload.leaving_member,
                group_id = %payload.group_id,
                "SECURITY: Leave notification sender mismatch — possible spoofing attempt, ignoring"
            );
            return;
        }

        // Verify sender is actually a member of the group using MLS state
        // (authoritative) rather than only the local cache.
        let self_id = self.local_id.clone();
        let members = self
            .refresh_group_members(&payload.group_id)
            .ok()
            .or_else(|| self.group_mesh.members.get(&payload.group_id).cloned())
            .unwrap_or_default();

        if !members.iter().any(|m| m == sender) {
            error!(
                sender = %sender,
                group_id = %payload.group_id,
                "SECURITY: Leave notification from non-member, ignoring"
            );
            return;
        }

        info!(
            group_id = %payload.group_id,
            leaving_member = %payload.leaving_member,
            "Received mesh group leave notification"
        );

        // Deterministic election: lexicographically-first remaining member
        // (excluding the leaver) issues the MLS remove-commit to advance epoch.
        let mut remaining: Vec<String> = members
            .iter()
            .filter(|m| m.as_str() != sender)
            .cloned()
            .collect();
        remaining.sort();

        let should_remove = remaining
            .first()
            .map(|first| first == &self_id)
            .unwrap_or(false);

        if should_remove {
            debug!(
                group_id = %payload.group_id,
                leaving_member = %sender,
                "Elected to issue MLS remove-commit for leaving member"
            );
            // Issue MLS remove + distribute commit to advance epoch and revoke keys.
            // remove_from_group emits GroupMemberRemoved, so we skip the event below.
            if let Err(e) = self.remove_from_group(&payload.group_id, sender) {
                warn!(
                    group_id = %payload.group_id,
                    leaving_member = %sender,
                    error = %e,
                    "Failed to issue MLS remove-commit for leaving member"
                );
            }
            // Clear any pending election for this leave (we handled it)
            let key = (payload.group_id.clone(), sender.to_string());
            self.group_mesh.pending_leave_elections.remove(&key);
        } else {
            // We're not the elected remover — record the election so we can
            // take over if the elected member fails to issue the commit in time.
            if self.group_mesh.pending_leave_elections.len() >= MAX_PENDING_LEAVE_ELECTIONS {
                // Evict the oldest entry to prevent unbounded growth.
                if let Some(oldest_key) = self
                    .group_mesh
                    .pending_leave_elections
                    .iter()
                    .min_by_key(|(_, e)| e.received_at)
                    .map(|(k, _)| k.clone())
                {
                    self.group_mesh.pending_leave_elections.remove(&oldest_key);
                }
            }
            let key = (payload.group_id.clone(), sender.to_string());
            self.group_mesh.pending_leave_elections.insert(
                key,
                PendingLeaveElection {
                    group_id: payload.group_id.clone(),
                    leaving_member: sender.to_string(),
                    received_at: Instant::now(),
                    last_attempt_at: None,
                },
            );
        }

        // Do NOT emit GroupMemberRemoved here for non-elected nodes.
        // The elected node issues an MLS remove-commit which all members
        // (including us) will process via `handle_group_mls_commit` →
        // `process_commit_core`, which emits the event based on the actual
        // MLS membership delta. Emitting here would cause a duplicate event
        // because we'd emit once now (premature, before MLS state changes)
        // and once when the commit arrives.
    }

    /// Refreshes the cached member list for a group from MlsManager.
    ///
    /// Also the reporting seam for leaves already seated in local group state:
    /// `get_group_info` filters out any leaf that does not derive its own
    /// credential and hands back the count, and a non-zero one is surfaced here
    /// as `GroupLeafIdentityUnproven`. This is the chokepoint for it because it
    /// is the roster read that runs after every membership change and before
    /// every fan-out, and — unlike the public `get_group_info` getter beside it
    /// — it holds `&mut self`, so it can emit.
    ///
    /// Rate-limited like the two wire sites, which matters more here than
    /// there: a seated leaf is *persistent*, so without suppression every
    /// commit, send and drain in the group would re-report the same finding.
    pub(crate) fn refresh_group_members(&mut self, group_id: &str) -> Result<Vec<String>> {
        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        let info = mls_guard
            .get_group_info(&gid)?
            .ok_or_else(|| Error::GroupNotFound(group_id.to_string()))?;
        let members = info.members.clone();
        let unproven_members = info.unproven_members;
        drop(mls_guard);
        self.group_mesh
            .members
            .insert(group_id.to_string(), members.clone());

        if unproven_members > 0 {
            let peer = self.local_id.clone();
            // The log rides the rate limit rather than the condition, which the
            // other three sites do not need to do: they log once per refused
            // *frame*, so inbound traffic bounds them. This one is driven by our
            // own activity — a roster read runs on every commit, send and drain
            // — and the finding is persistent, so an unthrottled line here would
            // put an `error!` in the log for every message the user sends, for
            // as long as the group exists. Same placement as
            // `report_unauthorized_membership_change`, which also logs only
            // after claiming the window.
            let reported = self.report_unproven_leaf(
                group_id,
                &peer,
                UnprovenLeafSite::RosterEntry,
                // Identifier-free like the other two sites, and count-free for
                // one further reason: the count is a property of local state,
                // not of anything a peer did, so it says nothing a sink needs
                // and narrows which install a record came from. It is in the
                // `error!` below.
                "This group holds membership state that could not be verified against the keys \
                 it claims, so messages in this group cannot be reliably attributed. The group \
                 should be treated as compromised and abandoned rather than repaired."
                    .to_string(),
            );
            if reported {
                error!(
                    group_id = %group_id,
                    unproven_members,
                    "SECURITY: local group state holds leaves that do not prove the identity \
                     they claim; they are kept out of the roster and cannot speak, but they \
                     have read everything sent to this group"
                );
            }
        }
        Ok(members)
    }

    /// Creates a new MLS group.
    ///
    /// The group is created locally via MLS. Members can be invited with
    /// `invite_to_group()`. Messages sent via `send_group_message()` are
    /// MLS-encrypted and route through whichever transport DORS selects.
    /// If Internet is available the group is also registered with the
    /// relay server for optimized fan-out.
    pub fn create_group(&mut self, group_name: &str) -> Result<offline_protocol_mls::GroupInfo> {
        let trimmed = group_name.trim();
        if trimmed.is_empty() {
            return Err(Error::InvalidArgument(
                "Group name cannot be empty".to_string(),
            ));
        }
        let mls_guard = self.read_mls_guard()?;
        let group_info = mls_guard.create_group(group_name)?;
        let group_id = group_info.group_id.as_str().to_string();
        let members = group_info.members.clone();
        drop(mls_guard);

        self.group_mesh
            .members
            .insert(group_id.clone(), members.clone());

        self.emit_event(Event::group_created(
            group_id.clone(),
            group_name.to_string(),
        ));

        // Best-effort relay registration
        let _ = self.try_relay_register_group(&group_id, Some(group_name), &members);

        Ok(group_info)
    }

    /// Invites a user to an MLS group.
    ///
    /// Requires the invitee's key package to be available in `pending_key_packages`.
    /// Sends a Welcome to the invitee and a Commit to all existing members.
    ///
    /// Admission is where recipient validation belongs. The removal and role
    /// paths deliberately do *not* validate: a roster entry admitted by an
    /// older build (before the id rules tightened) must stay removable, and a
    /// gate there would turn "a bad member exists" into "a bad member cannot be
    /// removed" — the wrong direction for a moderation control.
    pub fn invite_to_group(&mut self, group_id: &str, invitee_user_id: &str) -> Result<()> {
        Self::validate_outbound_recipient(invitee_user_id)?;

        // Admin check
        let self_id = self.local_id.clone();
        if !self.check_is_admin(group_id, &self_id)? {
            return Err(Error::PermissionDenied(
                "Only admins can invite members".to_string(),
            ));
        }

        // Check group member cap before adding
        let current_count = self
            .group_mesh
            .members
            .get(group_id)
            .map(|m| m.len())
            .or_else(|| {
                self.read_mls_guard().ok().and_then(|g| {
                    g.get_group_info(&offline_protocol_mls::GroupId::new(group_id).ok()?)
                        .ok()
                        .flatten()
                        .map(|info| info.members.len())
                })
            })
            .unwrap_or(0);
        let max_members = self.config.group.max_group_members;
        if current_count >= max_members {
            return Err(Error::InvalidState(format!(
                "Group has {} members, cannot exceed {} limit",
                current_count, max_members
            )));
        }

        // Try loading key package from storage (e.g. after restart or rapid
        // re-invite where a fresh package arrived between calls).
        self.try_load_key_package_from_storage_into_memory(invitee_user_id);

        // Get the invitee's key package and check expiry
        let now_ms = Utc::now().timestamp_millis() as u64;
        let received_pkg = self
            .pending_key_packages
            .get(invitee_user_id)
            .ok_or_else(|| Error::NoKeyPackage(invitee_user_id.to_string()))?;
        if now_ms >= received_pkg.local_expires_at_ms {
            self.pending_key_packages.remove(invitee_user_id);
            return Err(Error::InvalidState(format!(
                "Key package for {} has expired",
                invitee_user_id
            )));
        }
        let key_pkg = received_pkg.key_package_data.clone();

        // Add member via MLS — returns both Welcome (for invitee) and Commit (for existing members)
        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        let (welcome, commit) = mls_guard.add_group_member(&gid, invitee_user_id, &key_pkg)?;
        let group_name = welcome.group_name.clone();
        drop(mls_guard);

        // MLS key packages are single-use (RFC 9420). Now that add_group_member
        // consumed the package, remove it so subsequent group invites for the
        // same peer don't reuse a stale package.
        self.pending_key_packages.remove(invitee_user_id);
        self.delete_peer_key_package_from_storage(invitee_user_id);

        // Clear key-package-sent tracking so the invitee can reciprocate.
        // Without this, the invitee's handler sees us in `key_package_sent_to`
        // and skips reciprocation, leaving us without a key package for
        // future group invites.
        self.key_package_sent_to.remove(invitee_user_id);

        // Send our key package to the invitee. Their message dispatch handler
        // will reciprocate with a fresh key package, replenishing our supply
        // for future group invites or 1:1 session creation.
        if let Err(e) = self.send_key_package_to(invitee_user_id, false) {
            debug!(
                invitee = %invitee_user_id,
                error = %e,
                "Key package send to invitee deferred (will retry on next discovery)"
            );
        }

        // Refresh member list after add
        let members = self.refresh_group_members(group_id)?;

        // Store invitee as member role, then read back both role-overlay
        // fields the Welcome carries (roles and the creator of record) from a
        // single metadata load.
        let (member_roles, created_by) = {
            let mls_guard = self.read_mls_guard()?;
            let gid = offline_protocol_mls::GroupId::new(group_id)?;
            if let Err(e) = mls_guard.set_member_role(&gid, invitee_user_id, GroupRole::Member) {
                warn!(invitee = %invitee_user_id, error = %e, "Failed to store invitee role");
            }
            mls_guard
                .get_group_metadata(&gid)
                .ok()
                .flatten()
                .map(|m| (m.get_all_roles(), m.created_by.clone()))
                .unwrap_or_default()
        };

        // Attest rich-payload capability both directions of the knowledge
        // gap an add creates: existing members never exchange key packages
        // with the invitee (commit field below), and the invitee never
        // exchanges with anyone but us (welcome map here). Entries only
        // exist for members we know capable — directly or via an earlier
        // attestation, which is how knowledge chains across successive adds
        // — so absence means "no information", never a downgrade. Our own
        // entry self-advertises from config (belt to the key package sent
        // above, whose delivery is best-effort).
        let invitee_rich = self.attestable_rich_versions(invitee_user_id);
        let member_rich: HashMap<String, Vec<u8>> = members
            .iter()
            .filter(|m| m.as_str() != invitee_user_id)
            .filter_map(|m| {
                if *m == self_id {
                    self.config
                        .encryption
                        .rich_payload_enabled
                        .then(|| (m.clone(), vec![RICH_PAYLOAD_V1]))
                } else {
                    self.attestable_rich_versions(m).map(|v| (m.clone(), v))
                }
            })
            .collect();

        // Send Welcome to invitee
        let welcome_payload = GroupMlsWelcomePayload {
            group_id: group_id.to_string(),
            group_name,
            welcome_data: base64_encode(&welcome.welcome_data),
            member_list: members.clone(),
            member_roles,
            member_rich,
            // Carries our creator of record so the joiner's `check_is_admin`
            // has a fallback when the role snapshot above is incomplete.
            // Absent when we never learned it ourselves (joined via an older
            // SDK's Welcome) — absence is "no information", not a downgrade.
            created_by,
        };
        let welcome_content = format!(
            "{}{}",
            internal_prefixes::GROUP_MLS_WELCOME,
            serde_json::to_string(&welcome_payload)
                .map_err(|e| Error::Serialization(format!("Serialize welcome: {}", e)))?
        );
        self.send_internal_message(invitee_user_id, welcome_content, MessagePriority::High)?;

        // Send Commit to all existing members (excluding self and invitee)
        // so they can process it and advance their MLS epoch
        let commit_payload = GroupMlsCommitPayload {
            group_id: group_id.to_string(),
            commit_type: GroupCommitType::Add,
            ciphertext: base64_encode(&commit.ciphertext),
            epoch: commit.epoch,
            affected_member: Some(invitee_user_id.to_string()),
            role: Some(GroupRole::Member),
            affected_member_rich: invitee_rich,
        };
        let commit_content = format!(
            "{}{}",
            internal_prefixes::GROUP_MLS_COMMIT,
            serde_json::to_string(&commit_payload)
                .map_err(|e| Error::Serialization(format!("Serialize commit: {}", e)))?
        );
        let mut failed_commit_members: Vec<String> = Vec::new();
        for member in &members {
            if member == &self_id || member == invitee_user_id {
                continue;
            }
            if let Err(e) =
                self.send_internal_message(member, commit_content.clone(), MessagePriority::High)
            {
                warn!(
                    group_id = %group_id,
                    member = %member,
                    error = %e,
                    "Failed to send commit to group member during invite"
                );
                failed_commit_members.push(member.clone());
            }
        }
        // Single best-effort retry pass for transient failures
        for member in &failed_commit_members {
            let _ =
                self.send_internal_message(member, commit_content.clone(), MessagePriority::High);
        }

        self.emit_event(Event::group_member_added(
            group_id.to_string(),
            invitee_user_id.to_string(),
            self_id,
            None,
            // Our own invite, gated by the admin check at the top of this fn.
            Some(true),
        ));

        // Sync membership update to relay
        let _ = self.try_relay_register_group(group_id, None, &members);

        info!(group_id = %group_id, invitee = %invitee_user_id, "Invited member to group");
        Ok(())
    }

    /// Removes a member from an MLS group.
    ///
    /// Sends a Commit to all remaining members.
    pub fn remove_from_group(&mut self, group_id: &str, member_id: &str) -> Result<()> {
        // Deliberately unvalidated — see `invite_to_group`. Removal must work
        // on whatever is actually on the roster.
        let self_id = self.local_id.clone();

        // Admin check + last-admin guard (single metadata load)
        {
            let mls_guard = self.read_mls_guard()?;
            let gid = offline_protocol_mls::GroupId::new(group_id)?;
            let metadata = Self::group_metadata_or_not_found(&mls_guard, &gid, group_id)?;

            let is_admin = if let Some(ref meta) = metadata {
                if meta.has_any_admin() {
                    meta.get_role(&self_id) == GroupRole::Admin
                } else if let Some(ref creator) = meta.created_by {
                    creator == &self_id
                } else {
                    false
                }
            } else {
                false
            };
            if !is_admin {
                return Err(Error::PermissionDenied(
                    "Only admins can remove members".to_string(),
                ));
            }

            if let Some(ref meta) = metadata {
                if meta.get_role(member_id) == GroupRole::Admin {
                    let admin_count = meta
                        .get_all_roles()
                        .values()
                        .filter(|r| **r == GroupRole::Admin)
                        .count();
                    let member_count = self
                        .group_mesh
                        .members
                        .get(group_id)
                        .map(|m| m.len())
                        .unwrap_or(0);
                    // member_count > 2: the count is *before* removal, so > 2
                    // means at least 2 members will remain after the removal.
                    // When only 2 members exist (the admin being removed + one
                    // other), the remaining sole member gets auto-promoted, so
                    // we allow the removal.
                    if admin_count <= 1 && member_count > 2 {
                        return Err(Error::InvalidState(
                            "Cannot remove the last admin while other members remain. Promote another member to admin first.".to_string(),
                        ));
                    }
                }
            }
        }

        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        let commit_msg = mls_guard.remove_group_member(&gid, member_id)?;
        drop(mls_guard);

        // Refresh member list after removal
        let members = self.refresh_group_members(group_id)?;
        // Clean up removed member's role metadata
        if let Ok(mls_guard) = self.read_mls_guard() {
            if let Ok(gid) = offline_protocol_mls::GroupId::new(group_id) {
                if let Err(e) = mls_guard.remove_member_role(&gid, member_id) {
                    warn!(member = %member_id, error = %e, "Failed to clean up role metadata for removed member");
                }
            }
        }
        // Auto-promote if removal left zero admins
        self.auto_promote_if_no_admin(group_id, &members);

        let commit_payload = GroupMlsCommitPayload {
            group_id: group_id.to_string(),
            commit_type: GroupCommitType::Remove,
            ciphertext: base64_encode(&commit_msg.ciphertext),
            epoch: commit_msg.epoch,
            affected_member: Some(member_id.to_string()),
            role: None,
            affected_member_rich: None,
        };
        let commit_content = format!(
            "{}{}",
            internal_prefixes::GROUP_MLS_COMMIT,
            serde_json::to_string(&commit_payload)
                .map_err(|e| Error::Serialization(format!("Serialize commit: {}", e)))?
        );
        let mut failed_commit_members: Vec<String> = Vec::new();
        for member in &members {
            if member == &self_id {
                continue;
            }
            if let Err(e) =
                self.send_internal_message(member, commit_content.clone(), MessagePriority::High)
            {
                warn!(
                    group_id = %group_id,
                    member = %member,
                    error = %e,
                    "Failed to send commit to group member during remove"
                );
                failed_commit_members.push(member.clone());
            }
        }
        // Single best-effort retry pass for transient failures
        for member in &failed_commit_members {
            let _ =
                self.send_internal_message(member, commit_content.clone(), MessagePriority::High);
        }

        // Send a plaintext removal notification directly to the removed member.
        // The MLS commit alone is insufficient: the removed member cannot decrypt
        // it (they're no longer in the group), so they would never learn they were
        // removed. The plaintext notification uses the existing GROUP_MEMBER_REMOVED
        // prefix which the message dispatcher handles by emitting a
        // GroupMemberRemoved event and cleaning up local state.
        let removed_payload = GroupMemberRemovedPayload {
            group_id: group_id.to_string(),
            user_id: member_id.to_string(),
            removed_by: self_id.clone(),
        };
        if let Ok(json) = serde_json::to_string(&removed_payload) {
            let removed_content = format!("{}{}", internal_prefixes::GROUP_MEMBER_REMOVED, json);
            if let Err(e) =
                self.send_internal_message(member_id, removed_content, MessagePriority::High)
            {
                warn!(
                    group_id = %group_id,
                    member = %member_id,
                    error = %e,
                    "Failed to send removal notification to removed member"
                );
            }
        }

        self.emit_event(Event::group_member_removed(
            group_id.to_string(),
            member_id.to_string(),
            self_id,
            // Our own removal, gated by the admin check at the top of this fn.
            Some(true),
        ));

        // Sync membership update to relay
        let _ = self.try_relay_register_group(group_id, None, &members);

        info!(group_id = %group_id, member = %member_id, "Removed member from group");
        Ok(())
    }

    /// Leaves an MLS group.
    ///
    /// Notifies remaining members and then removes local group state.
    /// Note: The MLS layer does not support self-removal Commits, so remaining
    /// members receive a plaintext leave notification. The deterministic election
    /// in `handle_group_mls_leave` will select one member to issue the MLS
    /// remove-commit to properly advance the epoch.
    ///
    /// **Ordering note:** Leave notifications are sent *before* deleting local
    /// MLS state. If all notification sends fail, local state is preserved and
    /// the caller receives an error so the leave can be retried. This prevents
    /// orphaned membership where the leaver is gone locally but peers never
    /// learn about the departure.
    pub fn leave_group(&mut self, group_id: &str) -> Result<()> {
        // Get members before leaving
        let members = self
            .group_mesh
            .members
            .get(group_id)
            .cloned()
            .or_else(|| self.refresh_group_members(group_id).ok())
            .unwrap_or_default();

        let self_id = self.local_id.clone();

        // Block last admin from leaving if other members remain
        let other_members_exist = members.iter().any(|m| m != &self_id);
        if other_members_exist {
            let mls_guard = self.read_mls_guard()?;
            let gid = offline_protocol_mls::GroupId::new(group_id)?;
            if let Some(metadata) = mls_guard.get_group_metadata(&gid)? {
                let is_admin = metadata.get_role(&self_id) == GroupRole::Admin;
                if is_admin {
                    let admin_count = metadata
                        .get_all_roles()
                        .values()
                        .filter(|r| **r == GroupRole::Admin)
                        .count();
                    if admin_count <= 1 {
                        return Err(Error::InvalidState(
                            "Cannot leave group as the last admin while other members remain. Promote another member to admin first.".to_string(),
                        ));
                    }
                }
            }
            drop(mls_guard);
        }

        // Build leave notification payload before touching MLS state
        let leave_payload = GroupMlsLeavePayload {
            group_id: group_id.to_string(),
            leaving_member: self_id.clone(),
        };
        let leave_content = format!(
            "{}{}",
            internal_prefixes::GROUP_MLS_LEAVE,
            serde_json::to_string(&leave_payload)
                .map_err(|e| Error::Serialization(format!("Serialize leave: {}", e)))?
        );

        // Send notifications first — if all fail, keep local state intact for retry
        let mut any_sent = false;
        let mut had_recipients = false;
        for member in &members {
            if member == &self_id {
                continue;
            }
            had_recipients = true;
            match self.send_internal_message(member, leave_content.clone(), MessagePriority::Medium)
            {
                Ok(_) => {
                    any_sent = true;
                }
                Err(e) => {
                    warn!(
                        group_id = %group_id,
                        member = %member,
                        error = %e,
                        "Failed to send leave notification to group member"
                    );
                }
            }
        }

        // If there were other members but no notification succeeded, fail so the
        // caller can retry rather than silently orphaning the membership.
        if had_recipients && !any_sent {
            return Err(Error::Transport(
                offline_protocol_transport::Error::SendFailed(
                    "All leave notifications failed — local state preserved for retry".to_string(),
                ),
            ));
        }

        // Now safe to delete local MLS state — at least one peer was notified
        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        mls_guard.leave_group(&gid)?;
        drop(mls_guard);

        // Remove from caches. Buffered commits go too — they can never apply
        // after we leave, and a stale one retried after a rapid re-invite
        // would expire with retry_count > 0 and falsely flag an epoch fork.
        self.group_mesh.members.remove(group_id);
        let was_synced = self.group_mesh.relay_synced.remove(group_id);
        let was_pending = self
            .group_mesh
            .relay_register_pending
            .remove(group_id)
            .is_some();
        if was_synced || was_pending {
            self.emit_event(Event::group_relay_sync_changed(
                group_id.to_string(),
                false,
                "left",
            ));
        }
        self.group_mesh.pending_group_messages.remove(group_id);
        self.group_mesh.pending_commits.remove(group_id);

        info!(group_id = %group_id, "Left group");
        Ok(())
    }

    /// Sends a message to all members of an MLS group.
    ///
    /// If Internet transport is available and relay-enabled, sends a single
    /// relay broadcast (`__GRP_RELAY_BCAST__`). Otherwise falls back to
    /// per-member fan-out via `send_internal_message()` where each member's
    /// delivery goes through the full DORS/ACK/retry stack independently.
    pub fn send_group_message(
        &mut self,
        group_id: &str,
        content: &str,
        priority: Option<MessagePriority>,
        reply_to_msg: Option<&str>,
    ) -> Result<Vec<MessageId>> {
        // Reject reserved internal prefixes: receivers parse decrypted group
        // plaintext for the sealed `__RICH_V1__` body, so user content must
        // never be able to impersonate one (same rule as `send_message` and
        // the forward paths).
        if Self::is_internal_prefix(content) {
            return Err(Error::InvalidArgument(
                "Message content must not start with a reserved internal prefix".to_string(),
            ));
        }
        self.send_group_message_inner(
            group_id,
            content,
            priority.unwrap_or(MessagePriority::Medium),
            reply_to_msg,
            None,
            None,
            ContentType::Text,
        )
    }

    /// Like [`Self::send_group_message`], with rich media fields.
    ///
    /// The rich fields travel inside the MLS-sealed `__RICH_V1__` body of
    /// the group ciphertext, and only when every other member advertised
    /// `rich_versions` (see [`GroupSendOptions`]); otherwise they are
    /// silently dropped, never cleartext.
    pub fn send_group_message_with(
        &mut self,
        group_id: &str,
        content: &str,
        options: GroupSendOptions,
    ) -> Result<Vec<MessageId>> {
        // Same internal-prefix rejection as `send_group_message`.
        if Self::is_internal_prefix(content) {
            return Err(Error::InvalidArgument(
                "Message content must not start with a reserved internal prefix".to_string(),
            ));
        }
        // FileChunk is an internal transport content type — same boundary
        // rule as `send_message_with`.
        if options.content_type == Some(ContentType::FileChunk) {
            return Err(Error::InvalidArgument(
                "FileChunk is an internal content type and cannot be sent directly".to_string(),
            ));
        }
        Self::check_group_rich_extras_size(options.media_metadata.as_ref(), None)?;
        self.send_group_message_inner(
            group_id,
            content,
            options.priority.unwrap_or(MessagePriority::Medium),
            options.reply_to_msg.as_deref(),
            None,
            options.media_metadata,
            options.content_type.unwrap_or_default(),
        )
    }

    /// Forwards a message to all members of a group with forwarding attribution.
    ///
    /// Similar to `send_group_message` but attaches `ForwardInfo` to preserve
    /// the original sender and forward count. The message content is encrypted
    /// via MLS for the group and fan-out follows the same path as regular
    /// group messages (including relay broadcast when available).
    ///
    /// When every other group member advertised the sealed rich payload, the
    /// attribution and the original `media_metadata` — including cloud-media
    /// `encryption_key`/`iv` secrets, which only the sealed body may carry —
    /// travel inside the group MLS ciphertext, so forwarded cloud media stays
    /// openable. Otherwise the media metadata is dropped (never cleartext)
    /// and only the hop-visible payload attribution survives.
    pub fn forward_message_to_group(
        &mut self,
        original_message: &Message,
        group_id: &str,
        priority: Option<MessagePriority>,
    ) -> Result<Vec<MessageId>> {
        // Reject content that starts with an internal control prefix to prevent
        // injection of protocol-level messages through the forwarding API.
        if Self::is_internal_prefix(&original_message.content) {
            return Err(Error::InvalidArgument(
                "Cannot forward a message with reserved internal prefix content".to_string(),
            ));
        }

        // FileChunk is an internal transport content type — same boundary
        // rule as the DM forward path.
        if original_message.content_type == ContentType::FileChunk {
            return Err(Error::InvalidArgument(
                "FileChunk is an internal content type and cannot be forwarded".to_string(),
            ));
        }

        let forward_info = ForwardInfo::from_message(original_message);

        if forward_info.forward_count > crate::constants::MAX_FORWARD_COUNT {
            return Err(Error::InvalidArgument(format!(
                "Forward count {} exceeds maximum of {}",
                forward_info.forward_count,
                crate::constants::MAX_FORWARD_COUNT,
            )));
        }

        Self::check_group_rich_extras_size(
            original_message.media_metadata.as_ref(),
            Some(&forward_info),
        )?;

        self.send_group_message_inner(
            group_id,
            &original_message.content,
            priority.unwrap_or(MessagePriority::Medium),
            None,
            Some(forward_info),
            original_message.media_metadata.clone(),
            original_message.content_type,
        )
    }

    /// Boundary cap for group rich extras, mirroring `send_message_with`:
    /// bound the serialized extras here so the seal (or a relay-broadcast
    /// fallback re-send) can never fail on size later.
    fn check_group_rich_extras_size(
        media_metadata: Option<&MediaMetadata>,
        forward_info: Option<&ForwardInfo>,
    ) -> Result<()> {
        RichSendExtras {
            reply_context: None,
            media_metadata: media_metadata.cloned(),
            forward_info: forward_info.cloned(),
        }
        .check_size()
    }

    /// Whether a rich group send right now would seal its extras, and which
    /// members are in the way. See [`GroupRichReadiness`]. Read-only: uses
    /// the fan-out cache with an MLS fallback but never mutates state, and
    /// does not probe unknown members (the send path's drop branch does).
    pub fn group_rich_readiness(&self, group_id: &str) -> Result<GroupRichReadiness> {
        let members = match self.group_mesh.members.get(group_id) {
            Some(m) => m.clone(),
            None => {
                let mls_guard = self.read_mls_guard()?;
                let gid = offline_protocol_mls::GroupId::new(group_id)?;
                mls_guard
                    .get_group_info(&gid)?
                    .ok_or_else(|| Error::GroupNotFound(group_id.to_string()))?
                    .members
            }
        };
        let unknown_members = if self.config.encryption.rich_payload_enabled {
            self.group_rich_unknown_members(&members)
        } else {
            Vec::new()
        };
        Ok(GroupRichReadiness {
            ready: self.group_rich_seal_active(&members),
            unknown_members,
        })
    }

    /// The relay-side registration state of a group. See [`RelaySyncState`].
    ///
    /// `Synced` wins over an outstanding re-registration: once the relay has
    /// positively acknowledged the group on this connection, its registry
    /// entry survives regardless of any in-flight idempotent re-sync, so
    /// relay-dependent commands are already safe to issue.
    pub fn group_relay_sync_state(&self, group_id: &str) -> RelaySyncState {
        if self.group_mesh.relay_synced.contains(group_id) {
            RelaySyncState::Synced
        } else if self
            .group_mesh
            .relay_register_pending
            .contains_key(group_id)
        {
            RelaySyncState::Pending
        } else {
            RelaySyncState::Unsynced
        }
    }

    /// Registers (or re-registers) a group with the relay server on demand.
    ///
    /// The supported path for making a mesh-created group known to the
    /// relay before issuing relay-dependent server commands for it (invite
    /// links, server-side fan-out) — never raw-send `CreateGroup`. The
    /// outcome arrives asynchronously as `GroupRelaySyncChanged`:
    /// `synced: true, reason: "registered"` on the relay's ack, `false`
    /// with `"error"` / `"ack_timeout"` on denial or a relay that never
    /// answers. Idempotent: an already-`Synced` group returns `Ok(true)`
    /// without re-sending (the automatic re-sync on membership changes
    /// covers roster updates).
    ///
    /// Returns `Ok(true)` when the registration frame was queued (or the
    /// group is already synced), `Ok(false)` when relay grouping is
    /// disabled or the Internet transport is unavailable, `Err` when the
    /// group is unknown locally.
    pub fn request_group_relay_registration(&mut self, group_id: &str) -> Result<bool> {
        if self.group_mesh.relay_synced.contains(group_id) {
            return Ok(true);
        }
        // Fresh membership, like the retry processor: the MLS roster is
        // authoritative, the fan-out cache is the fallback.
        let members = self
            .refresh_group_members(group_id)
            .ok()
            .or_else(|| self.group_mesh.members.get(group_id).cloned())
            .ok_or_else(|| Error::GroupNotFound(group_id.to_string()))?;
        self.try_relay_register_group(group_id, None, &members)
    }

    /// Shared implementation for sending and forwarding group messages.
    ///
    /// Handles the sealed-rich decision, MLS encryption, member list
    /// caching, relay broadcast attempt, per-member fan-out, and event
    /// emission.
    #[allow(clippy::too_many_arguments)]
    fn send_group_message_inner(
        &mut self,
        group_id: &str,
        content: &str,
        priority: MessagePriority,
        reply_to_msg: Option<&str>,
        forward_info: Option<ForwardInfo>,
        media_metadata: Option<MediaMetadata>,
        content_type: ContentType,
    ) -> Result<Vec<MessageId>> {
        // Read member list from cache, falling back to MLS on cache miss.
        // Fetched before encryption because the sealed-rich decision below
        // needs the full membership: one ciphertext serves every member.
        let members = match self.group_mesh.members.get(group_id) {
            Some(m) => m.clone(),
            None => {
                let mls_guard = self.read_mls_guard()?;
                let gid = offline_protocol_mls::GroupId::new(group_id)?;
                let info = mls_guard
                    .get_group_info(&gid)?
                    .ok_or_else(|| Error::GroupNotFound(group_id.to_string()))?;
                info.members.clone()
            }
        };

        // Update cache if it was a miss
        if !self.group_mesh.members.contains_key(group_id) {
            self.group_mesh
                .members
                .insert(group_id.to_string(), members.clone());
        }

        // Rich extras travel only inside the sealed `__RICH_V1__` body of
        // the group ciphertext (media secrets must never leave the AEAD
        // boundary), and only when every other member advertised the
        // capability — a legacy member would render the sealed body as
        // literal JSON text. For unsealed sends the attribution rides the
        // hop-visible payload below as the fallback; media metadata has no
        // such fallback and simply drops (surfaced to the app via
        // `GroupRichExtrasDropped` — the send itself still succeeds). A
        // non-Text hint seals a hint-only body even without extras
        // (mirroring the DM path): the group payload has no outer
        // content_type carrier, so an unsealed hint would not merely go
        // unprotected — it would be lost.
        let extras = RichSendExtras {
            reply_context: None,
            media_metadata,
            forward_info: forward_info.clone(),
        };
        let wants_seal = extras.is_any() || content_type != ContentType::Text;
        let sealed = wants_seal && self.group_rich_seal_active(&members);
        let sealed_body;
        let plaintext: &str = if sealed {
            sealed_body = Self::seal_rich_payload(content, &extras, content_type)?;
            &sealed_body
        } else {
            // Members holding the gate closed (empty when the local kill
            // switch is the cause — with recording disabled, listing every
            // member would be noise, and probing them could not reopen the
            // gate anyway). Probing sends them our key package so their
            // auto-exchange reply teaches us their capability: unknown
            // members are typically ones somebody else added, healed here
            // for groups predating attestation or behind an old-SDK inviter.
            // Only sends that wanted to seal consume the set (backfill here,
            // blame on the drop event below) — plain text sends skip the
            // membership scan entirely.
            let unknown = if wants_seal && self.config.encryption.rich_payload_enabled {
                self.group_rich_unknown_members(&members)
            } else {
                Vec::new()
            };
            if !unknown.is_empty() {
                self.backfill_group_rich_capabilities(&unknown);
            }
            if extras.media_metadata.is_some() {
                warn!(
                    group_id = %group_id,
                    "Group not fully rich-capable, dropping rich media metadata (members \
                     will receive the text without the media attachment)"
                );
                self.emit_event(Event::group_rich_extras_dropped(
                    group_id.to_string(),
                    unknown,
                ));
            }
            content
        };

        // When the body sealed, every member reads the sealed attribution
        // and the receiver ignores the payload copy wholesale — omit it
        // rather than expose original-sender metadata to relays and mesh
        // hops for nobody's benefit. (A stale-cache just-added non-capable
        // member loses degraded-display attribution in that window;
        // accepted, consistent with them rendering the sealed body as
        // literal JSON anyway.)
        let payload_forward_info = if sealed { None } else { forward_info };

        // Encrypt via MLS — release the guard immediately after encryption
        // to minimize lock contention during the fan-out phase.
        let encrypted = {
            let mls_guard = self.read_mls_guard()?;
            let gid = offline_protocol_mls::GroupId::new(group_id)?;
            mls_guard.encrypt_for_group(&gid, plaintext.as_bytes())?
        };

        let ciphertext_b64 = base64_encode(&encrypted.ciphertext);
        let epoch = encrypted.epoch;

        let self_id = self.local_id.clone();

        // --- Attempt relay broadcast first ---
        // If the group is registered, the app opted in, and the relay
        // advertised the v3 group-delivery contract, a single relay
        // broadcast is O(1) instead of O(N) individual sends.
        //
        // The capability gate is what makes the broadcast safe to take by
        // default: a `group_delivery_v3` relay answers every broadcast with
        // a settled per-recipient delivery report, which the sender consumes
        // (`handle_relay_group_delivery_report`) to re-send per-member
        // copies to anyone the relay did not reach — so the broadcast keeps
        // a delivery contract instead of being fire-and-forget — and names
        // members in the same address space this SDK registered, so that
        // report is comparable against the MLS roster at all (see
        // [`RELAY_CAP_GROUP_DELIVERY_V3`] for why a v2 relay must fail this
        // gate). Against an older relay the gate simply fails and sends take
        // the always-correct per-member fan-out.
        //
        // `is_internet_available()` is re-checked here and not inferred from
        // `relay_synced`: sync state is cleared by the `process()` tick, so
        // between Internet dropping and the next tick a stale `relay_synced`
        // would otherwise route the broadcast into the mesh.
        if self.config.group.relay_broadcast_enabled
            && self.group_mesh.relay_synced.contains(group_id)
            && self
                .group_mesh
                .relay_capabilities
                .contains(RELAY_CAP_GROUP_DELIVERY_V3)
            && self.is_internet_available()
        {
            if let Ok(mid) = self.try_relay_broadcast(
                group_id,
                &ciphertext_b64,
                epoch,
                reply_to_msg,
                payload_forward_info.clone(),
                priority,
            ) {
                let member_count = members.iter().filter(|m| m.as_str() != self_id).count() as u32;
                self.emit_event(Event::group_message_sent(
                    group_id.to_string(),
                    vec![mid.as_str().to_string()],
                    member_count,
                ));
                return Ok(vec![mid]);
            }
            // Relay broadcast failed — fall through to per-member fan-out
        }

        // Per-member fan-out (mesh or DORS-selected transport)
        let (message_ids, succeeded_members, failed_members) = self
            .fanout_group_frames_per_member(
                group_id,
                &members,
                None,
                &ciphertext_b64,
                epoch,
                reply_to_msg,
                payload_forward_info,
                priority,
            )?;

        let member_count = succeeded_members.len() as u32;

        // Check for total delivery failure: there were members to send to but
        // every send failed. Return an error so callers don't confuse this with
        // a solo-group scenario (which legitimately returns Ok(vec![])).
        let had_recipients = members.iter().any(|m| m != &self_id);
        if had_recipients && message_ids.is_empty() {
            self.emit_event(Event::group_message_partial_failure(
                group_id.to_string(),
                failed_members,
                succeeded_members,
            ));
            return Err(Error::Transport(
                offline_protocol_transport::Error::SendFailed(
                    "All group message sends failed".to_string(),
                ),
            ));
        }

        // Emit appropriate event
        if failed_members.is_empty() {
            self.emit_event(Event::group_message_sent(
                group_id.to_string(),
                message_ids.iter().map(|m| m.as_str().to_string()).collect(),
                member_count,
            ));
        } else {
            self.emit_event(Event::group_message_partial_failure(
                group_id.to_string(),
                failed_members,
                succeeded_members,
            ));
        }

        Ok(message_ids)
    }

    /// Lists all MLS groups (excluding 1:1 sessions).
    pub fn list_groups(&self) -> Result<Vec<String>> {
        let mls_guard = self.read_mls_guard()?;
        let groups = mls_guard.list_groups()?;
        Ok(groups.into_iter().map(|g| g.as_str().to_string()).collect())
    }

    /// Gets information about an MLS group.
    pub fn get_group_info(
        &self,
        group_id: &str,
    ) -> Result<Option<offline_protocol_mls::GroupInfo>> {
        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        Ok(mls_guard.get_group_info(&gid)?)
    }

    // ========================================================================
    // GROUP ROLES
    // ========================================================================

    /// Deterministically promotes the lexicographically-first remaining member
    /// to admin if no admin role remains. All nodes use the same sort order,
    /// so the promotion converges to the same candidate network-wide.
    fn auto_promote_if_no_admin(&self, group_id: &str, members: &[String]) {
        if members.is_empty() {
            return;
        }
        if let Ok(mls_guard) = self.read_mls_guard() {
            let Ok(gid) = offline_protocol_mls::GroupId::new(group_id) else {
                return;
            };
            if let Some(metadata) = mls_guard.get_group_metadata(&gid).ok().flatten() {
                if metadata.has_any_admin() {
                    return;
                }
                let mut sorted = members.to_vec();
                sorted.sort();
                let promote_id = &sorted[0];
                if let Err(e) = mls_guard.set_member_role(&gid, promote_id, GroupRole::Admin) {
                    warn!(user_id = %promote_id, error = %e, "Failed to auto-promote member to admin");
                } else {
                    info!(user_id = %promote_id, group_id = %group_id, "Auto-promoted member to admin after last admin was removed");
                }
            }
        }
    }

    /// Loads a group's role metadata, failing with [`Error::GroupNotFound`]
    /// when the group has neither metadata nor MLS state. Admin-gated
    /// operations use this so a missing group is not misreported as a
    /// permissions failure.
    fn group_metadata_or_not_found(
        mls_guard: &offline_protocol_mls::MlsManager,
        gid: &offline_protocol_mls::GroupId,
        group_id: &str,
    ) -> Result<Option<offline_protocol_mls::GroupMetadata>> {
        let metadata = mls_guard.get_group_metadata(gid)?;
        if metadata.is_none() && mls_guard.get_group_info(gid)?.is_none() {
            return Err(Error::GroupNotFound(group_id.to_string()));
        }
        Ok(metadata)
    }

    /// Checks if a user is an admin of the given group.
    ///
    /// Falls back to `created_by` when no admin role has been stored yet
    /// (handles groups created before role tracking was introduced).
    ///
    /// Returns `GroupNotFound` when no MLS group exists locally, so
    /// admin-gated operations don't misreport a missing group as a
    /// permissions failure. Inbound handlers that verify senders treat
    /// this error the same as a deny.
    pub(crate) fn check_is_admin(&self, group_id: &str, user_id: &str) -> Result<bool> {
        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        let metadata = Self::group_metadata_or_not_found(&mls_guard, &gid, group_id)?;
        drop(mls_guard);

        if let Some(meta) = &metadata {
            if meta.has_any_admin() {
                return Ok(meta.get_role(user_id) == GroupRole::Admin);
            }
            // No admin role stored — fall back to created_by if available
            if let Some(creator) = &meta.created_by {
                return Ok(creator == user_id);
            }
        }

        // Group exists but has no role metadata — deny by default
        Ok(false)
    }

    /// Changes a member's role in a group (admin only).
    /// Broadcasts the change to all group members.
    pub fn set_member_role(
        &mut self,
        group_id: &str,
        target_user_id: &str,
        role: GroupRole,
    ) -> Result<()> {
        // Deliberately unvalidated — see `invite_to_group`. Demoting a member
        // admitted under older id rules must stay possible.
        let self_id = self.local_id.clone();
        if !self.check_is_admin(group_id, &self_id)? {
            return Err(Error::PermissionDenied(
                "Only admins can change roles".to_string(),
            ));
        }

        // Verify target is a member (before acquiring guard for role operations)
        let members = self
            .group_mesh
            .members
            .get(group_id)
            .cloned()
            .or_else(|| self.refresh_group_members(group_id).ok())
            .unwrap_or_default();
        if !members.iter().any(|m| m == target_user_id) {
            return Err(Error::InvalidState(format!(
                "User {} is not a member of group {}",
                target_user_id, group_id
            )));
        }

        // Single guard acquisition for both last-admin validation and role write
        {
            let mls_guard = self.read_mls_guard()?;
            let gid = offline_protocol_mls::GroupId::new(group_id)?;

            // Prevent demoting the last admin (whether self or another admin)
            if role == GroupRole::Member {
                if let Some(metadata) = mls_guard.get_group_metadata(&gid).ok().flatten() {
                    if metadata.get_role(target_user_id) == GroupRole::Admin {
                        let admin_count = metadata
                            .get_all_roles()
                            .values()
                            .filter(|r| **r == GroupRole::Admin)
                            .count();
                        if admin_count <= 1 {
                            return Err(Error::InvalidState(
                                "Cannot demote the last admin".to_string(),
                            ));
                        }
                    }
                }
            }

            // Store locally
            mls_guard.set_member_role(&gid, target_user_id, role)?;
        }

        // Broadcast to all members
        let payload = GroupRoleChangePayload {
            group_id: group_id.to_string(),
            target_user_id: target_user_id.to_string(),
            new_role: role,
            changed_by: self_id.clone(),
        };
        let content = format!(
            "{}{}",
            internal_prefixes::GROUP_ROLE_CHANGE,
            serde_json::to_string(&payload)
                .map_err(|e| Error::Serialization(format!("Serialize role change: {}", e)))?
        );
        for member in &members {
            if member == &self_id {
                continue;
            }
            if let Err(e) =
                self.send_internal_message(member, content.clone(), MessagePriority::High)
            {
                warn!(member = %member, group_id = %group_id, error = %e, "Failed to send role change broadcast");
            }
        }

        self.emit_event(Event::group_role_changed(
            group_id.to_string(),
            target_user_id.to_string(),
            role.to_string(),
            self_id,
        ));

        info!(group_id = %group_id, target = %target_user_id, role = %role, "Changed member role");
        Ok(())
    }

    /// Gets a member's role in a group.
    ///
    /// A group that exists but has no role metadata (created before role
    /// tracking) reports the same default an unrecorded user gets: `Member`.
    pub fn get_member_role(&self, group_id: &str, user_id: &str) -> Result<GroupRole> {
        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        let metadata = Self::group_metadata_or_not_found(&mls_guard, &gid, group_id)?;
        Ok(metadata.map(|m| m.get_role(user_id)).unwrap_or_default())
    }

    /// Gets all member roles in a group.
    ///
    /// A group that exists but has no role metadata (created before role
    /// tracking) reports no explicit roles.
    pub fn get_group_roles(&self, group_id: &str) -> Result<HashMap<String, GroupRole>> {
        let mls_guard = self.read_mls_guard()?;
        let gid = offline_protocol_mls::GroupId::new(group_id)?;
        let metadata = Self::group_metadata_or_not_found(&mls_guard, &gid, group_id)?;
        Ok(metadata.map(|m| m.get_all_roles()).unwrap_or_default())
    }

    /// Handles an incoming group role change notification.
    pub(crate) fn handle_group_role_change(&mut self, message_id: &str, sender: &str, data: &str) {
        let payload = match serde_json::from_str::<GroupRoleChangePayload>(data) {
            Ok(p) => p,
            Err(_) => {
                warn!(sender = %sender, "Failed to parse GroupRoleChange payload");
                return;
            }
        };

        // Dedup
        let dedup_key = message_id.to_string();
        if self.group_mesh.message_dedup.contains_key(&dedup_key) {
            return;
        }
        self.group_mesh
            .message_dedup
            .insert(dedup_key, Instant::now());

        // Verify sender is admin (use transport-authenticated sender, not payload.changed_by)
        match self.check_is_admin(&payload.group_id, sender) {
            Ok(true) => {}
            Ok(false) => {
                error!(
                    sender = %sender,
                    group_id = %payload.group_id,
                    "SECURITY: Role change from non-admin, ignoring"
                );
                return;
            }
            Err(e) => {
                warn!(
                    sender = %sender,
                    group_id = %payload.group_id,
                    error = %e,
                    "Failed to verify admin status for role change"
                );
                return;
            }
        }

        // Store role locally
        let Ok(gid) = offline_protocol_mls::GroupId::new(&payload.group_id) else {
            warn!(group_id = %payload.group_id, "Dropping role change with invalid group id");
            return;
        };
        if let Ok(mls_guard) = self.read_mls_guard() {
            if let Err(e) =
                mls_guard.set_member_role(&gid, &payload.target_user_id, payload.new_role)
            {
                warn!(
                    target = %payload.target_user_id,
                    error = %e,
                    "Failed to store role from incoming role change"
                );
            }
        }

        // Use transport-authenticated sender as changed_by, not the untrusted payload field
        self.emit_event(Event::group_role_changed(
            payload.group_id,
            payload.target_user_id,
            payload.new_role.to_string(),
            sender.to_string(),
        ));
    }

    // ========================================================================
    // GROUP RENAME
    // ========================================================================

    /// Renames a group (admin only).
    /// Updates the local group name and broadcasts the change to all members.
    pub fn rename_group(&mut self, group_id: &str, new_name: &str) -> Result<()> {
        let trimmed = new_name.trim();
        if trimmed.is_empty() {
            return Err(Error::InvalidArgument(
                "Group name cannot be empty".to_string(),
            ));
        }
        let self_id = self.local_id.clone();
        if !self.check_is_admin(group_id, &self_id)? {
            return Err(Error::PermissionDenied(
                "Only admins can rename groups".to_string(),
            ));
        }

        // Load old name before updating
        let old_name = {
            let mls_guard = self.read_mls_guard()?;
            let gid = offline_protocol_mls::GroupId::new(group_id)?;
            mls_guard
                .get_group_metadata(&gid)?
                .and_then(|m| m.name.clone())
        };

        // Update locally
        {
            let mls_guard = self.read_mls_guard()?;
            let gid = offline_protocol_mls::GroupId::new(group_id)?;
            mls_guard.set_group_name(&gid, new_name)?;
        }

        // Broadcast to all members
        let members = self
            .group_mesh
            .members
            .get(group_id)
            .cloned()
            .or_else(|| self.refresh_group_members(group_id).ok())
            .unwrap_or_default();

        let payload = GroupRenamePayload {
            group_id: group_id.to_string(),
            new_name: new_name.to_string(),
            renamed_by: self_id.clone(),
        };
        let content = format!(
            "{}{}",
            internal_prefixes::GROUP_RENAME,
            serde_json::to_string(&payload)
                .map_err(|e| Error::Serialization(format!("Serialize group rename: {}", e)))?
        );
        for member in &members {
            if member == &self_id {
                continue;
            }
            if let Err(e) =
                self.send_internal_message(member, content.clone(), MessagePriority::High)
            {
                warn!(member = %member, group_id = %group_id, error = %e, "Failed to send group rename broadcast");
            }
        }

        self.emit_event(Event::group_renamed(
            group_id.to_string(),
            new_name.to_string(),
            old_name,
            self_id,
        ));

        // Update relay registration with new name
        let _ = self.try_relay_register_group(group_id, Some(new_name), &members);

        info!(group_id = %group_id, new_name = %new_name, "Renamed group");
        Ok(())
    }

    /// Handles an incoming group rename notification.
    pub(crate) fn handle_group_rename(&mut self, message_id: &str, sender: &str, data: &str) {
        let payload = match serde_json::from_str::<GroupRenamePayload>(data) {
            Ok(p) => p,
            Err(_) => {
                warn!(sender = %sender, "Failed to parse GroupRename payload");
                return;
            }
        };

        // Dedup
        let dedup_key = message_id.to_string();
        if self.group_mesh.message_dedup.contains_key(&dedup_key) {
            return;
        }
        self.group_mesh
            .message_dedup
            .insert(dedup_key, Instant::now());

        // Verify sender is admin (use transport-authenticated sender)
        match self.check_is_admin(&payload.group_id, sender) {
            Ok(true) => {}
            Ok(false) => {
                error!(
                    sender = %sender,
                    group_id = %payload.group_id,
                    "SECURITY: Group rename from non-admin, ignoring"
                );
                return;
            }
            Err(e) => {
                warn!(
                    sender = %sender,
                    group_id = %payload.group_id,
                    error = %e,
                    "Failed to verify admin status for group rename"
                );
                return;
            }
        }

        let Ok(gid) = offline_protocol_mls::GroupId::new(&payload.group_id) else {
            warn!(group_id = %payload.group_id, "Dropping group rename with invalid group id");
            return;
        };

        // Load old name before updating
        let old_name = if let Ok(mls_guard) = self.read_mls_guard() {
            mls_guard
                .get_group_metadata(&gid)
                .ok()
                .flatten()
                .and_then(|m| m.name.clone())
        } else {
            None
        };

        // Store new name locally
        if let Ok(mls_guard) = self.read_mls_guard() {
            if let Err(e) = mls_guard.set_group_name(&gid, &payload.new_name) {
                warn!(
                    group_id = %payload.group_id,
                    error = %e,
                    "Failed to store new group name from incoming rename"
                );
            }
        }

        // Use transport-authenticated sender as renamed_by
        self.emit_event(Event::group_renamed(
            payload.group_id,
            payload.new_name,
            old_name,
            sender.to_string(),
        ));
    }

    /// Cleans up expired group message dedup entries and enforces size cap.
    pub(crate) fn cleanup_group_message_dedup(&mut self) {
        // Ages are compared with `saturating_duration_since` rather than a
        // precomputed `now - TTL` cutoff: on platforms where the monotonic
        // clock starts at boot, that subtraction underflows (and panics)
        // when the process is younger than the TTL.
        let now = Instant::now();
        let dedup_ttl = StdDuration::from_secs(GROUP_MESSAGE_DEDUP_TTL_SECS);
        self.group_mesh
            .message_dedup
            .retain(|_, seen_at| now.saturating_duration_since(*seen_at) < dedup_ttl);
        // If still over cap after TTL cleanup, drop oldest entries using O(N) selection
        let len = self.group_mesh.message_dedup.len();
        if len > MAX_GROUP_MESSAGE_DEDUP_ENTRIES {
            let mut entries: Vec<_> = self.group_mesh.message_dedup.drain().collect();
            // Partition so the newest MAX entries are in [..MAX]
            entries.select_nth_unstable_by_key(MAX_GROUP_MESSAGE_DEDUP_ENTRIES, |(_, ts)| {
                std::cmp::Reverse(*ts)
            });
            entries.truncate(MAX_GROUP_MESSAGE_DEDUP_ENTRIES);
            self.group_mesh.message_dedup = entries.into_iter().collect();
        }

        // Expire stale pending commits, tracking groups where retried commits
        // expired — these are strong epoch fork signals (same as drain_pending_commits).
        // Expired IDs are collected for replay-protection release below: the
        // group-level dedup entry is at least as old as the buffered copy and
        // was already dropped by the retain above (same `now`, same TTL), but
        // the transport-level deduplicator has a longer retention window and
        // must be released explicitly or a redelivery is swallowed at the
        // receive loop.
        let commit_ttl = StdDuration::from_secs(PENDING_COMMIT_TTL_SECS);
        let mut fork_candidates: Vec<String> = Vec::new();
        let mut expired_ids: Vec<String> = Vec::new();
        self.group_mesh.pending_commits.retain(|group_id, commits| {
            let mut retried_expired = false;
            commits.retain(|c| {
                let alive = now.saturating_duration_since(c.buffered_at) < commit_ttl;
                if !alive {
                    if c.retry_count > 0 {
                        retried_expired = true;
                    }
                    expired_ids.push(c.message_id.clone());
                }
                alive
            });
            if retried_expired {
                fork_candidates.push(group_id.clone());
            }
            !commits.is_empty()
        });
        // Flag forks for groups where retried commits expired during periodic
        // cleanup — this covers the case where drain_pending_commits is never
        // called because no new commits succeed for the group.
        for group_id in fork_candidates {
            if !self.group_mesh.epoch_forks.contains_key(&group_id) {
                self.flag_potential_epoch_fork(&group_id);
            }
        }

        // Expire stale pending group messages — covers groups where no
        // Welcome or commit ever arrives to trigger a drain.
        let msg_ttl = StdDuration::from_secs(PENDING_GROUP_MESSAGE_TTL_SECS);
        self.group_mesh.pending_group_messages.retain(|_, msgs| {
            msgs.retain(|m| {
                let alive = now.saturating_duration_since(m.buffered_at) < msg_ttl;
                if !alive {
                    expired_ids.push(m.message_id.clone());
                }
                alive
            });
            !msgs.is_empty()
        });

        // Entries that expired here were never processed/delivered — release
        // their replay protection so a redelivery is accepted fresh.
        for message_id in expired_ids {
            self.release_replay_protection(&message_id);
        }
    }

    // ========================================================================
    // RELAY OPTIMIZATION
    // ========================================================================

    /// Best-effort admin hint for relay group registration: `Some` only when
    /// role metadata (or the creator fallback) makes the answer definite,
    /// `None` when it cannot be determined. Unlike [`Self::check_is_admin`],
    /// this must not deny by default — a wrong `false` would make the bridge
    /// silently skip member deltas the relay would have accepted, and the
    /// relay registry would never learn the membership.
    fn relay_registration_admin_hint(&self, group_id: &str) -> Option<bool> {
        let mls_guard = self.read_mls_guard().ok()?;
        let gid = offline_protocol_mls::GroupId::new(group_id).ok()?;
        let metadata = Self::group_metadata_or_not_found(&mls_guard, &gid, group_id).ok()??;
        if metadata.has_any_admin() {
            return Some(metadata.get_role(&self.local_id) == GroupRole::Admin);
        }
        metadata
            .created_by
            .as_ref()
            .map(|creator| creator == &self.local_id)
    }

    /// Attempts to register (or update) a group with the relay server.
    ///
    /// Sends a `__GRP_RELAY_REG__` message to the user's own ID via Internet
    /// transport, for a relay (or platform bridge acting as relay adapter)
    /// that translates the prefix into a server-side group registration.
    ///
    /// Enqueueing this frame proves nothing about relay support: a relay
    /// without prefix interception simply echoes a self-addressed message
    /// back to the sender. `relay_synced` must therefore only be set by a
    /// positive acknowledgment from the relay (an inbound `__GROUP_CREATED__`
    /// for the group), never here — otherwise `send_group_message` takes the
    /// O(1) broadcast path and the messages vanish into the echo.
    ///
    /// Fire-and-forget: returns `Ok(true)` if sent, `Ok(false)` if Internet
    /// is unavailable, `Err` on serialization failure.
    fn try_relay_register_group(
        &mut self,
        group_id: &str,
        group_name: Option<&str>,
        members: &[String],
    ) -> Result<bool> {
        if !self.config.group.relay_enabled || !self.is_internet_available() {
            return Ok(false);
        }

        let payload = RelayGroupRegistrationPayload {
            group_id: group_id.to_string(),
            group_name: group_name.map(|s| s.to_string()),
            members: members.to_vec(),
            is_admin: self.relay_registration_admin_hint(group_id),
        };
        let content = format!(
            "{}{}",
            internal_prefixes::GROUP_RELAY_REGISTER,
            serde_json::to_string(&payload).map_err(|e| Error::Serialization(format!(
                "Serialize relay registration: {}",
                e
            )))?
        );

        // Send to self — a prefix-aware relay (or bridge adapter) translates it.
        // Deliberately does NOT set `relay_synced`: Ok here only means the frame
        // was queued locally, and a prefix-unaware relay echoes it back instead
        // of registering anything. Sync is confirmed only by the relay's
        // `__GROUP_CREATED__` acknowledgment.
        //
        // Un-ACKed and Internet-pinned (see `send_relay_hint_message`): the
        // retry policy for registration is the `relay_register_pending`
        // tracker armed just below, not the message ACK ladder — which could
        // never settle this frame and would re-send it ~10 times.
        match self.send_relay_hint_message(content, MessagePriority::Medium) {
            Ok(_) => {
                // Arm the ack correlation: only a `__GROUP_CREATED__` that
                // answers an outstanding registration may set `relay_synced`.
                // Attempts accumulate across re-sends on this connection so
                // the expiry processor can give up on a relay that never
                // answers; the counter resets whenever the entry is removed
                // (ack, error, leave, internet drop).
                let entry = self
                    .group_mesh
                    .relay_register_pending
                    .entry(group_id.to_string())
                    .or_insert(RelayRegisterPending {
                        armed_at: Utc::now(),
                        attempts: 0,
                    });
                entry.armed_at = Utc::now();
                entry.attempts = entry.attempts.saturating_add(1);
                debug!(group_id = %group_id, attempts = entry.attempts, "Sent group registration to relay server");
                Ok(true)
            }
            Err(e) => {
                debug!(group_id = %group_id, error = %e, "Failed to register group with relay");
                Ok(false)
            }
        }
    }

    /// Applies the sealed `__RICH_V1__` restore to a decrypted group
    /// message plaintext, returning the event-ready fields: content, media
    /// metadata, content-type hint, and forward attribution.
    ///
    /// Parsing is never capability-gated (whatever a peer chose to seal, we
    /// try to read). When the body parses, the sealed attribution is
    /// authoritative wholesale — absence included: a sealing sender always
    /// seals its `forward_info` when one exists, so the hop-visible payload
    /// copy is consulted only for unsealed messages. Falling back to it on
    /// a sealed body would let a relay attach fabricated attribution to a
    /// rich message that carried none (mirrors the DM restore, which
    /// overwrites the outer fields wholesale). A body that fails to parse
    /// surfaces as raw text with nothing restored: never drop an
    /// authenticated message.
    fn restore_group_rich(
        text: String,
        payload_forward_info: Option<ForwardInfo>,
        sender: &str,
    ) -> (
        String,
        Option<MediaMetadata>,
        Option<String>,
        Option<crate::events::ForwardInfoEvent>,
    ) {
        if let Some(rich) = RichPayloadV1::parse_sealed(&text, sender) {
            return (
                rich.text,
                rich.media_metadata,
                rich.content_type.map(|ct| ct.to_string()),
                rich.forward_info
                    .as_ref()
                    .map(crate::events::ForwardInfoEvent::from),
            );
        }
        (
            text,
            None,
            None,
            payload_forward_info
                .as_ref()
                .map(crate::events::ForwardInfoEvent::from),
        )
    }

    /// Attempts to send a group message via relay broadcast.
    ///
    /// Sends a single `__GRP_RELAY_BCAST__` message to the user's own ID.
    /// The bridge translator (not the relay — see
    /// [`RelayGroupBroadcastPayload`]) turns it into a relay-native
    /// `SendGroupMessage`; the relay fans out to registered members, whose
    /// bridges inject the delivery as `__GROUP_MSG__` frames.
    ///
    /// Callers must only take this path when all four of
    /// `GroupConfig::relay_broadcast_enabled`, `relay_synced` (the relay
    /// acknowledged the group; otherwise a prefix-unaware relay swallows the
    /// frame), the relay's [`RELAY_CAP_GROUP_DELIVERY_V3`] capability, and
    /// `is_internet_available()` hold.
    ///
    /// Mints the logical message id the whole group will know this message
    /// by, carries it in the payload (the bridge stamps it onto the relay
    /// frame), and arms a [`RelayBroadcastPending`] entry keyed by it: the
    /// relay's settled `GroupMessageSent` report settles the entry and
    /// re-sends per-member copies to members the relay did not reach; a
    /// lost report re-sends the broadcast (bounded) and finally downgrades
    /// to full per-member fan-out. Returns that logical id on success — it
    /// is what `group_message_sent` reports to the app.
    ///
    /// On error (relay unreachable) the caller falls back to per-member
    /// fan-out. The frame goes out via [`Self::send_relay_hint_message`], so
    /// it is a pinned, un-ACKed one-shot: a failure surfaces here
    /// immediately instead of being deferred into a retry ladder that could
    /// never settle — the *report* tracker above is the bounded retry.
    fn try_relay_broadcast(
        &mut self,
        group_id: &str,
        ciphertext_b64: &str,
        epoch: u64,
        reply_to: Option<&str>,
        forward_info: Option<ForwardInfo>,
        priority: MessagePriority,
    ) -> Result<MessageId> {
        let logical_id = MessageId::new();
        let payload = RelayGroupBroadcastPayload {
            group_id: group_id.to_string(),
            ciphertext: ciphertext_b64.to_string(),
            epoch,
            reply_to: reply_to.map(|s| s.to_string()),
            forward_info: forward_info.clone(),
            message_id: logical_id.as_str(),
        };
        self.send_relay_broadcast_frame(&payload)?;
        // Keep the tracker bounded (see `MAX_RELAY_BROADCAST_PENDING`).
        // Terminates: every iteration removes exactly one entry.
        while self.group_mesh.relay_broadcast_pending.len() >= MAX_RELAY_BROADCAST_PENDING {
            let Some(oldest) = self
                .group_mesh
                .relay_broadcast_pending
                .iter()
                .min_by_key(|(_, pending)| pending.armed_at)
                .map(|(id, _)| id.clone())
            else {
                break;
            };
            let Some(stale) = self.group_mesh.relay_broadcast_pending.remove(&oldest) else {
                break;
            };
            warn!(
                msg_id = %oldest,
                "Relay broadcast tracker full, downgrading oldest to per-member fan-out"
            );
            self.downgrade_broadcast_to_per_member(&oldest, stale);
        }
        self.group_mesh.relay_broadcast_pending.insert(
            logical_id.as_str(),
            RelayBroadcastPending {
                group_id: group_id.to_string(),
                ciphertext_b64: ciphertext_b64.to_string(),
                epoch,
                reply_to: reply_to.map(|s| s.to_string()),
                forward_info,
                priority,
                armed_at: Utc::now(),
                attempts: 1,
            },
        );
        debug!(
            group_id = %group_id,
            msg_id = %logical_id,
            "Sent group message via relay broadcast, awaiting delivery report"
        );
        Ok(logical_id)
    }

    /// Serializes and sends one `__GRP_RELAY_BCAST__` hint frame. Shared by
    /// the initial broadcast and the lost-report re-send, which must reuse
    /// the same payload (same logical `message_id`) so the relay's push
    /// dedup and every receiver's dedup hold across attempts.
    fn send_relay_broadcast_frame(&mut self, payload: &RelayGroupBroadcastPayload) -> Result<()> {
        let content = format!(
            "{}{}",
            internal_prefixes::GROUP_RELAY_BROADCAST,
            serde_json::to_string(payload)
                .map_err(|e| Error::Serialization(format!("Serialize relay broadcast: {}", e)))?
        );
        self.send_relay_hint_message(content, MessagePriority::Medium)?;
        Ok(())
    }

    /// Fans a group message's MLS ciphertext out as one `__GRP_MLS_MSG__`
    /// frame per member (skipping self), each through
    /// `send_internal_message` and therefore the whole per-member delivery
    /// ladder. `logical_id` is `Some` when the copies re-issue a relay
    /// broadcast — receivers then dedup/emit under that id (see
    /// [`GroupMlsMessagePayload::message_id`]).
    ///
    /// Returns `(frame ids, succeeded members, failed members)`; errors only
    /// on payload serialization.
    #[allow(clippy::too_many_arguments)]
    fn fanout_group_frames_per_member(
        &mut self,
        group_id: &str,
        members: &[String],
        logical_id: Option<&str>,
        ciphertext_b64: &str,
        epoch: u64,
        reply_to: Option<&str>,
        forward_info: Option<ForwardInfo>,
        priority: MessagePriority,
    ) -> Result<(Vec<MessageId>, Vec<String>, Vec<String>)> {
        let msg_payload = GroupMlsMessagePayload {
            group_id: group_id.to_string(),
            ciphertext: ciphertext_b64.to_string(),
            epoch,
            reply_to: reply_to.map(|s| s.to_string()),
            forward_info,
            message_id: logical_id.map(|s| s.to_string()),
        };
        let base_content = format!(
            "{}{}",
            internal_prefixes::GROUP_MLS_MSG,
            serde_json::to_string(&msg_payload)
                .map_err(|e| Error::Serialization(format!("Serialize group message: {}", e)))?
        );

        let self_id = self.local_id.clone();
        let mut message_ids = Vec::new();
        let mut succeeded_members = Vec::new();
        let mut failed_members = Vec::new();
        for member in members {
            if member == &self_id {
                continue;
            }
            match self.send_internal_message(member, base_content.clone(), priority) {
                Ok(mid) => {
                    message_ids.push(mid);
                    succeeded_members.push(member.clone());
                }
                Err(e) => {
                    warn!(
                        group_id = %group_id,
                        member = %member,
                        error = %e,
                        "Failed to send group message to member"
                    );
                    failed_members.push(member.clone());
                }
            }
        }
        Ok((message_ids, succeeded_members, failed_members))
    }

    /// Replaces the set of capability tokens advertised by the connected
    /// relay.
    ///
    /// Called by the platform internet bridge with the `capabilities` list
    /// from the relay's `Authenticated` answer, **before** it reports the
    /// transport up via `internet_status_changed(true)` — the false→true
    /// flush must already see the capabilities, or the first sends after a
    /// reconnect would take the capability-less path. Wholesale replace:
    /// each authentication describes the relay actually connected now.
    /// Relays that predate the advertisement yield an empty list, which
    /// reads as "no v2 contract" and keeps group sends on per-member
    /// fan-out.
    ///
    /// The list is wire-supplied: it is bounded to
    /// `MAX_RELAY_CAPABILITIES` tokens of at most
    /// `MAX_RELAY_CAPABILITY_TOKEN_BYTES` bytes each; excess entries and
    /// oversized tokens are dropped.
    pub fn set_relay_capabilities(&mut self, capabilities: Vec<String>) {
        let caps: HashSet<String> = capabilities
            .into_iter()
            .filter(|c| !c.is_empty() && c.len() <= MAX_RELAY_CAPABILITY_TOKEN_BYTES)
            .take(MAX_RELAY_CAPABILITIES)
            .collect();
        debug!(count = caps.len(), "Relay capabilities updated");
        self.group_mesh.relay_capabilities = caps;
    }

    /// Consumes a relay `GroupMessageSent` settled delivery report
    /// (forwarded verbatim by the platform bridge) for a broadcast this
    /// sender has in flight.
    ///
    /// Settles the `RelayBroadcastPending` entry correlated by
    /// `message_id`, then re-sends a per-member `__GRP_MLS_MSG__` copy —
    /// through the ordinary outbox/ACK/park ladder — to every MLS roster
    /// member the relay did not reach over a socket or a push: the members
    /// it names in `missed`, plus every roster member it does not name at
    /// all (the relay's registered roster can be a strict subset of the MLS
    /// roster, so "not mentioned" must read as "not reached", never as
    /// "covered"). Duplicates are safe: the copies carry the logical id, so
    /// a member that did receive the relay's copy absorbs them by dedup.
    ///
    /// Reports that correlate with nothing (already settled by a previous
    /// attempt's report, or downgraded meanwhile) are ignored. A report
    /// whose `group_id` does not match the armed entry is ignored too — the
    /// entry stays armed and the timeout path recovers.
    ///
    /// Emits [`Event::group_message_delivery_report`] with the relay's
    /// `delivered`/`pushed` lists and the members re-issued per-member.
    pub fn handle_relay_group_delivery_report(&mut self, report_json: &str) -> Result<()> {
        let report: RelayGroupDeliveryReport = serde_json::from_str(report_json)
            .map_err(|e| Error::Serialization(format!("Parse group delivery report: {}", e)))?;

        let Some(entry) = self
            .group_mesh
            .relay_broadcast_pending
            .get(&report.message_id)
        else {
            debug!(
                group_id = %report.group_id,
                msg_id = %report.message_id,
                "Group delivery report correlates with no in-flight broadcast, ignoring"
            );
            return Ok(());
        };
        if entry.group_id != report.group_id {
            warn!(
                report_group = %report.group_id,
                armed_group = %entry.group_id,
                msg_id = %report.message_id,
                "Group delivery report names a different group than the armed broadcast, ignoring"
            );
            return Ok(());
        }
        let entry = self
            .group_mesh
            .relay_broadcast_pending
            .remove(&report.message_id)
            .expect("checked above");

        for miss in &report.missed {
            debug!(
                group_id = %report.group_id,
                member = %miss.username,
                reason = %miss.reason,
                "Relay reports group member missed"
            );
        }

        // Authoritative roster from MLS, cache as fallback (idiom shared
        // with the relay registration paths).
        let members = self
            .refresh_group_members(&entry.group_id)
            .ok()
            .or_else(|| self.group_mesh.members.get(&entry.group_id).cloned())
            .unwrap_or_default();
        let reached: HashSet<&str> = report
            .delivered
            .iter()
            .chain(report.pushed.iter())
            .map(String::as_str)
            .collect();
        let self_id = self.local_id.clone();
        let unreached: Vec<String> = members
            .iter()
            .filter(|m| m.as_str() != self_id && !reached.contains(m.as_str()))
            .cloned()
            .collect();

        let mut reissued = Vec::new();
        if !unreached.is_empty() {
            info!(
                group_id = %entry.group_id,
                msg_id = %report.message_id,
                count = unreached.len(),
                "Re-sending group message per-member to members the relay did not reach"
            );
            // Never `?` here: the tracker entry is already removed, so
            // propagating would strand the whole contract — no re-issue, no
            // event, and no timeout left to recover it. Report what happened
            // instead and let the app see an empty `missed_reissued`.
            match self.fanout_group_frames_per_member(
                &entry.group_id,
                &unreached,
                Some(&report.message_id),
                &entry.ciphertext_b64,
                entry.epoch,
                entry.reply_to.as_deref(),
                entry.forward_info.clone(),
                entry.priority,
            ) {
                Ok((_ids, succeeded, _failed)) => reissued = succeeded,
                Err(e) => {
                    error!(
                        group_id = %entry.group_id,
                        msg_id = %report.message_id,
                        error = %e,
                        "Failed to re-issue per-member copies for unreached members"
                    );
                }
            }
        }

        self.emit_event(Event::group_message_delivery_report(
            entry.group_id,
            report.message_id,
            report.delivered,
            report.pushed,
            reissued,
        ));
        Ok(())
    }

    /// Returns `true` if the Internet transport is currently available.
    pub(crate) fn is_internet_available(&self) -> bool {
        self.transport_manager
            .get_available_transports()
            .contains_key(&TransportType::Internet)
    }

    /// Reads the current MLS epoch for a group, if available.
    fn read_current_epoch(&self, group_id: &str) -> Option<u64> {
        let guard = self.read_mls_guard().ok()?;
        let gid = offline_protocol_mls::GroupId::new(group_id).ok()?;
        let info = guard.get_group_info(&gid).ok()??;
        Some(info.epoch)
    }

    // ========================================================================
    // EPOCH FORK RESOLUTION
    // ========================================================================

    /// Checks for pending epoch forks and attempts resolution.
    ///
    /// Called from the `process()` tick. After the resolution delay, the
    /// deterministic leader (lex-first member) issues an `update_keys` commit
    /// to re-establish a canonical epoch. Members on the same branch will
    /// process the commit normally. Members on a different branch will fail
    /// to process it, at which point they need a re-invite (the leader
    /// emits `GroupEpochForkResolved` and the application layer can trigger
    /// re-invites for unreachable members).
    ///
    /// ## Stuck fork recovery
    ///
    /// If `update_keys` fails (e.g., the leader's MLS state is corrupted),
    /// `resolution_attempted` is set to `true` and no further automatic
    /// resolution is tried. The fork entry remains until the 5-minute stale
    /// cleanup removes it, at which point the fork may be re-detected if
    /// the underlying issue persists (creating a detect → fail → stale-cleanup
    /// → re-detect cycle). This is intentional: a persistent `update_keys`
    /// failure indicates the group likely needs manual intervention (e.g.,
    /// re-creating the group or re-inviting all members). The application
    /// layer should monitor `GroupEpochForkDetected` events and escalate if
    /// the same group is repeatedly detected.
    pub(crate) fn check_epoch_forks(&mut self) {
        let delay = StdDuration::from_secs(EPOCH_FORK_RESOLUTION_DELAY_SECS);
        let self_id = self.local_id.clone();

        // Collect forks ready for resolution
        let ready: Vec<EpochForkState> = self
            .group_mesh
            .epoch_forks
            .values()
            .filter(|f| !f.resolution_attempted && f.detected_at.elapsed() > delay)
            .cloned()
            .collect();

        for fork in ready {
            // Re-check: if the epoch has advanced since detection, the fork
            // was a delayed commit, not a real fork — cancel it.
            if let Some(detected_epoch) = fork.local_epoch {
                let current_epoch = self.read_current_epoch(&fork.group_id);
                if let Some(current) = current_epoch {
                    if current > detected_epoch {
                        debug!(
                            group_id = %fork.group_id,
                            detected_epoch,
                            current_epoch = current,
                            "Epoch fork auto-cancelled: epoch advanced since detection"
                        );
                        self.group_mesh.epoch_forks.remove(&fork.group_id);
                        continue;
                    }
                }
            }

            // Check if we're the leader for this group
            let members = self
                .refresh_group_members(&fork.group_id)
                .ok()
                .or_else(|| self.group_mesh.members.get(&fork.group_id).cloned())
                .unwrap_or_default();

            let mut sorted = members.clone();
            sorted.sort();
            let am_leader = sorted.first().map(|f| f == &self_id).unwrap_or(false);

            // Mark as attempted regardless — only the leader acts, but all
            // members should stop re-checking.
            if let Some(state) = self.group_mesh.epoch_forks.get_mut(&fork.group_id) {
                state.resolution_attempted = true;
            }

            if !am_leader {
                continue;
            }

            info!(
                group_id = %fork.group_id,
                local_epoch = ?fork.local_epoch,
                "Attempting epoch fork resolution as elected leader"
            );

            // Issue a key update commit to establish a canonical next epoch.
            // Members on our branch will process this normally and advance.
            // Members on a forked branch will fail — the app layer should
            // handle re-inviting them.
            //
            // NOTE: We use `read_mls_guard` (RwLock read lock) even though
            // `update_keys` mutates MLS state. This is correct because
            // `MlsManager` uses interior mutability (internal Mutex on the
            // group store), so a read guard is sufficient for all operations.
            //
            // Acquire MLS lock, perform key update, and fully release the
            // guard before touching any other &mut self state.
            let update_result = {
                if let Ok(guard) = self.read_mls_guard() {
                    let r = offline_protocol_mls::GroupId::new(&fork.group_id)
                        .and_then(|gid| guard.update_keys(&gid));
                    drop(guard);
                    Some(r)
                } else {
                    None
                }
            };
            // Guard is fully dropped here — safe to use &mut self.
            let update_result = match update_result {
                Some(r) => r,
                None => {
                    warn!(group_id = %fork.group_id, "MLS unavailable during epoch fork resolution");
                    if let Some(state) = self.group_mesh.epoch_forks.get_mut(&fork.group_id) {
                        state.resolution_attempted = false;
                    }
                    continue;
                }
            };

            match update_result {
                Ok(commit_msg) => {
                    // Distribute the key-update commit to all members
                    let commit_payload = GroupMlsCommitPayload {
                        group_id: fork.group_id.clone(),
                        commit_type: GroupCommitType::KeyUpdate,
                        ciphertext: base64_encode(&commit_msg.ciphertext),
                        epoch: commit_msg.epoch,
                        affected_member: None,
                        role: None,
                        affected_member_rich: None,
                    };
                    let commit_content = match serde_json::to_string(&commit_payload) {
                        Ok(json) => format!("{}{}", internal_prefixes::GROUP_MLS_COMMIT, json),
                        Err(e) => {
                            warn!(
                                group_id = %fork.group_id,
                                error = %e,
                                "Failed to serialize fork resolution commit"
                            );
                            continue;
                        }
                    };
                    let mut failed_members = Vec::new();
                    for member in &members {
                        if member == &self_id {
                            continue;
                        }
                        if let Err(e) = self.send_internal_message(
                            member,
                            commit_content.clone(),
                            MessagePriority::High,
                        ) {
                            warn!(
                                group_id = %fork.group_id,
                                member = %member,
                                error = %e,
                                "Failed to send fork resolution commit to member"
                            );
                            failed_members.push(member.clone());
                        }
                    }

                    info!(
                        group_id = %fork.group_id,
                        new_epoch = commit_msg.epoch,
                        failed_count = failed_members.len(),
                        "Epoch fork resolution commit distributed"
                    );

                    self.emit_event(Event::group_epoch_fork_resolved(
                        fork.group_id.clone(),
                        commit_msg.epoch,
                        failed_members,
                    ));

                    // Clean up the fork state
                    self.group_mesh.epoch_forks.remove(&fork.group_id);
                }
                Err(e) => {
                    warn!(
                        group_id = %fork.group_id,
                        error = %e,
                        "Failed to issue key update for epoch fork resolution"
                    );
                    // Leave resolution_attempted = true — a persistent failure
                    // means the group may need manual intervention.
                }
            }
        }

        // Clean up stale fork entries (older than 5 minutes)
        let stale_threshold = StdDuration::from_secs(300);
        self.group_mesh
            .epoch_forks
            .retain(|_, f| f.detected_at.elapsed() < stale_threshold);
    }

    // ========================================================================
    // LEAVE ELECTION FALLBACK
    // ========================================================================

    /// Checks for timed-out leave elections and re-elects the next eligible
    /// member to issue the MLS remove-commit.
    ///
    /// Called from the `process()` tick. If the originally elected remover
    /// hasn't issued a commit within `LEAVE_ELECTION_TIMEOUT_SECS`, we check
    /// whether the leaving member is still in the group (via MLS state). If
    /// so, the next eligible member in the sorted remaining list takes over.
    pub(crate) fn check_leave_election_timeouts(&mut self) {
        let timeout = StdDuration::from_secs(LEAVE_ELECTION_TIMEOUT_SECS);
        let max_lifetime = StdDuration::from_secs(LEAVE_ELECTION_MAX_LIFETIME_SECS);
        let attempt_cooldown = StdDuration::from_secs(LEAVE_ELECTION_ATTEMPT_COOLDOWN_SECS);
        let self_id = self.local_id.clone();

        // Collect timed-out elections (keys + values) for processing.
        let timed_out: Vec<((String, String), PendingLeaveElection)> = self
            .group_mesh
            .pending_leave_elections
            .iter()
            .filter(|(_, e)| e.received_at.elapsed() > timeout)
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect();

        for (election_key, election) in timed_out {
            // Circuit breaker: abandon the election after max lifetime to
            // prevent infinite per-tick retry loops when all candidates fail.
            if election.received_at.elapsed() > max_lifetime {
                warn!(
                    group_id = %election.group_id,
                    leaving_member = %election.leaving_member,
                    "Leave election exceeded max lifetime, abandoning — member may need manual removal"
                );
                self.group_mesh
                    .pending_leave_elections
                    .remove(&election_key);
                continue;
            }

            // Refresh membership from MLS (authoritative) to avoid using
            // stale election-time lists where members may have since left.
            let current_members = self
                .refresh_group_members(&election.group_id)
                .ok()
                .or_else(|| self.group_mesh.members.get(&election.group_id).cloned())
                .unwrap_or_default();

            let still_member = current_members
                .iter()
                .any(|id| id == &election.leaving_member);

            if !still_member {
                // Already removed — clean up
                self.group_mesh
                    .pending_leave_elections
                    .remove(&election_key);
                continue;
            }

            // Use current membership for candidate selection, not the stale
            // election-time list — members may have left since the election.
            let mut remaining: Vec<String> = current_members
                .iter()
                .filter(|m| m.as_str() != election.leaving_member)
                .cloned()
                .collect();
            remaining.sort();

            // Re-elect: walk the sorted remaining members. For each timeout
            // interval that has passed, advance one position in the list.
            // This staggers re-election so members don't all fire at once.
            // Interval 1 = first fallback (idx 0), interval 2 = second (idx 1), etc.
            // The original elected member (lex-first) already had their shot
            // during handle_group_mls_leave; this path only fires after timeout.
            let elapsed_intervals =
                (election.received_at.elapsed().as_secs() / LEAVE_ELECTION_TIMEOUT_SECS) as usize;
            let candidate_idx = elapsed_intervals.min(remaining.len().saturating_sub(1));

            if remaining
                .get(candidate_idx)
                .map(|c| c == &self_id)
                .unwrap_or(false)
            {
                // Rate-limit: skip if we already attempted within the cooldown window.
                if let Some(last) = election.last_attempt_at {
                    if last.elapsed() < attempt_cooldown {
                        continue;
                    }
                }

                info!(
                    group_id = %election.group_id,
                    leaving_member = %election.leaving_member,
                    attempt = candidate_idx + 1,
                    "Re-elected to issue MLS remove-commit (prior elected member timed out)"
                );

                // Record the attempt timestamp before trying, so the cooldown
                // applies even on failure.
                if let Some(state) = self
                    .group_mesh
                    .pending_leave_elections
                    .get_mut(&election_key)
                {
                    state.last_attempt_at = Some(Instant::now());
                }

                if let Err(e) = self.remove_from_group(&election.group_id, &election.leaving_member)
                {
                    warn!(
                        group_id = %election.group_id,
                        leaving_member = %election.leaving_member,
                        error = %e,
                        "Failed to issue MLS remove-commit during re-election"
                    );
                    // Don't remove from pending — cooldown will prevent spam,
                    // next interval will advance to the next candidate.
                } else {
                    self.group_mesh
                        .pending_leave_elections
                        .remove(&election_key);
                }
            }
            // If we're not the candidate at this interval, leave the election
            // in place — either the current candidate will handle it, or the
            // next interval will advance to us.
        }
    }

    // ========================================================================
    // TRANSPORT-RESILIENT SYNC
    // ========================================================================

    /// Checks for Internet availability transitions and syncs group state.
    ///
    /// Called from the `process()` tick. On a 0→1 transition (Internet just
    /// became available), all unsynced groups are registered with the relay.
    /// On a 1→0 transition (Internet lost), relay sync flags are cleared so
    /// groups are re-registered when connectivity returns.
    pub(crate) fn check_relay_group_sync(&mut self) {
        if !self.config.group.relay_enabled {
            return;
        }
        let internet_available = self.is_internet_available();
        let was_available = self.group_mesh.internet_was_available;
        self.group_mesh.internet_was_available = internet_available;

        if internet_available && !was_available {
            // Internet just became available — sync all groups
            self.sync_groups_to_relay();
        } else if !internet_available && was_available {
            // Internet just went down — clear sync state. In-flight
            // registration acks can never arrive on this connection, so the
            // pending set goes too (re-armed by the 0→1 re-sync). Each
            // affected group gets a sync-changed event: apps gating
            // relay-dependent commands (invite links) must re-wait for the
            // reconnect's re-registration ack.
            let mut affected: Vec<String> = self.group_mesh.relay_synced.drain().collect();
            for group_id in self.group_mesh.relay_register_pending.drain() {
                if !affected.contains(&group_id.0) {
                    affected.push(group_id.0);
                }
            }
            for group_id in affected {
                self.emit_event(Event::group_relay_sync_changed(
                    group_id,
                    false,
                    "internet_dropped",
                ));
            }
            // Capabilities described the relay on the dead connection; a
            // reconnect re-injects them (possibly from a different relay)
            // before the transport is reported up again.
            self.group_mesh.relay_capabilities.clear();
            // In-flight broadcast delivery reports can never arrive on this
            // connection either. Downgrade each to per-member fan-out now
            // rather than after the report timeout: the copies enter the
            // ordinary outbox/park machinery, which flushes on whatever
            // transport (mesh now, Internet on reconnect) becomes usable —
            // and members the relay did reach absorb them via the logical
            // id.
            let stranded: Vec<(String, RelayBroadcastPending)> =
                self.group_mesh.relay_broadcast_pending.drain().collect();
            for (logical_id, entry) in stranded {
                self.downgrade_broadcast_to_per_member(&logical_id, entry);
            }
        }
    }

    /// Expires outstanding relay registrations the relay never answered.
    ///
    /// Called from the `process()` tick. An entry older than
    /// [`RELAY_REGISTER_ACK_TIMEOUT_SECS`] either gets its registration
    /// re-sent (the frame may have been lost) or, past
    /// [`RELAY_REGISTER_MAX_ATTEMPTS`], is dropped so the ack-acceptance
    /// window closes: against a relay that never answers (prefix-unaware
    /// echo relay, legacy server, or a `__GROUP_ERROR__` that arrived
    /// without a `group_id` and so could not consume the correlation) an
    /// armed entry would otherwise sit indefinitely for a forged
    /// `__GROUP_CREATED__` to claim. Giving up is safe — the group stays
    /// unsynced and sends take the always-correct per-member fan-out path.
    pub(crate) fn process_relay_register_retries(&mut self) {
        if !self.config.group.relay_enabled
            || self.group_mesh.relay_register_pending.is_empty()
            || !self.is_internet_available()
        {
            return;
        }
        let cutoff = Utc::now() - chrono::Duration::seconds(RELAY_REGISTER_ACK_TIMEOUT_SECS);
        let expired: Vec<(String, u32)> = self
            .group_mesh
            .relay_register_pending
            .iter()
            .filter(|(_, pending)| pending.armed_at <= cutoff)
            .map(|(group_id, pending)| (group_id.clone(), pending.attempts))
            .collect();
        for (group_id, attempts) in expired {
            if attempts >= RELAY_REGISTER_MAX_ATTEMPTS
                || !self.group_mesh.members.contains_key(&group_id)
                || self.group_mesh.relay_synced.contains(&group_id)
            {
                self.group_mesh.relay_register_pending.remove(&group_id);
                debug!(
                    group_id = %group_id,
                    attempts,
                    "Expired unanswered relay group registration"
                );
                // Giving up on a still-tracked, unsynced group is an
                // app-visible outcome: without this event a caller awaiting
                // the registration ack (`ensure_group_registered`) only
                // learns via its own timeout. The other two removal causes
                // stay silent — a vanished group already surfaced its
                // teardown, and an already-synced group's stale entry is
                // pure bookkeeping.
                if attempts >= RELAY_REGISTER_MAX_ATTEMPTS
                    && self.group_mesh.members.contains_key(&group_id)
                    && !self.group_mesh.relay_synced.contains(&group_id)
                {
                    self.emit_event(Event::group_relay_sync_changed(
                        group_id.clone(),
                        false,
                        "ack_timeout",
                    ));
                }
                continue;
            }
            // Re-send with membership refreshed from MLS, like the 0→1
            // re-sync; try_relay_register_group re-arms the entry in place
            // with the attempt count carried forward.
            let members = self
                .refresh_group_members(&group_id)
                .ok()
                .or_else(|| self.group_mesh.members.get(&group_id).cloned());
            if let Some(members) = members {
                let _ = self.try_relay_register_group(&group_id, None, &members);
            } else {
                self.group_mesh.relay_register_pending.remove(&group_id);
            }
        }
    }

    /// Expires in-flight relay broadcasts whose settled delivery report
    /// never arrived.
    ///
    /// Called from the `process()` tick. An entry older than
    /// [`RELAY_BROADCAST_REPORT_TIMEOUT_SECS`] gets its broadcast re-sent
    /// under the same logical id (safe: the relay echoes the id, so
    /// receiver and push dedup absorb the duplicate fan-out) while the
    /// attempt budget and the broadcast gate still hold; past
    /// [`RELAY_BROADCAST_MAX_ATTEMPTS`] — or as soon as the gate fails —
    /// the message is downgraded to full per-member fan-out, which needs no
    /// report to be correct.
    pub(crate) fn process_relay_broadcast_report_timeouts(&mut self) {
        if self.group_mesh.relay_broadcast_pending.is_empty() {
            return;
        }
        let cutoff = Utc::now() - chrono::Duration::seconds(RELAY_BROADCAST_REPORT_TIMEOUT_SECS);
        let expired: Vec<String> = self
            .group_mesh
            .relay_broadcast_pending
            .iter()
            .filter(|(_, pending)| pending.armed_at <= cutoff)
            .map(|(logical_id, _)| logical_id.clone())
            .collect();
        for logical_id in expired {
            let Some(mut entry) = self.group_mesh.relay_broadcast_pending.remove(&logical_id)
            else {
                continue;
            };
            let gate_holds = self.config.group.relay_broadcast_enabled
                && self.group_mesh.relay_synced.contains(&entry.group_id)
                && self
                    .group_mesh
                    .relay_capabilities
                    .contains(RELAY_CAP_GROUP_DELIVERY_V3)
                && self.is_internet_available();
            if entry.attempts < RELAY_BROADCAST_MAX_ATTEMPTS && gate_holds {
                let payload = RelayGroupBroadcastPayload {
                    group_id: entry.group_id.clone(),
                    ciphertext: entry.ciphertext_b64.clone(),
                    epoch: entry.epoch,
                    reply_to: entry.reply_to.clone(),
                    forward_info: entry.forward_info.clone(),
                    message_id: logical_id.clone(),
                };
                if self.send_relay_broadcast_frame(&payload).is_ok() {
                    warn!(
                        group_id = %entry.group_id,
                        msg_id = %logical_id,
                        attempts = entry.attempts + 1,
                        "Group broadcast delivery report lost, re-sent broadcast"
                    );
                    entry.attempts += 1;
                    entry.armed_at = Utc::now();
                    self.group_mesh
                        .relay_broadcast_pending
                        .insert(logical_id, entry);
                    continue;
                }
                // Re-send failed — fall through to per-member downgrade.
            }
            self.downgrade_broadcast_to_per_member(&logical_id, entry);
        }
    }

    /// Downgrades one in-flight broadcast to full per-member fan-out (every
    /// roster member; receivers that did get the relay's copy absorb the
    /// duplicate via the logical id). Terminal for the broadcast attempt:
    /// the per-member copies own delivery from here through the ordinary
    /// outbox/ACK/park ladder.
    fn downgrade_broadcast_to_per_member(
        &mut self,
        logical_id: &str,
        entry: RelayBroadcastPending,
    ) {
        let members = self
            .refresh_group_members(&entry.group_id)
            .ok()
            .or_else(|| self.group_mesh.members.get(&entry.group_id).cloned())
            .unwrap_or_default();
        info!(
            group_id = %entry.group_id,
            msg_id = %logical_id,
            members = members.len(),
            "Downgrading relay group broadcast to per-member fan-out"
        );
        if let Err(e) = self.fanout_group_frames_per_member(
            &entry.group_id,
            &members,
            Some(logical_id),
            &entry.ciphertext_b64,
            entry.epoch,
            entry.reply_to.as_deref(),
            entry.forward_info.clone(),
            entry.priority,
        ) {
            error!(
                group_id = %entry.group_id,
                msg_id = %logical_id,
                error = %e,
                "Failed to downgrade group broadcast to per-member fan-out"
            );
        }
    }

    /// Re-registers all unsynced groups with the relay server.
    ///
    /// Refreshes each group's member list from MLS state before syncing so
    /// that the relay receives authoritative membership, not a stale cache.
    fn sync_groups_to_relay(&mut self) {
        let group_ids: Vec<String> = self.group_mesh.members.keys().cloned().collect();
        for group_id in group_ids {
            if self.group_mesh.relay_synced.contains(&group_id) {
                continue;
            }
            // Refresh from MLS to avoid syncing stale membership to relay
            let members = self
                .refresh_group_members(&group_id)
                .ok()
                .or_else(|| self.group_mesh.members.get(&group_id).cloned());
            if let Some(members) = members {
                let _ = self.try_relay_register_group(&group_id, None, &members);
            }
        }
    }

    // ========================================================================
    // RELAY INBOUND — MLS-AWARE ROUTING
    // ========================================================================

    /// Returns `true` if we hold local MLS state for `group_id`.
    ///
    /// The raw-emit fallbacks in [`Self::handle_relay_group_message_with_mls`]
    /// attribute unauthenticated plaintext to a caller-supplied `sender`. That
    /// is only ever acceptable for a genuine legacy relay-only (unencrypted)
    /// group, which has no MLS state. If we secure this group with MLS, a real
    /// member always sends MLS ciphertext, so plaintext naming the group is a
    /// spoof — this test lets the caller drop it rather than surface a message
    /// forged in a trusted member's name.
    ///
    /// Fail-closed: when MLS is initialized but the lookup cannot complete
    /// (lock poisoned, invalid id), assume state may exist and return `true`
    /// so a transient fault can never be leveraged to force a plaintext spoof
    /// through. When MLS is not initialized at all, there is no group to
    /// secure, so return `false` (genuine legacy).
    fn has_mls_group_state(&self, group_id: &str) -> bool {
        if !self.is_mls_initialized() {
            return false;
        }
        let Ok(gid) = offline_protocol_mls::GroupId::new(group_id) else {
            // An id we cannot even construct names no real MLS group.
            return false;
        };
        match self.read_mls_guard() {
            Ok(guard) => guard.has_group(&gid).unwrap_or(true),
            Err(_) => true,
        }
    }

    /// Handles an inbound relay group message by routing through MLS
    /// decryption.
    ///
    /// Called from `process_internal_message` for every relay `__GROUP_MSG__`
    /// when MLS is initialized (or when the group already has local MLS
    /// state) — including groups we have not joined yet, because a relay
    /// group message can outrun its Welcome exactly like a mesh one; such
    /// messages are buffered for deferred retry. Content that is not MLS
    /// ciphertext (base64-undecodable, or base64 that is not MLS wire
    /// framing for a group without local state) is a legacy relay-only
    /// group message and is emitted raw — but only for a group we do *not*
    /// secure with MLS. Plaintext naming a group we hold MLS state for is a
    /// sender-spoofing attempt (a real member sends ciphertext) and is
    /// dropped, since the raw emit would attribute attacker content to a
    /// trusted member with no authentication.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn handle_relay_group_message_with_mls(
        &mut self,
        group_id: &str,
        sender: &str,
        content: &str,
        timestamp: &str,
        message_id: &str,
        reply_to_msg: Option<String>,
        forward_info: Option<offline_protocol_core::ForwardInfo>,
    ) {
        // Dedup check — same pattern as handle_group_mls_msg, with one
        // deliberate difference. The relay-supplied id IS the logical id on
        // this path, and it is marked here, pre-decrypt, as the replay-
        // amplification defense (one MLS crypto op per id). But the mesh
        // handler's marking discipline exists for a reason this path is not
        // exempt from: a marked id suppresses every later copy of the same
        // logical message, including the per-member re-issue that is this
        // message's own delivery safety net. So every arm below that ends
        // with the frame neither delivered, nor buffered, nor consumed by
        // MLS must unmark before returning — otherwise a copy that was
        // *rejected* (e.g. mis-attributed by the relay) reads as *delivered*
        // to the duplicate check, and the genuine copy that follows is
        // absorbed and re-ACKed without ever being surfaced: silent loss.
        let dedup_key = message_id.to_string();
        if self.group_mesh.message_dedup.contains_key(&dedup_key) {
            debug!(group_id = %group_id, msg_id = %dedup_key, "Duplicate relay group message, skipping");
            return;
        }
        self.group_mesh
            .message_dedup
            .insert(dedup_key.clone(), Instant::now());
        if self.group_mesh.message_dedup.len() > MAX_GROUP_MESSAGE_DEDUP_ENTRIES {
            self.cleanup_group_message_dedup();
        }

        let forward_info_event = forward_info
            .as_ref()
            .map(crate::events::ForwardInfoEvent::from);

        // Attempt base64 decode — if it fails, the content is plaintext (legacy)
        let ciphertext_bytes = match base64_decode(content) {
            Ok(bytes) => bytes,
            Err(_) => {
                // Plaintext content naming a group we secure with MLS cannot be
                // legitimate: a real member always sends MLS ciphertext (which
                // is base64 and decodes here). Emitting it raw would attribute
                // attacker-chosen content to the unauthenticated inner `sender`
                // — a message forged in a trusted member's name. Drop it. Only
                // a genuine legacy relay-only group (no local MLS state) may be
                // emitted as plaintext.
                if self.has_mls_group_state(group_id) {
                    warn!(
                        group_id = %group_id,
                        sender = %sender,
                        "SECURITY: dropping non-MLS plaintext naming an MLS-secured group (sender spoofing)"
                    );
                    self.emit_event(Event::security_warning(
                        sender.to_string(),
                        crate::events::SecurityWarningCode::PlaintextReceiveRejected,
                        "Plaintext group message rejected: the named group is secured with MLS, \
                         so unauthenticated plaintext cannot be attributed to the claimed sender"
                            .to_string(),
                    ));
                    // Nothing was delivered and no MLS state was touched: the
                    // id on this frame is attacker-chosen wire input, and
                    // leaving it marked would let a spoofed frame suppress the
                    // genuine logical message it names (see the marking note
                    // at the top of this function).
                    self.group_mesh.message_dedup.remove(&dedup_key);
                    return;
                }
                // Not ciphertext and no MLS state — legacy relay-only group.
                self.emit_event(Event::group_message_received(
                    group_id.to_string(),
                    sender.to_string(),
                    content.to_string(),
                    timestamp.to_string(),
                    message_id.to_string(),
                    reply_to_msg,
                    forward_info_event,
                    None,
                    None,
                ));
                return;
            }
        };

        match self.decrypt_group_application(group_id, ciphertext_bytes, sender) {
            GroupDecryptOutcome::Plaintext(pt) => match String::from_utf8(pt) {
                Ok(text) => {
                    let (content, media_metadata, content_type, forward_info_event) =
                        Self::restore_group_rich(text, forward_info, sender);
                    self.emit_event(Event::group_message_received(
                        group_id.to_string(),
                        sender.to_string(),
                        content,
                        timestamp.to_string(),
                        message_id.to_string(),
                        reply_to_msg,
                        forward_info_event,
                        media_metadata,
                        content_type,
                    ));
                }
                Err(_) => {
                    warn!(
                        group_id = %group_id,
                        "Decrypted relay group payload is not valid UTF-8, dropping"
                    );
                }
            },
            GroupDecryptOutcome::Retriable => {
                self.buffer_pending_group_message(
                    group_id,
                    PendingGroupMessage {
                        sender: sender.to_string(),
                        message_id: message_id.to_string(),
                        // The relay-supplied id IS the logical id on this
                        // path (a v2 relay echoes the broadcast's id), so a
                        // separate copy would be redundant.
                        logical_id: None,
                        ciphertext_b64: content.to_string(),
                        timestamp: Some(timestamp.to_string()),
                        reply_to: reply_to_msg,
                        forward_info,
                        buffered_at: Instant::now(),
                        // Relay path: the relay sender is not ACK-gated (it uses
                        // try_relay_broadcast, not per-member ensure_ack_registration),
                        // so there is no deferred ACK to send on drain.
                        received_via: None,
                    },
                );
            }
            GroupDecryptOutcome::NonApplication => {
                // Same as the mesh path: MLS consumed a commit or proposal
                // riding the message channel — group state may have advanced.
                self.drain_pending_commits(group_id);
                self.drain_pending_group_messages(group_id);
            }
            GroupDecryptOutcome::PolicyRejected {
                committer,
                added,
                removed,
            } => {
                // Same as the mesh path: a commit reframed onto the message
                // channel, refused before merging. Dropped, never buffered.
                self.report_unauthorized_membership_change(
                    group_id,
                    &committer,
                    &added,
                    &removed,
                    "sender_not_admin",
                    true,
                );
            }
            GroupDecryptOutcome::NotMlsCiphertext => {
                // Valid base64 that is not MLS framing, for a group without
                // local MLS state: a legacy relay-only group message whose
                // plaintext happens to decode (e.g. a base64 media blob).
                // Emit it raw, exactly like the base64-undecodable path.
                self.emit_event(Event::group_message_received(
                    group_id.to_string(),
                    sender.to_string(),
                    content.to_string(),
                    timestamp.to_string(),
                    message_id.to_string(),
                    reply_to_msg,
                    forward_info_event,
                    None,
                    None,
                ));
            }
            GroupDecryptOutcome::SecurityRejected | GroupDecryptOutcome::Failed => {
                warn!(
                    group_id = %group_id,
                    "Failed to decrypt relay group message via MLS, dropping"
                );
                // Rejected, not delivered — unmark so a later copy of the
                // same logical message is processed instead of absorbed.
                // `SecurityRejected` is the load-bearing case: a v2 relay
                // attributes group frames by username, which fails the
                // SEC-M1 wire-sender/credential match after the decrypt —
                // leaving the id marked would then swallow the per-member
                // re-issue of the very same message (delivered exactly
                // nowhere, ACKed as a duplicate). `Failed` covers pre-decrypt
                // refusals (MLS unavailable, invalid group id) that a later
                // copy may outlive. The cost of unmarking is one MLS crypto
                // op per replayed copy — bounded by the same reasoning as
                // the mesh handler's post-decrypt-only logical-id marking.
                self.group_mesh.message_dedup.remove(&dedup_key);
            }
        }
    }
}