offline-protocol 0.29.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
//! Event types and callbacks.

use offline_protocol_core::{ContentType, MediaMetadata, Message, MessageId};
use offline_protocol_services::ServiceEvent;
use offline_protocol_transport::TransportType;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

/// Presence status for a peer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PresenceStatus {
    /// Peer is online and available.
    Online,
    /// Peer is away / idle.
    Away,
    /// Peer is explicitly offline.
    Offline,
}

/// Where a `PresenceUpdated` event came from.
///
/// Apps that render relay-style presence UI (e.g. a direct-chat header's
/// "Online" / "Last seen …") should filter on `Internet` so a nearby peer's
/// self-report can't flip a header that is defined as relay-observed.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PresenceSource {
    /// Relay-observed presence: the relay's authoritative answer to
    /// `CheckPresence` (`PresenceStatus` / `PresenceStatusWithLastSeen`),
    /// or relay-derived reachability — the platform bridges also report
    /// `offline` here when a relay `DeliveryError` names the recipient
    /// unreachable, so a failed send can produce an `Internet`-sourced
    /// offline event without any explicit presence query.
    Internet,
    /// Gateway-observed presence over the Reticulum daemon contract: a
    /// `PresenceStatus` answer from the gateway this device is attached to,
    /// whether solicited by the SDK's watchlist or pushed when a watched
    /// peer's state changes.
    ///
    /// Named for the carrier rather than for "gateway", because that is what
    /// [`Self::Internet`] names too: the relay is a gateway, and an app that
    /// wants to know which carrier answered has to be able to tell them
    /// apart. A claim from either has the same standing and the same decay.
    Reticulum,
    /// A peer-sent `__PRESENCE__` self-report. Transport-agnostic: it may
    /// arrive over BLE, WiFi Direct, or even relay-forwarded frames — hence
    /// "peer", not "mesh". Default for deserializing legacy events that
    /// predate the field.
    #[default]
    Peer,
}

/// Event callback type for handling protocol events.
pub type EventCallback = Arc<dyn Fn(Event) + Send + Sync>;

/// Machine-readable reason taxonomy for welcome delivery failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum WelcomeReasonCode {
    /// No transport was available or all transport sends failed.
    TransportUnavailable,
    /// The transport is up but this specific peer is unreachable on it
    /// (e.g. the internet relay reported the recipient offline). Treated as
    /// per-peer no-carrier: the welcome parks instead of aging.
    PeerUnreachable,
    /// Peer was disconnected or became unavailable during send.
    PeerDisconnected,
    /// Send operation timed out.
    Timeout,
    /// Local/internal error prevented send.
    InternalError,
    /// Retry budget or lifecycle TTL was exhausted.
    RetryExhausted,
}

impl WelcomeReasonCode {
    /// Returns the stable machine-readable reason code.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::TransportUnavailable => "TRANSPORT_UNAVAILABLE",
            Self::PeerUnreachable => "PEER_UNREACHABLE",
            Self::PeerDisconnected => "PEER_DISCONNECTED",
            Self::Timeout => "TIMEOUT",
            Self::InternalError => "INTERNAL_ERROR",
            Self::RetryExhausted => "RETRY_EXHAUSTED",
        }
    }

    /// The settlement reason for a message dropped because the Welcome that
    /// would have carried its session never arrived.
    ///
    /// Spelled out per variant rather than interpolated into a prefix so the
    /// result is a `&'static str`: it becomes [`Event::message_failed`]'s
    /// reason, which the telemetry pipe forwards to the ingest verbatim. See
    /// that constructor for why the type is the guard.
    pub fn welcome_failure_reason(&self) -> &'static str {
        match self {
            Self::TransportUnavailable => "Welcome delivery failed: TRANSPORT_UNAVAILABLE",
            Self::PeerUnreachable => "Welcome delivery failed: PEER_UNREACHABLE",
            Self::PeerDisconnected => "Welcome delivery failed: PEER_DISCONNECTED",
            Self::Timeout => "Welcome delivery failed: TIMEOUT",
            Self::InternalError => "Welcome delivery failed: INTERNAL_ERROR",
            Self::RetryExhausted => "Welcome delivery failed: RETRY_EXHAUSTED",
        }
    }
}

/// Machine-readable taxonomy for [`Event::SecurityWarning`], so consumers can
/// branch on a stable code instead of matching the human-readable `reason`
/// string (which is for logs/UI and may change between versions).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SecurityWarningCode {
    /// A control message's signature verified, but the key that signed it does
    /// not derive to the address the frame claims to come from.
    ///
    /// There is no benign reading. An address *is* the hash of its identity
    /// key, so a legitimate peer's frames always re-derive to their own
    /// address: a rotated key is a *different address*, i.e. a different peer,
    /// not the same peer with new bytes. This is either an impersonation
    /// attempt or a peer running a build with a broken derivation.
    ///
    /// Replaces `TOFU_KEY_MISMATCH`, whose remedy (`resetTofuForPeer`) no longer
    /// exists because there is no pin to reset.
    SenderAddressMismatch,
    /// A control message's signed sender did not match its transport peer
    /// identity.
    TransportIdentityMismatch,
    /// A control message's signature failed verification (invalid signature or
    /// malformed metadata).
    ControlSignatureInvalid,
    /// An unsigned control message was rejected.
    ///
    /// All security-gated control traffic must be signed by the key its sender
    /// address derives from. This is unconditional: it does not depend on
    /// `require_transport_identity`, nor on whether the sender was seen before.
    /// A peer that will not sign is making a claim that cannot be checked.
    UnsignedControlRejected,
    /// An encrypted media chunk's MLS group did not match the 1:1 session
    /// group of the claimed wire sender — a valid ciphertext (from some
    /// session) delivered under a different sender's name is a media
    /// forgery/misattribution attempt.
    MediaSenderGroupMismatch,
    /// An outbound message left this node as plaintext because encryption is
    /// disabled or MLS is uninitialized while `require_encryption` is `false`
    /// (an explicit opt-out — the default fails closed). Emitted at most once
    /// per peer per protocol instance.
    PlaintextSend,
    /// Inbound plaintext content (text or legacy media) was rejected by the
    /// encryption policy: either `require_encryption` is enabled, or a
    /// confirmed MLS session exists with the claimed sender and plaintext
    /// from that peer is a downgrade/forgery attempt (plaintext carries no
    /// sender authentication). Emitted at most once per peer; the per-peer
    /// tracking set is bounded, so after a flood of forged sender ids a
    /// peer may warn again.
    PlaintextReceiveRejected,
    /// An encrypted 1:1 envelope named an MLS group that is not the session
    /// slot shared with the claimed wire sender. The text-path counterpart to
    /// [`Self::MediaSenderGroupMismatch`]: it catches the same misattribution
    /// on paths where MLS cannot, because the envelope failed before it
    /// authenticated anything.
    SessionSenderGroupMismatch,
    /// A 1:1 MLS session was torn down and re-advertised after an epoch
    /// desync. Expected occasionally (a genuine fork heals this way), but the
    /// triggering frame is not authenticated — see `schedule_session_rekey` —
    /// so a sustained rate of these for one peer indicates injected frames
    /// rather than a real fork.
    SessionRekeyTriggered,
    /// A Nostr key-package publication slot could not be refilled, so cold
    /// first contact over Nostr is degraded or unavailable until it succeeds.
    ///
    /// Slots are consumed locally — an init key leaves provider storage only
    /// when *this* node processes a Welcome built against it — so consumption
    /// itself is normal traffic, and a stranger can drive it only by actually
    /// establishing sessions with us. What this warns about is the refill
    /// failing (MLS or storage error), which is the failure the publication
    /// design must never absorb silently: a stale published record makes every
    /// stranger who fetches it build a Welcome that can never be processed.
    NostrKeyPackageSlotExhausted,
    /// The per-peer key-package pool hit its ceiling, so a peer was advertised
    /// an init key another peer already holds.
    ///
    /// The push path normally gives each peer its own single-use init key. Past
    /// the ceiling it reuses one instead of growing the pool without bound —
    /// weakening forward secrecy at session establishment (one compromised init
    /// key opens every Welcome built against it) and re-introducing the race
    /// where the second peer to use a package finds it already consumed. Both
    /// clear as packages are consumed or expire.
    ///
    /// Reaching it means a device has accumulated unconsumed advertisements:
    /// many peers met that never established a session. Sustained emission is
    /// the signal that the ceiling, not peer churn, is now the binding
    /// constraint.
    PushKeyPackagePoolExhausted,
    /// The relay acknowledged an address declaration naming an address that is
    /// not this node's.
    ///
    /// There is no benign reading. The bridge declares `local_address()` and
    /// signs a proof over a per-connection challenge; the relay verifies that
    /// the declared address derives from the key that signed it, and echoes
    /// back what it bound. So the echo can only differ if the relay bound
    /// something other than what it verified — a broken or hostile relay, or a
    /// frame injected into the socket.
    ///
    /// Nothing is torn down: a relay that controls the socket already controls
    /// everything a local refusal could protect, so the mitigation is that the
    /// signal is loud rather than that the connection dies. What it means in
    /// practice is that this connection's frames are attributed to an identity
    /// this node cannot prove, so receivers strict-matching the sender against
    /// the transport identity will reject its security-gated control traffic.
    RelayAddressBindingMismatch,
    /// The relay refused this connection's address declaration, so it stays
    /// attributed by account name.
    ///
    /// Operational degradation, not an attack signal: the refusal path is
    /// deliberately non-fatal on both sides, and the connection keeps working
    /// exactly as it did before addresses existed. What is lost is *new* MLS
    /// session establishment over the relay — `__MLS_KEY_PKG__` and
    /// `__MLS_WELCOME__` are security-gated, so a receiver that strict-matches
    /// the account name against the `off1…` sender rejects them, while already
    /// established sessions keep working because `__MLS_ENC__` is data-plane.
    ///
    /// The relay's own text is **not** carried on the event. It is
    /// remote-chosen, and this event's `reason` is shipped verbatim by the
    /// telemetry scrubber, so the wording stays bounded in the device log
    /// while the code above is the classification. The causes it distinguishes
    /// range from unusable key material to this socket having been displaced
    /// by a newer login; none of them changes what an app should do. No retry
    /// is attempted — the next reconnect declares from scratch.
    RelayAddressDeclarationRefused,
    /// A group leaf carries a credential its own signature key does not derive
    /// to — an identity claimed inside a group without the key to prove it.
    ///
    /// There is no benign reading, and unlike most codes here it accuses
    /// someone the user is already in a room with. An address *is* the hash of
    /// its identity key, so every honest leaf reproduces its own credential;
    /// producing one that does not means deliberately building a leaf around
    /// someone else's name.
    ///
    /// `peer_id` is **who the finding concerns, not always who to blame**. On
    /// the three refusal sites it is the peer that delivered the forgery — the
    /// Welcome's inviter, or the sender of the frame carrying the commit — and
    /// never the address the forged leaf claimed. That attribution is worth
    /// something because it is proved independently: `__GRP_MLS_WELCOME__`,
    /// `__GRP_MLS_COMMIT__` and `__MLS_WELCOME__` are all security-gated, so
    /// the sender signed with the key its own address derives from. On the
    /// fourth site there is no delivering peer at all and `peer_id` is this
    /// device's own id.
    ///
    /// `reason` is diagnostic text, must not be parsed, and deliberately
    /// carries **no identifier** — the impersonated address appears only in
    /// this device's logs. Telemetry scrubbing hashes `peer_id` and passes
    /// `reason` through verbatim, and the identity at stake belongs to a third
    /// party who is not even part of the exchange.
    ///
    /// Emitted from four sites. The first three refuse a claim *arriving*, so
    /// nothing is installed and the frame is dropped:
    ///
    /// 1. joining a group Welcome whose ratchet tree contains such a leaf (the
    ///    invite is declined outright);
    /// 2. processing a membership commit that would install one (the commit is
    ///    not merged, and is never buffered for retry);
    /// 3. joining a 1:1 session Welcome whose ratchet tree contains one —
    ///    including when we already hold a session with that peer, where the
    ///    refusal is non-destructive and the existing session stays live (so a
    ///    `secure_session_failed` alongside this does *not* mean the working
    ///    session ended).
    ///
    /// The fourth is different in kind and needs a different response:
    ///
    /// 4. a roster read skipping a leaf **already seated in local group
    ///    state**. No wire gate can have admitted it, so it arrived by a direct
    ///    write to this device's secure store or via a group joined by a build
    ///    predating those gates. Such a leaf is kept out of every roster and
    ///    cannot speak — but it holds live group secrets and reads everything
    ///    sent to the group, which no later refusal undoes. The remedy is to
    ///    abandon the group, not to evict a member of it.
    ///
    /// Apps should treat a group that produces this as untrusted for
    /// attribution — a message shown as coming from a member is exactly what
    /// the forged leaf was for.
    GroupLeafIdentityUnproven,
    /// A control frame was refused for what its signature says about *when*:
    /// stamped further in the past than this node accepts, further ahead of
    /// this node's clock than it accepts, or carrying the older signing
    /// payload from a peer that has proved it can produce the newer one.
    ///
    /// The three share a code because they share a remedy, and the remedy is
    /// the first thing to check: **this device's own clock**. The signed
    /// timestamp is compared against it, so a device whose clock is wrong
    /// refuses honest peers in bulk, and the event stream then looks like a
    /// coordinated attack rather than a local fault. A run of these naming
    /// *many different* peers is a clock; a run naming *one* peer while others
    /// are fine is that peer, either replaying captures or running a broken
    /// build.
    ///
    /// It is the fresh-frame counterpart to
    /// [`Self::UnsignedControlRejected`]: both refuse a frame whose signature
    /// proves less than this node requires, one for what it omits and one for
    /// what it fails to state. Recovery of last resort is
    /// `security.control_freshness_enforced = false`, which returns this node
    /// to accepting frames of any age (see issue 403 for what that gives back
    /// to an attacker).
    StaleControlFrame,
    /// A gateway echoed an `AddressDeclared` naming an address that is not
    /// this device's.
    ///
    /// The gateway twin of [`Self::RelayAddressBindingMismatch`], and it has
    /// the same absence of a benign reading: the gateway verifies that the
    /// declared address derives from the key that signed the proof, so an
    /// echo naming anything else means it bound what it did not verify. A
    /// session attached under an address this device does not control is how
    /// another device's inbound traffic gets drawn here, and how the presence
    /// answers given about that address are poisoned.
    ///
    /// Reported and not acted on, for the reason the relay case gives: a
    /// gateway that owns the socket already owns everything a local teardown
    /// would protect. What the bridges do act on is narrower and is not this
    /// signal: they refuse to offer a carrier whose session was never bound.
    GatewayAddressBindingMismatch,
    /// A gateway refused this connection's address declaration.
    ///
    /// Unlike the relay case ([`Self::RelayAddressDeclarationRefused`]), this
    /// is not a degraded-but-working connection. The relay keeps delivering
    /// on established sessions in account-name space; a gateway has no such
    /// space, so an unproved session can only be told verdicts and is never
    /// registered as a recipient. The bridge therefore never reports the
    /// carrier available, and this warning explains a transport that stays
    /// down while its socket connects fine.
    GatewayAddressDeclarationRefused,
    /// A peer's key package was refused because this device's clock is
    /// outside its validity window: the window has not started yet, or has
    /// already closed.
    ///
    /// Like [`Self::StaleControlFrame`], the first thing to check is a clock,
    /// and it is usually this device's. A package is valid from an hour before
    /// it was minted until 30 days after, by the receiver's clock. So a device
    /// more than an hour behind a peer cannot start a session with it, though
    /// the peer, whose clock accepts this device's package, still can. Once
    /// the gap passes 30 days each side refuses the other's package and no
    /// session forms at all: messages and connection requests wait for as long
    /// as the clocks disagree, and both sides report this. Phones that have not
    /// been online are where this happens. Many different peers is this
    /// device's clock; one peer while others are fine is that peer's.
    ///
    /// A window that has already closed is not always a clock: a relay can
    /// hold a package for days, and the receiver anchors its cached expiry to
    /// when the frame arrived. That package is discarded, as an expired one
    /// is, and the `reason` says either cause; the next package the peer sends
    /// replaces it. A window that has not started is kept, since it becomes
    /// valid once the clocks agree.
    ///
    /// Raised on every route that admits a pending package: when it arrives,
    /// and on the first send after a restart. The package has not proved its
    /// sender when the window is checked, so the peer named is a claim, and
    /// the event is reported at most once per peer.
    KeyPackageOutsideValidityWindow,
}

impl SecurityWarningCode {
    /// Returns the stable machine-readable reason code.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::SenderAddressMismatch => "SENDER_ADDRESS_MISMATCH",
            Self::TransportIdentityMismatch => "TRANSPORT_IDENTITY_MISMATCH",
            Self::ControlSignatureInvalid => "CONTROL_SIGNATURE_INVALID",
            Self::UnsignedControlRejected => "UNSIGNED_CONTROL_REJECTED",
            Self::MediaSenderGroupMismatch => "MEDIA_SENDER_GROUP_MISMATCH",
            Self::PlaintextSend => "PLAINTEXT_SEND",
            Self::PlaintextReceiveRejected => "PLAINTEXT_RECEIVE_REJECTED",
            Self::SessionSenderGroupMismatch => "SESSION_SENDER_GROUP_MISMATCH",
            Self::SessionRekeyTriggered => "SESSION_REKEY_TRIGGERED",
            Self::NostrKeyPackageSlotExhausted => "NOSTR_KEY_PACKAGE_SLOT_EXHAUSTED",
            Self::PushKeyPackagePoolExhausted => "PUSH_KEY_PACKAGE_POOL_EXHAUSTED",
            Self::RelayAddressBindingMismatch => "RELAY_ADDRESS_BINDING_MISMATCH",
            Self::RelayAddressDeclarationRefused => "RELAY_ADDRESS_DECLARATION_REFUSED",
            Self::GroupLeafIdentityUnproven => "GROUP_LEAF_IDENTITY_UNPROVEN",
            Self::StaleControlFrame => "STALE_CONTROL_FRAME",
            Self::GatewayAddressBindingMismatch => "GATEWAY_ADDRESS_BINDING_MISMATCH",
            Self::GatewayAddressDeclarationRefused => "GATEWAY_ADDRESS_DECLARATION_REFUSED",
            Self::KeyPackageOutsideValidityWindow => "KEY_PACKAGE_OUTSIDE_VALIDITY_WINDOW",
        }
    }
}

/// Machine-readable reason for DORS selection or switch (observability).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DorsReasonCode {
    /// First selection; no previous transport.
    InitialSelection,
    /// DORS selected primary (before send attempt).
    PrimarySelected,
    /// Primary send succeeded; active transport is now primary.
    PrimarySuccess,
    /// Primary failed; fallback send succeeded.
    FallbackSuccess,
    /// BLE → WiFi fallback succeeded (escalation applied).
    EscalationApplied,
    /// Previous transport unavailable; switched to best available.
    CurrentUnavailable,
}

impl DorsReasonCode {
    /// Returns the stable machine-readable reason code.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::InitialSelection => "INITIAL_SELECTION",
            Self::PrimarySelected => "PRIMARY_SELECTED",
            Self::PrimarySuccess => "PRIMARY_SUCCESS",
            Self::FallbackSuccess => "FALLBACK_SUCCESS",
            Self::EscalationApplied => "ESCALATION_APPLIED",
            Self::CurrentUnavailable => "CURRENT_UNAVAILABLE",
        }
    }
}

/// Phase of DORS escalation: recommendation (trigger boundary) vs actual transition (applied).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DorsEscalationPhase {
    /// DORS decided to escalate (typed trigger reason); fallback may not succeed.
    Triggered,
    /// BLE→WiFi fallback send succeeded; escalation was applied.
    Applied,
}

impl DorsEscalationPhase {
    /// Returns the stable string representation (TRIGGERED / APPLIED).
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Triggered => "TRIGGERED",
            Self::Applied => "APPLIED",
        }
    }
}

/// Machine-readable reason for DORS escalation (BLE→Wi‑Fi) observability.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DorsEscalationReasonCode {
    /// Fallback to WiFi succeeded after primary (BLE) send failed.
    FallbackSuccess,
    /// Escalation suggested due to retry threshold (e.g. ble_to_wifi_retry_threshold).
    RetryThreshold,
    /// Escalation suggested due to sustained poor BLE signal.
    PoorSignal,
    /// Escalation suggested due to congestion.
    Congestion,
    /// Escalation suggested due to low TTL on messages.
    LowTtl,
    /// Escalation suggested due to BLE success rate below configured minimum (quality degradation).
    LowSuccessRate,
}

impl DorsEscalationReasonCode {
    /// Returns the stable machine-readable reason code.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::FallbackSuccess => "FALLBACK_SUCCESS",
            Self::RetryThreshold => "RETRY_THRESHOLD",
            Self::PoorSignal => "POOR_SIGNAL",
            Self::Congestion => "CONGESTION",
            Self::LowTtl => "LOW_TTL",
            Self::LowSuccessRate => "LOW_SUCCESS_RATE",
        }
    }
}

/// Machine-readable reason taxonomy for inbound decryption failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum DecryptionFailureCode {
    /// Incoming encrypted payload is malformed and cannot be parsed.
    InvalidPayload,
    /// MLS subsystem is not initialized locally.
    NotInitialized,
    /// Ciphertext is invalid or cannot be decrypted.
    InvalidCiphertext,
    /// Sender identity/signature verification failed.
    IdentityMismatch,
    /// Cryptographic operation failed.
    CryptoFailure,
    /// An encrypted message — a text frame or a media chunk — was evicted from
    /// the pending-decryption queue (overflow or TTL expiry, or it aged out of
    /// the persisted queue across restarts) before the sender's session became
    /// ready. For a media chunk the file transfer it belongs to is currently
    /// stalled; for a text message the message itself is gone locally.
    ///
    /// Under the deferred-ACK model this is **advisory, not terminal**: the
    /// evicted frame was never ACKed, so a sender still retrying resends it and
    /// a later resend re-enters the queue and can still complete once the
    /// session confirms. Treat this as "at risk, may need a resend", not
    /// "permanently failed" — the terminal failure signal for media is
    /// `FileReceiveFailed`. It is emitted for text as well as for chunks: a
    /// relay that pushes ciphertext without store-and-forward has no second
    /// copy, so a silent text eviction was a lost message with no signal to the
    /// app. The same is true of a hard decrypt failure while
    /// `crypto_recovery_enabled`, which surfaces under its own code but is
    /// equally un-ACKed and equally recoverable by a resend; see the
    /// `MessageDecryptionFailed` docs.
    PendingQueueDropped,
    /// Failure class is unknown.
    Unknown,
}

/// Forwarding attribution in events (mirrors `ForwardInfo` from core).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForwardInfoEvent {
    /// The original sender of the message.
    pub original_sender: String,
    /// The original message ID.
    pub original_message_id: String,
    /// The original timestamp (wall-clock ms).
    pub original_timestamp: i64,
    /// Number of times this message has been forwarded.
    pub forward_count: u32,
}

impl From<&offline_protocol_core::ForwardInfo> for ForwardInfoEvent {
    fn from(fwd: &offline_protocol_core::ForwardInfo) -> Self {
        Self {
            original_sender: fwd.original_sender.as_str().to_string(),
            original_message_id: fwd.original_message_id.as_str(),
            original_timestamp: fwd.original_timestamp.as_millis(),
            forward_count: fwd.forward_count,
        }
    }
}

/// Quoted-reply context in events (mirrors `ReplyContext` from core).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReplyContextEvent {
    /// Sender of the message being replied to.
    pub sender: String,
    /// Text (or excerpt) of the message being replied to.
    pub text: String,
    /// Timestamp of the quoted message (wall-clock ms).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<i64>,
    /// Short human-readable label for quoted media (e.g. a file name).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reply_media_label: Option<String>,
    /// Content type of the quoted message, as a display string.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reply_content_type: Option<String>,
}

impl From<&offline_protocol_core::ReplyContext> for ReplyContextEvent {
    fn from(rc: &offline_protocol_core::ReplyContext) -> Self {
        Self {
            sender: rc.sender.as_str().to_string(),
            text: rc.text.clone(),
            timestamp: rc.timestamp.map(|t| t.as_millis()),
            reply_media_label: rc.reply_media_label.clone(),
            reply_content_type: rc.reply_content_type.clone(),
        }
    }
}

/// One device's verified claim to a username.
///
/// Every field here has already passed verification: the address derives from
/// the public key, the record's signature verifies under that key, and the
/// record was published under the Nostr key it names. What that proves is
/// narrow and worth stating exactly — **this key asserts this name**. It does
/// not prove the name belongs to the claimant, because nothing can: the
/// directory is non-authoritative by design.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UsernameClaim {
    /// The claimed address, in canonical `off1…` form.
    ///
    /// This is the value to keep. An app that stores the *name* has stored
    /// something anyone can re-claim tomorrow; the address is self-certifying.
    pub address: String,
    /// The Ed25519 identity key the address derives from, base64.
    pub public_key: String,
    /// When the claimant signed the record, in milliseconds since the epoch.
    ///
    /// **Advisory.** A record is not a liveness signal — the key-package fetch
    /// that follows it is. An old claim from a peer who has been offline for a
    /// month is still perfectly valid, and rejecting it here would make them
    /// unreachable by name while their key packages sit live on a relay. Sort
    /// by it if that helps a user choose; do not filter on it.
    pub issued_at_ms: i64,
}

/// Who removed a replicated document, on [`Event::DataDocRemoved`].
///
/// A fixed token this crate chooses, never a peer's words, which is what
/// lets the telemetry scrubber pass it through unhashed. Serialises as
/// `local` or `peer`, which is the contract every binding types against.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DocRemovedBy {
    /// This device removed it.
    Local,
    /// A removal learned from the space.
    Peer,
}

impl fmt::Display for DocRemovedBy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Local => "local",
            Self::Peer => "peer",
        })
    }
}

/// Events that can occur in the protocol.
///
/// Note: This type implements a custom Debug that redacts sensitive fields
/// (message content) to prevent accidental logging of sensitive data.
#[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
    /// A message was sent (queued for delivery).
    MessageSent {
        /// ID of the sent message.
        message_id: String,
        /// Sender's user ID.
        sender: String,
        /// Recipient's user ID.
        recipient: String,
        /// Content of the sent message.
        content: String,
        /// Priority of the message when sent.
        priority: String,
        /// Whether the message requires an acknowledgement.
        requires_ack: bool,
        /// When the message was queued for delivery (wall-clock, for display).
        timestamp: i64,
        /// Lamport logical clock value for causal ordering.
        #[serde(default)]
        lamport_clock: u64,
        /// Forwarding attribution (present when this is a forwarded message).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        forward_info: Option<ForwardInfoEvent>,
    },

    /// A message was received.
    MessageReceived {
        /// ID of the received message.
        message_id: String,
        /// Sender's user ID.
        sender: String,
        /// Recipient's user ID.
        recipient: String,
        /// Message content.
        content: String,
        /// Number of hops the message traversed.
        hop_count: u8,
        /// Transport used for final delivery.
        transport: String,
        /// When the message was received (wall-clock, for display).
        timestamp: i64,
        /// Lamport logical clock value for causal ordering.
        #[serde(default)]
        lamport_clock: u64,
        /// ID of the message this is replying to (optional).
        #[serde(skip_serializing_if = "Option::is_none")]
        reply_to_msg: Option<String>,
        /// Quoted-reply context (present when this message quotes another).
        /// Boxed to keep the `Event` enum's by-value size in check.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reply_context: Option<Box<ReplyContextEvent>>,
        /// The type of content (text, image, video, etc.).
        #[serde(default)]
        content_type: String,
        /// Media metadata (present for non-text content).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_metadata: Option<MediaMetadata>,
        /// Forwarding attribution (present when this is a forwarded message).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        forward_info: Option<ForwardInfoEvent>,
        /// `true` when the content arrived MLS-encrypted and was decrypted by
        /// this node; `false` for plaintext accepted under the
        /// `require_encryption = false` opt-out.
        #[serde(default)]
        encrypted: bool,
        /// Application id the sender stamped on this message: its configured
        /// id, or the per-send id of a rich send.
        ///
        /// For an instance serving several local applications, this is what
        /// routes the message to the right client. It is cleartext and
        /// unsigned on the wire, so any carrier could have rewritten it
        /// (threat model R17): route on it, never authorize on it. The
        /// engine delivers every message whatever this says.
        #[serde(default)]
        app_id: String,
    },

    /// A message was successfully delivered (ACK received).
    MessageDelivered {
        /// ID of the delivered message.
        message_id: String,
        /// Latency in milliseconds.
        latency_ms: u64,
        /// Number of hops traversed.
        hop_count: u8,
        /// Transport used.
        transport: String,
    },

    /// A message failed to deliver.
    MessageFailed {
        /// ID of the failed message.
        message_id: String,
        /// Reason for failure.
        reason: String,
        /// Number of retries attempted.
        retry_count: u32,
    },

    /// An inbound encrypted message failed to decrypt on this attempt.
    ///
    /// **Advisory, not terminal, and emitted once per failed *attempt*.** While
    /// `EncryptionConfig::crypto_recovery_enabled` is on (the default) a
    /// message that fails to decrypt is not delivery-ACKed, so the sender keeps
    /// retrying — and each resend of a DM is re-sealed against the peer's
    /// current session, so a resend can actually land. Every failing attempt
    /// reports again, bounded by the sender's ACK retry budget. Read this as
    /// "this attempt did not decrypt"; the terminal signals are
    /// [`Event::MessageFailed`] on the sender and `FileReceiveFailed` for
    /// media.
    MessageDecryptionFailed {
        /// ID of the message that could not be decrypted.
        message_id: String,
        /// Sender's user ID.
        sender: String,
        /// Machine-readable decryption failure code.
        code: DecryptionFailureCode,
        /// Clear failure reason for application handling/logging.
        reason: String,
        /// When the sender sealed the frame (sender clock, ms), read from the
        /// cleartext envelope. Unauthenticated: a hint for local heuristics,
        /// never for security decisions. `None` when the failure is not a 1:1
        /// decrypt attempt (pending-queue drop, unparseable envelope, group).
        sealed_at_ms: Option<u64>,
        /// When this device's current session with `sender` was created or
        /// adopted (local clock, ms). `None` when there is no session, or it
        /// was established by an SDK that did not record the time. A frame
        /// sealed before this cannot have been sealed under this session, so
        /// its failure says nothing about whether the two sides agree now.
        session_established_at_ms: Option<u64>,
    },

    /// Transport was switched by DORS.
    TransportSwitched {
        /// Previous transport (if any).
        from: Option<String>,
        /// New transport.
        to: String,
        /// Reason for switch.
        reason: String,
    },

    /// This device started acting as a relay — carrying traffic for other
    /// devices that cannot reach each other directly.
    ///
    /// Reports observed behaviour, not capability: it fires because this
    /// device has been forwarding, so it needs no battery feed and can fire on
    /// a device that has never reported a level.
    RelayPromoted {
        /// Neighbors held when this device started relaying.
        connection_count: usize,
        /// Battery level at the time, or `None` when the host has reported
        /// none — the standing does not depend on it.
        battery_level: Option<u8>,
    },

    /// This device was demoted from relay role.
    RelayDemoted {
        /// Reason for demotion.
        reason: String,
    },

    /// A new neighbor was discovered.
    NeighborDiscovered {
        /// The peer's canonical user id — the same value the peer supplied
        /// as `ProtocolConfig.user_id`, on every transport. Valid directly
        /// as the `recipient` of `send_message` / `send_connection_request`.
        peer_id: String,
        /// Transport used to discover.
        transport: String,
        /// RSSI signal strength (if available).
        rssi: Option<i16>,
    },

    /// A neighbor was lost (disconnected).
    NeighborLost {
        /// Peer ID of the lost neighbor.
        peer_id: String,
    },

    /// This device's own address is known: MLS storage was opened and the
    /// identity key in it derived to `address`.
    ///
    /// Fires once per successful `initialize_mls`, before any frame can be
    /// sent. `address` is this device's `Message.sender` from here on, and what
    /// peers must be given to reach it. It is stable across restarts of the
    /// same profile, so an app that already stored it will be handed the same
    /// value rather than a new one.
    IdentityReady {
        /// This device's self-certifying address (`off1…`).
        address: String,
    },

    /// Network metrics update.
    NetworkMetrics {
        /// Number of active neighbors.
        neighbor_count: usize,
        /// Number of active relays.
        relay_count: usize,
        /// Message delivery ratio (0.0-1.0).
        delivery_ratio: f32,
        /// Average message latency in milliseconds.
        avg_latency_ms: u64,
    },

    /// File transfer progress update.
    FileProgress {
        /// File identifier.
        file_id: String,
        /// Number of chunks sent so far.
        chunks_sent: u32,
        /// Total number of chunks.
        total_chunks: u32,
        /// Progress percentage (0-100).
        percentage: u8,
    },

    /// File was completely received.
    FileReceived {
        /// File identifier.
        file_id: String,
        /// File name.
        file_name: String,
        /// File size in bytes.
        file_size: u64,
        /// Sender's user ID.
        sender: String,
        /// The content type of the media (image, video, file, etc.).
        content_type: String,
        /// Media metadata from the first chunk (present for typed media).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_metadata: Option<MediaMetadata>,
        /// Base64-encoded reassembled file data.
        file_data: String,
        /// When the sender queued the transfer (chunk-0 outer message
        /// timestamp, wall-clock ms) — for display ordering alongside
        /// `MessageReceived.timestamp`. Absent only if the chunk-0 record
        /// was evicted before completion.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timestamp: Option<i64>,
        /// Caption text from the sealed chunk-0 rich extras.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        caption: Option<String>,
        /// ID of the message this media replies to (sealed chunk-0 extras).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reply_to_msg: Option<String>,
        /// Quoted-reply context (sealed chunk-0 extras). Boxed to keep the
        /// `Event` enum's by-value size in check.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reply_context: Option<Box<ReplyContextEvent>>,
        /// Forwarding attribution (sealed chunk-0 extras).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        forward_info: Option<ForwardInfoEvent>,
        /// Application id the sender stamped on the transfer (chunk-0 outer
        /// message), with the meaning and the cleartext caveat of
        /// `MessageReceived.app_id`. Absent only if the chunk-0 record was
        /// evicted before completion, like `timestamp`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        app_id: Option<String>,
    },

    /// An inbound file transfer was dropped before completion — the receiver
    /// hit a resource limit (too many concurrent transfers, per-sender
    /// quota, or the buffered-bytes budget), the reassembled file failed
    /// its integrity checks, or the transfer went stale (no chunks within
    /// the stale timeout). Terminal and fired at most once per transfer:
    /// the failed transfer's remaining in-flight chunks are dropped
    /// silently. No `FileReceived` will follow for this `file_id`; the
    /// sender must re-send the file (under a fresh `file_id`) to retry.
    FileReceiveFailed {
        /// File identifier.
        file_id: String,
        /// File name from the chunk metadata.
        file_name: String,
        /// Sender's user ID.
        sender: String,
        /// Machine-readable reason the transfer was dropped.
        reason: String,
    },

    /// All chunks of a media attachment were ACK-delivered.
    MediaSent {
        /// File identifier for tracking.
        file_id: String,
        /// The content type of the media.
        content_type: String,
        /// Recipient's user ID.
        recipient: String,
    },

    /// An outbound media transfer was aborted before all chunks were
    /// delivered — a chunk failed to encrypt, or a chunk failed terminally
    /// in the outbox. No `MediaSent` will follow for this `file_id`; retry
    /// with a new `send_media` call.
    MediaSendFailed {
        /// File identifier for tracking.
        file_id: String,
        /// Recipient's user ID.
        recipient: String,
        /// Reason the transfer was aborted.
        reason: String,
    },

    /// A message was deferred due to network conditions.
    /// The message will be retried automatically.
    MessageDeferred {
        /// ID of the deferred message.
        message_id: String,
        /// Recipient's user ID.
        ///
        /// Added when `reason` stopped rendering the transport error: the
        /// counterparty used to reach apps only inside that prose, which put an
        /// unhashed address on every telemetry record for a routine send
        /// failure. Carried as a field so the scrubber hashes it like any
        /// other actor id.
        recipient: String,
        /// Stable classification of the deferral, not a rendered error.
        ///
        /// One of a fixed local vocabulary (`peer_not_reachable`,
        /// `transport_not_connected`, `transport_send_failed`, …). Branch on it
        /// if you must, but do not parse it for detail: the underlying error —
        /// which renders the peer — stays in the device log.
        reason: String,
        /// Current retry count.
        retry_count: u32,
        /// Next retry scheduled time (Unix timestamp ms).
        next_retry_at: Option<i64>,
    },

    /// A retry for a previously deferred/unacked message was scheduled.
    ///
    /// Emitted each time the retry machinery re-queues a message after a
    /// failed attempt (transport send error or ACK timeout). Non-terminal:
    /// `MessageDelivered` or `MessageFailed` still settles the message.
    MessageRetrying {
        /// ID of the retrying message.
        message_id: String,
        /// Recipient's user ID.
        recipient: String,
        /// Retry count this schedule corresponds to.
        retry_count: u32,
        /// Absolute time the retry is scheduled for (Unix timestamp ms).
        next_retry_at: i64,
    },

    /// The transport layer reported the recipient unreachable for an
    /// in-flight message (e.g. the internet relay's DeliveryError).
    ///
    /// Non-terminal: the message stays in the outbox. A plain DM is
    /// *parked* — its ACK retry budget stops burning while the peer is
    /// provably offline — and is re-driven on reachability edges (transport
    /// reconnect, peer discovery, presence-online; the SDK adds parked
    /// recipients to the presence watchlist). It settles only via
    /// `MessageDelivered` or, at outbox-lifetime expiry, `MessageFailed`.
    /// Media chunks are not parked and keep the normal retry machinery.
    /// May fire multiple times for the same `message_id` while the
    /// recipient remains offline: a parked DM keeps an escalating
    /// reachability probe on every carrier (15s → 600s cap), and each probe
    /// that reaches the relay while the peer is still offline earns a fresh
    /// verdict and re-emits this event. Apps must treat it as a repeatable
    /// status signal, never as a terminal one. `file_id` is set when the
    /// message is a chunk of an outbound media transfer.
    MessageUndeliverable {
        /// ID of the affected message.
        message_id: String,
        /// Recipient's user ID.
        recipient: String,
        /// Stable classification of the failure — `recipient_unreachable` on
        /// the relay-verdict path this event is normally reached by.
        ///
        /// The transport's own wording used to be appended here verbatim, and
        /// on the relay path that wording is written by the relay: unbounded
        /// remote text, shipped beside a `recipient` the telemetry scrubber
        /// hashes. It is now dropped at the boundary — kept in the device log,
        /// and on the internet path still delivered raw to apps on the
        /// bridges' `diagnostic` channel.
        reason: String,
        /// Owning media transfer when the message is a media chunk.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        file_id: Option<String>,
    },

    /// An outbound media transfer was in flight when the previous process
    /// died. The SDK persists only the transfer descriptor (never chunk
    /// bytes), so it cannot resume the transfer itself: the app must
    /// re-supply the file bytes via `send_media` with this `file_id` —
    /// they are checksum-validated against the original transfer.
    MediaResendRequired {
        /// File identifier of the interrupted transfer.
        file_id: String,
        /// Recipient's user ID.
        recipient: String,
        /// Original file name.
        file_name: String,
        /// Total file size in bytes.
        file_size: u64,
        /// Per-send application id the transfer was started with, absent
        /// when it used the configured one. An instance serving several
        /// applications asks this one for the bytes.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        app_id: Option<String>,
    },

    /// A pending ACK was evicted due to capacity constraints.
    AckEvicted {
        /// ID of the message whose ACK was evicted.
        message_id: String,
        /// Priority of the evicted message.
        priority: String,
        /// Reason for eviction.
        reason: String,
    },

    /// A fragment assembly was evicted to make room for new fragments.
    FragmentAssemblyEvicted {
        /// ID of the message whose fragments were evicted.
        message_id: String,
        /// Completion percentage when evicted.
        completion_percent: u8,
        /// Reason for eviction.
        reason: String,
    },

    /// Relay role was demoted due to battery constraints.
    RelayDemotedBattery {
        /// Battery level at time of demotion.
        battery_level: u8,
        /// Minimum required battery level.
        min_required: u8,
    },

    /// A secure MLS session was successfully established.
    SecureSessionEstablished {
        /// Peer ID of the other party.
        peer_id: String,
        /// MLS group ID for the session.
        group_id: String,
        /// Whether this is a 1:1 session (true) or a multi-party group (false).
        is_session: bool,
        /// Whether the local device initiated the session (sent the Welcome).
        initiated_by_local: bool,
    },

    /// Failed to establish a secure MLS session.
    ///
    /// Reports a failed *handshake attempt*, which is not the same as "the
    /// session with this peer is gone". One case makes the difference visible:
    /// a Welcome refused for carrying an unprovable identity
    /// ([`SecurityWarningCode::GroupLeafIdentityUnproven`], emitted alongside)
    /// is refused non-destructively, so any session already held with that peer
    /// stays live and usable. Apps must not tear down session state on this
    /// event alone.
    ///
    /// `reason` is diagnostic text and must not be parsed. It carries no
    /// identifier, of this peer or of anyone else: the telemetry scrubber
    /// hashes `peer_id` and ships `reason` verbatim, so every arm that fills it
    /// contributes either a fixed string or
    /// [`MlsError::privacy_safe_reason`](offline_protocol_mls::MlsError::privacy_safe_reason),
    /// never a rendered error. The full error stays in the device log at the
    /// refusal site. This is a classification, so apps get the failure *class*
    /// here and must look to the log for the specifics.
    SecureSessionFailed {
        /// Peer ID of the other party.
        peer_id: String,
        /// Reason for the failure.
        reason: String,
    },

    /// Diagnostic breadcrumb for the 1:1 MLS convergence (Welcome receive /
    /// adopt / confirm) path. Emitted so the receiver side — which otherwise
    /// produces no event until it fully establishes or loudly fails — is
    /// observable in Metro. Pure instrumentation; carries no protocol effect.
    ConvergenceDiag {
        /// Fixed stage label, e.g. "welcome_received" or "welcome_branch".
        stage: String,
        /// Peer ID this breadcrumb concerns.
        peer_id: String,
        /// Free-form `key=value` context (counts, branch taken, errors).
        detail: String,
    },

    /// Welcome send lifecycle entered attempted state.
    WelcomeSendAttempted {
        /// Peer identifier for this welcome lifecycle.
        peer_id: String,
        /// Welcome message identifier for lifecycle correlation.
        message_id: String,
        /// MLS group identifier associated with the welcome.
        group_id: String,
        /// 1-based send attempt number.
        attempt: u32,
    },

    /// Welcome send lifecycle reached successful sent state.
    WelcomeSendSucceeded {
        /// Peer identifier for this welcome lifecycle.
        peer_id: String,
        /// Welcome message identifier for lifecycle correlation.
        message_id: String,
        /// MLS group identifier associated with the welcome.
        group_id: String,
        /// 1-based send attempt number.
        attempt: u32,
    },

    /// Welcome send attempt failed and may be retried.
    WelcomeSendFailed {
        /// Peer identifier for this welcome lifecycle.
        peer_id: String,
        /// Welcome message identifier for lifecycle correlation.
        message_id: String,
        /// MLS group identifier associated with the welcome.
        group_id: String,
        /// 1-based send attempt number.
        attempt: u32,
        /// Machine-readable reason code.
        reason_code: WelcomeReasonCode,
        #[serde(skip_serializing_if = "Option::is_none")]
        /// Stable classification of the transport failure, when one was
        /// recorded — never the rendered error.
        ///
        /// Both feeders named an identifier: the platform-supplied string is
        /// the relay's own `DeliveryError` prose, and the locally raised one
        /// renders a transport error that interpolates the peer. `peer_id` and
        /// `group_id` beside it are hashed, so either would have undone that.
        /// Classified at the boundary, so the persisted record holds the token
        /// too — and again at each emit as a backstop. The second pass is
        /// unreachable today (every writer overwrites the field before its
        /// emit, so no record restored from an older build can carry raw text
        /// into an event) and kept because the field is persisted and has five
        /// writers: it holds the invariant if one of them ever becomes
        /// conditional.
        transport_error: Option<String>,
        /// Whether this failure will be retried.
        retryable: bool,
        #[serde(skip_serializing_if = "Option::is_none")]
        /// Next scheduled retry timestamp in Unix ms.
        next_retry_at: Option<i64>,
    },

    /// Welcome send lifecycle reached terminal expiry.
    WelcomeSendExpired {
        /// Peer identifier for this welcome lifecycle.
        peer_id: String,
        /// Welcome message identifier for lifecycle correlation.
        message_id: String,
        /// Final attempt number when lifecycle expired.
        attempt: u32,
        /// Terminal machine-readable reason code.
        reason_code: WelcomeReasonCode,
    },

    /// A connection request was received from another user.
    ConnectionRequestReceived {
        /// User ID of the sender.
        sender: String,
        /// Display name of the sender.
        sender_name: String,
        /// Timestamp of the request (Unix ms).
        timestamp: i64,
        /// MLS key package data (if provided for encrypted session setup).
        #[serde(skip_serializing_if = "Option::is_none")]
        key_package: Option<Vec<u8>>,
        /// Optional first message sent along with the request.
        #[serde(skip_serializing_if = "Option::is_none")]
        initial_message: Option<String>,
    },

    /// An outbound connection request could not be delivered: the transport
    /// reported the recipient unreachable (e.g. the relay's DeliveryError
    /// for an offline peer), or the request exhausted its ACK retry budget
    /// (in which case a generic `MessageFailed` also fires for the same
    /// id). This is a status signal, not proof of permanent failure — the
    /// original request may still be delivered by the retry machinery if
    /// the peer comes back online. Apps typically surface "user is
    /// offline"; a user-initiated resend can therefore arrive alongside the
    /// retried original (the recipient sees the request event again, which
    /// accept/reject flows already tolerate).
    ConnectionRequestUndeliverable {
        /// Recipient the request was addressed to.
        recipient: String,
        /// Message id returned by `send_connection_request`.
        message_id: String,
        /// Failure reason, drawn from a fixed local vocabulary:
        /// `recipient_unreachable` on the transport verdict path, or
        /// `max_retries_exceeded` / `outbox_lifetime_exceeded` /
        /// `outbox_capacity_exceeded` on the give-up paths.
        ///
        /// The relay's wording is no longer appended to the first of these —
        /// it is remote-chosen text, and `recipient` beside it is hashed by
        /// the telemetry scrubber.
        reason: String,
    },

    /// A previously sent connection request was accepted.
    ConnectionAccepted {
        /// User ID of the accepting party.
        accepted_by: String,
        /// Display name of the accepting party.
        accepted_by_name: String,
        /// Timestamp of the acceptance (Unix ms).
        timestamp: i64,
        /// MLS key package data (if provided for encrypted session setup).
        #[serde(skip_serializing_if = "Option::is_none")]
        key_package: Option<Vec<u8>>,
    },

    /// A previously sent connection request was rejected.
    ConnectionRejected {
        /// User ID of the rejecting party.
        rejected_by: String,
    },

    /// A previously sent connection request was cancelled by the sender.
    ConnectionRequestCancelled {
        /// User ID of the party who cancelled their request.
        cancelled_by: String,
    },

    // --- Group (relay) events ---
    /// A group was created (from relay).
    GroupCreated {
        /// Group identifier.
        group_id: String,
        /// Human-readable group name.
        name: String,
    },

    /// A message was received in a group (from relay).
    GroupMessageReceived {
        /// Group identifier.
        group_id: String,
        /// User ID of the sender.
        sender: String,
        /// Message content.
        content: String,
        /// ISO-8601 timestamp.
        timestamp: String,
        /// Unique message identifier.
        message_id: String,
        /// Optional reply-to message ID.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reply_to_msg: Option<String>,
        /// Forwarding attribution (present when this is a forwarded message).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        forward_info: Option<ForwardInfoEvent>,
        /// Media metadata restored from the sealed `__RICH_V1__` body of a
        /// rich group message (cloud attachments — including the
        /// `encryption_key`/`iv` secrets, which only ever travel inside the
        /// group MLS ciphertext). Absent on plain group messages.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        media_metadata: Option<MediaMetadata>,
        /// Content-type rendering hint from the sealed body (text, image,
        /// video, ...). Absent on plain group messages.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        content_type: Option<String>,
    },

    /// A member was added to a group (from relay).
    GroupMemberAdded {
        /// Group identifier.
        group_id: String,
        /// User ID of the added member.
        user_id: String,
        /// User ID of who performed the add.
        added_by: String,
        /// Human-readable group name (present when the invitee first joins).
        #[serde(skip_serializing_if = "Option::is_none")]
        group_name: Option<String>,
        /// Whether `added_by` was authorized to make this change.
        ///
        /// `Some(false)` means the change **did** happen — MLS accepted the
        /// commit and the roster really has changed — but the committer was
        /// not a known admin. The membership event is still emitted because
        /// the local roster must not diverge from MLS state; see
        /// [`Event::GroupUnauthorizedMembershipChange`] for the full signal.
        ///
        /// `None` (absent in JSON) means authorization was **not evaluated**
        /// on the path that produced this event: our own join accepted from
        /// a Welcome (there is no prior group state to judge the inviter
        /// against) and relay reconciliation frames (no authenticated
        /// committer to judge). Events from an older core also omit the
        /// field. Only `Some(_)` is a positive statement either way.
        ///
        /// The judgment is made against this member's **local replica** of
        /// role state, which replicates best-effort and can lag — a
        /// legitimate change may be flagged `Some(false)`, and different
        /// members can disagree about the same commit. Do not act on it
        /// automatically.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        authorized: Option<bool>,
    },

    /// A member was removed from a group (from relay).
    GroupMemberRemoved {
        /// Group identifier.
        group_id: String,
        /// User ID of the removed member.
        user_id: String,
        /// User ID of who performed the removal.
        removed_by: String,
        /// Whether this change was authorized (`None` = not evaluated on
        /// this path). See [`Event::GroupMemberAdded::authorized`]. On the
        /// relay reconciliation path the judgment applies to the frame's
        /// authenticated wire sender, which is not necessarily the
        /// `removed_by` named here.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        authorized: Option<bool>,
    },

    /// Group info was received (from relay).
    GroupInfo {
        /// Group identifier.
        group_id: String,
        /// Human-readable group name.
        name: String,
        /// User ID of the group creator.
        created_by: String,
        /// ISO-8601 creation timestamp.
        created_at: String,
        /// Group member list.
        members: Vec<GroupInfoMember>,
    },

    /// User's groups list was received (from relay).
    UserGroups {
        /// List of group summaries.
        groups: Vec<UserGroupSummary>,
    },

    /// A group operation failed (from relay).
    ///
    /// The relay's own wording is **not** carried here. `__GROUP_ERROR__` is
    /// a relay answer, accepted unsigned on the relay ingest path (the
    /// bridges inject it unattributed), so its text is chosen by whoever put
    /// the frame on that socket — arbitrary content, arbitrary length, and
    /// not something this SDK can vouch for. `reason` is a fixed code
    /// classified locally instead; the
    /// relay's exact text is logged on-device and reaches apps, when they
    /// want it, as the raw `GroupError` frame the bridges dual-emit on the
    /// server-message channel.
    GroupError {
        /// Why the operation failed, from a fixed set: `not_found` (the
        /// relay has no such group — invite links and relay fan-out for it
        /// are dead, not merely refused), `sync_denied` (the relay refused
        /// to register or sync the group for this caller), or `error` (any
        /// other refusal).
        reason: String,
        /// Group the error concerns, when the relay scoped it. Absent for
        /// unscoped errors.
        ///
        /// This is the group-scoping the free-text `reason` used to smuggle
        /// past the telemetry scrubber — as a real field it is hashed like
        /// every other `group_id` instead.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        group_id: Option<String>,
    },

    /// The relay-side registration state of a group changed.
    ///
    /// `synced: true` fires only on the relay's positive registration
    /// acknowledgment (a `GroupCreated` answering a registration this
    /// device actually sent, over the Internet transport) — including the
    /// idempotent re-sync ack after a membership change. It is the signal
    /// that relay-dependent server commands for the group (invite links,
    /// server-side fan-out) can be issued. `synced: false` fires when that
    /// trust is revoked; `reason` says why. Not emitted for groups the
    /// relay was never asked about.
    GroupRelaySyncChanged {
        /// MLS group identifier.
        group_id: String,
        /// Whether the relay currently holds a positively acknowledged
        /// registration for this group.
        synced: bool,
        /// Why the state changed: `registered` (relay ack), `error`
        /// (group-scoped relay error), `removed` (we were removed from the
        /// group), `left` (local leave), `internet_dropped` (Internet
        /// transport lost; re-registration re-arms on reconnect), or
        /// `ack_timeout` (relay never answered the registration — likely a
        /// relay without group support).
        reason: String,
    },

    /// A username resolution finished, carrying **every** claim found.
    ///
    /// # The set is the whole point, and there is deliberately no "best" claim
    ///
    /// Anyone may publish any username claim, so a name resolves to a set of
    /// assertions, never to an answer. Even a single-device user is a set of
    /// one. This event is emitted exactly once per resolution and carries the
    /// complete set precisely so an app cannot accidentally treat the first
    /// arrival as the winner: there is no per-claim event to race, and no
    /// ordering field to mistake for a ranking.
    ///
    /// **An app MUST let the user choose.** Silently picking one claim converts
    /// a non-authoritative directory into an authoritative-looking one, which
    /// is worse than not shipping the feature: the user believes they are
    /// talking to the name, and the protocol only ever promised them a key.
    /// Present the claims, let a human confirm out of band (a QR code, a
    /// shared secret, a voice), and remember the address rather than the name.
    ///
    /// An empty `claims` list is an ordinary outcome: the name may be
    /// unclaimed, the claimant offline-published to relays we do not use, or
    /// every claim we saw failed verification.
    UsernameResolved {
        /// The normalized username that was resolved.
        username: String,
        /// Every claim that verified, in no meaningful order.
        claims: Vec<UsernameClaim>,
        /// How many records were seen but rejected.
        ///
        /// Non-zero is *normal*, not an error: the tag is public, anyone may
        /// publish to it, and junk arrives. Surfaced because a resolution that
        /// returns nothing while rejecting many records means something
        /// different from one that returns nothing having seen nothing, and an
        /// app showing "not found" may want to distinguish them.
        rejected: u32,
        /// How many *verified* claims were dropped at the accumulator's
        /// ceiling.
        ///
        /// Separate from `rejected` because it is the opposite statement: these
        /// records were good and are missing anyway. Without it a crowded name
        /// renders exactly like an uncrowded one, a clean set with nothing
        /// refused, which hides the single signal that a name is being
        /// squatted at volume. Non-zero means `claims` is a sample and no
        /// absence in it can be trusted.
        truncated: u32,
    },

    /// A group message was sent to all members via mesh (MLS-encrypted fan-out).
    GroupMessageSent {
        /// MLS group identifier.
        group_id: String,
        /// Per-member message IDs from fan-out.
        message_ids: Vec<String>,
        /// Number of members the message was sent to.
        member_count: u32,
    },

    /// A group message was only partially delivered (some members failed).
    GroupMessagePartialFailure {
        /// MLS group identifier.
        group_id: String,
        /// Members for whom send failed.
        failed_members: Vec<String>,
        /// Members for whom send succeeded.
        succeeded_members: Vec<String>,
    },

    /// The relay's settled per-recipient delivery report for a group
    /// message sent via relay broadcast, after the SDK acted on it.
    ///
    /// Fires once per broadcast whose report arrived, seconds after
    /// `group_message_sent` (the relay reports only when its whole fan-out
    /// has settled — correlate by `message_id`, never by order). Members in
    /// `delivered` took the message over a live relay socket; members in
    /// `pushed` took a device push carrying the ciphertext. Every other
    /// MLS roster member — the ones the relay reported missed *and* the
    /// ones it did not know about at all — has already been re-sent a
    /// per-member copy through the ordinary outbox/ACK/park delivery
    /// ladder (`missed_reissued`), so no app action is required; the event
    /// is delivery observability, not a failure signal. Not emitted when
    /// the report itself is lost — the SDK then re-broadcasts (bounded)
    /// and finally downgrades the whole message to per-member fan-out,
    /// which reports per-member like any mesh send.
    GroupMessageDeliveryReport {
        /// MLS group identifier.
        group_id: String,
        /// The logical group message id, as returned by the send and echoed
        /// by the relay.
        message_id: String,
        /// Members whose relay socket write was confirmed (a relay-side
        /// write-ack, not an end-to-end delivery ACK).
        delivered: Vec<String>,
        /// Members offline at the relay who took a device push.
        pushed: Vec<String>,
        /// Members re-sent a per-member copy because the relay reached them
        /// neither way (or never knew them).
        missed_reissued: Vec<String>,
    },

    /// Rich media metadata was dropped from an outbound group message
    /// because the group is not fully rich-capable (not every member
    /// advertised sealed rich payload support, or the local kill switch
    /// disabled it). The text was still sent; members receive it without
    /// the media attachment. Apps can use this to warn the sender that an
    /// attachment did not go through.
    GroupRichExtrasDropped {
        /// MLS group identifier.
        group_id: String,
        /// Members not known to parse the sealed rich payload — the ones
        /// holding the seal gate closed. Absence of knowledge and known
        /// non-support are indistinguishable here. Empty when the drop was
        /// caused by the local `rich_payload_enabled` kill switch instead.
        /// The SDK probes these members for their capability automatically;
        /// apps can retry the send once a later attempt stops dropping.
        unknown_members: Vec<String>,
    },

    /// An MLS membership change was applied that its committer was not
    /// authorized to make.
    ///
    /// The change **has been applied** — MLS authenticated the committer as a
    /// group member and accepted the commit, and the local epoch advanced with
    /// it. The SDK's admin model is an application-layer overlay on top of MLS
    /// (RFC 9420 leaves membership access control to the application), enforced
    /// on the *sending* side; refusing the change on receipt would mean
    /// refusing the merge, which permanently forks this member away from every
    /// peer that accepted it. So the change stands and is reported here instead.
    ///
    /// **This signal can false-positive.** "Unauthorized" is judged against
    /// this member's local replica of role state, which replicates
    /// best-effort (a joiner receives a point-in-time snapshot, role changes
    /// ride unreconciled mesh notifications) and can lag — so a legitimate
    /// change, e.g. a voluntary leave committed by a member whose admin role
    /// this device has not yet learned, may be reported here, and different
    /// members can disagree about the same commit.
    ///
    /// Apps should treat this as a moderation signal for a *human* admin: an
    /// admin can undo the change with `remove_from_group` /
    /// `invite_to_group`. Never reverse a change automatically off a single
    /// member's event — corroborate first. A member added this way can read
    /// all subsequent group traffic until removed.
    ///
    /// Reports are rate-limited per `(group, committer)`: a repeat within a
    /// short window is not re-emitted (divergent role metadata would
    /// otherwise re-fire it on every commit), but every affected
    /// [`Event::GroupMemberAdded`] / [`Event::GroupMemberRemoved`] still
    /// carries `authorized: Some(false)`.
    ///
    /// Known limitation: the member *removed* by an unauthorized Remove does
    /// not receive this event — it can no longer decrypt the commit that
    /// removed it, and it refuses to trust a non-admin's unencrypted claim
    /// that it was removed. Only the remaining members report the removal.
    GroupUnauthorizedMembershipChange {
        /// MLS group identifier.
        group_id: String,
        /// The MLS-authenticated committer that made the change.
        committer: String,
        /// Members the commit added, sorted. Empty for a pure removal.
        added: Vec<String>,
        /// Members the commit removed, sorted. Empty for a pure addition.
        removed: Vec<String>,
        /// Why the change was judged unauthorized. Currently
        /// `"sender_not_admin"` (the committer is not a known admin) or
        /// `"affected_member_mismatch"` (an admin committed, but the commit's
        /// unencrypted framing named a different member than the MLS delta
        /// actually changed). Treat as an opaque string — values may be added.
        reason: String,
        /// Whether the commit was *refused* rather than applied.
        ///
        /// `false` (the default configuration) means the membership change
        /// happened and is being reported after the fact — `added`/`removed`
        /// describe real roster changes an admin can undo. `true` means
        /// `GroupConfig::enforce_admin_commits` was on and the commit was
        /// rejected before merging: no roster event accompanies this one, no
        /// membership changed locally, and `added`/`removed` describe what the
        /// commit *would* have done.
        ///
        /// A `true` here also means this device declined an epoch every
        /// accepting member advanced to, so it can no longer decrypt that
        /// group's traffic and needs re-inviting — treat it as a partition
        /// alarm, not just a moderation signal. Note the re-invite arrives as
        /// a Welcome, which is not policy-gated, so it readmits us to the
        /// group *including* whatever the refused commit did; the change
        /// itself still has to be resolved separately.
        enforced: bool,
    },

    /// An epoch fork was detected in a group — concurrent commits caused
    /// members to diverge onto different MLS branches. The deterministic
    /// leader will attempt automatic resolution via a key-update commit.
    GroupEpochForkDetected {
        /// MLS group identifier.
        group_id: String,
        /// Our local epoch when the fork was detected, or `None` if MLS
        /// state was unavailable at detection time.
        local_epoch: Option<u64>,
    },

    /// An epoch fork was successfully resolved by the leader issuing a
    /// resync commit that re-established a canonical epoch.
    ///
    /// Members in `failed_members` could not be reached with the resolution
    /// commit and may still be on a forked branch — the application layer
    /// should consider re-inviting them.
    GroupEpochForkResolved {
        /// MLS group identifier.
        group_id: String,
        /// The new canonical epoch after resolution.
        resolved_epoch: u64,
        /// Members to whom the resolution commit could not be sent.
        /// These members may still be on a forked epoch branch and
        /// may need a re-invite to rejoin the canonical group state.
        failed_members: Vec<String>,
    },

    /// A member's role was changed in a group.
    GroupRoleChanged {
        /// Group identifier.
        group_id: String,
        /// User ID of the member whose role changed.
        user_id: String,
        /// New role (e.g. "admin", "member").
        new_role: String,
        /// User ID of who changed the role.
        changed_by: String,
    },

    /// A group was renamed.
    GroupRenamed {
        /// Group identifier.
        group_id: String,
        /// New group name.
        new_name: String,
        /// Previous group name (if known).
        old_name: Option<String>,
        /// User ID of who renamed the group.
        renamed_by: String,
    },

    // --- Service discovery ---
    /// A service was discovered on the mesh in response to a discovery query.
    ServiceDiscovered {
        /// Query ID that triggered this discovery.
        query_id: String,
        /// Service identifier.
        service_id: String,
        /// Service version.
        version: String,
        /// Peer user ID of the provider.
        provider_peer_id: String,
        /// Service capabilities.
        capabilities: HashMap<String, String>,
        /// Number of hops from the provider.
        hop_count: u8,
    },

    /// A service request was received from another peer.
    ServiceRequestReceived {
        /// Unique request identifier.
        request_id: String,
        /// Service identifier being invoked.
        service_id: String,
        /// Method name or action.
        method: String,
        /// Request body (JSON or arbitrary string).
        body: String,
        /// Peer user ID of the requester.
        sender: String,
        /// Whether the request arrived sealed inside the 1:1 MLS session with
        /// `sender`, so no device that carried it could read the body and the
        /// session authenticated `sender`. `false` means it arrived as signed
        /// plaintext, readable by every hop (threat model R9).
        #[serde(default)]
        encrypted: bool,
    },

    /// A response to a service request was received.
    ServiceResponseReceived {
        /// Request identifier this response corresponds to.
        request_id: String,
        /// Service identifier.
        service_id: String,
        /// Status: "ok", "not_found", or "error".
        status: String,
        /// Response body.
        body: String,
        /// Peer user ID of the provider.
        provider_peer_id: String,
        /// Whether the response arrived sealed inside the 1:1 MLS session
        /// with the provider. `false` means it arrived as signed plaintext,
        /// readable by every hop (threat model R9).
        #[serde(default)]
        encrypted: bool,
    },

    // --- Presence, typing, and read receipts ---
    /// A peer's presence status was updated.
    PresenceUpdated {
        /// Peer whose presence changed.
        peer_id: String,
        /// Presence status.
        status: PresenceStatus,
        /// Timestamp of the update (Unix ms).
        timestamp: i64,
        /// When the peer was last seen (Unix ms), if the source knows it —
        /// e.g. the internet relay's PresenceStatusWithLastSeen. Absent for
        /// peer-sent `__PRESENCE__` updates.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        last_seen_ms: Option<i64>,
        /// Which channel produced this update: the internet relay's
        /// authoritative answer, or a peer-sent self-report. Always
        /// serialized; defaults to `peer` when deserializing legacy events.
        #[serde(default)]
        source: PresenceSource,
    },

    /// A typing indicator was received from a peer.
    TypingIndicatorReceived {
        /// User who is typing (or stopped typing).
        sender: String,
        /// Conversation identifier, echoed back verbatim from the sender.
        ///
        /// Opaque to the SDK — never parsed or routed on. Whatever key the
        /// sender chose (conventionally a peer address for a DM, the group
        /// id for a group) arrives here unchanged.
        conversation_id: String,
        /// Whether the user is currently typing.
        is_typing: bool,
        /// Timestamp of the indicator (Unix ms).
        timestamp: i64,
    },

    /// A read receipt was received from a peer.
    ReadReceiptReceived {
        /// User who read the messages.
        sender: String,
        /// IDs of the messages that were read.
        message_ids: Vec<String>,
        /// Timestamp when the messages were read (Unix ms).
        timestamp: i64,
    },

    // --- DORS observability (OFF-258) ---
    /// DORS scored all available transports for this decision cycle.
    DorsScoreUpdated {
        /// Transport type and score pairs (descending by score).
        scores: Vec<(String, f32)>,
    },
    /// DORS selected a transport for the current message.
    DorsTransportSelected {
        /// Previous transport (if any); provides decision boundary context.
        from: Option<String>,
        /// Selected transport.
        transport: String,
        /// Typed reason for selection (initial vs primary selected).
        reason_code: DorsReasonCode,
        /// Score of the selected transport (supplemental).
        score: f32,
    },
    /// DORS switched from one transport to another. Emitted only when active transport
    /// actually changes after a successful send.
    DorsTransportSwitched {
        /// Previous transport (if any).
        from: Option<String>,
        /// New transport (now active).
        to: String,
        /// Stable enum-backed reason for the transition.
        reason_code: DorsReasonCode,
        /// Optional human-readable context (e.g. "primary failed, fallback succeeded").
        #[serde(skip_serializing_if = "Option::is_none")]
        reason_detail: Option<String>,
    },
    /// DORS escalation from BLE to Wi‑Fi. Use `phase` to distinguish recommendation vs applied.
    DorsEscalationTriggered {
        /// TRIGGERED = DORS decided to escalate (reason = trigger); APPLIED = fallback succeeded.
        phase: DorsEscalationPhase,
        /// Transport we escalated from (e.g. "ble").
        from: String,
        /// Transport we escalated to (e.g. "wifiDirect").
        to: String,
        /// Stable enum-backed reason code.
        reason_code: DorsEscalationReasonCode,
        /// Optional human-readable context.
        #[serde(skip_serializing_if = "Option::is_none")]
        reason_detail: Option<String>,
    },

    /// A security-relevant anomaly was detected (e.g. sender spoofing, a
    /// signing key that does not derive to its claimed address, an unsigned
    /// control message).
    SecurityWarning {
        /// Peer ID involved in the warning.
        peer_id: String,
        /// Stable machine-readable classification of the warning. Branch on
        /// this rather than parsing `reason`.
        reason_code: SecurityWarningCode,
        /// Human-readable description of the security issue.
        reason: String,
    },

    /// A message was relayed (forwarded for a third party).
    MessageRelayed {
        /// ID of the relayed message.
        message_id: String,
        /// Original sender.
        sender: String,
        /// Intended recipient.
        recipient: String,
        /// Current hop count after increment.
        hop_count: u8,
        /// Remaining TTL after decrement.
        remaining_ttl: u8,
    },

    /// A user was blocked. Emitted for local UI notification only.
    UserBlocked {
        /// User ID that was blocked.
        user_id: String,
    },

    /// A user was unblocked. Emitted for local UI notification only.
    UserUnblocked {
        /// User ID that was unblocked.
        user_id: String,
    },

    /// A replicated document changed and the change reached storage.
    ///
    /// Emitted after the delta is durable, never before: an application that
    /// re-renders on this event is then rendering state that survives a
    /// crash.
    DataChanged {
        /// The space the document belongs to.
        space_id: String,
        /// The document that changed.
        doc_id: String,
        /// Size of the change that was persisted.
        delta_bytes: u64,
    },

    /// A replicated document was removed from every replica of its space.
    ///
    /// Distinct from a document merely disappearing locally: this one is a
    /// decision that travels. It fires when this device removes a document
    /// and when it learns of a removal from a peer, so an application
    /// holding the document open can close it either way.
    ///
    /// A removal loses to a concurrent edit, so a document may come back
    /// after this fires. That arrives as an ordinary `DataChanged` on a
    /// document the application thought was gone, which is the honest
    /// report: the edit won, and its contents are the contents.
    DataDocRemoved {
        /// The space the document belonged to.
        space_id: String,
        /// The document that was removed.
        doc_id: String,
        /// Who removed it: `local` for this device, `peer` for a removal
        /// learned from the space.
        by: DocRemovedBy,
    },

    /// A replicated document is approaching the per-document size cap.
    ///
    /// Fires while there is still room to act. Without it the cap would be a
    /// cliff an application meets for the first time as a failed write.
    DataDocSizeWarning {
        /// The space the document belongs to.
        space_id: String,
        /// The document approaching the cap.
        doc_id: String,
        /// Its current compacted size.
        compacted_bytes: u64,
        /// The cap it is measured against.
        cap_bytes: u64,
    },

    /// A peer asked for the bytes behind an attachment reference.
    ///
    /// The SDK does not hold blob bytes, so it cannot answer this on its
    /// own: the application either supplies them with
    /// `data_provide_attachment` or says it cannot with
    /// `data_decline_attachment`. An application that handles neither leaves
    /// the asking peer with a reference it can see and never open, which is
    /// why declining is a first-class answer rather than silence.
    DataAttachmentRequested {
        /// The space the request arrived in.
        space_id: String,
        /// The peer that asked.
        peer_id: String,
        /// Lowercase hex SHA-256 of the blob they want.
        hash: String,
    },

    /// Attachment bytes arrived and matched the hash that asked for them.
    ///
    /// The bytes are handed over rather than stored: blobs never enter
    /// protocol state, so where this file lives is the application's
    /// decision and its storage.
    DataAttachmentReceived {
        /// The space the attachment arrived in.
        space_id: String,
        /// The peer that supplied it.
        peer_id: String,
        /// Lowercase hex SHA-256 of the blob, verified against these bytes.
        hash: String,
        /// The blob, base64.
        data: String,
    },

    /// A fetch ended without bytes.
    ///
    /// Either the peer answered that it no longer holds the blob, or the
    /// transfer carrying it failed. Both are ordinary: an attachment
    /// reference outlives the bytes it names, because the reference
    /// replicates and the bytes do not.
    DataAttachmentUnavailable {
        /// The space the fetch was made in.
        space_id: String,
        /// The peer that was asked.
        peer_id: String,
        /// Lowercase hex SHA-256 that was asked for.
        hash: String,
        /// Why it ended: `declined` (the peer answered that it no longer
        /// holds the blob), `timeout`, `evicted` (displaced by newer
        /// fetches), `hash_mismatch`, `peer_gone` (the peer was blocked,
        /// forgotten, or came back without the replication capability), or a
        /// transfer
        /// failure reason. A fixed token this crate chooses, never a peer's
        /// words.
        reason: String,
    },

    /// A document cannot be replicated, in any form this protocol has.
    ///
    /// The honest report of a real dead end rather than a warning in a log
    /// nobody reads. It fires when a document is too large for a sync frame
    /// and the peer cannot carry it over the media path either, which leaves
    /// two replicas that will not converge and no further rung to try.
    DataDocUnsyncable {
        /// The space the document belongs to.
        space_id: String,
        /// The document that cannot be sent.
        doc_id: String,
        /// Size of the encoding that had nowhere to go.
        bytes: u64,
        /// Why it could not be sent.
        reason: String,
    },
}

/// Member entry in GroupInfo.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupInfoMember {
    /// User ID of the member.
    pub user_id: String,
    /// Role within the group (e.g. "admin", "member").
    pub role: String,
    /// ISO-8601 timestamp when the member joined.
    pub joined_at: String,
}

/// Group summary in UserGroups.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserGroupSummary {
    /// Group identifier.
    pub group_id: String,
    /// Human-readable group name.
    pub name: String,
    /// ISO-8601 creation timestamp.
    pub created_at: String,
}

impl Event {
    /// Creates a MessageSent event.
    pub fn message_sent(message: &Message) -> Self {
        use offline_protocol_core::MessagePriority;

        let priority = match message.priority {
            MessagePriority::Low => "low",
            MessagePriority::Medium => "medium",
            MessagePriority::High => "high",
            MessagePriority::Critical => "critical",
        };

        let forward_info = message.forwarded_from.as_ref().map(ForwardInfoEvent::from);

        Self::MessageSent {
            message_id: message.id.as_str(),
            sender: message.sender.as_str().to_string(),
            recipient: message.recipient.as_str().to_string(),
            content: message.content.clone(),
            priority: priority.to_string(),
            requires_ack: message.requires_ack,
            timestamp: message.timestamp.as_millis(),
            lamport_clock: message.lamport_clock.value(),
            forward_info,
        }
    }

    /// Creates a MessageDelivered event.
    pub fn message_delivered(
        message_id: MessageId,
        latency_ms: u64,
        hop_count: u8,
        transport: TransportType,
    ) -> Self {
        Self::MessageDelivered {
            message_id: message_id.as_str(),
            latency_ms,
            hop_count,
            transport: transport.to_string(),
        }
    }

    /// Creates a MessageFailed event.
    ///
    /// `reason` is `&'static str` for the same load-bearing reason
    /// [`Event::message_deferred`] is, and
    /// `protocol::types::classify_transport_send_error` returns one: the
    /// telemetry pipe forwards this field to the ingest verbatim, without the
    /// scrubber, because the classification taxonomy is the ingest's. A
    /// `String` parameter makes `format!("{err}")` at a call site
    /// representable, and the transport layer renders the counterparty into
    /// its own error text, so that one interpolation would ship a peer
    /// address beside identifiers the same record hashes. A static string
    /// cannot carry runtime data, which makes the mistake unrepresentable
    /// rather than merely discouraged. Callers with a classified failure pass
    /// the token; callers with a fixed condition pass its literal.
    pub fn message_failed(message_id: MessageId, reason: &'static str, retry_count: u32) -> Self {
        Self::MessageFailed {
            message_id: message_id.as_str(),
            reason: reason.to_string(),
            retry_count,
        }
    }

    /// Creates a MessageDecryptionFailed event.
    pub fn message_decryption_failed(
        message_id: MessageId,
        sender: String,
        code: DecryptionFailureCode,
        reason: String,
    ) -> Self {
        Self::MessageDecryptionFailed {
            message_id: message_id.as_str(),
            sender,
            code,
            reason,
            sealed_at_ms: None,
            session_established_at_ms: None,
        }
    }

    /// Creates a MessageDecryptionFailed event for a failed 1:1 decrypt,
    /// carrying the frame's seal time and the current session's
    /// establishment time (see the variant's fields).
    pub fn message_decryption_failed_for_frame(
        message_id: MessageId,
        sender: String,
        code: DecryptionFailureCode,
        reason: String,
        sealed_at_ms: u64,
        session_established_at_ms: Option<u64>,
    ) -> Self {
        Self::MessageDecryptionFailed {
            message_id: message_id.as_str(),
            sender,
            code,
            reason,
            sealed_at_ms: Some(sealed_at_ms),
            session_established_at_ms,
        }
    }

    /// Creates a TransportSwitched event.
    pub fn transport_switched(
        from: Option<TransportType>,
        to: TransportType,
        reason: String,
    ) -> Self {
        Self::TransportSwitched {
            from: from.map(|t| t.to_string()),
            to: to.to_string(),
            reason,
        }
    }

    /// Creates a RelayPromoted event.
    pub fn relay_promoted(connection_count: usize, battery_level: Option<u8>) -> Self {
        Self::RelayPromoted {
            connection_count,
            battery_level,
        }
    }

    /// Creates a RelayDemoted event.
    ///
    /// `&'static str` for the reason given on [`Event::message_failed`]: the
    /// telemetry pipe forwards this field raw.
    pub fn relay_demoted(reason: &'static str) -> Self {
        Self::RelayDemoted {
            reason: reason.to_string(),
        }
    }

    /// Creates a NeighborDiscovered event.
    pub fn neighbor_discovered(
        peer_id: String,
        transport: TransportType,
        rssi: Option<i16>,
    ) -> Self {
        Self::NeighborDiscovered {
            peer_id,
            transport: format!("{:?}", transport),
            rssi,
        }
    }

    /// Creates a NeighborLost event.
    pub fn neighbor_lost(peer_id: String) -> Self {
        Self::NeighborLost { peer_id }
    }

    /// Creates an IdentityReady event.
    pub fn identity_ready(address: impl Into<String>) -> Self {
        Self::IdentityReady {
            address: address.into(),
        }
    }

    /// Creates a NetworkMetrics event.
    pub fn network_metrics(
        neighbor_count: usize,
        relay_count: usize,
        delivery_ratio: f32,
        avg_latency_ms: u64,
    ) -> Self {
        Self::NetworkMetrics {
            neighbor_count,
            relay_count,
            delivery_ratio,
            avg_latency_ms,
        }
    }

    /// Creates a FileProgress event.
    pub fn file_progress(file_id: String, chunks_sent: u32, total_chunks: u32) -> Self {
        let percentage = if total_chunks > 0 {
            ((chunks_sent as f32 / total_chunks as f32) * 100.0) as u8
        } else {
            0
        };

        Self::FileProgress {
            file_id,
            chunks_sent,
            total_chunks,
            percentage,
        }
    }

    /// Creates a FileReceived event.
    #[allow(clippy::too_many_arguments)]
    pub fn file_received(
        file_id: String,
        file_name: String,
        file_size: u64,
        sender: String,
        content_type: ContentType,
        media_metadata: Option<MediaMetadata>,
        file_data: Vec<u8>,
        timestamp: Option<i64>,
        caption: Option<String>,
        reply_to_msg: Option<String>,
        reply_context: Option<&offline_protocol_core::ReplyContext>,
        forward_info: Option<&offline_protocol_core::ForwardInfo>,
        app_id: Option<String>,
    ) -> Self {
        use base64::{engine::general_purpose::STANDARD, Engine};
        Self::FileReceived {
            file_id,
            file_name,
            file_size,
            sender,
            content_type: content_type.to_string(),
            media_metadata,
            file_data: STANDARD.encode(&file_data),
            timestamp,
            caption,
            reply_to_msg,
            reply_context: reply_context.map(|rc| Box::new(ReplyContextEvent::from(rc))),
            forward_info: forward_info.map(ForwardInfoEvent::from),
            app_id,
        }
    }

    /// Creates a FileReceiveFailed event.
    pub fn file_receive_failed(
        file_id: String,
        file_name: String,
        sender: String,
        reason: String,
    ) -> Self {
        Self::FileReceiveFailed {
            file_id,
            file_name,
            sender,
            reason,
        }
    }

    /// Creates a MediaSent event.
    pub fn media_sent(file_id: String, content_type: ContentType, recipient: String) -> Self {
        Self::MediaSent {
            file_id,
            content_type: content_type.to_string(),
            recipient,
        }
    }

    /// Creates a MediaSendFailed event.
    pub fn media_send_failed(file_id: String, recipient: String, reason: String) -> Self {
        Self::MediaSendFailed {
            file_id,
            recipient,
            reason,
        }
    }

    /// Creates a MessageDeferred event.
    pub fn message_deferred(
        message_id: MessageId,
        recipient: String,
        reason: &'static str,
        retry_count: u32,
        next_retry_at: Option<i64>,
    ) -> Self {
        Self::MessageDeferred {
            message_id: message_id.as_str(),
            recipient,
            reason: reason.to_string(),
            retry_count,
            next_retry_at,
        }
    }

    /// Creates a MessageRetrying event.
    pub fn message_retrying(
        message_id: MessageId,
        recipient: String,
        retry_count: u32,
        next_retry_at: i64,
    ) -> Self {
        Self::MessageRetrying {
            message_id: message_id.as_str(),
            recipient,
            retry_count,
            next_retry_at,
        }
    }

    /// Creates a MessageUndeliverable event.
    pub fn message_undeliverable(
        message_id: MessageId,
        recipient: String,
        reason: &'static str,
        file_id: Option<String>,
    ) -> Self {
        Self::MessageUndeliverable {
            message_id: message_id.as_str(),
            recipient,
            reason: reason.to_string(),
            file_id,
        }
    }

    /// Creates a MediaResendRequired event.
    pub fn media_resend_required(
        file_id: String,
        recipient: String,
        file_name: String,
        file_size: u64,
        app_id: Option<String>,
    ) -> Self {
        Self::MediaResendRequired {
            file_id,
            recipient,
            file_name,
            file_size,
            app_id,
        }
    }

    /// Creates an AckEvicted event.
    pub fn ack_evicted(message_id: MessageId, priority: &str, reason: String) -> Self {
        Self::AckEvicted {
            message_id: message_id.as_str(),
            priority: priority.to_string(),
            reason,
        }
    }

    /// Creates a FragmentAssemblyEvicted event.
    pub fn fragment_assembly_evicted(
        message_id: String,
        completion_percent: u8,
        reason: String,
    ) -> Self {
        Self::FragmentAssemblyEvicted {
            message_id,
            completion_percent,
            reason,
        }
    }

    /// Creates a RelayDemotedBattery event.
    pub fn relay_demoted_battery(battery_level: u8, min_required: u8) -> Self {
        Self::RelayDemotedBattery {
            battery_level,
            min_required,
        }
    }

    /// Creates a SecureSessionEstablished event.
    pub fn secure_session_established(
        peer_id: String,
        group_id: String,
        is_session: bool,
        initiated_by_local: bool,
    ) -> Self {
        Self::SecureSessionEstablished {
            peer_id,
            group_id,
            is_session,
            initiated_by_local,
        }
    }

    /// Creates a SecureSessionFailed event.
    pub fn secure_session_failed(peer_id: String, reason: String) -> Self {
        Self::SecureSessionFailed { peer_id, reason }
    }

    /// Creates a ConvergenceDiag event (1:1 MLS convergence instrumentation).
    pub fn convergence_diag(stage: String, peer_id: String, detail: String) -> Self {
        Self::ConvergenceDiag {
            stage,
            peer_id,
            detail,
        }
    }

    /// Creates a WelcomeSendAttempted event.
    pub fn welcome_send_attempted(
        peer_id: String,
        message_id: String,
        group_id: String,
        attempt: u32,
    ) -> Self {
        Self::WelcomeSendAttempted {
            peer_id,
            message_id,
            group_id,
            attempt,
        }
    }

    /// Creates a WelcomeSendSucceeded event.
    pub fn welcome_send_succeeded(
        peer_id: String,
        message_id: String,
        group_id: String,
        attempt: u32,
    ) -> Self {
        Self::WelcomeSendSucceeded {
            peer_id,
            message_id,
            group_id,
            attempt,
        }
    }

    /// Creates a WelcomeSendFailed event.
    #[allow(clippy::too_many_arguments)]
    pub fn welcome_send_failed(
        peer_id: String,
        message_id: String,
        group_id: String,
        attempt: u32,
        reason_code: WelcomeReasonCode,
        transport_error: Option<&'static str>,
        retryable: bool,
        next_retry_at: Option<i64>,
    ) -> Self {
        Self::WelcomeSendFailed {
            peer_id,
            message_id,
            group_id,
            attempt,
            reason_code,
            transport_error: transport_error.map(str::to_string),
            retryable,
            next_retry_at,
        }
    }

    /// Creates a WelcomeSendExpired event.
    pub fn welcome_send_expired(
        peer_id: String,
        message_id: String,
        attempt: u32,
        reason_code: WelcomeReasonCode,
    ) -> Self {
        Self::WelcomeSendExpired {
            peer_id,
            message_id,
            attempt,
            reason_code,
        }
    }

    /// Creates a ConnectionRequestReceived event.
    pub fn connection_request_received(
        sender: String,
        sender_name: String,
        timestamp: i64,
        key_package: Option<Vec<u8>>,
        initial_message: Option<String>,
    ) -> Self {
        Self::ConnectionRequestReceived {
            sender,
            sender_name,
            timestamp,
            key_package,
            initial_message,
        }
    }

    /// Creates a ConnectionRequestUndeliverable event.
    pub fn connection_request_undeliverable(
        recipient: String,
        message_id: String,
        reason: &'static str,
    ) -> Self {
        Self::ConnectionRequestUndeliverable {
            recipient,
            message_id,
            reason: reason.to_string(),
        }
    }

    /// Creates a ConnectionAccepted event.
    pub fn connection_accepted(
        accepted_by: String,
        accepted_by_name: String,
        timestamp: i64,
        key_package: Option<Vec<u8>>,
    ) -> Self {
        Self::ConnectionAccepted {
            accepted_by,
            accepted_by_name,
            timestamp,
            key_package,
        }
    }

    /// Creates a ConnectionRejected event.
    pub fn connection_rejected(rejected_by: String) -> Self {
        Self::ConnectionRejected { rejected_by }
    }

    /// Creates a ConnectionRequestCancelled event.
    pub fn connection_request_cancelled(cancelled_by: String) -> Self {
        Self::ConnectionRequestCancelled { cancelled_by }
    }

    /// Creates a PresenceUpdated event for a peer-sent `__PRESENCE__`
    /// self-report (`source: peer`).
    pub fn presence_updated(peer_id: String, status: PresenceStatus, timestamp: i64) -> Self {
        Self::PresenceUpdated {
            peer_id,
            status,
            timestamp,
            last_seen_ms: None,
            source: PresenceSource::Peer,
        }
    }

    /// Creates a PresenceUpdated event carrying a last-seen timestamp
    /// (relay-sourced presence, `source: internet`).
    pub fn presence_updated_with_last_seen(
        peer_id: String,
        status: PresenceStatus,
        timestamp: i64,
        last_seen_ms: Option<i64>,
    ) -> Self {
        Self::presence_updated_from(
            peer_id,
            status,
            timestamp,
            last_seen_ms,
            PresenceSource::Internet,
        )
    }

    /// Creates a PresenceUpdated event for a gateway answer, naming which
    /// carrier answered.
    ///
    /// The relay is one gateway among others now, so the source is a
    /// parameter rather than a constant. It is still not free-form: a
    /// peer-sent self-report goes through [`Self::presence_updated`], which
    /// is the only way to produce `PresenceSource::Peer`, so a carrier answer
    /// can never be mislabelled as one.
    pub fn presence_updated_from(
        peer_id: String,
        status: PresenceStatus,
        timestamp: i64,
        last_seen_ms: Option<i64>,
        source: PresenceSource,
    ) -> Self {
        Self::PresenceUpdated {
            peer_id,
            status,
            timestamp,
            last_seen_ms,
            source,
        }
    }

    /// Creates a TypingIndicatorReceived event.
    pub fn typing_indicator_received(
        sender: String,
        conversation_id: String,
        is_typing: bool,
        timestamp: i64,
    ) -> Self {
        Self::TypingIndicatorReceived {
            sender,
            conversation_id,
            is_typing,
            timestamp,
        }
    }

    /// Creates a ReadReceiptReceived event.
    pub fn read_receipt_received(sender: String, message_ids: Vec<String>, timestamp: i64) -> Self {
        Self::ReadReceiptReceived {
            sender,
            message_ids,
            timestamp,
        }
    }

    /// Creates a GroupCreated event.
    pub fn group_created(group_id: String, name: String) -> Self {
        Self::GroupCreated { group_id, name }
    }

    /// Creates a GroupMessageReceived event.
    #[allow(clippy::too_many_arguments)]
    pub fn group_message_received(
        group_id: String,
        sender: String,
        content: String,
        timestamp: String,
        message_id: String,
        reply_to_msg: Option<String>,
        forward_info: Option<ForwardInfoEvent>,
        media_metadata: Option<MediaMetadata>,
        content_type: Option<String>,
    ) -> Self {
        Self::GroupMessageReceived {
            group_id,
            sender,
            content,
            timestamp,
            message_id,
            reply_to_msg,
            forward_info,
            media_metadata,
            content_type,
        }
    }

    /// Creates a GroupMemberAdded event.
    pub fn group_member_added(
        group_id: String,
        user_id: String,
        added_by: String,
        group_name: Option<String>,
        authorized: Option<bool>,
    ) -> Self {
        Self::GroupMemberAdded {
            group_id,
            user_id,
            added_by,
            group_name,
            authorized,
        }
    }

    /// Creates a GroupMemberRemoved event.
    pub fn group_member_removed(
        group_id: String,
        user_id: String,
        removed_by: String,
        authorized: Option<bool>,
    ) -> Self {
        Self::GroupMemberRemoved {
            group_id,
            user_id,
            removed_by,
            authorized,
        }
    }

    /// Creates a GroupRoleChanged event.
    pub fn group_role_changed(
        group_id: String,
        user_id: String,
        new_role: String,
        changed_by: String,
    ) -> Self {
        Self::GroupRoleChanged {
            group_id,
            user_id,
            new_role,
            changed_by,
        }
    }

    /// Creates a GroupRenamed event.
    pub fn group_renamed(
        group_id: String,
        new_name: String,
        old_name: Option<String>,
        renamed_by: String,
    ) -> Self {
        Self::GroupRenamed {
            group_id,
            new_name,
            old_name,
            renamed_by,
        }
    }

    /// Creates a GroupInfo event.
    pub fn group_info(
        group_id: String,
        name: String,
        created_by: String,
        created_at: String,
        members: Vec<GroupInfoMember>,
    ) -> Self {
        Self::GroupInfo {
            group_id,
            name,
            created_by,
            created_at,
            members,
        }
    }

    /// Creates a UserGroups event.
    pub fn user_groups(groups: Vec<UserGroupSummary>) -> Self {
        Self::UserGroups { groups }
    }

    /// Creates a GroupError event.
    ///
    /// `reason` must be a locally-minted code, never relay text — callers on
    /// the wire path get theirs from `GroupErrorPayload::classify_reason`.
    pub fn group_error(reason: String, group_id: Option<String>) -> Self {
        Self::GroupError { reason, group_id }
    }

    /// Creates a GroupRelaySyncChanged event.
    pub fn group_relay_sync_changed(group_id: String, synced: bool, reason: &str) -> Self {
        Self::GroupRelaySyncChanged {
            group_id,
            synced,
            reason: reason.to_string(),
        }
    }

    /// Creates a GroupMessageSent event.
    pub fn group_message_sent(
        group_id: String,
        message_ids: Vec<String>,
        member_count: u32,
    ) -> Self {
        Self::GroupMessageSent {
            group_id,
            message_ids,
            member_count,
        }
    }

    /// Creates a GroupMessagePartialFailure event.
    pub fn group_message_partial_failure(
        group_id: String,
        failed_members: Vec<String>,
        succeeded_members: Vec<String>,
    ) -> Self {
        Self::GroupMessagePartialFailure {
            group_id,
            failed_members,
            succeeded_members,
        }
    }

    /// Creates a GroupMessageDeliveryReport event.
    pub fn group_message_delivery_report(
        group_id: String,
        message_id: String,
        delivered: Vec<String>,
        pushed: Vec<String>,
        missed_reissued: Vec<String>,
    ) -> Self {
        Self::GroupMessageDeliveryReport {
            group_id,
            message_id,
            delivered,
            pushed,
            missed_reissued,
        }
    }

    /// Creates a GroupRichExtrasDropped event.
    pub fn group_rich_extras_dropped(group_id: String, unknown_members: Vec<String>) -> Self {
        Self::GroupRichExtrasDropped {
            group_id,
            unknown_members,
        }
    }

    /// Creates a GroupUnauthorizedMembershipChange event.
    pub fn group_unauthorized_membership_change(
        group_id: String,
        committer: String,
        added: Vec<String>,
        removed: Vec<String>,
        reason: String,
        enforced: bool,
    ) -> Self {
        Self::GroupUnauthorizedMembershipChange {
            group_id,
            committer,
            added,
            removed,
            reason,
            enforced,
        }
    }

    /// Creates a GroupEpochForkDetected event.
    pub fn group_epoch_fork_detected(group_id: String, local_epoch: Option<u64>) -> Self {
        Self::GroupEpochForkDetected {
            group_id,
            local_epoch,
        }
    }

    /// Creates a GroupEpochForkResolved event.
    pub fn group_epoch_fork_resolved(
        group_id: String,
        resolved_epoch: u64,
        failed_members: Vec<String>,
    ) -> Self {
        Self::GroupEpochForkResolved {
            group_id,
            resolved_epoch,
            failed_members,
        }
    }

    /// Creates a ServiceDiscovered event.
    pub fn service_discovered(
        query_id: String,
        service_id: String,
        version: String,
        provider_peer_id: String,
        capabilities: HashMap<String, String>,
        hop_count: u8,
    ) -> Self {
        Self::ServiceDiscovered {
            query_id,
            service_id,
            version,
            provider_peer_id,
            capabilities,
            hop_count,
        }
    }

    /// Creates a ServiceRequestReceived event for a request that arrived as
    /// signed plaintext (`encrypted: false`).
    pub fn service_request_received(
        request_id: String,
        service_id: String,
        method: String,
        body: String,
        sender: String,
    ) -> Self {
        Self::ServiceRequestReceived {
            request_id,
            service_id,
            method,
            body,
            sender,
            encrypted: false,
        }
    }

    /// Creates a ServiceResponseReceived event for a response that arrived as
    /// signed plaintext (`encrypted: false`).
    pub fn service_response_received(
        request_id: String,
        service_id: String,
        status: String,
        body: String,
        provider_peer_id: String,
    ) -> Self {
        Self::ServiceResponseReceived {
            request_id,
            service_id,
            status,
            body,
            provider_peer_id,
            encrypted: false,
        }
    }

    /// Creates a DorsScoreUpdated event (DORS observability).
    pub fn dors_score_updated(scores: Vec<(String, f32)>) -> Self {
        Self::DorsScoreUpdated { scores }
    }

    /// Creates a DorsTransportSelected event (DORS observability).
    pub fn dors_transport_selected(
        from: Option<String>,
        transport: String,
        reason_code: DorsReasonCode,
        score: f32,
    ) -> Self {
        Self::DorsTransportSelected {
            from,
            transport,
            reason_code,
            score,
        }
    }

    /// Creates a DorsTransportSwitched event (DORS observability).
    /// Emitted only when active transport actually changes after a successful send.
    pub fn dors_transport_switched(
        from: Option<String>,
        to: String,
        reason_code: DorsReasonCode,
        reason_detail: Option<String>,
    ) -> Self {
        Self::DorsTransportSwitched {
            from,
            to,
            reason_code,
            reason_detail,
        }
    }

    /// Creates a DorsEscalationTriggered event (DORS observability).
    /// Use phase Triggered at the DORS trigger boundary, Applied when fallback succeeds.
    pub fn dors_escalation_triggered(
        phase: DorsEscalationPhase,
        from: String,
        to: String,
        reason_code: DorsEscalationReasonCode,
        reason_detail: Option<String>,
    ) -> Self {
        Self::DorsEscalationTriggered {
            phase,
            from,
            to,
            reason_code,
            reason_detail,
        }
    }

    /// Creates a SecurityWarning event.
    pub fn security_warning(
        peer_id: String,
        reason_code: SecurityWarningCode,
        reason: String,
    ) -> Self {
        Self::SecurityWarning {
            peer_id,
            reason_code,
            reason,
        }
    }

    /// Creates a MessageRelayed event.
    pub fn message_relayed(
        message_id: String,
        sender: String,
        recipient: String,
        hop_count: u8,
        remaining_ttl: u8,
    ) -> Self {
        Self::MessageRelayed {
            message_id,
            sender,
            recipient,
            hop_count,
            remaining_ttl,
        }
    }

    /// Creates a UserBlocked event.
    pub fn user_blocked(user_id: String) -> Self {
        Self::UserBlocked { user_id }
    }

    /// Creates a UserUnblocked event.
    pub fn user_unblocked(user_id: String) -> Self {
        Self::UserUnblocked { user_id }
    }

    /// Converts the event to JSON.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }

    /// Parses an event from JSON.
    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        serde_json::from_str(json)
    }

    /// Returns the stable `snake.dot.case` telemetry name for this event.
    ///
    /// Names are compatible with OpenTelemetry naming conventions and are
    /// considered stable across minor versions of the SDK.
    pub fn telemetry_name(&self) -> &'static str {
        match self {
            Self::MessageSent { .. } => "protocol.message.sent",
            Self::MessageReceived { .. } => "protocol.message.received",
            Self::MessageDelivered { .. } => "protocol.message.delivered",
            Self::MessageFailed { .. } => "protocol.message.failed",
            Self::MessageDecryptionFailed { .. } => "protocol.message.decryption_failed",
            Self::TransportSwitched { .. } => "protocol.transport.switched",
            Self::RelayPromoted { .. } => "protocol.relay.promoted",
            Self::RelayDemoted { .. } => "protocol.relay.demoted",
            Self::NeighborDiscovered { .. } => "protocol.neighbor.discovered",
            Self::NeighborLost { .. } => "protocol.neighbor.lost",
            Self::IdentityReady { .. } => "protocol.identity.ready",
            Self::NetworkMetrics { .. } => "protocol.network.metrics",
            Self::FileProgress { .. } => "protocol.file.progress",
            Self::FileReceived { .. } => "protocol.file.received",
            Self::FileReceiveFailed { .. } => "protocol.file.receive_failed",
            Self::MediaSent { .. } => "protocol.media.sent",
            Self::MediaSendFailed { .. } => "protocol.media.send_failed",
            Self::MessageDeferred { .. } => "protocol.message.deferred",
            Self::MessageRetrying { .. } => "protocol.message.retrying",
            Self::MessageUndeliverable { .. } => "protocol.message.undeliverable",
            Self::MediaResendRequired { .. } => "protocol.media.resend_required",
            Self::AckEvicted { .. } => "protocol.ack.evicted",
            Self::FragmentAssemblyEvicted { .. } => "protocol.fragment.assembly_evicted",
            Self::RelayDemotedBattery { .. } => "protocol.relay.demoted_battery",
            Self::SecureSessionEstablished { .. } => "protocol.secure_session.established",
            Self::SecureSessionFailed { .. } => "protocol.secure_session.failed",
            Self::ConvergenceDiag { .. } => "protocol.convergence.diag",
            Self::WelcomeSendAttempted { .. } => "protocol.welcome.send_attempted",
            Self::WelcomeSendSucceeded { .. } => "protocol.welcome.send_succeeded",
            Self::WelcomeSendFailed { .. } => "protocol.welcome.send_failed",
            Self::WelcomeSendExpired { .. } => "protocol.welcome.send_expired",
            Self::ConnectionRequestReceived { .. } => "protocol.connection.request_received",
            Self::ConnectionRequestUndeliverable { .. } => {
                "protocol.connection.request_undeliverable"
            }
            Self::ConnectionAccepted { .. } => "protocol.connection.accepted",
            Self::ConnectionRejected { .. } => "protocol.connection.rejected",
            Self::ConnectionRequestCancelled { .. } => "protocol.connection.request_cancelled",
            Self::GroupCreated { .. } => "protocol.group.created",
            Self::GroupMessageReceived { .. } => "protocol.group.message_received",
            Self::GroupMemberAdded { .. } => "protocol.group.member_added",
            Self::GroupMemberRemoved { .. } => "protocol.group.member_removed",
            Self::GroupInfo { .. } => "protocol.group.info",
            Self::UserGroups { .. } => "protocol.group.user_groups",
            Self::GroupError { .. } => "protocol.group.error",
            Self::GroupRelaySyncChanged { .. } => "protocol.group.relay_sync_changed",
            Self::UsernameResolved { .. } => "protocol.username.resolved",
            Self::GroupMessageSent { .. } => "protocol.group.message_sent",
            Self::GroupMessagePartialFailure { .. } => "protocol.group.message_partial_failure",
            Self::GroupMessageDeliveryReport { .. } => "protocol.group.delivery_report",
            Self::GroupRichExtrasDropped { .. } => "protocol.group.rich_extras_dropped",
            Self::GroupUnauthorizedMembershipChange { .. } => {
                "protocol.group.unauthorized_membership_change"
            }
            Self::GroupEpochForkDetected { .. } => "protocol.group.epoch_fork_detected",
            Self::GroupEpochForkResolved { .. } => "protocol.group.epoch_fork_resolved",
            Self::GroupRoleChanged { .. } => "protocol.group.role_changed",
            Self::GroupRenamed { .. } => "protocol.group.renamed",
            Self::ServiceDiscovered { .. } => "protocol.service.discovered",
            Self::ServiceRequestReceived { .. } => "protocol.service.request_received",
            Self::ServiceResponseReceived { .. } => "protocol.service.response_received",
            Self::PresenceUpdated { .. } => "protocol.presence.updated",
            Self::TypingIndicatorReceived { .. } => "protocol.typing.received",
            Self::ReadReceiptReceived { .. } => "protocol.read_receipt.received",
            Self::DorsScoreUpdated { .. } => "protocol.dors.score_updated",
            Self::DorsTransportSelected { .. } => "protocol.dors.transport_selected",
            Self::DorsTransportSwitched { .. } => "protocol.dors.transport_switched",
            Self::DorsEscalationTriggered { .. } => "protocol.dors.escalation_triggered",
            Self::SecurityWarning { .. } => "protocol.security.warning",
            Self::MessageRelayed { .. } => "protocol.message.relayed",
            Self::UserBlocked { .. } => "protocol.user.blocked",
            Self::UserUnblocked { .. } => "protocol.user.unblocked",
            Self::DataChanged { .. } => "protocol.data.changed",
            Self::DataDocRemoved { .. } => "protocol.data.doc_removed",
            Self::DataDocSizeWarning { .. } => "protocol.data.doc_size_warning",
            Self::DataAttachmentRequested { .. } => "protocol.data.attachment_requested",
            Self::DataAttachmentReceived { .. } => "protocol.data.attachment_received",
            Self::DataAttachmentUnavailable { .. } => "protocol.data.attachment_unavailable",
            Self::DataDocUnsyncable { .. } => "protocol.data.doc_unsyncable",
        }
    }
}

impl From<ServiceEvent> for Event {
    fn from(event: ServiceEvent) -> Self {
        match event {
            ServiceEvent::ServiceDiscovered {
                query_id,
                service_id,
                version,
                provider_peer_id,
                capabilities,
                hop_count,
            } => Self::ServiceDiscovered {
                query_id,
                service_id,
                version,
                provider_peer_id,
                capabilities,
                hop_count,
            },
            ServiceEvent::ServiceRequestReceived {
                request_id,
                service_id,
                method,
                body,
                sender,
            } => Self::ServiceRequestReceived {
                request_id,
                service_id,
                method,
                body,
                sender,
                // The service layer cannot know; the engine sets it for a
                // frame that arrived sealed (`handle_service_message`).
                encrypted: false,
            },
            ServiceEvent::ServiceResponseReceived {
                request_id,
                service_id,
                status,
                body,
                provider_peer_id,
            } => Self::ServiceResponseReceived {
                request_id,
                service_id,
                status,
                body,
                provider_peer_id,
                encrypted: false,
            },
        }
    }
}

/// Custom Debug implementation that redacts sensitive fields to prevent
/// accidental logging of message content and other potentially sensitive data.
impl fmt::Debug for Event {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MessageSent {
                message_id,
                sender: _,
                recipient: _,
                content,
                priority,
                requires_ack,
                timestamp,
                lamport_clock,
                forward_info,
            } => f
                .debug_struct("MessageSent")
                .field("message_id", message_id)
                .field("sender", &"[REDACTED]")
                .field("recipient", &"[REDACTED]")
                .field("content", &format!("[REDACTED {} bytes]", content.len()))
                .field("priority", priority)
                .field("requires_ack", requires_ack)
                .field("timestamp", timestamp)
                .field("lamport_clock", lamport_clock)
                .field("forward_info", &forward_info.is_some())
                .finish(),
            Self::MessageReceived {
                message_id,
                sender: _,
                recipient: _,
                content,
                hop_count,
                transport,
                timestamp,
                lamport_clock,
                reply_to_msg: _,
                reply_context,
                content_type,
                media_metadata: _,
                forward_info,
                encrypted,
                app_id,
            } => f
                .debug_struct("MessageReceived")
                .field("message_id", message_id)
                .field("sender", &"[REDACTED]")
                .field("recipient", &"[REDACTED]")
                .field("content", &format!("[REDACTED {} bytes]", content.len()))
                .field("hop_count", hop_count)
                .field("transport", transport)
                .field("timestamp", timestamp)
                .field("lamport_clock", lamport_clock)
                .field("reply_to_msg", &"[REDACTED]")
                .field("reply_context", &reply_context.is_some())
                .field("content_type", content_type)
                .field("forward_info", &forward_info.is_some())
                .field("encrypted", encrypted)
                .field("app_id", app_id)
                .finish(),
            Self::MessageDelivered {
                message_id,
                latency_ms,
                hop_count,
                transport,
            } => f
                .debug_struct("MessageDelivered")
                .field("message_id", message_id)
                .field("latency_ms", latency_ms)
                .field("hop_count", hop_count)
                .field("transport", transport)
                .finish(),
            Self::MessageFailed {
                message_id,
                reason,
                retry_count,
            } => f
                .debug_struct("MessageFailed")
                .field("message_id", message_id)
                .field("reason", reason)
                .field("retry_count", retry_count)
                .finish(),
            Self::MessageDecryptionFailed {
                message_id,
                sender: _,
                code,
                reason,
                sealed_at_ms,
                session_established_at_ms,
            } => f
                .debug_struct("MessageDecryptionFailed")
                .field("message_id", message_id)
                .field("sender", &"[REDACTED]")
                .field("code", code)
                .field("reason", reason)
                .field("sealed_at_ms", sealed_at_ms)
                .field("session_established_at_ms", session_established_at_ms)
                .finish(),
            Self::TransportSwitched { from, to, reason } => f
                .debug_struct("TransportSwitched")
                .field("from", from)
                .field("to", to)
                .field("reason", reason)
                .finish(),
            Self::RelayPromoted {
                connection_count,
                battery_level,
            } => f
                .debug_struct("RelayPromoted")
                .field("connection_count", connection_count)
                .field("battery_level", battery_level)
                .finish(),
            Self::RelayDemoted { reason } => f
                .debug_struct("RelayDemoted")
                .field("reason", reason)
                .finish(),
            Self::NeighborDiscovered {
                peer_id: _,
                transport,
                rssi,
            } => f
                .debug_struct("NeighborDiscovered")
                .field("peer_id", &"[REDACTED]")
                .field("transport", transport)
                .field("rssi", rssi)
                .finish(),
            Self::NeighborLost { peer_id: _ } => f
                .debug_struct("NeighborLost")
                .field("peer_id", &"[REDACTED]")
                .finish(),
            // Redacted like any other identifier: this one names *this* device,
            // which is the strongest correlator a log can carry.
            Self::IdentityReady { address: _ } => f
                .debug_struct("IdentityReady")
                .field("address", &"[REDACTED]")
                .finish(),
            Self::NetworkMetrics {
                neighbor_count,
                relay_count,
                delivery_ratio,
                avg_latency_ms,
            } => f
                .debug_struct("NetworkMetrics")
                .field("neighbor_count", neighbor_count)
                .field("relay_count", relay_count)
                .field("delivery_ratio", delivery_ratio)
                .field("avg_latency_ms", avg_latency_ms)
                .finish(),
            Self::FileProgress {
                file_id,
                chunks_sent,
                total_chunks,
                percentage,
            } => f
                .debug_struct("FileProgress")
                .field("file_id", file_id)
                .field("chunks_sent", chunks_sent)
                .field("total_chunks", total_chunks)
                .field("percentage", percentage)
                .finish(),
            Self::FileReceived {
                file_id,
                file_name,
                file_size,
                sender: _,
                content_type,
                media_metadata: _,
                file_data,
                timestamp,
                caption,
                reply_to_msg: _,
                reply_context,
                forward_info,
                app_id,
            } => f
                .debug_struct("FileReceived")
                .field("file_id", file_id)
                .field("file_name", file_name)
                .field("file_size", file_size)
                .field("sender", &"[REDACTED]")
                .field("content_type", content_type)
                .field("file_data", &format!("[{} bytes base64]", file_data.len()))
                .field("timestamp", timestamp)
                .field("caption", &caption.is_some())
                .field("reply_to_msg", &"[REDACTED]")
                .field("reply_context", &reply_context.is_some())
                .field("forward_info", &forward_info.is_some())
                .field("app_id", app_id)
                .finish(),
            Self::FileReceiveFailed {
                file_id,
                file_name,
                sender: _,
                reason,
            } => f
                .debug_struct("FileReceiveFailed")
                .field("file_id", file_id)
                .field("file_name", file_name)
                .field("sender", &"[REDACTED]")
                .field("reason", reason)
                .finish(),
            Self::MediaSent {
                file_id,
                content_type,
                recipient: _,
            } => f
                .debug_struct("MediaSent")
                .field("file_id", file_id)
                .field("content_type", content_type)
                .field("recipient", &"[REDACTED]")
                .finish(),
            Self::MediaSendFailed {
                file_id,
                recipient: _,
                reason,
            } => f
                .debug_struct("MediaSendFailed")
                .field("file_id", file_id)
                .field("recipient", &"[REDACTED]")
                .field("reason", reason)
                .finish(),
            Self::MessageDeferred {
                message_id,
                recipient: _,
                reason,
                retry_count,
                next_retry_at,
            } => f
                .debug_struct("MessageDeferred")
                .field("message_id", message_id)
                .field("recipient", &"[REDACTED]")
                .field("reason", reason)
                .field("retry_count", retry_count)
                .field("next_retry_at", next_retry_at)
                .finish(),
            Self::MessageRetrying {
                message_id,
                recipient: _,
                retry_count,
                next_retry_at,
            } => f
                .debug_struct("MessageRetrying")
                .field("message_id", message_id)
                .field("recipient", &"[REDACTED]")
                .field("retry_count", retry_count)
                .field("next_retry_at", next_retry_at)
                .finish(),
            Self::MessageUndeliverable {
                message_id,
                recipient: _,
                reason,
                file_id,
            } => f
                .debug_struct("MessageUndeliverable")
                .field("message_id", message_id)
                .field("recipient", &"[REDACTED]")
                .field("reason", reason)
                .field("file_id", file_id)
                .finish(),
            Self::MediaResendRequired {
                file_id,
                recipient: _,
                file_name,
                file_size,
                app_id,
            } => f
                .debug_struct("MediaResendRequired")
                .field("file_id", file_id)
                .field("recipient", &"[REDACTED]")
                .field("file_name", file_name)
                .field("file_size", file_size)
                .field("app_id", app_id)
                .finish(),
            Self::AckEvicted {
                message_id,
                priority,
                reason,
            } => f
                .debug_struct("AckEvicted")
                .field("message_id", message_id)
                .field("priority", priority)
                .field("reason", reason)
                .finish(),
            Self::FragmentAssemblyEvicted {
                message_id,
                completion_percent,
                reason,
            } => f
                .debug_struct("FragmentAssemblyEvicted")
                .field("message_id", message_id)
                .field("completion_percent", completion_percent)
                .field("reason", reason)
                .finish(),
            Self::RelayDemotedBattery {
                battery_level,
                min_required,
            } => f
                .debug_struct("RelayDemotedBattery")
                .field("battery_level", battery_level)
                .field("min_required", min_required)
                .finish(),
            Self::SecureSessionEstablished {
                peer_id: _,
                group_id,
                is_session,
                initiated_by_local,
            } => f
                .debug_struct("SecureSessionEstablished")
                .field("peer_id", &"[REDACTED]")
                .field("group_id", group_id)
                .field("is_session", is_session)
                .field("initiated_by_local", initiated_by_local)
                .finish(),
            Self::SecureSessionFailed { peer_id: _, reason } => f
                .debug_struct("SecureSessionFailed")
                .field("peer_id", &"[REDACTED]")
                .field("reason", reason)
                .finish(),
            Self::ConvergenceDiag {
                stage,
                peer_id: _,
                detail,
            } => f
                .debug_struct("ConvergenceDiag")
                .field("stage", stage)
                .field("peer_id", &"[REDACTED]")
                .field("detail", detail)
                .finish(),
            Self::WelcomeSendAttempted {
                peer_id: _,
                message_id,
                group_id,
                attempt,
            } => f
                .debug_struct("WelcomeSendAttempted")
                .field("peer_id", &"[REDACTED]")
                .field("message_id", message_id)
                .field("group_id", group_id)
                .field("attempt", attempt)
                .finish(),
            Self::WelcomeSendSucceeded {
                peer_id: _,
                message_id,
                group_id,
                attempt,
            } => f
                .debug_struct("WelcomeSendSucceeded")
                .field("peer_id", &"[REDACTED]")
                .field("message_id", message_id)
                .field("group_id", group_id)
                .field("attempt", attempt)
                .finish(),
            Self::WelcomeSendFailed {
                peer_id: _,
                message_id,
                group_id,
                attempt,
                reason_code,
                transport_error,
                retryable,
                next_retry_at,
            } => f
                .debug_struct("WelcomeSendFailed")
                .field("peer_id", &"[REDACTED]")
                .field("message_id", message_id)
                .field("group_id", group_id)
                .field("attempt", attempt)
                .field("reason_code", reason_code)
                .field("transport_error", transport_error)
                .field("retryable", retryable)
                .field("next_retry_at", next_retry_at)
                .finish(),
            Self::WelcomeSendExpired {
                peer_id: _,
                message_id,
                attempt,
                reason_code,
            } => f
                .debug_struct("WelcomeSendExpired")
                .field("peer_id", &"[REDACTED]")
                .field("message_id", message_id)
                .field("attempt", attempt)
                .field("reason_code", reason_code)
                .finish(),
            Self::ConnectionRequestReceived {
                sender: _,
                sender_name: _,
                timestamp,
                key_package,
                initial_message,
            } => f
                .debug_struct("ConnectionRequestReceived")
                .field("sender", &"[REDACTED]")
                .field("sender_name", &"[REDACTED]")
                .field("timestamp", timestamp)
                .field("has_key_package", &key_package.is_some())
                .field("has_initial_message", &initial_message.is_some())
                .finish(),
            Self::ConnectionRequestUndeliverable {
                recipient: _,
                message_id,
                reason,
            } => f
                .debug_struct("ConnectionRequestUndeliverable")
                .field("recipient", &"[REDACTED]")
                .field("message_id", message_id)
                .field("reason", reason)
                .finish(),
            Self::ConnectionAccepted {
                accepted_by: _,
                accepted_by_name: _,
                timestamp,
                key_package,
            } => f
                .debug_struct("ConnectionAccepted")
                .field("accepted_by", &"[REDACTED]")
                .field("accepted_by_name", &"[REDACTED]")
                .field("timestamp", timestamp)
                .field("has_key_package", &key_package.is_some())
                .finish(),
            Self::ConnectionRejected { rejected_by: _ } => f
                .debug_struct("ConnectionRejected")
                .field("rejected_by", &"[REDACTED]")
                .finish(),
            Self::ConnectionRequestCancelled { cancelled_by: _ } => f
                .debug_struct("ConnectionRequestCancelled")
                .field("cancelled_by", &"[REDACTED]")
                .finish(),
            Self::ServiceDiscovered {
                query_id,
                service_id,
                version,
                provider_peer_id: _,
                capabilities,
                hop_count,
            } => f
                .debug_struct("ServiceDiscovered")
                .field("query_id", query_id)
                .field("service_id", service_id)
                .field("version", version)
                .field("provider_peer_id", &"[REDACTED]")
                .field("capabilities_count", &capabilities.len())
                .field("hop_count", hop_count)
                .finish(),
            Self::ServiceRequestReceived {
                request_id,
                service_id,
                method,
                body,
                sender: _,
                encrypted,
            } => f
                .debug_struct("ServiceRequestReceived")
                .field("request_id", request_id)
                .field("service_id", service_id)
                .field("method", method)
                .field("body", &format!("[REDACTED {} bytes]", body.len()))
                .field("sender", &"[REDACTED]")
                .field("encrypted", encrypted)
                .finish(),
            Self::ServiceResponseReceived {
                request_id,
                service_id,
                status,
                body,
                provider_peer_id: _,
                encrypted,
            } => f
                .debug_struct("ServiceResponseReceived")
                .field("request_id", request_id)
                .field("service_id", service_id)
                .field("status", status)
                .field("body", &format!("[REDACTED {} bytes]", body.len()))
                .field("provider_peer_id", &"[REDACTED]")
                .field("encrypted", encrypted)
                .finish(),
            Self::GroupCreated { group_id, name } => f
                .debug_struct("GroupCreated")
                .field("group_id", group_id)
                .field("name", name)
                .finish(),
            Self::GroupMessageReceived {
                group_id,
                sender: _,
                content,
                forward_info,
                ..
            } => f
                .debug_struct("GroupMessageReceived")
                .field("group_id", group_id)
                .field("sender", &"[REDACTED]")
                .field("content", &format!("[REDACTED {} bytes]", content.len()))
                .field("forward_info", &forward_info.is_some())
                .finish(),
            Self::GroupMemberAdded {
                group_id,
                user_id: _,
                added_by: _,
                group_name,
                authorized,
            } => f
                .debug_struct("GroupMemberAdded")
                .field("group_id", group_id)
                .field("user_id", &"[REDACTED]")
                .field("added_by", &"[REDACTED]")
                .field("group_name", group_name)
                .field("authorized", authorized)
                .finish(),
            Self::GroupMemberRemoved {
                group_id,
                user_id: _,
                removed_by: _,
                authorized,
            } => f
                .debug_struct("GroupMemberRemoved")
                .field("group_id", group_id)
                .field("user_id", &"[REDACTED]")
                .field("removed_by", &"[REDACTED]")
                .field("authorized", authorized)
                .finish(),
            Self::GroupInfo {
                group_id,
                name,
                created_by: _,
                created_at,
                members,
            } => f
                .debug_struct("GroupInfo")
                .field("group_id", group_id)
                .field("name", name)
                .field("created_by", &"[REDACTED]")
                .field("created_at", created_at)
                .field("members_count", &members.len())
                .finish(),
            Self::UserGroups { groups } => f
                .debug_struct("UserGroups")
                .field("groups_count", &groups.len())
                .finish(),
            Self::GroupError { reason, group_id } => f
                .debug_struct("GroupError")
                .field("reason", reason)
                .field("group_id", group_id)
                .finish(),
            Self::GroupRelaySyncChanged {
                group_id,
                synced,
                reason,
            } => f
                .debug_struct("GroupRelaySyncChanged")
                .field("group_id", group_id)
                .field("synced", synced)
                .field("reason", reason)
                .finish(),
            // The username is redacted: it is a human-readable name for a
            // person, which is exactly the class of identifier this Debug
            // exists to keep out of logs. The counts say everything a reader
            // debugging a resolution needs.
            Self::UsernameResolved {
                username: _,
                claims,
                rejected,
                truncated,
            } => f
                .debug_struct("UsernameResolved")
                .field("username", &"<redacted>")
                .field("claim_count", &claims.len())
                .field("rejected", rejected)
                .field("truncated", truncated)
                .finish(),
            Self::GroupMessageSent {
                group_id,
                message_ids,
                member_count,
            } => f
                .debug_struct("GroupMessageSent")
                .field("group_id", group_id)
                .field("message_count", &message_ids.len())
                .field("member_count", member_count)
                .finish(),
            Self::GroupMessagePartialFailure {
                group_id,
                failed_members,
                succeeded_members,
            } => f
                .debug_struct("GroupMessagePartialFailure")
                .field("group_id", group_id)
                .field("failed_count", &failed_members.len())
                .field("succeeded_count", &succeeded_members.len())
                .finish(),
            Self::GroupMessageDeliveryReport {
                group_id,
                message_id,
                delivered,
                pushed,
                missed_reissued,
            } => f
                .debug_struct("GroupMessageDeliveryReport")
                .field("group_id", group_id)
                .field("message_id", message_id)
                .field("delivered_count", &delivered.len())
                .field("pushed_count", &pushed.len())
                .field("missed_reissued_count", &missed_reissued.len())
                .finish(),
            Self::GroupRichExtrasDropped {
                group_id,
                unknown_members,
            } => f
                .debug_struct("GroupRichExtrasDropped")
                .field("group_id", group_id)
                .field("unknown_count", &unknown_members.len())
                .finish(),
            Self::GroupUnauthorizedMembershipChange {
                group_id,
                committer: _,
                added,
                removed,
                reason,
                enforced,
            } => f
                .debug_struct("GroupUnauthorizedMembershipChange")
                .field("group_id", group_id)
                .field("committer", &"[REDACTED]")
                .field("added_count", &added.len())
                .field("removed_count", &removed.len())
                .field("reason", reason)
                .field("enforced", enforced)
                .finish(),
            Self::GroupEpochForkDetected {
                group_id,
                local_epoch,
            } => f
                .debug_struct("GroupEpochForkDetected")
                .field("group_id", group_id)
                .field("local_epoch", local_epoch)
                .finish(),
            Self::GroupEpochForkResolved {
                group_id,
                resolved_epoch,
                failed_members,
            } => f
                .debug_struct("GroupEpochForkResolved")
                .field("group_id", group_id)
                .field("resolved_epoch", resolved_epoch)
                .field("failed_members", failed_members)
                .finish(),
            Self::PresenceUpdated {
                peer_id: _,
                status,
                timestamp,
                last_seen_ms,
                source,
            } => f
                .debug_struct("PresenceUpdated")
                .field("peer_id", &"[REDACTED]")
                .field("status", status)
                .field("timestamp", timestamp)
                .field("last_seen_ms", last_seen_ms)
                .field("source", source)
                .finish(),
            Self::TypingIndicatorReceived {
                sender: _,
                conversation_id: _,
                is_typing,
                timestamp,
            } => f
                .debug_struct("TypingIndicatorReceived")
                .field("sender", &"[REDACTED]")
                .field("conversation_id", &"[REDACTED]")
                .field("is_typing", is_typing)
                .field("timestamp", timestamp)
                .finish(),
            Self::ReadReceiptReceived {
                sender: _,
                message_ids,
                timestamp,
            } => f
                .debug_struct("ReadReceiptReceived")
                .field("sender", &"[REDACTED]")
                .field("message_count", &message_ids.len())
                .field("timestamp", timestamp)
                .finish(),
            Self::DorsScoreUpdated { scores } => f
                .debug_struct("DorsScoreUpdated")
                .field("scores", scores)
                .finish(),
            Self::DorsTransportSelected {
                from,
                transport,
                reason_code,
                score,
            } => f
                .debug_struct("DorsTransportSelected")
                .field("from", from)
                .field("transport", transport)
                .field("reason_code", reason_code)
                .field("score", score)
                .finish(),
            Self::DorsTransportSwitched {
                from,
                to,
                reason_code,
                reason_detail,
            } => f
                .debug_struct("DorsTransportSwitched")
                .field("from", from)
                .field("to", to)
                .field("reason_code", reason_code)
                .field("reason_detail", reason_detail)
                .finish(),
            Self::DorsEscalationTriggered {
                phase,
                from,
                to,
                reason_code,
                reason_detail,
            } => f
                .debug_struct("DorsEscalationTriggered")
                .field("phase", phase)
                .field("from", from)
                .field("to", to)
                .field("reason_code", reason_code)
                .field("reason_detail", reason_detail)
                .finish(),
            // The one arm that used to print `peer_id` verbatim, and the worst
            // one to: a security warning is precisely the event an operator
            // dumps into a log while investigating, and the peer it names is
            // usually attacker-controlled — an injected frame carries whatever
            // sender it likes, so this field doubles as a log-injection
            // surface. The telemetry scrubber already hashed it; only `{:?}`
            // disagreed.
            Self::SecurityWarning {
                peer_id: _,
                reason_code,
                reason,
            } => f
                .debug_struct("SecurityWarning")
                .field("peer_id", &"[REDACTED]")
                .field("reason_code", reason_code)
                .field("reason", reason)
                .finish(),
            Self::MessageRelayed {
                message_id,
                sender: _,
                recipient: _,
                hop_count,
                remaining_ttl,
            } => f
                .debug_struct("MessageRelayed")
                .field("message_id", message_id)
                .field("sender", &"[REDACTED]")
                .field("recipient", &"[REDACTED]")
                .field("hop_count", hop_count)
                .field("remaining_ttl", remaining_ttl)
                .finish(),
            Self::UserBlocked { user_id: _ } => f
                .debug_struct("UserBlocked")
                .field("user_id", &"[REDACTED]")
                .finish(),
            Self::UserUnblocked { user_id: _ } => f
                .debug_struct("UserUnblocked")
                .field("user_id", &"[REDACTED]")
                .finish(),
            Self::DataChanged {
                space_id: _,
                doc_id: _,
                delta_bytes,
            } => f
                .debug_struct("DataChanged")
                // A space id is the peer or group the space rides on, and a
                // document name is application content. Both are identifiers,
                // so both redact.
                .field("space_id", &"[REDACTED]")
                .field("doc_id", &"[REDACTED]")
                .field("delta_bytes", delta_bytes)
                .finish(),
            Self::DataDocRemoved {
                space_id: _,
                doc_id: _,
                by,
            } => f
                .debug_struct("DataDocRemoved")
                .field("space_id", &"[REDACTED]")
                .field("doc_id", &"[REDACTED]")
                // A fixed token this crate chooses, never a peer's words.
                .field("by", by)
                .finish(),
            Self::DataDocSizeWarning {
                space_id: _,
                doc_id: _,
                compacted_bytes,
                cap_bytes,
            } => f
                .debug_struct("DataDocSizeWarning")
                .field("space_id", &"[REDACTED]")
                .field("doc_id", &"[REDACTED]")
                .field("compacted_bytes", compacted_bytes)
                .field("cap_bytes", cap_bytes)
                .finish(),
            Self::DataAttachmentRequested {
                space_id: _,
                peer_id: _,
                hash,
            } => f
                .debug_struct("DataAttachmentRequested")
                .field("space_id", &"[REDACTED]")
                .field("peer_id", &"[REDACTED]")
                // A blob hash names bytes, not a person, and it is the one
                // field that makes a report about a fetch actionable.
                .field("hash", hash)
                .finish(),
            Self::DataAttachmentReceived {
                space_id: _,
                peer_id: _,
                hash,
                data,
            } => f
                .debug_struct("DataAttachmentReceived")
                .field("space_id", &"[REDACTED]")
                .field("peer_id", &"[REDACTED]")
                .field("hash", hash)
                // The blob itself is content and never goes near a log.
                .field("data", &format!("[{} base64 chars]", data.len()))
                .finish(),
            Self::DataAttachmentUnavailable {
                space_id: _,
                peer_id: _,
                hash,
                reason,
            } => f
                .debug_struct("DataAttachmentUnavailable")
                .field("space_id", &"[REDACTED]")
                .field("peer_id", &"[REDACTED]")
                .field("hash", hash)
                .field("reason", reason)
                .finish(),
            Self::DataDocUnsyncable {
                space_id: _,
                doc_id: _,
                bytes,
                reason,
            } => f
                .debug_struct("DataDocUnsyncable")
                .field("space_id", &"[REDACTED]")
                .field("doc_id", &"[REDACTED]")
                .field("bytes", bytes)
                .field("reason", reason)
                .finish(),
            Self::GroupRoleChanged {
                group_id,
                user_id: _,
                new_role,
                changed_by: _,
            } => f
                .debug_struct("GroupRoleChanged")
                .field("group_id", group_id)
                .field("user_id", &"[REDACTED]")
                .field("new_role", new_role)
                .field("changed_by", &"[REDACTED]")
                .finish(),
            Self::GroupRenamed {
                group_id,
                new_name,
                old_name: _,
                renamed_by: _,
            } => f
                .debug_struct("GroupRenamed")
                .field("group_id", group_id)
                .field("new_name", new_name)
                .field("renamed_by", &"[REDACTED]")
                .finish(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::protocol::SEND_FAIL_REASON_RECIPIENT_UNREACHABLE;
    use offline_protocol_core::{AppId, Message, MessagePriority, UserId};

    #[test]
    fn test_message_sent_event() {
        let message = Message::builder(
            UserId::new("alice").unwrap(),
            UserId::new("bob").unwrap(),
            AppId::new("app").unwrap(),
        )
        .content("Hello")
        .priority(MessagePriority::High)
        .build();

        let event = Event::message_sent(&message);

        match event {
            Event::MessageSent {
                message_id,
                sender,
                recipient,
                content,
                priority,
                requires_ack,
                timestamp,
                lamport_clock,
                forward_info,
            } => {
                assert_eq!(message_id, message.id.as_str());
                assert_eq!(sender, message.sender.as_str());
                assert_eq!(recipient, message.recipient.as_str());
                assert_eq!(content, message.content);
                assert_eq!(priority, "high");
                assert!(requires_ack);
                assert_eq!(timestamp, message.timestamp.as_millis());
                assert_eq!(lamport_clock, message.lamport_clock.value());
                assert!(forward_info.is_none());
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_message_delivered_event() {
        let msg_id = MessageId::new();
        let event = Event::message_delivered(msg_id.clone(), 100, 3, TransportType::BLE);

        match event {
            Event::MessageDelivered {
                message_id,
                latency_ms,
                hop_count,
                transport,
            } => {
                assert_eq!(message_id, msg_id.as_str());
                assert_eq!(latency_ms, 100);
                assert_eq!(hop_count, 3);
                assert_eq!(transport, "ble");
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_transport_switched_event() {
        let event = Event::transport_switched(
            Some(TransportType::BLE),
            TransportType::WiFiDirect,
            "Poor signal".to_string(),
        );

        match event {
            Event::TransportSwitched { from, to, reason } => {
                assert_eq!(from.as_deref(), Some("ble"));
                assert_eq!(to, "wifiDirect");
                assert_eq!(reason, "Poor signal");
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_relay_promoted_event() {
        let event = Event::relay_promoted(5, Some(80));

        match event {
            Event::RelayPromoted {
                connection_count,
                battery_level,
            } => {
                assert_eq!(connection_count, 5);
                assert_eq!(battery_level, Some(80));
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_file_progress_event() {
        let event = Event::file_progress("file123".to_string(), 50, 100);

        match event {
            Event::FileProgress {
                file_id,
                chunks_sent,
                total_chunks,
                percentage,
            } => {
                assert_eq!(file_id, "file123");
                assert_eq!(chunks_sent, 50);
                assert_eq!(total_chunks, 100);
                assert_eq!(percentage, 50);
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_event_serialization() {
        let event = Event::relay_promoted(5, Some(80));
        let json = event.to_json().unwrap();
        let deserialized = Event::from_json(&json).unwrap();

        match deserialized {
            Event::RelayPromoted {
                connection_count,
                battery_level,
            } => {
                assert_eq!(connection_count, 5);
                assert_eq!(battery_level, Some(80));
            }
            _ => panic!("Wrong event type after deserialization"),
        }
    }

    /// Pins the JSON wire shape the RN `types.ts` declarations model
    /// (`ConnectionRequestUndeliverableEvent` / `initial_message` on
    /// `ConnectionRequestReceivedEvent`) — events cross the FFI as JSON, so
    /// this contract is otherwise enforced only by convention.
    #[test]
    fn test_connection_request_event_wire_shapes() {
        let event = Event::connection_request_undeliverable(
            "bob".to_string(),
            "m1".to_string(),
            SEND_FAIL_REASON_RECIPIENT_UNREACHABLE,
        );
        let json: serde_json::Value = serde_json::from_str(&event.to_json().unwrap()).unwrap();
        assert_eq!(json["type"], "connection_request_undeliverable");
        assert_eq!(json["recipient"], "bob");
        assert_eq!(json["message_id"], "m1");
        // The bare token, never the relay's `recipient_unreachable: <prose>`.
        assert_eq!(json["reason"], "recipient_unreachable");

        let received = Event::connection_request_received(
            "alice".to_string(),
            "Alice".to_string(),
            12345,
            None,
            Some("hey".to_string()),
        );
        let json: serde_json::Value = serde_json::from_str(&received.to_json().unwrap()).unwrap();
        assert_eq!(json["type"], "connection_request_received");
        assert_eq!(json["initial_message"], "hey");

        // None must omit the key entirely (skip_serializing_if), keeping the
        // event byte-shape identical to pre-initial-message builds.
        let received = Event::connection_request_received(
            "alice".to_string(),
            "Alice".to_string(),
            12345,
            None,
            None,
        );
        assert!(!received.to_json().unwrap().contains("initial_message"));
    }

    /// Pins the `group_error` wire shape (#349).
    ///
    /// `group_id` is additive, so a build that never scopes an error must
    /// serialize byte-identically to pre-change builds — the same
    /// `skip_serializing_if` contract `initial_message` is pinned on above.
    #[test]
    fn test_group_error_event_wire_shape() {
        let scoped = Event::group_error("sync_denied".to_string(), Some("g-1".to_string()));
        let json: serde_json::Value = serde_json::from_str(&scoped.to_json().unwrap()).unwrap();
        assert_eq!(json["type"], "group_error");
        assert_eq!(json["reason"], "sync_denied");
        assert_eq!(json["group_id"], "g-1");

        let unscoped = Event::group_error("error".to_string(), None);
        assert!(!unscoped.to_json().unwrap().contains("group_id"));
    }

    #[test]
    fn test_network_metrics_event() {
        let event = Event::network_metrics(10, 3, 0.95, 150);

        match event {
            Event::NetworkMetrics {
                neighbor_count,
                relay_count,
                delivery_ratio,
                avg_latency_ms,
            } => {
                assert_eq!(neighbor_count, 10);
                assert_eq!(relay_count, 3);
                assert_eq!(delivery_ratio, 0.95);
                assert_eq!(avg_latency_ms, 150);
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_file_received_event() {
        let event = Event::file_received(
            "file123".to_string(),
            "photo.jpg".to_string(),
            1024000,
            "alice".to_string(),
            ContentType::Image,
            None,
            vec![1, 2, 3, 4],
            None,
            None,
            None,
            None,
            None,
            None,
        );

        match event {
            Event::FileReceived {
                file_id,
                file_name,
                file_size,
                sender,
                content_type,
                file_data,
                ..
            } => {
                assert_eq!(file_id, "file123");
                assert_eq!(file_name, "photo.jpg");
                assert_eq!(file_size, 1024000);
                assert_eq!(sender, "alice");
                assert_eq!(content_type, "image");
                assert!(!file_data.is_empty());
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_file_received_event_rich_fields_absent_from_json_when_none() {
        // The rich fields are additive on the event's JSON wire form: a
        // plain transfer must serialize exactly as it did before they
        // existed, so older consumers see no new keys.
        let event = Event::file_received(
            "file123".to_string(),
            "f.bin".to_string(),
            4,
            "alice".to_string(),
            ContentType::File,
            None,
            vec![1, 2, 3, 4],
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let json = serde_json::to_value(&event).unwrap();
        for key in [
            "timestamp",
            "caption",
            "reply_to_msg",
            "reply_context",
            "forward_info",
        ] {
            assert!(json.get(key).is_none(), "{} must be absent when unset", key);
        }
    }

    #[test]
    fn test_file_received_event_rich_fields_round_trip() {
        use offline_protocol_core::UserId;
        let rc = offline_protocol_core::ReplyContext {
            sender: UserId::new("carol").unwrap(),
            text: "the original".to_string(),
            timestamp: None,
            reply_media_label: None,
            reply_content_type: Some("text".to_string()),
        };
        let fwd = offline_protocol_core::ForwardInfo {
            original_sender: UserId::new("dave").unwrap(),
            original_message_id: offline_protocol_core::MessageId::new(),
            original_timestamp: offline_protocol_core::Timestamp::now(),
            forward_count: 1,
        };
        let event = Event::file_received(
            "file123".to_string(),
            "photo.jpg".to_string(),
            1024,
            "alice".to_string(),
            ContentType::Image,
            None,
            vec![1, 2, 3],
            Some(1_700_000_000_000),
            Some("look".to_string()),
            Some("0192aaaa-bbbb-cccc-dddd-eeeeffff0000".to_string()),
            Some(&rc),
            Some(&fwd),
            None,
        );
        let json = serde_json::to_string(&event).unwrap();
        let parsed: Event = serde_json::from_str(&json).unwrap();
        match parsed {
            Event::FileReceived {
                timestamp,
                caption,
                reply_to_msg,
                reply_context,
                forward_info,
                ..
            } => {
                assert_eq!(timestamp, Some(1_700_000_000_000));
                assert_eq!(caption.as_deref(), Some("look"));
                assert_eq!(
                    reply_to_msg.as_deref(),
                    Some("0192aaaa-bbbb-cccc-dddd-eeeeffff0000")
                );
                let rc = reply_context.expect("reply_context must round-trip");
                assert_eq!(rc.sender, "carol");
                assert_eq!(rc.text, "the original");
                let fwd = forward_info.expect("forward_info must round-trip");
                assert_eq!(fwd.original_sender, "dave");
                assert_eq!(fwd.forward_count, 1);
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[test]
    fn test_security_warning_code_as_str_matches_serde_wire_form() {
        // `SecurityWarningCode::as_str()` is hand-written, while the JSON wire
        // form is derived from `#[serde(rename_all = "SCREAMING_SNAKE_CASE")]`.
        // JS consumers branch on the wire string (e.g. keying reinstall handling
        // off `SENDER_ADDRESS_MISMATCH`), so the two must never drift. Pin every
        // variant to its serialized form — a single-variant test would let the
        // others rot.
        let all = [
            SecurityWarningCode::SenderAddressMismatch,
            SecurityWarningCode::TransportIdentityMismatch,
            SecurityWarningCode::ControlSignatureInvalid,
            SecurityWarningCode::UnsignedControlRejected,
            SecurityWarningCode::MediaSenderGroupMismatch,
            SecurityWarningCode::PlaintextSend,
            SecurityWarningCode::PlaintextReceiveRejected,
            SecurityWarningCode::SessionSenderGroupMismatch,
            SecurityWarningCode::SessionRekeyTriggered,
            SecurityWarningCode::NostrKeyPackageSlotExhausted,
            SecurityWarningCode::PushKeyPackagePoolExhausted,
            SecurityWarningCode::RelayAddressBindingMismatch,
            SecurityWarningCode::RelayAddressDeclarationRefused,
            SecurityWarningCode::GroupLeafIdentityUnproven,
            SecurityWarningCode::StaleControlFrame,
            SecurityWarningCode::GatewayAddressBindingMismatch,
            SecurityWarningCode::GatewayAddressDeclarationRefused,
            SecurityWarningCode::KeyPackageOutsideValidityWindow,
        ];
        for code in all {
            // serde renders a unit enum variant as a quoted JSON string.
            let wire = serde_json::to_string(&code).unwrap();
            assert_eq!(
                format!("\"{}\"", code.as_str()),
                wire,
                "as_str() drifted from the serde wire form for {code:?}",
            );
            // Exhaustiveness guard (no wildcard): adding a variant makes this
            // match fail to compile until it is also added to `all` above and
            // pinned to its wire form.
            match code {
                SecurityWarningCode::SenderAddressMismatch
                | SecurityWarningCode::TransportIdentityMismatch
                | SecurityWarningCode::ControlSignatureInvalid
                | SecurityWarningCode::UnsignedControlRejected
                | SecurityWarningCode::MediaSenderGroupMismatch
                | SecurityWarningCode::PlaintextSend
                | SecurityWarningCode::PlaintextReceiveRejected
                | SecurityWarningCode::SessionSenderGroupMismatch
                | SecurityWarningCode::SessionRekeyTriggered
                | SecurityWarningCode::NostrKeyPackageSlotExhausted
                | SecurityWarningCode::PushKeyPackagePoolExhausted
                | SecurityWarningCode::RelayAddressBindingMismatch
                | SecurityWarningCode::RelayAddressDeclarationRefused
                | SecurityWarningCode::GroupLeafIdentityUnproven
                | SecurityWarningCode::StaleControlFrame
                | SecurityWarningCode::GatewayAddressBindingMismatch
                | SecurityWarningCode::GatewayAddressDeclarationRefused
                | SecurityWarningCode::KeyPackageOutsideValidityWindow => {}
            }
        }
    }

    #[test]
    fn test_debug_redacts_every_peer_identifying_field() {
        // `SecurityWarning` printed its `peer_id` verbatim while the other
        // twelve peer-bearing arms redacted theirs, so a single missed arm was
        // invisible: `{:?}` on any *other* event looked correct. Pinning one
        // arm would leave the next omission just as invisible, so this
        // enumerates every variant carrying a peer-identifying field and
        // asserts the sentinel never survives formatting.
        //
        // Deliberately a *value* assertion rather than a field-name one: the
        // question is whether the id reaches the log, not how the arm spells
        // its placeholder.
        const SENTINEL: &str = "off1qy4aspkf0u8qptc6rlpn9ra8vw5jd9ereq4cwpfs";

        let events = vec![
            Event::NeighborDiscovered {
                peer_id: SENTINEL.to_string(),
                transport: "ble".to_string(),
                rssi: Some(-40),
            },
            Event::NeighborLost {
                peer_id: SENTINEL.to_string(),
            },
            Event::SecureSessionEstablished {
                peer_id: SENTINEL.to_string(),
                group_id: "session:a:b".to_string(),
                is_session: true,
                initiated_by_local: true,
            },
            Event::SecureSessionFailed {
                peer_id: SENTINEL.to_string(),
                reason: "nope".to_string(),
            },
            Event::ConvergenceDiag {
                stage: "stage".to_string(),
                peer_id: SENTINEL.to_string(),
                detail: "detail".to_string(),
            },
            Event::WelcomeSendAttempted {
                peer_id: SENTINEL.to_string(),
                message_id: "m1".to_string(),
                group_id: "g1".to_string(),
                attempt: 1,
            },
            Event::WelcomeSendSucceeded {
                peer_id: SENTINEL.to_string(),
                message_id: "m1".to_string(),
                group_id: "g1".to_string(),
                attempt: 1,
            },
            Event::WelcomeSendFailed {
                peer_id: SENTINEL.to_string(),
                message_id: "m1".to_string(),
                group_id: "g1".to_string(),
                attempt: 1,
                reason_code: WelcomeReasonCode::Timeout,
                transport_error: None,
                retryable: true,
                next_retry_at: None,
            },
            Event::WelcomeSendExpired {
                peer_id: SENTINEL.to_string(),
                message_id: "m1".to_string(),
                attempt: 3,
                reason_code: WelcomeReasonCode::RetryExhausted,
            },
            Event::ServiceDiscovered {
                query_id: "q1".to_string(),
                service_id: "s1".to_string(),
                version: "1".to_string(),
                provider_peer_id: SENTINEL.to_string(),
                capabilities: HashMap::new(),
                hop_count: 1,
            },
            Event::ServiceResponseReceived {
                request_id: "r1".to_string(),
                service_id: "s1".to_string(),
                status: "ok".to_string(),
                body: "body".to_string(),
                provider_peer_id: SENTINEL.to_string(),
                encrypted: true,
            },
            Event::PresenceUpdated {
                peer_id: SENTINEL.to_string(),
                status: PresenceStatus::Online,
                timestamp: 0,
                last_seen_ms: None,
                source: PresenceSource::Peer,
            },
            Event::SecurityWarning {
                peer_id: SENTINEL.to_string(),
                reason_code: SecurityWarningCode::SenderAddressMismatch,
                reason: "mismatch".to_string(),
            },
        ];

        for event in &events {
            let rendered = format!("{:?}", event);
            assert!(
                !rendered.contains(SENTINEL),
                "Debug leaked a peer identifier: {rendered}",
            );
        }
    }

    /// Mirrors serde's `rename_all = "snake_case"` rule.
    fn serde_snake_case(name: &str) -> String {
        let mut out = String::new();
        for (i, ch) in name.chars().enumerate() {
            if ch.is_ascii_uppercase() {
                if i > 0 {
                    out.push('_');
                }
                out.push(ch.to_ascii_lowercase());
            } else {
                out.push(ch);
            }
        }
        out
    }

    /// Drift guard: every `Event` variant must have a typed declaration in the
    /// React Native bindings. Events cross UniFFI as tagged JSON, so nothing
    /// else fails when `types.ts` lags — the event just arrives untyped and
    /// invisible to the `ProtocolEvent` union (7 variants had silently drifted
    /// before this guard existed).
    #[test]
    fn react_native_types_cover_all_event_variants() {
        use std::collections::BTreeSet;

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let events_rs = std::fs::read_to_string(manifest_dir.join("src/events.rs")).unwrap();
        let types_ts_path = manifest_dir.join("../../bindings/react-native/src/types.ts");
        let types_ts = std::fs::read_to_string(&types_ts_path)
            .unwrap_or_else(|e| panic!("cannot read {}: {e}", types_ts_path.display()));

        // Collect each `Event` variant's serde tag by scanning the enum block:
        // variant names sit at 4-space indent, brace depth 1.
        let mut rust_tags = BTreeSet::new();
        let mut in_enum = false;
        let mut depth = 0usize;
        for line in events_rs.lines() {
            if !in_enum {
                if line.starts_with("pub enum Event {") {
                    in_enum = true;
                    depth = 1;
                }
                continue;
            }
            let trimmed = line.trim();
            if trimmed.starts_with("//") || trimmed.starts_with("#[") {
                continue;
            }
            if depth == 1
                && line.starts_with("    ")
                && !line.starts_with("     ")
                && trimmed
                    .chars()
                    .next()
                    .is_some_and(|c| c.is_ascii_uppercase())
            {
                let name: String = trimmed
                    .chars()
                    .take_while(|c| c.is_ascii_alphanumeric())
                    .collect();
                rust_tags.insert(serde_snake_case(&name));
            }
            depth += line.matches('{').count();
            depth = depth.saturating_sub(line.matches('}').count());
            if depth == 0 {
                break;
            }
        }
        assert!(
            rust_tags.len() >= 60,
            "enum scan looks broken: only {} variants found",
            rust_tags.len()
        );

        // Event interface discriminants in types.ts: `  type: '<tag>';` at
        // exactly 2-space indent (nested object fields sit deeper).
        let ts_tags: BTreeSet<String> = types_ts
            .lines()
            .filter_map(|l| l.strip_prefix("  type: '"))
            .filter_map(|rest| rest.strip_suffix("';"))
            .map(str::to_string)
            .collect();

        // Emitted by the native iOS/Android bridges, not the core enum.
        let bridge_only: BTreeSet<String> = [
            "diagnostic",
            "internet_server_message",
            "internet_status_changed",
            "internet_session_superseded",
            // Android only: the mesh foreground service's notification has no
            // iOS counterpart.
            "mesh_stopped_by_user",
        ]
        .map(str::to_string)
        .into();

        let missing: Vec<_> = rust_tags.difference(&ts_tags).collect();
        assert!(
            missing.is_empty(),
            "Event variants missing a typed declaration in bindings/react-native/src/types.ts \
             (add the interface AND its ProtocolEvent union entry): {missing:?}"
        );

        let stale: Vec<_> = ts_tags
            .difference(&rust_tags)
            .filter(|t| !bridge_only.contains(*t))
            .collect();
        assert!(
            stale.is_empty(),
            "types.ts declares event tags with no core Event variant \
             (stale, or a new bridge-only event that needs allowlisting here): {stale:?}"
        );
    }

    /// Drift guard for the *payload* side of the same seam: apps switch on
    /// `reason_code`, so a code with no entry in the RN union is invisible to
    /// exhaustive handling on the app side and silently falls into whatever
    /// default a `switch` has. `NOSTR_KEY_PACKAGE_SLOT_EXHAUSTED` had already
    /// drifted this way before this guard existed.
    #[test]
    fn react_native_types_cover_all_security_warning_codes() {
        use std::collections::BTreeSet;

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let events_rs = std::fs::read_to_string(manifest_dir.join("src/events.rs")).unwrap();
        let types_ts_path = manifest_dir.join("../../bindings/react-native/src/types.ts");
        let types_ts = std::fs::read_to_string(&types_ts_path)
            .unwrap_or_else(|e| panic!("cannot read {}: {e}", types_ts_path.display()));

        // The wire forms are exactly the string literals `as_str` maps to, and
        // the test above already pins those to serde's rendering.
        // Anchored on the impl block: several enums in this file have an
        // identical `as_str` signature, and the first match is a different one.
        let as_str_body = events_rs
            .split_once("impl SecurityWarningCode {")
            .expect("impl SecurityWarningCode not found")
            .1
            .split_once("    pub fn as_str(&self) -> &'static str {")
            .expect("SecurityWarningCode::as_str not found")
            .1
            .split_once("\n    }")
            .expect("as_str body not terminated")
            .0;
        let rust_codes: BTreeSet<String> = as_str_body
            .lines()
            .filter_map(|l| l.split_once("=> \""))
            .filter_map(|(_, rest)| rest.split_once('"'))
            .map(|(code, _)| code.to_string())
            .collect();

        // Negative control: a scan that silently matched nothing would make
        // every assertion below vacuously true. The floor tracks the variant
        // count loosely — it exists to catch a broken scan, not to freeze the
        // taxonomy, so it moves when variants are deliberately added or (as
        // when the TOFU codes were deleted) removed.
        assert!(
            rust_codes.len() >= 11,
            "as_str scan looks broken: only {} codes found",
            rust_codes.len()
        );

        let union = types_ts
            .split_once("export type SecurityWarningCode =")
            .expect("SecurityWarningCode union not found in types.ts")
            .1
            .split_once(';')
            .expect("SecurityWarningCode union not terminated")
            .0;
        let ts_codes: BTreeSet<String> = union
            .lines()
            .filter_map(|l| l.trim().strip_prefix("| '"))
            .filter_map(|rest| rest.strip_suffix('\''))
            .map(str::to_string)
            .collect();

        let missing: Vec<_> = rust_codes.difference(&ts_codes).collect();
        assert!(
            missing.is_empty(),
            "SecurityWarningCode variants missing from the union in \
             bindings/react-native/src/types.ts: {missing:?}"
        );

        let stale: Vec<_> = ts_codes.difference(&rust_codes).collect();
        assert!(
            stale.is_empty(),
            "types.ts declares security warning codes with no Rust variant: {stale:?}"
        );
    }

    /// The same drift guard for `PresenceSource`, which had none.
    ///
    /// This union is the discriminator on the one event that merges two
    /// unrelated streams, and the documented advice is to filter on it, so an
    /// app that switches exhaustively over the TS union silently drops every
    /// event carrying a source TypeScript has never heard of. Nothing else
    /// catches that: unlike `SecurityWarningCode` there is no `as_str` here,
    /// the wire form is serde's alone, and a new variant compiles and ships
    /// green on both sides of a seam that disagrees.
    #[test]
    fn react_native_types_cover_all_presence_sources() {
        use std::collections::BTreeSet;

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let events_rs = std::fs::read_to_string(manifest_dir.join("src/events.rs")).unwrap();
        let types_ts_path = manifest_dir.join("../../bindings/react-native/src/types.ts");
        let types_ts = std::fs::read_to_string(&types_ts_path)
            .unwrap_or_else(|e| panic!("cannot read {}: {e}", types_ts_path.display()));

        // Scanned from the source text rather than from a hand-kept list of
        // variants, because a hand-kept list is the thing that drifts.
        let body = events_rs
            .split_once("pub enum PresenceSource {")
            .expect("PresenceSource not found")
            .1
            .split_once(
                "
}",
            )
            .expect("PresenceSource body not terminated")
            .0;
        let rust_sources: BTreeSet<String> = body
            .lines()
            .map(str::trim)
            .filter(|l| !l.starts_with("//") && !l.starts_with("#["))
            .filter_map(|l| l.strip_suffix(','))
            .filter(|name| !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric()))
            .map(|name| serde_snake_case(name))
            .collect();

        // Negative control: an empty scan would make both assertions below
        // vacuously true.
        assert!(
            rust_sources.len() >= 2,
            "PresenceSource scan looks broken: only {} found",
            rust_sources.len()
        );

        // Pins the scan against serde itself, so a rename rule change is
        // caught here rather than in an app's switch statement.
        assert_eq!(
            serde_json::to_string(&PresenceSource::Internet).unwrap(),
            "\"internet\"",
            "serde's rendering of PresenceSource changed"
        );

        let union = types_ts
            .split_once("export type PresenceSource =")
            .expect("PresenceSource union not found in types.ts")
            .1
            .split_once(';')
            .expect("PresenceSource union not terminated")
            .0;
        let ts_sources: BTreeSet<String> = union
            .split('|')
            .map(str::trim)
            .filter_map(|t| t.strip_prefix('\''))
            .filter_map(|t| t.strip_suffix('\''))
            .map(str::to_string)
            .collect();

        let missing: Vec<_> = rust_sources.difference(&ts_sources).collect();
        assert!(
            missing.is_empty(),
            "PresenceSource variants missing from the union in \
             bindings/react-native/src/types.ts: {missing:?}"
        );

        let stale: Vec<_> = ts_sources.difference(&rust_sources).collect();
        assert!(
            stale.is_empty(),
            "types.ts declares presence sources with no Rust variant: {stale:?}"
        );
    }
}