derec-library 0.1.0

Rust SDK for the DeRec protocol, including native and WebAssembly bindings.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

#[cfg(any(feature = "ffi", target_arch = "wasm32"))]
pub(crate) mod wire;

#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::fmt;
use std::fmt::Debug;
use std::fmt::Formatter;

use crate::protocol::types::ChannelShare;
use crate::protocol::types::Secret;
use crate::{
    primitives::discovery::response::SecretVersionEntry,
    protocol::types::{Target, UserSecret},
    types::{ChannelId, SharedKey},
};
use derec_proto::{
    ContactMessage, GetSecretIdsVersionsRequestMessage, GetShareRequestMessage, PairRequestMessage,
    PrePairRequestMessage, SenderKind, StoreShareRequestMessage, TransportProtocol,
    UnpairRequestMessage, UpdateChannelInfoRequestMessage, VerifyShareRequestMessage,
};

/// A Helper as the recovering owner knows it, named in
/// [`DeRecEvent::RecoveryConflict`] and [`DeRecEvent::RecoveryDisputed`] so
/// the application can tell the owner who is on which side.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecoveryHelper {
    /// The channel the Helper answered on.
    pub channel_id: ChannelId,
    /// What the Helper advertised about itself when it paired, as stored on
    /// its channel. Empty when the channel is no longer stored.
    pub communication_info: HashMap<String, String>,
}

/// One secret a recovery reconstructed, reported in
/// [`DeRecEvent::RecoveryConflict`].
#[derive(Clone, Debug, PartialEq)]
pub struct RecoveryCandidate {
    /// The reconstructed secret, decoded as [`DeRecEvent::SecretRecovered`]
    /// would carry it.
    pub secret: Secret,
    /// The Helpers whose shares reconstruct it, in the order their shares
    /// were collected.
    pub supported_by: Vec<RecoveryHelper>,
}

/// Why [`DeRecEvent::MessageIgnored`] dropped an inbound message.
///
/// Every case leaves every store untouched and sends nothing back, so the
/// sender learns nothing from the drop and a retry is always safe.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum IgnoreReason {
    /// The channel's fingerprint has not been confirmed on this device yet:
    /// a `Pending` helper channel, or a `Pending` replica member on the
    /// channel the message arrived on. The comparison is the only defence
    /// against a man-in-the-middle, so nothing a peer sends is acted on
    /// before it. Once [`super::DeRecProtocol::verify_fingerprint`] succeeds
    /// the channel accepts traffic, but a dropped message is not replayed.
    ///
    /// Admitting a replica leaves `Pending` members only on that pairing's
    /// own channel, so traffic on an established group channel is never
    /// held back by a pairing in progress.
    PendingVerification,
    /// The message is older than the configured inbound timeout
    /// ([`crate::protocol::types::Timeouts::inbound_message`]).
    Expired,
    /// The envelope's timestamp and the encrypted inner message's timestamp
    /// differ, or either or both are absent. A sender stamps both with the
    /// one time the message was sent, so a mismatch means the envelope was
    /// altered or built by a non-conforming peer. Every body, including
    /// `ErrorResponse`, carries the field and obeys the same rule. Checked
    /// after decryption and before dispatch.
    TimestampMismatch,
    /// A `VerifyShareResponse` whose `(nonce, secret_id, version)` does not
    /// match the challenge outstanding on its channel: an answer to an
    /// earlier challenge that a newer one has replaced. The outstanding
    /// challenge is kept, so its own answer still completes it.
    StaleResponse,
    /// A `StoreShareRequest` for a version older than the newest one this
    /// Helper stores on the channel, and not stored itself: a delayed or
    /// repeated delivery of a request a newer one has replaced. Storing it
    /// would bring back a version the Owner already dropped, so it is not
    /// stored, not raised as [`DeRecEvent::ActionRequired`], and not
    /// answered.
    Superseded,
    /// The envelope names a protocol version older than the minimum this
    /// device accepts
    /// ([`with_min_protocol_version`](crate::protocol::DeRecProtocolBuilder::with_min_protocol_version)).
    /// Checked before anything else, so nothing is decrypted, stored or
    /// answered.
    ProtocolVersionTooOld,
    /// The envelope's protocol version and the copy inside the encrypted
    /// payload differ: the envelope was altered, or built by a non-conforming
    /// peer. A payload from a release that writes no version reads as 0.0,
    /// the version such a release puts on its envelope. Checked after
    /// decryption and before dispatch, like
    /// [`TimestampMismatch`](Self::TimestampMismatch).
    ProtocolVersionMismatch,
}

/// Why [`DeRecEvent::VerifySharesFailed`] reached no verdict for a channel.
///
/// Every case is a condition on this device, not an answer from the helper:
/// a helper's answer always ends as [`DeRecEvent::ShareVerified`],
/// [`DeRecEvent::ShareVerifyInvalid`] or [`DeRecEvent::ShareVerifyRejected`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VerifyFailureReason {
    /// The channel has no shared key, so no challenge can be encrypted to
    /// the helper. Nothing is sent.
    NoSharedKey,
    /// This device holds no proof of the share for the channel at the
    /// challenged version, so no answer could be checked. Reported when the
    /// round starts, in which case nothing is sent, or when the answer
    /// arrives after the proof was removed.
    ///
    /// The publishing device removes a proof when the Helper failed to store
    /// that version, or when the Helper confirmed a later version whose
    /// `keepVersion` was another version, since the Helper has then removed
    /// it too.
    NoProof,
    /// A local store or transport failure while preparing or sending the
    /// challenge; `error` names the cause.
    DispatchFailed,
}

/// Why [`DeRecEvent::PeerNotRestored`] left a roster entry without a channel.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NotRestoredReason {
    /// The recovered roster names no endpoint for the peer, so a channel to
    /// it would have nothing to send to. A legacy roster whose single URI had
    /// a scheme this library does not serve decodes this way.
    NoTransports,
}

/// Why [`DeRecEvent::RecoveryShareCorrupted`] set a helper's share aside.
///
/// Every case means the helper answered with an OK status but a share that
/// cannot be part of the recovered secret. An honest helper never sends one,
/// so each is a sign of storage or transport damage on that helper — or of a
/// compromised helper.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum CorruptionReason {
    /// The response carries no decodable share for the requested secret and
    /// version: the share bytes are missing or undecodable, or the share is
    /// bound to another secret or version. Judged on arrival.
    ///
    /// Also covers a share whose committed bytes exceed this device's own
    /// configured `parameter_range.max_share_size` (`0` or no range means
    /// unbounded): it is set aside on size alone, before being parsed, since
    /// the owner holds no proofs to validate it against during recovery.
    Malformed,
    /// The share decodes but its Merkle proof does not open to its own
    /// commitment root — for example a share whose value was altered after it
    /// was split. Judged on arrival.
    InvalidProof,
    /// The share belongs to a group of shares that reconstructs under one
    /// key, but what it reconstructs is not a secret: it does not decode, or
    /// it does not fit the threshold it declares. An honest split never
    /// produces that, so every Helper in the group is reported. Only
    /// judgeable against the other shares, so it is reported with the
    /// recovery's decision.
    Forged,
}

/// Lightweight discriminant of [`PendingAction`].
///
/// Carries no payload — useful for the
/// [`DeRecEvent::AutoAccepted`] event (so listeners can route on
/// "what flow just got auto-accepted" without holding the action's
/// inner request/key material) and for the
/// [`AutoAcceptPolicy::allows`] dispatch.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PendingActionKind {
    Pairing,
    PrePair,
    StoreShare,
    VerifyShare,
    Discovery,
    GetShare,
    Unpair,
    UpdateChannelInfo,
    /// A [`PendingAction::RespondToFailure`]: a request that failed and still
    /// owes its sender a response. [`AutoAcceptPolicy`] never allows it.
    Failed,
}

/// Per-flow opt-in for auto-accepting incoming requests.
///
/// Default = every field `false` (no flow auto-accepted; `process()`
/// emits [`DeRecEvent::ActionRequired`] like today). When a field is
/// `true`, `process()` invokes the equivalent of
/// [`super::DeRecProtocol::accept`] internally and emits
/// [`DeRecEvent::AutoAccepted`] **in place of**
/// [`DeRecEvent::ActionRequired`], followed by the same flow events
/// the caller would have seen from a manual `accept`.
///
/// Wire the policy through
/// [`super::DeRecProtocolBuilder::with_auto_accept`].
///
/// # Per-flow notes
///
/// - [`Self::pairing`] covers both standard and replica pairing.
///   Standard pairing transitions the channel to `Paired` immediately;
///   auto-accepting it skips any UI confirmation of "User X wants to
///   pair." Replica pairing leaves the channel in `Pending` until both
///   sides run `verify_fingerprint()`, so auto-accept here is benign
///   (channel is inert until the out-of-band fingerprint match).
/// - [`Self::pre_pair`] gates the plaintext `PrePair` leg of HashedKeys
///   pairing. The MITM defence is on the *scanner* side
///   (binding-hash check) and is unaffected by this flag, but enabling
///   it turns the initiator into a request-amplification oracle: any
///   party that knows the contact's `nonce` + `channel_id` can elicit
///   a key-publish response. Prefer to keep this off unless you
///   control both ends of the transport (LAN, integration tests).
/// - [`Self::store_share`] is the helper's admission-control point for
///   inbound shares *beyond* what the library already checks: this
///   device's own configured `minShareSize`/`maxShareSize` from
///   [`derec_proto::ParameterRange`] is enforced against every inbound
///   share's actual length regardless of this flag, before
///   [`DeRecEvent::ActionRequired`] is ever considered — an out-of-range
///   share is refused with `SIZE_LIMIT_EXCEEDED` either way, and this flag
///   has no say in it. While this flag is `false`, the
///   [`DeRecEvent::ActionRequired`] carrying [`PendingAction::StoreShare`]
///   hands the application the decoded
///   [`derec_proto::StoreShareRequestMessage`], which is where a *tighter
///   or per-user* size limit, storage quota, or any other app-specific
///   decline belongs — see [`super::DeRecProtocol::reject`] for a worked
///   example. Setting it `true` removes that opportunity: every
///   in-range share from every paired Owner is stored unconditionally,
///   unless the share store refuses it. Keep it `false` in any
///   deployment with per-user storage limits tighter than this device's
///   own configured range.
/// - [`Self::unpair`] is destructive — accepting deletes the local
///   channel record and any shares/secrets associated with it. The
///   [`DeRecEvent::Unpaired`] event still fires (after the deletion),
///   so observability is preserved, but the user has no chance to
///   intervene before the data is gone. Apps that want a "are you
///   sure?" gate should keep this off.
/// - [`Self::update_channel_info`] silently overwrites the stored
///   channel record with the peer's new transport / communication
///   info, and outbound traffic on the channel re-routes to whatever
///   endpoint the update announced. Holding the channel key is not
///   proof that the peer sent it: both ends encrypt under one key and
///   the envelope does not say which end sent it, so an update this
///   device sent, delivered back to it, decrypts like one from the peer.
///   An older update delivered again, or held back and delivered after
///   a newer one, decrypts too. Catching both is the application's
///   replay detection (see the security note on
///   [`process`](crate::protocol::DeRecProtocol::process)), and rejecting a
///   contact update older than the last one accepted on the channel
///   needs the application to see each update, which this flag
///   removes. Keep it `false` unless the transport rules both out. It
///   also removes the owner's chance to refuse the repeated contact
///   changes that let a helper read the vault through its compressed
///   length; see the [`secret`](crate::protocol::types::secret) module.
///
/// All other fields wrap routine request/response flows and have no
/// caveats beyond "the caller decided not to gate them." Note that this
/// applies to gating alone: auto-accept never relaxes an invariant the
/// protocol enforces itself, only the application's opportunity to
/// refuse.
///
/// No field covers [`PendingAction::RespondToFailure`]. A failed request can
/// only be rejected, so [`Self::allows`] is `false` for it under every
/// policy, [`Self::all`] included.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AutoAcceptPolicy {
    pub pairing: bool,
    pub pre_pair: bool,
    pub store_share: bool,
    pub verify_share: bool,
    pub discovery: bool,
    pub get_share: bool,
    pub unpair: bool,
    pub update_channel_info: bool,
}

impl AutoAcceptPolicy {
    /// Enable auto-accept for every flow. Equivalent to setting every
    /// field to `true` — read the field-level docs on
    /// [`AutoAcceptPolicy`] before using this in production; several
    /// flows are state-changing or expose a request-amplification
    /// surface.
    pub fn all() -> Self {
        Self {
            pairing: true,
            pre_pair: true,
            store_share: true,
            verify_share: true,
            discovery: true,
            get_share: true,
            unpair: true,
            update_channel_info: true,
        }
    }

    /// `true` when the policy opts in to auto-accepting the given action.
    /// Used by [`super::DeRecProtocol::process`] at the auto-accept
    /// intercept site.
    pub fn allows(&self, action: &PendingAction) -> bool {
        match action.kind() {
            PendingActionKind::Pairing => self.pairing,
            PendingActionKind::PrePair => self.pre_pair,
            PendingActionKind::StoreShare => self.store_share,
            PendingActionKind::VerifyShare => self.verify_share,
            PendingActionKind::Discovery => self.discovery,
            PendingActionKind::GetShare => self.get_share,
            PendingActionKind::Unpair => self.unpair,
            PendingActionKind::UpdateChannelInfo => self.update_channel_info,
            PendingActionKind::Failed => false,
        }
    }
}

/// An opaque action token emitted inside [`DeRecEvent::ActionRequired`] events.
///
/// When `process()` receives an incoming protocol request, it returns an
/// `ActionRequired` event carrying a `PendingAction`. The application must
/// pass this token to [`super::DeRecProtocol::accept`] or
/// [`super::DeRecProtocol::reject`] to complete the flow.
///
/// `Debug` shows only the [`PendingActionKind`] discriminant plus
/// `channel_id`, keeping any peer-supplied request contents out of log
/// lines. No variant carries private key material — the accept handlers
/// reload the pairing secret from the secret store (single source of
/// truth), so the token stays small and safe to persist or ship across a
/// language boundary.
///
/// `Clone` lets an application keep a copy of an action it passes to
/// [`super::DeRecProtocol::accept`], so it can still hand that copy to
/// [`super::DeRecProtocol::reject`] if a
/// [`DeRecEvent::RequestFailed`] follows.
///
/// The library never expires an unresolved action: a token stays valid until
/// the application resolves it, however long that takes.
#[derive(Clone)]
pub enum PendingAction {
    Pairing {
        channel_id: ChannelId,
        request: PairRequestMessage,
        kind: SenderKind,
        peer_communication_info: HashMap<String, String>,
        /// Trace id read from the inbound `PairRequest` envelope. Echoed
        /// verbatim on the `PairResponse` envelope when the application
        /// calls `accept` or `reject`; see `DeRecMessage.traceId`.
        trace_id: u64,
    },
    /// The peer scanned a `HashedKeys`-mode `ContactMessage` and is asking
    /// for the real pairing public keys via a plaintext `PrePairRequest`.
    ///
    /// Accepting fetches `PairingSecret` from the secret store and replies
    /// with the actual `mlkemEncapsulationKey` / `eciesPublicKey`; the
    /// scanner then validates the published keys against the contact's
    /// `contactBindingHash` and proceeds to a normal `PairRequest` flow.
    /// Rejecting sends back a non-Ok `PrePairResponse` and keeps no state.
    ///
    /// Carries no `pairing_secret` — the handler loads it from the secret
    /// store at `accept` time (single source of truth) and the action stays
    /// small enough to round-trip cheaply across the WASM boundary.
    PrePair {
        channel_id: ChannelId,
        request: PrePairRequestMessage,
        /// Trace id read from the inbound `PrePairRequest` envelope. Echoed
        /// verbatim on the `PrePairResponse` when the application calls
        /// `accept` or `reject`; see `DeRecMessage.traceId`.
        trace_id: u64,
    },
    StoreShare {
        channel_id: ChannelId,
        request: StoreShareRequestMessage,
        shared_key: SharedKey,
        /// Trace id read from the inbound request envelope. Echoed verbatim
        /// on the response envelope when the application calls `accept` or
        /// `reject`; see `DeRecMessage.traceId`.
        trace_id: u64,
    },
    VerifyShare {
        channel_id: ChannelId,
        request: VerifyShareRequestMessage,
        shared_key: SharedKey,
        trace_id: u64,
    },
    /// The peer is asking us to enumerate which `(secret_id, version)`
    /// tuples we currently hold for them on this channel (see
    /// [`crate::primitives::discovery`]). Accepting replies with the
    /// catalog so the asker can correlate it with their own view —
    /// commonly the precursor an owner uses to drive `Recovery`, but
    /// useful any time the owner wants to know what a given helper
    /// still has. Rejecting sends back a non-`Ok` response and
    /// discloses no catalog content.
    Discovery {
        channel_id: ChannelId,
        request: GetSecretIdsVersionsRequestMessage,
        shared_key: SharedKey,
        trace_id: u64,
    },
    GetShare {
        channel_id: ChannelId,
        request: GetShareRequestMessage,
        shared_key: SharedKey,
        trace_id: u64,
    },
    /// The peer has asked us to drop our state for this channel
    /// (see [`crate::primitives::unpairing`]). Accepting deletes the local
    /// channel/share/secret state and sends back an `Ok` response; rejecting
    /// sends a non-`Ok` response and keeps the state.
    Unpair {
        channel_id: ChannelId,
        request: UnpairRequestMessage,
        shared_key: SharedKey,
        trace_id: u64,
    },
    /// The peer has announced an update to their communication info and/or
    /// transport endpoints.
    ///
    /// Calling [`super::DeRecProtocol::accept`] on this action does the
    /// state mutation **for you**: the orchestrator writes the new fields
    /// onto the stored [`crate::protocol::types::HelperChannel`] and sends back
    /// an `Ok` response. When the update carries endpoints, the response is
    /// routed to the **new** endpoints, so subsequent outbound traffic on this
    /// channel already targets the new addresses.
    /// Applications do not need to call any setter themselves on the
    /// receiving side — receiving-side endpoint changeover is handled
    /// inside `accept`. The local-node endpoint setters
    /// [`crate::protocol::DeRecProtocol::set_communication_info`] and
    /// [`crate::protocol::DeRecProtocol::set_own_transports`] exist for
    /// the **initiating** side only, where the announcement comes from.
    ///
    /// Calling [`super::DeRecProtocol::reject`] sends a non-`Ok`
    /// response and leaves the stored channel state unchanged.
    UpdateChannelInfo {
        channel_id: ChannelId,
        request: UpdateChannelInfoRequestMessage,
        shared_key: SharedKey,
        trace_id: u64,
    },
    /// A request that arrived on an authenticated channel failed, and the
    /// response it is owed has not been sent. Carried by
    /// [`DeRecEvent::RequestFailed`].
    ///
    /// The only resolution is [`super::DeRecProtocol::reject`], which sends
    /// exactly one response with the given status and memo.
    /// [`super::DeRecProtocol::accept`] returns
    /// [`crate::Error::InvalidInput`]: there is no success to send for a
    /// request that already failed.
    ///
    /// Carries no shared key. The key is loaded from the channel named by
    /// `reply` when the response is sent.
    ///
    /// No token is issued when `reject` could never answer it, and
    /// [`DeRecEvent::RequestFailed`] then carries `action: None`:
    ///
    /// - no reply target can exist: a request on a replica group channel that
    ///   names no member and carries no `reply_to`;
    /// - the channel whose key would encrypt the response has no key stored.
    ///   A replica copy that hands this device the group key and fails before
    ///   the copy is applied is the case: the admitter dropped the key of the
    ///   channel it arrived on, so the response is owed on the group channel,
    ///   whose key this device has not stored yet. The admitter learns of the
    ///   failure by timing out. With `auto_respond_on_failure` on, the
    ///   library answers it with the group key it holds in memory.
    ///
    /// The library is stateless and cannot tell a token it already answered
    /// from a fresh one: rejecting the same token twice sends two responses.
    /// Resolving each token once is the application's part.
    RespondToFailure {
        /// The channel the failed request arrived on.
        channel_id: ChannelId,
        /// Trace id read from the inbound request envelope. Echoed verbatim
        /// on the response envelope; see `DeRecMessage.traceId`.
        trace_id: u64,
        /// Where the response goes.
        reply: ReplyTarget,
        /// The request being answered, which decides the response type.
        request: FailedRequest,
    },
}

/// Where the response to a [`PendingAction::RespondToFailure`] is sent.
///
/// The key is not part of the target: it is loaded from `channel_id` when
/// the response is sent.
#[derive(Clone, Debug, PartialEq)]
pub struct ReplyTarget {
    /// The channel whose shared key encrypts the response.
    pub channel_id: ChannelId,
    /// The endpoints the response is delivered to.
    pub endpoints: Vec<TransportProtocol>,
}

/// The request a [`PendingAction::RespondToFailure`] answers.
///
/// One variant per request type that is owed a response, each holding the
/// decoded request so the response can be built for it. Helper-bound and
/// replica-bound requests share a variant: the request message is the same,
/// and only the reply target differs.
///
/// `Debug` shows only the variant name, keeping peer-supplied request
/// contents out of log lines.
#[derive(Clone, PartialEq)]
pub enum FailedRequest {
    /// Answered with a `StoreShareResponse`.
    StoreShare(StoreShareRequestMessage),
    /// Answered with a `VerifyShareResponse`.
    VerifyShare(VerifyShareRequestMessage),
    /// Answered with a `GetSecretIdsVersionsResponse`.
    GetSecretIdsVersions(GetSecretIdsVersionsRequestMessage),
    /// Answered with a `GetShareResponse`.
    GetShare(GetShareRequestMessage),
    /// Answered with an `UnpairResponse`.
    Unpair(UnpairRequestMessage),
    /// Answered with an `UpdateChannelInfoResponse`.
    UpdateChannelInfo(UpdateChannelInfoRequestMessage),
    /// The message decrypted under the channel key but its body could not be
    /// decoded, or it was a request type not expected under a channel key.
    /// Answered with an `ErrorResponseMessage`.
    Undecodable,
}

impl Debug for FailedRequest {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            FailedRequest::StoreShare(_) => "StoreShare",
            FailedRequest::VerifyShare(_) => "VerifyShare",
            FailedRequest::GetSecretIdsVersions(_) => "GetSecretIdsVersions",
            FailedRequest::GetShare(_) => "GetShare",
            FailedRequest::Unpair(_) => "Unpair",
            FailedRequest::UpdateChannelInfo(_) => "UpdateChannelInfo",
            FailedRequest::Undecodable => "Undecodable",
        })
    }
}

impl Debug for PendingAction {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        let channel_id = match self {
            PendingAction::Pairing { channel_id, .. }
            | PendingAction::PrePair { channel_id, .. }
            | PendingAction::StoreShare { channel_id, .. }
            | PendingAction::VerifyShare { channel_id, .. }
            | PendingAction::Discovery { channel_id, .. }
            | PendingAction::GetShare { channel_id, .. }
            | PendingAction::Unpair { channel_id, .. }
            | PendingAction::UpdateChannelInfo { channel_id, .. }
            | PendingAction::RespondToFailure { channel_id, .. } => channel_id,
        };
        f.debug_struct("PendingAction")
            .field("kind", &self.kind())
            .field("channel_id", &channel_id.0)
            .finish()
    }
}

impl PendingAction {
    /// Return this action's discriminant — used by
    /// [`AutoAcceptPolicy::allows`] and by the [`DeRecEvent::AutoAccepted`]
    /// event so callers can route on flow kind without inspecting the
    /// inner payload.
    pub fn kind(&self) -> PendingActionKind {
        match self {
            PendingAction::Pairing { .. } => PendingActionKind::Pairing,
            PendingAction::PrePair { .. } => PendingActionKind::PrePair,
            PendingAction::StoreShare { .. } => PendingActionKind::StoreShare,
            PendingAction::VerifyShare { .. } => PendingActionKind::VerifyShare,
            PendingAction::Discovery { .. } => PendingActionKind::Discovery,
            PendingAction::GetShare { .. } => PendingActionKind::GetShare,
            PendingAction::Unpair { .. } => PendingActionKind::Unpair,
            PendingAction::UpdateChannelInfo { .. } => PendingActionKind::UpdateChannelInfo,
            PendingAction::RespondToFailure { .. } => PendingActionKind::Failed,
        }
    }

    /// The token of the exchange that raised this action.
    ///
    /// Every variant carries one: an action only exists because a request
    /// arrived, and the response the application's decision produces echoes
    /// the same token. Reading it uniformly is what lets
    /// [`accept`](super::DeRecProtocol::accept) and
    /// [`reject`](super::DeRecProtocol::reject) attribute their work to that
    /// exchange without matching on the variant.
    pub fn trace_id(&self) -> u64 {
        match self {
            PendingAction::Pairing { trace_id, .. }
            | PendingAction::PrePair { trace_id, .. }
            | PendingAction::StoreShare { trace_id, .. }
            | PendingAction::VerifyShare { trace_id, .. }
            | PendingAction::Discovery { trace_id, .. }
            | PendingAction::GetShare { trace_id, .. }
            | PendingAction::Unpair { trace_id, .. }
            | PendingAction::UpdateChannelInfo { trace_id, .. }
            | PendingAction::RespondToFailure { trace_id, .. } => *trace_id,
        }
    }
}

/// Describes an outbound protocol flow to initiate via [`super::DeRecProtocol::start`].
///
/// # Role gating
///
/// The orchestrator enforces flow directionality against
/// [`crate::protocol::types::HelperChannel::peer_role`] (set at pairing time):
///
/// - [`Self::Discovery`], [`Self::ProtectSecret`], [`Self::VerifyShares`],
///   [`Self::RecoverSecret`], and [`Self::Unpair`] require the peer to be
///   a [`SenderKind::Helper`] on every targeted channel; otherwise
///   [`crate::Error::RoleMismatch`] is returned.
/// - [`Self::Pairing`] creates the channel, so no role exists yet.
/// - [`Self::UpdateChannelInfo`] is symmetric — either party may initiate.
pub enum DeRecFlow {
    Pairing {
        kind: SenderKind,
        contact: ContactMessage,
        /// App-level identity metadata for the peer being paired with.
        /// Stored verbatim on the resulting [`crate::protocol::types::HelperChannel`]
        /// (`channel.communication_info`). The protocol does not inspect
        /// it — pass an empty map to record nothing.
        peer_communication_info: HashMap<String, String>,
    },
    Discovery {
        target: Target,
    },
    /// Publish the current secret to the protocol's paired peers.
    ///
    /// The secret identifier comes from the
    /// [`super::DeRecProtocol`] instance (set at construction via
    /// [`crate::protocol::DeRecProtocolBuilder::new`]) — one protocol
    /// instance manages exactly one secret.
    ///
    /// The target set is derived from the channel store: every paired
    /// Owner→Helper channel receives a share if the round's threshold
    /// is met, and every paired Source→ReplicaDestination channel
    /// receives the full secret payload. Apps that need to drive a single
    /// peer should pair just that peer; the protocol no longer accepts
    /// a per-call subset.
    ///
    /// When the total subshares across paired Helpers (the sum of their
    /// weights) is below the round's threshold (see
    /// [`threshold`](DeRecFlow::ProtectSecret::threshold)), no VSS
    /// split runs and Helpers receive nothing — the secret still lands on
    /// any paired Replica destinations in "secret-only" form. No
    /// [`DeRecEvent::ProtectSecretStarted`] or
    /// [`DeRecEvent::ProtectSecretFailed`] is
    /// emitted for a Helper, since none was targeted; with no Replicas
    /// paired either, [`super::DeRecProtocol::start`] returns `Ok` with no
    /// events at all. This is deliberately not an error: the version is
    /// still advanced and the secrets and description are saved as the
    /// latest snapshot, so the next publish that reaches `threshold` —
    /// including one the library starts on its own — shares that snapshot.
    /// An app can tell the two cases apart without waiting on events, by
    /// comparing the weights it is about to assign (or, for a
    /// library-initiated publish, the stored
    /// [`HelperChannel::weight`](crate::protocol::types::HelperChannel::weight)
    /// of every paired Helper) against the round's threshold before calling.
    ///

    /// # Weights are recorded
    ///
    /// Each round writes the weight it gave every paired Helper to that
    /// Helper's channel record
    /// ([`HelperChannel::weight`](crate::protocol::types::HelperChannel::weight)),
    /// before anything is sent. Publishes the library starts on its own
    /// (after pairing completes, after a fingerprint is confirmed) reuse
    /// those stored weights, and a newly paired Helper starts at `1`. The
    /// weights also travel in the roster, so a device that restores from a
    /// recovered secret, or hydrates as a replica, publishes with the same
    /// weights. Weights change only through this flow.
    ProtectSecret {
        secrets: Vec<UserSecret>,
        description: Option<String>,
        /// The subshare weight of every paired Helper, by channel. The map is
        /// the **full assignment**, not a patch: a paired Helper it does not
        /// name receives one subshare.
        ///
        /// Weights are the user's choice. Before this call, the application
        /// shows the user each paired Helper's current weight, pre-filled
        /// from its channel store
        /// ([`HelperChannel::weight`](crate::protocol::types::HelperChannel::weight)),
        /// and passes the user's final choice as the whole map. Reading the
        /// stored weights first is the normal flow.
        ///
        /// Every other call here the application makes, such as a republish
        /// after editing the secrets or the publish that follows
        /// [`restore`](crate::protocol::DeRecProtocol::restore), must pass
        /// the stored weights unchanged. A Helper left out returns to `1`,
        /// which silently undoes the user's choice. Only the publishes the
        /// library starts on its own (after pairing completes, after a
        /// fingerprint is confirmed) reuse the stored weights by themselves.
        ///
        /// Every key must be a paired Helper channel of this secret, and every
        /// weight must satisfy `1 <= weight < threshold`, so no Helper can
        /// recover alone. Any invalid entry fails the call with
        /// [`crate::Error::Sharing`] before anything is written or sent, or a
        /// version is consumed. Publishes the library starts on its own check
        /// the stored weights the same way: a weight stored under a higher
        /// threshold fails them with
        /// [`SharingError::InvalidWeight`](crate::primitives::sharing::SharingError::InvalidWeight)
        /// and nothing is sent, until a call here assigns valid weights.
        /// The failure surfaces where the publish ran:
        ///
        /// - [`process`](crate::protocol::DeRecProtocol::process) returns a
        ///   [`ProcessError`](crate::protocol::ProcessError) whose `events`
        ///   keep the message's events, [`DeRecEvent::PairingCompleted`]
        ///   included.
        /// - [`accept`](crate::protocol::DeRecProtocol::accept) returns `Err`.
        ///   The pairing has completed and its response was sent, but
        ///   `PairingCompleted` is not returned.
        /// - [`verify_fingerprint`](crate::protocol::DeRecProtocol::verify_fingerprint)
        ///   returns `Err`. The promotion stands, a retry returns `Ok(true)`,
        ///   and nothing is published.
        ///
        /// In each case a call here with valid weights publishes to every
        /// Helper.
        ///
        /// Large totals are costly to recover: reconstruction time grows
        /// quadratically with the total number of subshares. A cap set with
        /// [`crate::protocol::DeRecProtocolBuilder::with_max_subshares`]
        /// bounds the total; a round above it fails with
        /// [`SharingError::TooManySubshares`](crate::primitives::sharing::SharingError::TooManySubshares)
        /// under the same guarantees. Publishes the library starts on its own
        /// count the stored weights against the same cap.
        weights: HashMap<ChannelId, u32>,
        /// The threshold `t` this round splits at: the number of distinct
        /// subshares that reconstruct this version.
        ///
        /// `t` is recorded. Each round writes the `t` it used to the
        /// [`UserSecrets::threshold`](crate::protocol::types::UserSecrets::threshold)
        /// snapshot, the roster carries it, and
        /// [`restore`](crate::protocol::DeRecProtocol::restore) and replica
        /// hydration put it back. The round's `t` is, in order:
        ///
        /// 1. this value, when `Some`;
        /// 2. otherwise the stored `UserSecrets::threshold`;
        /// 3. otherwise the builder's
        ///    [`with_threshold`](crate::protocol::DeRecProtocolBuilder::with_threshold).
        ///
        /// Pass `None` to keep the stored `t`, including on the publish that
        /// follows `restore`. Pass `Some(t)` only to change it; once the
        /// round passes validation the new `t` is written only to this
        /// round's own snapshot, saved after distribution, so no earlier
        /// snapshot is rewritten and a round that fails before its snapshot
        /// is saved leaves the previous `t` in place. Publishes the library
        /// starts on its own always use the stored `t`.
        ///
        /// The resolved `t` must be at least `2`
        /// ([`SharingError::InvalidThreshold`](crate::primitives::sharing::SharingError::InvalidThreshold)),
        /// above every resolved weight
        /// ([`SharingError::InvalidWeight`](crate::primitives::sharing::SharingError::InvalidWeight)),
        /// and no greater than a
        /// [`with_max_subshares`](crate::protocol::DeRecProtocolBuilder::with_max_subshares)
        /// cap ([`crate::Error::InvalidInput`]). Each check runs before a
        /// version is chosen: a failing round writes and sends nothing.
        threshold: Option<u32>,
    },
    VerifyShares {
        /// Must equal this instance's own `secret_id`.
        ///
        /// Verification challenges the helpers holding *this* device's
        /// shares, so there is no other secret it could address. Passing a
        /// different id is refused with [`crate::Error::InvalidInput`] rather
        /// than ignored — a caller that believed it was verifying another
        /// secret would otherwise be told the wrong thing succeeded.
        ///
        /// Contrast [`Self::RecoverSecret`], whose `secret_id` genuinely
        /// names another instance's secret.
        secret_id: u64,
        version: u32,
        target: Target,
    },
    /// Ask every paired Helper for its share of `(secret_id, version)` and
    /// reconstruct the secret once every Helper asked has answered.
    ///
    /// Each answer settles as one of [`DeRecEvent::RecoveryShareReceived`],
    /// [`DeRecEvent::RecoveryShareRefused`] or
    /// [`DeRecEvent::RecoveryShareCorrupted`]. Nothing is reconstructed
    /// while an answer is still due: a secret chosen early could be
    /// contradicted by a share still on its way. The recovery decides when
    /// the last Helper answers, or when
    /// [`Timeouts::get_share_response`](crate::protocol::types::Timeouts::get_share_response)
    /// has elapsed since the requests went out — each silent Helper is then
    /// reported as [`DeRecEvent::RecoverSecretFailed`] with error
    /// `"timeout"`. The decision is exactly one of:
    ///
    /// - [`DeRecEvent::SecretRecovered`] — one secret reconstructs and
    ///   every collected share is part of it;
    /// - [`DeRecEvent::RecoveryDisputed`] — one secret reconstructs, but
    ///   other Helpers hold valid shares of a different split, and the owner
    ///   has to confirm it;
    /// - [`DeRecEvent::RecoveryConflict`] — two or more different secrets
    ///   reconstruct, and the owner has to choose;
    /// - [`DeRecEvent::RecoveryIncomplete`] — none does. The recovery is
    ///   closed; start it again to retry.
    ///
    /// A share that fails on its own — it does not decode, or fails its
    /// Merkle proof — is reported as it arrives and never collected. Shares
    /// that are each valid are grouped by `(root, ciphertext)`, and every
    /// group is tried: it needs shares from at least two Helpers, must
    /// decrypt, and must fit the threshold its own secret declares. A group
    /// that decrypts to something that is not a secret is reported as
    /// [`CorruptionReason::Forged`]. Every other share outside the
    /// reconstructing groups is a dispute, never a corruption: how many
    /// Helpers back a split says nothing about which split is the owner's.
    ///
    /// An honest Helper never sends a corrupted share, so the application
    /// may treat [`DeRecEvent::RecoveryShareCorrupted`] as a sign that the
    /// Helper is damaged or compromised — for example by offering to unpair
    /// it.
    RecoverSecret {
        secret_id: u64,
        version: u32,
    },
    /// Ask the replica group whether this device is behind, and catch up if
    /// it is.
    ///
    /// **Replica-only.** Requires a configured `replica_id` and at least one
    /// other group member. Every member is asked which version it holds,
    /// except one whose pairing this device has not confirmed (its record is
    /// still `Pending`): it drops every message at its pending gate, so it
    /// is not a member yet. The one holding the newest state is then asked
    /// for it, and the reply is
    /// hydrated exactly as an inbound sync would be. Ties resolve to the
    /// group's `Source`.
    ///
    /// A member reporting an *older* version than this device is ignored —
    /// the check never turns into a publish. Nothing here writes to a peer.
    ///
    /// Nothing triggers this automatically: the library provides the
    /// mechanism and the application chooses when to run it (a user action, a
    /// timer, app start). Concludes with [`DeRecEvent::ReplicaDiscoveryComplete`],
    /// plus the usual hydration event when a fetch actually happened.
    ///
    /// The check concludes once every member asked has answered, or once
    /// [`Timeouts::get_share_response`](crate::protocol::types::Timeouts::get_share_response)
    /// has elapsed, on whatever was reported by then: a member that never
    /// answers contributes nothing. Only [`DeRecProtocol::tick`](crate::protocol::DeRecProtocol::tick)
    /// or a later `process` notices the elapsed budget.
    ReplicaDiscovery,
    /// Remove a member from the replica group.
    ///
    /// **Replica-only.** `replica_id` names the member being removed — as a
    /// plain `u64`, matching the decimal form ids take everywhere else.
    /// Naming this device is a voluntary departure; naming another is an
    /// eviction. A `replica_id` that names no current member is rejected with
    /// [`crate::Error::InvalidInput`] rather than silently doing nothing.
    ///
    /// # What this flow does
    ///
    /// `start` tells every member, the departing one included, and then:
    ///
    /// - **Removing another member:** drops it on this device at once, with any
    ///   key only it used, and reports [`DeRecEvent::ReplicaRemoved`].
    /// - **Removing this device:** keeps its own row out of the roster for the
    ///   publish below, then drops this device's whole `secret_id` partition
    ///   and reports [`DeRecEvent::SelfRemovedFromGroup`].
    ///
    /// Either way it then publishes the latest snapshot, or an empty payload
    /// when there is none, with a roster that omits the member: the events of
    /// that round follow, as for [`DeRecFlow::ProtectSecret`]. The application
    /// does not publish anything itself to complete a removal.
    ///
    /// The departing member is on no distribution list from then on: it
    /// receives nothing more. Every other member flags it when told and drops
    /// it, with [`DeRecEvent::ReplicaRemoved`], once that roster arrives.
    /// Absence from a roster alone never removes anyone, since a device may
    /// hold members a roster has not caught up with yet.
    ///
    /// When this device removes itself, the remaining members acknowledge the
    /// publish after it has dropped the group channel; `process` fails those
    /// acknowledgements with an unknown-channel error, which the application
    /// can disregard.
    ///
    /// # Who may remove whom
    ///
    /// Any member may remove any member, the source included: a lost or
    /// stolen source must be removable by the devices that remain. The library
    /// checks no role, and could not enforce one, since every member holds the
    /// same group key. Ask the user before starting this flow, above all when
    /// it names the source.
    ///
    /// Removing the source promotes a successor: the first remaining member in
    /// the order [`DeRecChannelStore::replicas`](crate::protocol::DeRecChannelStore::replicas)
    /// returns, which is how the application chooses it. The device running
    /// this flow decides, and every other member reads the result from the
    /// roster. Removing a sole source dissolves the group.
    ///
    /// # What the removed member experiences
    ///
    /// It is not asked. When the notice naming it arrives, it drops its whole
    /// `secret_id` partition automatically and emits
    /// [`DeRecEvent::SelfRemovedFromGroup`]. If the notice is lost, it keeps
    /// what it held, but it is sent nothing new and the remaining members
    /// refuse its messages once the roster without it has reached them. The
    /// secret survives on the remaining members and the helpers.
    ///
    /// # Removal does not protect against a compromised device
    ///
    /// Every member holds the same group key, and removal does not replace
    /// it. The remaining members keep publishing under it, and nothing more is
    /// sent to the removed member, but removal still relies on the removed
    /// device's own library deleting its copy. That covers a lost or stolen device whose storage was not
    /// read. It does not cover a device whose storage was read: whoever read
    /// it keeps the group key and can decrypt every later publication it
    /// obtains, the one completing the removal included. Shared-key rotation
    /// does not help either, since each key is derived from the one before.
    /// Nothing recovers what such a device already copied, the secret
    /// included.
    UnpairReplica {
        replica_id: u64,
        memo: Option<String>,
    },
    /// Initiate an unpair flow against a paired channel.
    ///
    /// **Owner-initiated only.** This node must hold
    /// [`derec_proto::SenderKind::Owner`] on `channel_id`; otherwise
    /// [`crate::Error::RoleMismatch`] is returned. Helpers cannot tear
    /// down the relationship from the protocol layer — they may only
    /// refuse an incoming unpair request via
    /// [`super::DeRecProtocol::reject`].
    ///
    /// Whether the local state for `channel_id` is dropped immediately on
    /// `start(Unpair)` or only after the peer acknowledges is governed by
    /// [`crate::protocol::DeRecProtocolBuilder::with_unpair_ack`].
    Unpair {
        channel_id: ChannelId,
        /// Optional human-readable reason embedded into the wire request.
        /// Pass `None` (or an empty string) to omit.
        memo: Option<String>,
    },
    /// Broadcast updated communication info and/or transport endpoints to one
    /// or more paired helper channels.
    ///
    /// Either party may initiate. `communication_info: None` and an empty
    /// `own_transports` each leave that part unchanged; presence of
    /// `communication_info` (even with an empty map) instructs the peer to
    /// replace its stored map for this channel with the supplied one. A
    /// non-empty `own_transports` instructs the peer to use the new endpoints
    /// for the response and all subsequent messages.
    ///
    /// Replica members do not receive this flow: a member announces new values
    /// to its group by publishing a new version, which carries its refreshed
    /// roster row.
    ///
    /// The application is responsible for calling
    /// [`crate::protocol::DeRecProtocol::set_communication_info`] and/or
    /// [`crate::protocol::DeRecProtocol::set_own_transports`] **before**
    /// initiating this flow so the local state matches what is announced.
    /// See the setter docs for the endpoint-changeover discipline.
    UpdateChannelInfo {
        target: Target,
        /// Updated communication info. `None` leaves the peer's stored map
        /// untouched; `Some(_)` replaces it (an empty `HashMap` clears it).
        communication_info: Option<HashMap<String, String>>,
        /// Every endpoint this device can now be reached on, in its own
        /// preference order. Empty leaves the peer's stored set untouched;
        /// non-empty replaces it outright.
        own_transports: Vec<TransportProtocol>,
    },
}

/// Determines whether the unpair initiator waits for the peer's
/// acknowledgement before dropping its local state for the channel.
///
/// See [`crate::protocol::DeRecProtocolBuilder::with_unpair_ack`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UnpairAck {
    /// The initiator keeps its local channel/share/secret state until the
    /// peer's `Ok` response arrives — or until the configured protocol
    /// timeout elapses, at which point the state is dropped anyway and an
    /// [`DeRecEvent::Unpaired`] event surfaces.
    #[default]
    Required,
    /// The initiator drops its local state immediately after sending the
    /// request and emits [`DeRecEvent::Unpaired`] right away. Any later
    /// response is silently ignored.
    NotRequired,
}

/// Events emitted by [`super::DeRecProtocol::process`].
///
/// The application reacts to these instead of routing raw messages manually.
#[non_exhaustive]
#[derive(Debug)]
#[allow(clippy::large_enum_variant)]
pub enum DeRecEvent {
    /// Pairing completed — the shared key for `channel_id` is now persisted.
    ///
    /// `kind` is the local party's role in the pairing. The channel record
    /// stores its inverse — the peer's role — on
    /// [`crate::protocol::types::HelperChannel::peer_role`], which the
    /// orchestrator consults on every subsequent flow start and inbound
    /// message. Applications use `kind` to decide what to do next:
    ///
    /// - [`SenderKind::Owner`] — the Owner completed pairing with a Helper.
    ///   Call [`super::DeRecProtocol::start`] with [`DeRecFlow::ProtectSecret`]
    ///   to distribute shares, or [`DeRecFlow::Discovery`] to ask the Helper
    ///   which secrets it holds (e.g. after a recovery re-pairing).
    /// - [`SenderKind::Helper`] — the Helper side completed pairing; no
    ///   additional action is required (the Helper waits for incoming messages).
    /// - [`SenderKind::ReplicaSource`] / [`SenderKind::ReplicaDestination`] —
    ///   a replica pairing completed; the application may use the channel
    ///   as needed (Source pushes via `ProtectSecret`, Destination receives
    ///   via [`Self::ReplicaSecretReceived`]).
    PairingCompleted {
        /// Long-term `channel_id` both peers atomically rotated to at the
        /// end of the handshake. All post-pairing traffic and library
        /// state for this relationship keys on this value.
        channel_id: ChannelId,
        /// The transient `channel_id` used only during the pairing
        /// handshake — the one that traveled on the `ContactMessage` and
        /// the pairing envelopes. Already replaced with `channel_id` in
        /// library state; the library will refuse messages routed to it
        /// from this point on. Provided so applications that persisted
        /// the pairing id (e.g. displayed it in a UI or mirrored it to
        /// their own store) can rekey their own records.
        pairing_channel_id: ChannelId,
        kind: SenderKind,
        /// Key-value pairs extracted from the peer's `CommunicationInfo`
        /// (e.g. `"name"`, `"email"`, `"phone"`). Empty if the peer sent none.
        peer_communication_info: HashMap<String, String>,
    },

    /// A replica-mode pair handshake completed. Fires **alongside**
    /// [`Self::PairingCompleted`] on replica channels.
    ///
    /// Under the unidirectional replica model, the peer's role
    /// (`ReplicaDestination` or `ReplicaSource`) is already on
    /// [`crate::protocol::types::HelperChannel::peer_role`] — this event just adds the
    /// peer's `replica_id`, which the app needs as a `from_replica_id`
    /// when subsequent secret syncs arrive or when targeting the peer via
    /// `ProtectSecret`.
    ReplicaPaired {
        /// The channel the pair handshake just completed on.
        channel_id: ChannelId,
        /// The peer's replica identity, extracted from
        /// `derec.replica_id` in the peer's `CommunicationInfo`.
        peer_replica_id: u64,
    },

    /// A share was accepted and stored locally (Helper side).
    ///
    /// A helper never learns which replica wrote a share: helper-bound
    /// requests carry no replica identity, so every member of a group
    /// publishes to a helper as the owner. A replica learns the author of a
    /// version from [`Self::ReplicaSecretReceived`] instead.
    ShareStored { channel_id: ChannelId, version: u32 },

    /// The library refused an inbound `StoreShareRequest` (Helper side):
    /// nothing was stored, no stored version was removed, and the Owner was
    /// sent a `StoreShareResponse` carrying `status` and `memo`, which it
    /// observes as [`Self::ShareRejected`] with the same values.
    ///
    /// Emitted for every refusal the library itself makes, whatever the
    /// [`AutoAcceptPolicy`] or the `auto_respond_on_failure` setting, and
    /// always in place of [`Self::ActionRequired`] — a refused share never
    /// reaches the application's accept/reject decision:
    ///
    /// - `FORMAT_ERROR` — `share` is empty, is not a `CommittedDeRecShare`,
    ///   lacks its wrapped share, commitment or Merkle path, or does not
    ///   wrap a `DeRecShare`.
    /// - `VERIFICATION_FAILED` — the wrapped share does not verify against
    ///   its commitment: no subshares, a repeated `x`, or a Merkle path that
    ///   does not lead to the commitment.
    /// - `SIZE_LIMIT_EXCEEDED` — `share` is outside the Helper's
    ///   [`ParameterRange`](derec_proto::ParameterRange).
    /// - `VERSION_CONFLICT` — a different share is already stored at
    ///   `version` on this channel.
    ///
    /// A refusal decided by the application's
    /// [`DeRecShareStore::save`](crate::protocol::DeRecShareStore::save) is
    /// the application's own decision and does not emit this event.
    ShareRefused {
        channel_id: ChannelId,
        version: u32,
        /// The `StatusEnum` value sent to the Owner.
        status: i32,
        /// Human-readable reason sent to the Owner.
        memo: String,
    },

    /// A `ReplicaSource` peer pushed a secret sync on a `ReplicaDestination`
    /// channel. The library has already auto-acked the inbound
    /// `StoreShareRequest` and decoded the `ReplicaSecretPayload` into
    /// typed fields — the application can install `secret` directly,
    /// optionally using `shares` to verify or to take over the recovery
    /// flow toward each helper.
    ///
    /// **Recovery transitivity**: `secret.helpers[i].shared_key` lets
    /// the receiver authenticate as the Source toward each helper. For
    /// replica-to-replica traffic, all replicas share a single
    /// group-wide channel key (see
    /// [`crate::protocol::types::ReplicaSecretPayload`] for the handover
    /// protocol) — the receiver's own
    /// [`crate::protocol::DeRecSecretStore`] entry for this channel
    /// holds that group key, so impersonating the Source toward another
    /// destination is just a normal channel-key load. Treat the
    /// receiving device accordingly — see
    /// [`crate::protocol::types::ReplicaInfo`] for the security note.
    ReplicaSecretReceived {
        /// The channel the request arrived on.
        channel_id: ChannelId,
        /// The member this copy came from: the publisher on a push, the
        /// member that answered on a catch-up.
        from_replica_id: u64,
        /// The member that published `version`, now stored with it. Equal
        /// to `from_replica_id` on a push; on a catch-up it names the
        /// original publisher. `None` when the serving member's snapshot
        /// records no author.
        author_replica_id: Option<u64>,
        /// `secret_id` echoed from the inbound `StoreShareRequest`.
        secret_id: u64,
        /// `version` echoed from the inbound `StoreShareRequest`.
        version: u32,
        /// Decoded full secret — same shape the sender wrote. The
        /// `helpers`, `replicas` and `secrets` fields carry the canonical
        /// roster snapshot for this version.
        secret: Secret,
        /// Per-helper VSS share map. Each entry pairs a helper's
        /// `channel_id` with the serialized `CommittedDeRecShare` bytes
        /// the helper received — sufficient material for the receiver
        /// to drive a recovery against those helpers if needed.
        shares: Vec<ChannelShare>,
    },

    /// The first sync for a `secret_id` this device had no snapshot for —
    /// the secret now exists here.
    ///
    /// Distinguished from [`Self::ReplicaSecretReceived`], which reports a
    /// later version of a secret the device already held. Both are hydrated
    /// by the library before the event fires; the difference is what the
    /// application should show the user, since only this one changes the set
    /// of secrets on the device.
    ///
    /// This is **not** a recovery. Recovery reconstructs a secret from helper
    /// shares and is driven by the application through
    /// [`crate::protocol::DeRecProtocol::restore`]; this arrives unsolicited
    /// from a group member and is applied on receipt.
    ReplicaSecretInstalled {
        /// The channel the request arrived on. During an admission handover
        /// this is the ephemeral pairing channel, not the group channel —
        /// the group's own id is `secret.replicas.channel_id`.
        channel_id: ChannelId,
        /// The member this copy came from, as on
        /// [`Self::ReplicaSecretReceived`].
        from_replica_id: u64,
        /// The member that published `version`, as on
        /// [`Self::ReplicaSecretReceived`].
        author_replica_id: Option<u64>,
        /// `secret_id` echoed from the inbound `StoreShareRequest`.
        secret_id: u64,
        /// `version` echoed from the inbound `StoreShareRequest`.
        version: u32,
        /// Decoded full secret, already written to the stores.
        secret: Secret,
        /// Per-helper VSS share map, as on [`Self::ReplicaSecretReceived`].
        shares: Vec<ChannelShare>,
    },

    /// A member offered a different copy of the version this device holds.
    ///
    /// Two members published the same version independently — each derives
    /// the next version from what it held, so concurrent changes collide.
    /// Either change may be legitimate: one member may have paired a helper
    /// while another edited the secrets. Nothing was written; this device
    /// keeps its own copy and refused the incoming one with
    /// `VERSION_CONFLICT`, so the publisher sees
    /// [`Self::ReplicaSyncRejected`].
    ///
    /// The conflict is the application's to resolve. Both copies are
    /// complete states: the held one is in the local stores, the incoming
    /// one is `secret`. Publishing the resolved state with
    /// [`crate::protocol::DeRecFlow::ProtectSecret`] writes the next
    /// version, which supersedes both on every member and helper.
    ///
    /// Until then, the application must not publish from this device: any
    /// further `ProtectSecret` is a higher version that every other member
    /// applies over its own copy, losing the change it never merged.
    ReplicaVersionConflict {
        /// The channel the copy arrived on.
        channel_id: ChannelId,
        /// The member this copy came from.
        from_replica_id: u64,
        /// `secret_id` of the incoming copy.
        secret_id: u64,
        /// The contested version.
        version: u32,
        /// Who published the copy this device holds. `None` when its
        /// snapshot records no author.
        held_author_replica_id: Option<u64>,
        /// Who published the incoming copy. `None` when the serving
        /// member's snapshot records no author.
        incoming_author_replica_id: Option<u64>,
        /// The incoming copy's full state: secrets, helpers and replicas.
        secret: Secret,
    },

    /// This device refused a group member's copy of the secret.
    ///
    /// Emitted by the library on a group member receiving a copy of the
    /// secret it will not apply. The whole payload is checked before
    /// anything is written, so nothing was: no helper channel or key, no
    /// tracking share, no group member and no snapshot.
    ///
    /// - On a push (a replica-bound `StoreShareRequest`) the publisher has
    ///   already been answered with `status` and `memo`, whatever
    ///   `auto_respond_on_failure` says, and sees
    ///   [`Self::ReplicaSyncRejected`] carrying the same values. An
    ///   admission handover is answered on the group channel under the
    ///   group key it carries, since the admitter no longer holds the
    ///   ephemeral key. A handover that does not decode, or whose group key
    ///   or channel is unusable, leaves no channel the admitter can read:
    ///   the answer is sent where the request arrived and the admitter
    ///   learns of the refusal only by timing out.
    /// - On a catch-up (a member's `GetShareResponse` carrying the secret)
    ///   no answer is sent, since the payload is itself an answer.
    ///   `from_replica_id` is the member that served it.
    ///
    /// - `FORMAT_ERROR` — the payload does not decode, lacks its `secret`,
    ///   disagrees with the request's version or with the roster's group
    ///   key, carries a key that is not 32 bytes or a member with a reserved
    ///   id or unknown role, names a Helper in its share map that the roster
    ///   does not list, or carries a share map entry that does not decode.
    /// - `VERIFICATION_FAILED` — a share map entry does not verify against
    ///   its commitment.
    ///
    /// A different copy of a version already held is reported as
    /// [`Self::ReplicaVersionConflict`] instead.
    ReplicaSecretRefused {
        /// The channel the copy arrived on.
        channel_id: ChannelId,
        /// The member the copy came from.
        from_replica_id: u64,
        /// `secret_id` echoed from the inbound `StoreShareRequest`.
        secret_id: u64,
        /// `version` echoed from the inbound `StoreShareRequest`.
        version: u32,
        /// The `StatusEnum` value of the refusal, as sent to the publisher
        /// on a push.
        status: i32,
        /// Human-readable reason, as sent to the publisher on a push.
        memo: String,
    },

    /// A replica peer's `StoreShareResponse` to a secret sync we sent
    /// earlier. Fires on the replica channel, mirroring
    /// [`Self::ShareConfirmed`] / [`Self::ShareRejected`] on the helper
    /// side.
    ///
    /// `status` and `memo` come straight from the peer's
    /// `StoreShareResponseMessage.result`. Apps decide whether to retry,
    /// rebroadcast, or surface the failure to the user.
    ReplicaSecretAcked {
        channel_id: ChannelId,
        /// The peer's replica identity (from `Channel.replica_id`).
        from_replica_id: u64,
        /// `secret_id` echoed from the response.
        secret_id: u64,
        /// `version` echoed from the response.
        version: u32,
        /// The `StatusEnum` value from the peer's response.
        status: i32,
        /// Human-readable explanation from the peer (empty on `Ok`).
        memo: String,
    },

    /// A group member **refused** a secret sync we sent.
    ///
    /// The member answered and declined — distinct from
    /// [`Self::ReplicaSyncFailed`], where no usable answer arrived at all
    /// (transport error, encoding error, or timeout). Either way the member
    /// lands in `behind` on [`Self::ReplicaSyncComplete`] rather than failing
    /// the round; replicas are best-effort.
    ///
    /// Keyed by `replica_id`, not `channel_id`: every member answers on the
    /// one group channel, so the channel cannot say who replied.
    ReplicaSyncRejected {
        /// The member that refused, from the response payload.
        replica_id: u64,
        /// `secret_id` echoed from the response.
        secret_id: u64,
        /// `version` echoed from the response.
        version: u32,
        /// The `StatusEnum` value from the member's response.
        /// `VERSION_CONFLICT` means another member holds a different copy of
        /// this version. The application must not publish from this device
        /// again until the conflict is resolved: run
        /// [`crate::protocol::DeRecFlow::ReplicaDiscovery`] to receive the
        /// group's copy as [`Self::ReplicaVersionConflict`], merge, and publish
        /// the result once with
        /// [`crate::protocol::DeRecFlow::ProtectSecret`].
        status: i32,
        /// Human-readable explanation from the member.
        memo: String,
    },

    /// A secret sync could not be delivered to a member, or the member did
    /// not acknowledge it in time.
    ///
    /// Distinct from [`Self::ReplicaSyncRejected`], which is the member
    /// answering "no". The member is reported once, either at dispatch, when
    /// nothing could be sent, or by [`super::DeRecProtocol::tick`] when no
    /// acknowledgement arrived within
    /// [`Timeouts::sharing_round`](crate::protocol::types::Timeouts::sharing_round),
    /// and appears in [`Self::ReplicaSyncComplete::behind`].
    ReplicaSyncFailed {
        /// The member that could not be reached.
        replica_id: u64,
        /// The version this round was publishing.
        version: u32,
        /// `"timeout"` when the member did not acknowledge in time; otherwise
        /// the transport or encoding failure, rendered for display.
        reason: String,
    },

    /// A member was removed from the group and its roster row dropped.
    ///
    /// Fires on the device that ran the removal, when it starts it, and on
    /// every other remaining member when the roster without the member
    /// arrives. The departing device instead reports
    /// [`Self::SelfRemovedFromGroup`].
    ///
    /// The group key is unchanged, so a removed device whose storage was read
    /// can still decrypt later publications; see
    /// [`DeRecFlow::UnpairReplica`].
    ReplicaRemoved {
        /// The member that left or was evicted.
        replica_id: u64,
    },

    /// The group's [`crate::protocol::types::ReplicaRole::Source`] moved to a
    /// different member, because the previous source is leaving.
    ///
    /// Fires on the device that ran the removal, naming the successor it chose,
    /// and on any member whose own row is promoted by an arriving roster. A
    /// member that is neither is unaffected: it learns the new source from
    /// `ReplicaInfo.role` like any other roster field.
    ReplicaSourceChanged {
        /// The member that now holds the source role.
        replica_id: u64,
    },

    /// This device has left the group and dropped its entire `secret_id`
    /// partition — group channel, helper channels, shares, secrets and the
    /// user-secret snapshot.
    ///
    /// Fires when this device is told to leave, when it removes itself after
    /// publishing the roster without it, or when a roster excluding it
    /// arrives after it was told to leave by a device on an earlier release.
    ///
    /// The teardown is automatic: this device is not asked first, and gets no
    /// earlier event. The secret survives on the remaining members and the
    /// helpers. Any member may cause it, the source included — see
    /// [`DeRecFlow::UnpairReplica`].
    SelfRemovedFromGroup {
        /// The newest version this device held when it left.
        version: u32,
    },

    /// A replica catch-up finished.
    ///
    /// `group_version` is the newest version any member reported; it is `0`
    /// when no member answered. `fetched_from` names the member the state was
    /// pulled from, and is `None` when this device was already current — in
    /// which case no hydration event follows.
    ReplicaDiscoveryComplete {
        /// The version this device held when the check started.
        local_version: u32,
        /// The newest version any member reported.
        group_version: u32,
        /// The member the newest state was pulled from, if a fetch happened.
        fetched_from: Option<u64>,
    },

    /// The replica leg of a publishing round finished.
    ///
    /// Reported separately from [`Self::SharingComplete`] because the two
    /// populations have different success rules and different keys. Replicas
    /// are **best-effort**: a member in `behind` does not fail the round. A
    /// replica holds a full copy and contributes nothing to the recovery
    /// quorum, so blocking on one offline device would freeze writes for the
    /// whole group while buying no safety.
    ///
    /// `behind` is the application's retry list. The library keeps no durable
    /// per-member sync state, so an application that wants convergence across
    /// restarts must persist this itself or republish to the whole group.
    ///
    /// # Best-effort governs the *outcome*, not the timing
    ///
    /// A member that never answers does not fail the round — but it does
    /// delay the report. This event and [`Self::SharingComplete`] are emitted
    /// together, once both populations have settled, so an unreachable member
    /// holds *both* back until it times out
    /// ([`Timeouts::sharing_round`](crate::protocol::types::Timeouts::sharing_round)).
    /// Per-peer events ([`Self::ShareConfirmed`],
    /// [`Self::ReplicaSecretAcked`]) are not delayed and can be watched
    /// instead where promptness matters.
    ReplicaSyncComplete {
        /// The version this round was publishing.
        version: u32,
        /// Members that acknowledged.
        synced: Vec<u64>,
        /// Members that refused, timed out, or could not be reached.
        behind: Vec<u64>,
    },

    /// A Helper confirmed it stored our share (Owner side).
    ///
    /// Reported as the response arrives, without matching it to a request
    /// this device sent: pairing it with what was asked is the application's
    /// concern.
    /// A sharing round counts a confirmation only while it is open and still
    /// waiting on that Helper, so decide which versions committed from
    /// [`Self::SharingComplete`], not by counting these.
    ShareConfirmed { channel_id: ChannelId, version: u32 },

    /// A Helper rejected or failed to store our share (Owner side).
    ///
    /// The protocol absorbs sharing failures and converts them to events
    /// so the application can display per-participant progress. `status` and
    /// `memo` come from the Helper's response, except for a Helper that did
    /// not answer within
    /// [`Timeouts::sharing_round`](crate::protocol::types::Timeouts::sharing_round):
    /// [`super::DeRecProtocol::tick`] then reports it with status `FAIL` and
    /// memo `"timeout"`. The memo of a Helper's own answer is free text and
    /// can read the same.
    ///
    /// Reported as the response arrives, without matching it to a request
    /// this device sent: pairing it with what was asked is the application's
    /// concern.
    ShareRejected {
        channel_id: ChannelId,
        version: u32,
        /// The `StatusEnum` value from the Helper's response.
        status: i32,
        /// Human-readable reason from the Helper, or `"timeout"`.
        memo: String,
    },

    /// A sharing round has completed (all participants responded or timed out).
    ///
    /// Emitted once per round after every targeted Helper has either
    /// confirmed, rejected, or timed out.
    ///
    /// # It also waits for the replica leg
    ///
    /// A round that targeted replica group members as well as Helpers does
    /// **not** report until *both* populations have settled. The counts below
    /// describe Helpers only, and they are known as soon as the Helpers answer
    /// — but the event is withheld until every member has acknowledged,
    /// refused, or timed out.
    ///
    /// The practical consequence: **one unreachable member delays this event
    /// by up to the configured timeout**
    /// ([`Timeouts::sharing_round`](crate::protocol::types::Timeouts::sharing_round)),
    /// even though the Helpers may have confirmed in milliseconds. An
    /// application waiting on `SharingComplete` to tell the user their secret
    /// is protected will appear to hang for that window. Nothing is lost and
    /// the round does terminate — the timeout sweep closes it — but the
    /// application is told late.
    ///
    /// A Helpers-only round is unaffected and completes as soon as the Helpers
    /// answer.
    ///
    /// If the two legs need to be observed independently, watch the per-peer
    /// events instead: [`DeRecEvent::ShareConfirmed`] /
    /// [`DeRecEvent::ShareRejected`] land as each Helper answers, without
    /// waiting for anyone else.
    ///
    /// The replica leg reports separately via
    /// [`DeRecEvent::ReplicaSyncComplete`], which is emitted at the same
    /// moment as this event when the round had members.
    SharingComplete {
        version: u32,
        confirmed_count: usize,
        failed_count: usize,
        /// `true` when the confirmed weight `>= threshold`, the threshold
        /// this round split at: the subshares
        /// held by the confirmed Helpers, counting each Helper's weight from
        /// the share this device dispatched to it (`1` when that share is
        /// missing or does not decode). `confirmed_count` and `failed_count`
        /// count Helpers.
        threshold_met: bool,
    },

    /// A Helper's verification proof checked out (Owner side).
    ///
    /// To judge whether `version` is recoverable, sum `subshares` over the
    /// `ShareVerified` events for that version and compare the sum with
    /// their `threshold`: recovery needs that many distinct subshares. If
    /// either value is `None` on any of those events, the result is
    /// unknown: a `None` count is not `0` or `1`.
    ShareVerified {
        channel_id: ChannelId,
        version: u32,
        /// How many subshares this Helper holds for `version`: the
        /// [`Share::subshares`](crate::protocol::types::Share::subshares) of
        /// the owner's stored share for this channel and version. It is the
        /// weight of the round that published `version`, not the Helper's
        /// current weight. `None` when that row was written before the count
        /// was recorded.
        subshares: Option<u32>,
        /// The threshold `version` was split with: the
        /// [`Share::threshold`](crate::protocol::types::Share::threshold) of
        /// the same owner row. It is that version's `t`, not the current one.
        /// `None` when that row was written before the threshold was recorded.
        threshold: Option<u32>,
    },

    /// A Helper answered a verification challenge with an OK status, but
    /// its proof does not match the share this device committed to (Owner
    /// side). The helper no longer holds the exact share bytes: its copy is
    /// corrupted, or it is answering for a different share.
    ///
    /// The challenge is spent, as with [`Self::ShareVerifyRejected`].
    ShareVerifyInvalid { channel_id: ChannelId, version: u32 },

    /// A Helper refused a verification challenge (Owner side): its
    /// `VerifyShareResponse` carried a non-OK status instead of a proof.
    ///
    /// The challenge is spent either way — a later response to it is dropped
    /// — so checking this helper again takes a new
    /// [`DeRecFlow::VerifyShares`] round.
    ShareVerifyRejected {
        channel_id: ChannelId,
        version: u32,
        /// The `StatusEnum` value from the Helper's response.
        status: i32,
        /// Human-readable reason from the Helper.
        memo: String,
    },

    /// A Helper reported all secrets it currently stores for this channel (Owner side).
    ///
    /// Emitted after the Owner calls [`super::DeRecProtocol::start`] with
    /// [`DeRecFlow::Discovery`] and the Helper responds. Each
    /// [`SecretVersionEntry`] carries a `secret_id` and a list of
    /// `(version, description)` pairs for every share the Helper holds.
    ///
    /// The application should persist this list and, once enough Helpers have
    /// responded, call [`super::DeRecProtocol::start`] with
    /// [`DeRecFlow::RecoverSecret`] for the desired `(secret_id, version)`.
    ///
    /// Reported as the response arrives, without matching it to a request
    /// this device sent: pairing it with what was asked is the application's
    /// concern.
    SecretsDiscovered {
        channel_id: ChannelId,
        /// All secrets and their stored versions the Helper holds for this channel.
        secrets: Vec<SecretVersionEntry>,
    },

    /// A Helper's share was collected for a recovery (Owner side). Nothing is
    /// reconstructed until every Helper asked has answered or the recovery
    /// times out; see [`DeRecFlow::RecoverSecret`].
    ///
    /// - `channel_id` identifies the Helper that sent this share response.
    /// - `shares_received` is the number of Helpers whose shares are collected
    ///   so far for this `(secret_id, version)` recovery context: one per
    ///   channel, not counting refused or corrupted shares.
    RecoveryShareReceived {
        channel_id: ChannelId,
        shares_received: usize,
    },

    /// A Helper refused a recovery share request (Owner side): its
    /// `GetShareResponse` carried a non-OK status instead of a share — for
    /// example `UNKNOWN_SHARE_VERSION` when it holds no share for `version`.
    ///
    /// The refusal is not collected and does not count towards
    /// `shares_received`. It is still that Helper's answer: it answers the
    /// [`Self::RecoverSecretStarted`] issued for `channel_id`, and when it is
    /// the last answer due the recovery decides on the shares it holds.
    RecoveryShareRefused {
        channel_id: ChannelId,
        version: u32,
        /// The `StatusEnum` value from the Helper's response.
        status: i32,
        /// Human-readable reason from the Helper.
        memo: String,
    },

    /// A Helper answered a recovery share request with a share that cannot
    /// be part of the recovered secret (Owner side). `reason` says how it
    /// failed; see [`CorruptionReason`].
    ///
    /// The share is set aside: it is never used for reconstruction, does not
    /// count towards `shares_received`, and cannot block the recovery — the
    /// other Helpers' shares still complete it. A share that fails on its
    /// own ([`CorruptionReason::Malformed`],
    /// [`CorruptionReason::InvalidProof`]) is reported as it arrives, and
    /// counts as that Helper's answer; one in a group that reconstructs
    /// something that is not a secret ([`CorruptionReason::Forged`]) is
    /// reported with the recovery's decision, once per Helper.
    ///
    /// An honest Helper never sends a corrupted share, so the application may
    /// treat this as a sign that the Helper's device or storage is damaged or
    /// compromised — for example by offering to unpair it. A share that only
    /// disagrees with the others is never reported here; see
    /// [`Self::RecoveryDisputed`] and [`Self::RecoveryConflict`]. It also answers
    /// the [`Self::RecoverSecretStarted`] issued for `channel_id`.
    ///
    /// A share bigger than this device's own configured `max_share_size` is
    /// also reported here, as [`CorruptionReason::Malformed`] — the owner
    /// has no proof to check an unsolicited share against during recovery,
    /// so a byte limit is the only bound it can enforce before parsing.
    RecoveryShareCorrupted {
        channel_id: ChannelId,
        version: u32,
        reason: CorruptionReason,
    },

    /// Recovery completed — the reconstructed
    /// [`crate::protocol::types::Secret`] is returned exactly once.
    ///
    /// The variant mirrors [`Self::ReplicaSecretReceived`]: the
    /// inner `secret` carries the full typed snapshot
    /// — `secrets: Vec<UserSecret>` (the user-facing entries the
    /// owner originally protected) plus the roster snapshot
    /// (`helpers` and `replicas`) captured at
    /// distribution time. Apps that only care about the user-facing
    /// entries read `secret.secrets`; the roster fields are useful
    /// when the recovering owner wants to know who held the shares,
    /// re-pair with the same helpers, or sync replicas after the
    /// recovery completes.
    ///
    /// The replica group is `secret.replicas`: its `members` (each with
    /// `replica_id`, `role` and `transports`, the lost device among them) and
    /// the group `channel_id`. A group with members other than the lost
    /// device is what the application checks before calling `restore`: if
    /// any of them is still live, offer to join the group rather than
    /// restore. See [`super::DeRecProtocol::restore`] for why.
    ///
    /// The library decodes the two-layer (`DeRecSecret` → `Secret`)
    /// wrapping internally; a group whose bytes do not decode is not a
    /// secret, and never surfaces here with bogus contents.
    ///
    /// Pass `secret` to [`super::DeRecProtocol::restore`] on the same
    /// protocol instance that ran recovery — it holds the recovery-mode
    /// channels `restore` unpairs — to commit canonical helper / replica
    /// state and wipe those throwaway channels.
    SecretRecovered { secret: Secret },

    /// A recovery reconstructed two or more different secrets for `version`
    /// (Owner side), so it cannot tell which is the owner's.
    ///
    /// Each candidate is a complete, self-consistent secret, rebuilt from the
    /// shares of the Helpers it names. Fewer than the threshold of colluding
    /// Helpers can forge one, so the library never picks: the application has
    /// to involve the owner — for example by showing what each candidate
    /// holds and who backs it — and pass the one the owner confirms to
    /// [`super::DeRecProtocol::restore`], exactly as it would the `secret` of
    /// [`Self::SecretRecovered`]. The Helpers backing a rejected candidate are
    /// suspect.
    ///
    /// `disputed_by` names the Helpers holding valid shares of yet another
    /// split that does not reconstruct, so no Helper's answer goes unshown.
    ///
    /// The recovery is closed when this is emitted.
    RecoveryConflict {
        version: u32,
        candidates: Vec<RecoveryCandidate>,
        disputed_by: Vec<RecoveryHelper>,
    },

    /// A recovery reconstructed one secret for `version`, but other Helpers
    /// hold valid shares of a different split that does not reconstruct
    /// (Owner side).
    ///
    /// `secret` is complete and self-consistent, rebuilt from the shares of
    /// `supported_by`. The shares of `disputed_by` each pass their own proof
    /// but belong to another split at the same version, which an honest
    /// sharing never produces. Either side can be the owner's: colluding
    /// Helpers can forge a complete split, and the honest Helpers may be too
    /// few to reconstruct theirs. The library never picks: the application
    /// has to involve the owner — for example by showing what `secret`
    /// holds and who stands on each side — and pass `secret` to
    /// [`super::DeRecProtocol::restore`] only once the owner confirms it.
    ///
    /// The recovery is closed when this is emitted.
    RecoveryDisputed {
        version: u32,
        secret: Secret,
        supported_by: Vec<RecoveryHelper>,
        disputed_by: Vec<RecoveryHelper>,
    },

    /// A recovery of `(secret_id, version)` closed without reconstructing a
    /// secret (Owner side): every Helper asked has answered, or the rest
    /// timed out, and no collected shares reconstruct.
    ///
    /// `secret_id` and `version` name the recovery that closed, as passed to
    /// [`DeRecFlow::RecoverSecret`]; recoveries of several secrets can be
    /// open at once. `shares_received` is the number of Helpers whose shares
    /// were collected. The recovery is closed; run
    /// [`DeRecFlow::RecoverSecret`] again to retry, for example once more
    /// Helpers are reachable.
    RecoveryIncomplete {
        secret_id: u64,
        version: u32,
        shares_received: usize,
    },

    /// An incoming request requires application confirmation before the library responds.
    ///
    /// Emitted by [`super::DeRecProtocol::process`] for every incoming request
    /// that is **not** opted into auto-accept by [`AutoAcceptPolicy`].
    /// The application must call [`super::DeRecProtocol::accept`] or
    /// [`super::DeRecProtocol::reject`] to complete the flow.
    ActionRequired {
        channel_id: ChannelId,
        action: PendingAction,
    },

    /// The library auto-accepted an incoming request because the
    /// configured [`AutoAcceptPolicy`] opted in to its flow.
    ///
    /// Emitted by [`super::DeRecProtocol::process`] **in place of**
    /// [`Self::ActionRequired`] for the auto-accepted flow, followed
    /// (in the same event vec) by the same flow events a manual
    /// `accept(action)` would have produced (e.g. `ShareStored`,
    /// `PairingCompleted`, `Unpaired`). Applications use this event
    /// for observability / audit logging — no further action is
    /// required from the caller.
    AutoAccepted {
        channel_id: ChannelId,
        /// The action's discriminant. The original
        /// [`PendingAction`] payload is consumed by the internal
        /// `accept` and is not surfaced here; routing on the kind is
        /// enough for observability since the flow-completion events
        /// that follow carry the per-flow details.
        action_kind: PendingActionKind,
    },

    /// A request that arrived on an authenticated channel failed while it was
    /// being handled.
    ///
    /// Every such request is owed exactly one response. When the library sent
    /// it, `responded` is `true` and `action` is `None`. Otherwise `responded`
    /// is `false` and `action` holds a [`PendingAction::RespondToFailure`];
    /// pass it to [`super::DeRecProtocol::reject`] to send the response.
    ///
    /// `action` is also `None`, with `responded` `false`, when no token could
    /// ever be answered:
    ///
    /// - a request on a replica group channel that names no member and
    ///   carries no `reply_to`, such as a body that could not be decoded. No
    ///   reply target can exist for it, and nothing is sent in either
    ///   `auto_respond_on_failure` mode;
    /// - with `auto_respond_on_failure` off, a replica copy that hands this
    ///   device the group key and fails before the copy is applied. The
    ///   response is owed on the group channel, whose key is not stored yet.
    ///
    /// Reported instead of an error from [`super::DeRecProtocol::process`] or
    /// [`super::DeRecProtocol::accept`], so the other events of the same call
    /// are kept.
    RequestFailed {
        /// The channel the request arrived on.
        channel_id: ChannelId,
        /// The type of the request that failed. [`PendingActionKind::Failed`]
        /// for a body that could not be decoded or a request the channel
        /// cannot carry.
        action_kind: PendingActionKind,
        /// `true` when the response was handed to the transport.
        responded: bool,
        /// The `StatusEnum` value that was sent, or that would have been
        /// sent.
        status: i32,
        /// The memo sent with `status`, or that would have been: wire-safe,
        /// never the local error text. Passing `status` and `memo` to
        /// [`super::DeRecProtocol::reject`] with `action` sends the response
        /// `auto_respond_on_failure` would have sent.
        memo: String,
        /// The error's code name, as the SDKs surface it.
        error_code: String,
        /// Local description of the failure. Never sent to the peer.
        message: String,
        /// The token that answers the request, present only when
        /// `responded` is `false` and a reply target can exist.
        action: Option<PendingAction>,
    },

    /// The peer answered a message from this device with an
    /// `ErrorResponseMessage`: it could not process it, typically because
    /// the body could not be decoded (`FORMAT_ERROR`).
    ///
    /// Reported only once the message passes the envelope timestamp binding,
    /// like any other body. It is never answered, in either
    /// `auto_respond_on_failure` mode, so two peers cannot trade them.
    ///
    /// Reported as the response arrives, without matching it to a request
    /// this device sent: pairing it with what was asked is the application's
    /// concern.
    ErrorResponseReceived {
        channel_id: ChannelId,
        /// The `StatusEnum` value from the peer's response.
        status: i32,
        /// Human-readable reason from the peer.
        memo: String,
    },

    /// The local channel state for `channel_id` has been dropped as the
    /// result of an unpair flow.
    ///
    /// Surfaces on **both** sides of the flow:
    ///
    /// - Initiator: emitted when (a) `UnpairAck::NotRequired` and the request
    ///   has just been sent, (b) `UnpairAck::Required` and the peer
    ///   acknowledged with `Ok`, (c) `UnpairAck::Required` and the
    ///   configured timeout elapsed without a response, or (d) a recovery
    ///   channel `restore` tears down was refused, right after
    ///   [`Self::UnpairRejected`].
    /// - Responder: emitted by [`super::DeRecProtocol::accept`] after the
    ///   channel/share/secret state for the requesting peer has been removed.
    Unpaired { channel_id: ChannelId },

    /// The peer answered an outbound unpair request with a non-`Ok` status.
    ///
    /// After `start(Unpair)` the initiator's local state is **not** dropped,
    /// and the channel is `Paired` again — the application decides what to do
    /// (retry, escalate, or force-delete locally). A recovery channel
    /// `restore` tears down is dropped all the same, and
    /// [`Self::Unpaired`] follows.
    UnpairRejected {
        channel_id: ChannelId,
        /// The `StatusEnum` value from the peer's response.
        status: i32,
        /// Human-readable reason from the peer.
        memo: String,
    },

    /// The contact creator answered our `PrePairRequest` with a non-`Ok`
    /// status (scanner side, `HashedKeys` flow).
    ///
    /// The scanner cannot proceed to a normal `PairRequest` because the
    /// public keys were never published. Distinct from
    /// [`crate::primitives::pairing::PairingError::PrePairHashMismatch`],
    /// which fires when keys *were* published but failed the binding-hash
    /// check — a cryptographic failure surfaced as `Err`, not an event.
    PrePairRejected {
        channel_id: ChannelId,
        /// The `StatusEnum` value from the contact creator's response.
        status: i32,
        /// Human-readable reason from the contact creator.
        memo: String,
    },

    /// This device refused an inbound `PairRequest` under a protocol rule,
    /// whatever the [`AutoAcceptPolicy`] or the `auto_respond_on_failure`
    /// setting, and sent the requester a `PairResponse` carrying `status`
    /// and `memo`. No channel was created.
    ///
    /// The rules are a parameter range that does not overlap this device's
    /// (`INCOMPATIBLE_PARAMETER_RANGE`) and a replica id already held by a
    /// member of the group (`REPLICA_ID_CONFLICT`). The refusal is the
    /// result of [`super::DeRecProtocol::process`], not an error; a refusal
    /// that could not be sent fails `process` instead.
    ///
    /// `memo` is what the requester reads, written from its side. The local
    /// reason is carried by `error_code` and `message`, in the same shape as
    /// [`Self::RequestFailed`], so the application can log or render it.
    PairingRefused {
        channel_id: ChannelId,
        /// The `StatusEnum` value sent to the requester.
        status: i32,
        /// Human-readable reason sent to the requester.
        memo: String,
        /// The refusal's error code name, as the SDKs surface it:
        /// `incompatible_parameter_range` or `replica_id_conflict`.
        error_code: String,
        /// Local description of the refusal. Never sent to the peer.
        message: String,
    },

    /// The stored [`crate::protocol::types::HelperChannel`] for `channel_id` has been updated
    /// with new communication info and/or transport endpoint.
    ///
    /// Surfaces on **both** sides of the flow:
    ///
    /// - Responder: emitted by [`super::DeRecProtocol::accept`] after the
    ///   update has been persisted to the local channel store.
    /// - Initiator: emitted by [`super::DeRecProtocol::process`] when the
    ///   peer's `Ok` response arrives.
    ///
    /// The new `communication_info` / endpoint values are
    /// already on the local
    /// [`crate::protocol::types::HelperChannel`] by the time the event fires;
    /// applications that care about the post-update state read it from
    /// the channel store directly.
    ///
    /// On the initiator it is reported as the response arrives, without
    /// matching it to a request this device sent: pairing it with what was
    /// asked is the application's concern.
    ChannelInfoUpdated { channel_id: ChannelId },

    /// The peer answered an outbound `UpdateChannelInfo` request with a
    /// non-`Ok` status. The peer's stored state is unchanged. The initiator's
    /// own state is also unaffected.
    ///
    /// Reported as the response arrives, without matching it to a request
    /// this device sent: pairing it with what was asked is the application's
    /// concern.
    ChannelInfoUpdateRejected {
        channel_id: ChannelId,
        /// The `StatusEnum` value from the peer's response.
        status: i32,
        /// Human-readable reason from the peer.
        memo: String,
    },

    /// Well-formed message with no actionable effect (e.g. an ACK).
    NoOp,

    /// An inbound message was dropped without being acted on: no store was
    /// written and nothing was sent back. `reason` says why and whether it
    /// can succeed later.
    ///
    /// `PendingVerification` is the case an application should surface. It
    /// means the peer sent something before this device confirmed the
    /// channel's fingerprint, and it is typically a replica source pushing
    /// its first copy while the destination is still showing the code.
    /// Confirming does not replay the message. Once
    /// [`super::DeRecProtocol::verify_fingerprint`] succeeds, a replica
    /// destination starts [`DeRecFlow::ReplicaDiscovery`] to pull the copy
    /// from the source itself.
    MessageIgnored {
        /// The channel the message arrived on.
        channel_id: ChannelId,
        reason: IgnoreReason,
        /// The envelope's trace id, so the drop can be matched to the
        /// peer's `*Started` event for the same round. `0` when the sender
        /// set none.
        trace_id: u64,
    },

    /// [`super::DeRecProtocol::restore`] wrote no channel for one entry of
    /// the recovered roster. Every other entry and the user-secret snapshot
    /// were restored as usual; `reason` says why this one was not.
    ///
    /// Nothing is stored for the peer, so this device cannot reach it. The
    /// peer itself is untouched: a helper still holds its share, and pairing
    /// with it again is what makes it reachable from this device.
    PeerNotRestored {
        /// The helper's channel, or the replica group's channel when the
        /// entry is a group member.
        channel_id: ChannelId,
        /// The member's `replica_id` when the entry is a replica group
        /// member; `None` for a helper.
        replica_id: Option<u64>,
        reason: NotRestoredReason,
    },

    /// A pairing flow was initiated for `channel_id` with the local
    /// role `kind`. Emitted synchronously from
    /// [`super::DeRecProtocol::start`] when the `PairRequest` (or
    /// `PrePairRequest` for `HashedKeys` / `NoKeys` modes) was
    /// dispatched successfully. Followed by
    /// [`Self::PairingCompleted`] (or a failure variant) once the peer
    /// responds. On a local send failure, `start` returns `Err` instead
    /// — no `PairingStarted` is emitted.
    PairingStarted {
        channel_id: ChannelId,
        /// Correlates this request with the response it will draw, and with
        /// every other request this same [`DeRecProtocol::start`](super::DeRecProtocol::start)
        /// call dispatched. One token is drawn per round, so a fan-out shares
        /// it across all of its targets.
        trace_id: u64,

        /// The local party's role in the pairing (same value that will
        /// appear on [`Self::PairingCompleted::kind`]; the channel record
        /// persists its inverse as
        /// [`crate::protocol::types::HelperChannel::peer_role`]).
        kind: SenderKind,
    },

    /// A discovery request was dispatched to `channel_id`. Emitted per
    /// targeted channel by [`super::DeRecProtocol::start`]. Followed by
    /// [`Self::SecretsDiscovered`] once the helper responds.
    DiscoveryStarted {
        channel_id: ChannelId,
        /// Correlates this request with the response it will draw, and with
        /// every other request this same [`DeRecProtocol::start`](super::DeRecProtocol::start)
        /// call dispatched. One token is drawn per round, so a fan-out shares
        /// it across all of its targets.
        trace_id: u64,
    },

    /// A discovery request could not be dispatched to `channel_id`.
    /// Emitted per targeted channel by [`super::DeRecProtocol::start`]
    /// when the outbound send (or per-channel preparation) failed. The
    /// remaining channels in the same fan-out are unaffected.
    DiscoveryFailed {
        channel_id: ChannelId,
        error: String,
    },

    /// A share-storage request was dispatched to `channel_id` for
    /// `version`. Emitted **per targeted helper** by
    /// [`super::DeRecProtocol::start`]. Followed by [`Self::ShareStored`] /
    /// [`Self::ShareConfirmed`] / [`Self::ShareRejected`] as the peer
    /// responds; the helper leg finishes with [`Self::SharingComplete`].
    ///
    /// The replica leg is **not** reported here. This event is keyed by
    /// channel, and every member of a group shares one — emitting per member
    /// would yield indistinguishable duplicates. Members report through
    /// [`Self::ReplicaSyncFailed`] at dispatch and
    /// [`Self::ReplicaSyncComplete`] at the end, both keyed by `replica_id`.
    ProtectSecretStarted {
        channel_id: ChannelId,
        version: u32,
        /// Correlates this request with the response it will draw, and with
        /// every other request this same [`DeRecProtocol::start`](super::DeRecProtocol::start)
        /// call dispatched. One token is drawn per round, so a fan-out shares
        /// it across all of its targets.
        trace_id: u64,
        /// The number of subshares sent to `channel_id` this round, which is
        /// also the weight now stored for it: its entry in
        /// [`DeRecFlow::ProtectSecret`]'s `weights`, `1` for a Helper the map
        /// does not name, or the stored weight on a publish the library
        /// starts on its own.
        weight: u32,
    },

    /// A share-storage request could not be dispatched to `channel_id`
    /// for `version`. Remaining fan-out targets are unaffected.
    ProtectSecretFailed {
        channel_id: ChannelId,
        version: u32,
        error: String,
        /// The number of subshares that were meant for `channel_id` this
        /// round, with the same meaning as on [`Self::ProtectSecretStarted`].
        weight: u32,
    },

    /// A verify-share challenge was dispatched to `channel_id` for
    /// `version`. Followed by [`Self::ShareVerified`],
    /// [`Self::ShareVerifyInvalid`] or [`Self::ShareVerifyRejected`] once the
    /// helper responds, or by [`Self::VerifySharesFailed`] with
    /// [`VerifyFailureReason::NoProof`] if the proof is removed first.
    VerifySharesStarted {
        channel_id: ChannelId,
        version: u32,
        /// Correlates this request with the response it will draw, and with
        /// every other request this same [`DeRecProtocol::start`](super::DeRecProtocol::start)
        /// call dispatched. One token is drawn per round, so a fan-out shares
        /// it across all of its targets.
        trace_id: u64,
    },

    /// No verdict could be reached for `channel_id` at `version` because of
    /// a condition on this device; `reason` says which. Remaining fan-out
    /// targets are unaffected.
    VerifySharesFailed {
        channel_id: ChannelId,
        version: u32,
        reason: VerifyFailureReason,
        error: String,
    },

    /// A recovery share request was dispatched to `channel_id` for
    /// `version`. Answered by [`Self::RecoveryShareReceived`] /
    /// [`Self::RecoveryShareRefused`] / [`Self::RecoveryShareCorrupted`], or
    /// by [`Self::RecoverSecretFailed`] with error `"timeout"` when the
    /// Helper stays silent; see [`DeRecFlow::RecoverSecret`].
    RecoverSecretStarted {
        channel_id: ChannelId,
        version: u32,
        /// Correlates this request with the response it will draw, and with
        /// every other request this same [`DeRecProtocol::start`](super::DeRecProtocol::start)
        /// call dispatched. One token is drawn per round, so a fan-out shares
        /// it across all of its targets.
        trace_id: u64,
    },

    /// A recovery share request could not be dispatched to `channel_id`
    /// for `version`, or the Helper did not answer it within
    /// [`Timeouts::get_share_response`](crate::protocol::types::Timeouts::get_share_response).
    ///
    /// `error` is exactly `"timeout"` for a Helper that did not answer in
    /// time, reported by [`super::DeRecProtocol::tick`]; otherwise it is the
    /// dispatch failure, rendered for display.
    RecoverSecretFailed {
        channel_id: ChannelId,
        version: u32,
        error: String,
    },

    /// An unpair request could not be dispatched to `channel_id`.
    ///
    /// Emitted by [`super::DeRecProtocol::restore`] when tearing down the
    /// ephemeral recovery channels. A helper gone away is the expected
    /// condition during recovery and the restore has already committed, so
    /// the peer's reachability is not load-bearing: local state is dropped
    /// anyway and a [`Self::Unpaired`] for the same channel follows. The pair reports "the channel is gone locally, but the
    /// peer was not told" — the application may notify it out-of-band.
    UnpairFailed {
        channel_id: ChannelId,
        error: String,
    },

    /// An unpair request was dispatched to `channel_id`, by
    /// `start(Unpair)` or by `restore` for each recovery channel. Under
    /// [`UnpairAck::Required`] the channel is now
    /// [`ChannelStatus::Unpairing`](crate::protocol::types::ChannelStatus::Unpairing),
    /// and [`Self::Unpaired`] follows once the peer acknowledges or the
    /// acknowledgement window elapses, or [`Self::UnpairRejected`] if the
    /// peer refuses. Under [`UnpairAck::NotRequired`], `Unpaired` is
    /// emitted in the same event vec immediately after `UnpairStarted`.
    UnpairStarted {
        channel_id: ChannelId,
        /// Correlates this request with the response it will draw, and with
        /// every other request this same [`DeRecProtocol::start`](super::DeRecProtocol::start)
        /// call dispatched. One token is drawn per round, so a fan-out shares
        /// it across all of its targets.
        trace_id: u64,
    },

    /// An update-channel-info request was dispatched to `channel_id`.
    /// Followed by [`Self::ChannelInfoUpdated`] once the peer responds.
    UpdateChannelInfoStarted {
        channel_id: ChannelId,
        /// Correlates this request with the response it will draw, and with
        /// every other request this same [`DeRecProtocol::start`](super::DeRecProtocol::start)
        /// call dispatched. One token is drawn per round, so a fan-out shares
        /// it across all of its targets.
        trace_id: u64,
    },

    /// An update-channel-info request could not be dispatched to
    /// `channel_id`.
    UpdateChannelInfoFailed {
        channel_id: ChannelId,
        error: String,
    },
}