derec-library 0.0.4

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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 DeRec Alliance. All rights reserved.

use super::super::{
    DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, DeRecTransport,
    MissingPolicy, PendingAction, SecretKind, SecretValue, Share,
};
use super::replicas::sharing as replica;
use crate::derec_message::DeRecMessageBuilder;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::extensions::message_body::{MessageBodyExt as _, Route};
use crate::primitives::sharing::request::SHARE_ALGORITHM_REPLICA_SECRET;
use crate::protocol::DeRecUserSecretStore;
use crate::protocol::context::{Exchange, Local, Round};
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::ChannelQuery;
use crate::{
    Error, Result,
    derec_message::current_timestamp,
    primitives::sharing::{
        request::{produce as produce_store_share_request_message, split},
        response::{self as sharing_response},
    },
    protocol::types::{HelperInfo, Secret, UserSecret},
    types::{ChannelId, SharedKey},
};
use derec_proto::{
    DeRecResult, DeRecSecret, MessageBody, SenderKind, StatusEnum, StoreShareRequestMessage,
    StoreShareResponseMessage,
};
use prost::Message;

#[cfg_attr(
    feature = "logging",
    tracing::instrument(skip_all, fields(trace_id = exchange.trace_id, channel_id = exchange.channel_id.0))
)]
pub(in crate::protocol) async fn handle<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    exchange: &Exchange<'_>,
    inner: MessageBody,
) -> Result<Vec<DeRecEvent>> {
    let channel_id = exchange.channel_id;
    match (inner.route(), &inner) {
        (Route::Replica(author), _) => {
            replica::handle(stores, local, exchange, author, inner).await
        }
        (Route::Helper, _) => {
            let channel = stores
                .channels
                .load(local.secret_id, ChannelQuery::Helper { channel_id })
                .await?
                .and_then(|r| r.as_helper().cloned())
                .ok_or(Error::InvalidInput(
                    "channel id not present in channel store",
                ))?;
            match (channel.peer_role, inner) {
                (SenderKind::Owner, MessageBody::StoreShareRequest(request)) => {
                    on_request(exchange, request)
                }
                (SenderKind::Helper, MessageBody::StoreShareResponse(response)) => {
                    on_response(channel_id, &response)
                }
                (actual, _) => Err(Error::RoleMismatch {
                    channel_id,
                    expected: SenderKind::Owner,
                    actual,
                }),
            }
        }
    }
}

/// Run one `ProtectSecret` round: VSS-split the secret to every paired
/// Helper and ship the full secret to every paired Replica Destination.
///
/// Returns `Ok(None)` when no peer is paired — the secret has nowhere to
/// land, and callers treat it as a no-op so the auto-publish-on-pair
/// hook can fire safely before any peer exists.
///
/// Version progression is anchored to `stores.user_secrets`, so it bumps
/// on every round — including roster-only auto-publishes to Destinations
/// that never write to `stores.shares`. The snapshot written at the end of
/// this function is the source of truth the next round reads.
///
/// The split runs once and feeds both the helper-distribution path and
/// the Destination composite. Below `threshold` no split runs at all:
/// Helpers receive nothing this round and any paired Replicas receive a
/// secret-only composite carrying no share material.
///
/// The snapshot is persisted only *after* distribution attempts
/// complete, so an interrupted round never leaves the version ahead of
/// what peers actually received. Per-channel failures surface as
/// `ProtectSecretFailed` and do not block the snapshot — the round stays
/// addressable and failed peers retry on the next one.
#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = round.trace_id, secret_id = local.secret_id)))]
pub(in crate::protocol) async fn start<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    secrets: Vec<UserSecret>,
    description: Option<String>,
    threshold: usize,
    keep_versions_count: usize,
    round: &Round<'_>,
) -> Result<Option<SharingRoundResult>> {
    let secret_id = local.secret_id;
    let (helpers, replicas) = load_all_paired_targets(stores, local).await?;

    if helpers.is_empty() && replicas.is_empty() {
        return Ok(None);
    }

    let snapshot_secrets = secrets.clone();
    let snapshot_description = description.clone();

    // The roster names every member, including this device — a group whose
    // members cannot name themselves is not reconstructible from the payload.
    // The dispatch list above is the same set minus self.
    let roster = stores
        .channels
        .replicas_matching(secret_id, crate::protocol::types::ReplicaFilter::default())
        .await?;
    let group_channel = group_channel_of(local, &roster)?;
    let group_key = match group_channel {
        Some(channel_id) => match stores
            .secrets
            .load(secret_id, channel_id, SecretKind::SharedKey)
            .await?
        {
            Some(SecretValue::SharedKey(key)) => Some(key),
            _ => {
                return Err(Error::Invariant(
                    "replica group channel has no key in the secret store",
                ));
            }
        },
        None => None,
    };
    let secret = build_secret(&helpers, &roster, secrets, group_channel, group_key)?;

    // A helper holds exactly one endpoint: the one it paired with. Every other
    // member of the group is invisible to it, so a publish from a group must
    // carry `round.reply_to` on the helper leg or the acknowledgement is routed to
    // whoever paired — which for a member that joined later is the wrong
    // device entirely. Decided here, where the roster is known, rather than
    // left to the application's `auto_reply_to` setting.
    let helper_reply_to: Vec<derec_proto::TransportProtocol> = if roster.is_empty() {
        round.reply_to.to_vec()
    } else {
        vec![local.primary().clone()]
    };
    let derec_secret_bytes = wrap_for_helper_split(&secret, threshold);

    let version = stores
        .user_secrets
        .load_latest(secret_id)
        .await?
        .map(|s| s.version + 1)
        .unwrap_or(1);
    let description = description.as_deref().unwrap_or("").to_owned();

    let helper_channel_ids: Vec<ChannelId> = helpers.iter().map(|(ch, _)| ch.channel_id).collect();
    let split_result = if helpers.len() >= threshold {
        Some(split(
            &helper_channel_ids,
            secret_id,
            version,
            &derec_secret_bytes,
            threshold,
        )?)
    } else {
        None
    };

    let mut outcomes: Vec<(ChannelId, Result<()>)> = Vec::new();
    let mut replica_outcomes: Vec<(crate::types::ReplicaId, Result<()>)> = Vec::new();

    if let Some(ref result) = split_result {
        let helper_outcomes = distribute_shares(
            stores,
            local,
            &helpers,
            result,
            keep_versions_count,
            version,
            &description,
            &Round {
                reply_to: &helper_reply_to,
                trace_id: round.trace_id,
            },
        )
        .await;
        outcomes.extend(helper_outcomes);
    }

    if !replicas.is_empty() {
        let composite = build_replica_composite(&secret, split_result.as_ref());
        let k_group = group_key;
        let replica_results = distribute_composite_to_destinations(
            stores,
            local,
            &replicas,
            &composite,
            k_group,
            version,
            &description,
            round,
        )
        .await;
        replica_outcomes.extend(replica_results);
    }

    stores
        .user_secrets
        .save_latest(
            secret_id,
            crate::protocol::types::UserSecrets {
                version,
                secrets: snapshot_secrets,
                description: snapshot_description,
                replicas: secret.replicas.clone(),
            },
        )
        .await?;

    Ok(Some(SharingRoundResult {
        version,
        outcomes,
        replica_outcomes,
    }))
}

/// The output of [`start`] on a round with at least one targeted peer.
///
/// `outcomes` carries one `(ChannelId, Result<()>)` per targeted
/// helper / replica — `Ok(())` on successful dispatch, `Err` on
/// per-channel stores.transport / store failure. The orchestrator maps each
/// entry to `ProtectSecretStarted` / `ProtectSecretFailed`.
pub(in crate::protocol) struct SharingRoundResult {
    pub(in crate::protocol) version: u32,
    /// One entry per helper written to, keyed by its channel.
    pub(in crate::protocol) outcomes: Vec<(ChannelId, Result<()>)>,
    /// One entry per group member written to, keyed by its `ReplicaId`.
    ///
    /// Separate from `outcomes` because members share one channel: keying
    /// them by `ChannelId` would collapse the whole group into a single
    /// entry, and the first answer would settle the round for all of them.
    pub(in crate::protocol) replica_outcomes: Vec<(crate::types::ReplicaId, Result<()>)>,
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(
        skip_all,
        fields(trace_id = exchange.trace_id,
            channel_id = exchange.channel_id.0,
            secret_id = request.secret_id,
            version = request.version
        )
    )
)]
pub(in crate::protocol) async fn accept<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    exchange: &Exchange<'_>,
    request: &StoreShareRequestMessage,
) -> Result<Vec<DeRecEvent>> {
    let channel_id = exchange.channel_id;
    let secret_id = local.secret_id;
    let version = request.version;
    let replica_id = request.replica_id;
    let encoded_request = request.encode_to_vec();

    // A version has exactly one writer, so an existing entry at this
    // version is either that writer re-sending the identical envelope —
    // an idempotent retry, acknowledged without rewriting — or a second
    // writer publishing concurrently, which is a conflict only the
    // application can resolve.
    //
    // A single writer derives `version` as `latest + 1` and so can never
    // rewrite a version with different content; differing bytes at the
    // same version therefore imply a second writer.
    //
    // Enforced here rather than delegated to store implementations so
    // every binding inherits one rule.
    let already_stored = stores
        .shares
        .load(secret_id, channel_id, &[version])
        .await?
        .into_iter()
        .find(|stored| stored.version == version);

    match already_stored {
        Some(stored) if stored.bytes != encoded_request => {
            reject(
                stores,
                local,
                exchange,
                request,
                StatusEnum::VersionConflict,
                "a different share is already stored at this version",
            )
            .await?;

            #[cfg(feature = "logging")]
            tracing::warn!(
                channel_id = channel_id.0,
                secret_id = secret_id,
                version = version,
                "version conflict — refused a second writer at an existing version"
            );

            return Ok(vec![DeRecEvent::NoOp]);
        }
        Some(_) => {
            // Byte-identical re-send: acknowledge without rewriting.
            #[cfg(feature = "logging")]
            tracing::debug!(
                channel_id = channel_id.0,
                secret_id = secret_id,
                version = version,
                "idempotent re-send of an already-stored share"
            );
        }
        None => {
            stores
                .shares
                .save(
                    secret_id,
                    channel_id,
                    Share {
                        secret_id: request.secret_id,
                        version,
                        bytes: encoded_request,
                    },
                )
                .await?;
        }
    }

    let resp = sharing_response::produce(channel_id, request, exchange.shared_key)?;
    let envelope = crate::derec_message::apply_trace_id(&resp.envelope, exchange.trace_id)?;
    let endpoint = stores
        .channels
        .resolve_response_endpoints(
            secret_id,
            channel_id,
            &crate::extensions::advertised_endpoints::reply_to_owned(request),
        )
        .await?;
    stores.transport.send(&endpoint, envelope).await?;

    #[cfg(feature = "logging")]
    tracing::info!(
        channel_id = channel_id.0,
        secret_id = secret_id,
        version = version,
        "share stored and acknowledged"
    );

    Ok(vec![DeRecEvent::ShareStored {
        channel_id,
        version,
        replica_id,
    }])
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(
        skip_all,
        fields(trace_id = exchange.trace_id,
            channel_id = exchange.channel_id.0,
            secret_id = request.secret_id,
            version = request.version
        )
    )
)]
pub(in crate::protocol) async fn reject<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    exchange: &Exchange<'_>,
    request: &StoreShareRequestMessage,
    status: StatusEnum,
    memo: &str,
) -> Result<()> {
    let channel_id = exchange.channel_id;
    let secret_id = local.secret_id;
    let response = StoreShareResponseMessage {
        result: Some(DeRecResult {
            status: status as i32,
            memo: memo.to_owned(),
        }),
        secret_id: request.secret_id,
        version: request.version,
        timestamp: Some(current_timestamp()),
        // Mirror the request's audience: only a replica-bound request is
        // rejected by a replica, and only then is a writer identity due.
        replica_id: request.replica_id.and(local.replica_id),
    };
    crate::extensions::channel_store::send_channel_message(
        stores.channels,
        stores.transport,
        secret_id,
        channel_id,
        MessageBody::StoreShareResponse(response),
        exchange.shared_key,
        exchange.trace_id,
        &crate::extensions::advertised_endpoints::reply_to_owned(request),
    )
    .await?;

    #[cfg(feature = "logging")]
    tracing::info!(
        channel_id = channel_id.0,
        secret_id = request.secret_id,
        version = request.version,
        status = status as i32,
        "share rejection sent"
    );

    Ok(())
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(
        skip_all,
        fields(trace_id = exchange.trace_id,
            channel_id = exchange.channel_id.0,
            secret_id = request.secret_id,
            version = request.version
        )
    )
)]
fn on_request(
    exchange: &Exchange<'_>,
    request: StoreShareRequestMessage,
) -> Result<Vec<DeRecEvent>> {
    Ok(vec![DeRecEvent::ActionRequired {
        channel_id: exchange.channel_id,
        action: PendingAction::StoreShare {
            channel_id: exchange.channel_id,
            request,
            shared_key: *exchange.shared_key,
            trace_id: exchange.trace_id,
        },
    }])
}

#[cfg_attr(
    feature = "logging",
    tracing::instrument(
        skip_all,
        fields(
            channel_id = channel_id.0,
            secret_id = response.secret_id,
            version = response.version
        )
    )
)]
fn on_response(
    channel_id: ChannelId,
    response: &StoreShareResponseMessage,
) -> Result<Vec<DeRecEvent>> {
    let version = response.version;
    match sharing_response::process(version, response) {
        Ok(()) => {
            #[cfg(feature = "logging")]
            tracing::info!(
                channel_id = channel_id.0,
                secret_id = response.secret_id,
                version = version,
                "share confirmed by helper"
            );

            Ok(vec![DeRecEvent::ShareConfirmed {
                channel_id,
                version,
            }])
        }
        Err(err) => {
            if let Some((status, memo)) = err.as_non_ok_status() {
                #[cfg(feature = "logging")]
                tracing::warn!(
                    channel_id = channel_id.0,
                    secret_id = response.secret_id,
                    version = version,
                    status,
                    memo,
                    "share rejected by helper"
                );

                Ok(vec![DeRecEvent::ShareRejected {
                    channel_id,
                    version,
                    status,
                    memo: memo.to_owned(),
                }])
            } else {
                Err(err)
            }
        }
    }
}

async fn load_all_paired_targets<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
) -> Result<(
    Vec<(crate::protocol::types::HelperChannel, SharedKey)>,
    Vec<(crate::protocol::types::ReplicaMember, SharedKey)>,
)> {
    let secret_id = local.secret_id;
    use crate::protocol::types::ChannelStatus;

    let helper_rows: Vec<_> = stores
        .channels
        .helpers_matching(
            secret_id,
            crate::protocol::types::HelperFilter {
                status: vec![ChannelStatus::Paired],
                role: Some(SenderKind::Helper),
                ..Default::default()
            },
        )
        .await?;

    // Every member is a target except this device itself. `replicas()`
    // deliberately includes our own row so the roster is reconstructible from
    // stores alone, so the exclusion is asked for here.
    //
    // `Unpairing` members stay on the distribution list even though the roster
    // built below drops them: receiving the version that excludes them is
    // exactly how they learn their departure is complete.
    let member_rows: Vec<_> = stores
        .channels
        .replicas_matching(
            secret_id,
            crate::protocol::types::ReplicaFilter {
                status: vec![ChannelStatus::Paired, ChannelStatus::Unpairing],
                exclude: local.exclude_self(),
                ..Default::default()
            },
        )
        .await?;

    if helper_rows.is_empty() && member_rows.is_empty() {
        return Ok((Vec::new(), Vec::new()));
    }

    // Every key lives at the channel its record names. Members of one group
    // converge on a single channel and therefore a single key, but resolving
    // per record keeps this correct while a group spans several pairings.
    let mut key_ids: Vec<ChannelId> = helper_rows.iter().map(|c| c.channel_id).collect();
    for m in &member_rows {
        if !key_ids.contains(&m.channel_id) {
            key_ids.push(m.channel_id);
        }
    }

    let keys: std::collections::HashMap<ChannelId, SharedKey> = stores
        .secrets
        .load_many(
            secret_id,
            &key_ids,
            SecretKind::SharedKey,
            MissingPolicy::Fail,
        )
        .await?
        .into_iter()
        .filter_map(|(cid, v)| match v {
            SecretValue::SharedKey(k) => Some((cid, k)),
            _ => None,
        })
        .collect();

    let helpers: Vec<(crate::protocol::types::HelperChannel, SharedKey)> = helper_rows
        .into_iter()
        .map(|c| {
            let key = *keys
                .get(&c.channel_id)
                .expect("load_many(MissingPolicy::Fail) guarantees an entry per id");
            (c, key)
        })
        .collect();

    let replicas: Vec<(crate::protocol::types::ReplicaMember, SharedKey)> = member_rows
        .into_iter()
        .map(|m| {
            let key = *keys
                .get(&m.channel_id)
                .expect("load_many(MissingPolicy::Fail) guarantees an entry per id");
            (m, key)
        })
        .collect();

    Ok((helpers, replicas))
}

/// Assemble the payload from the stores.
///
/// `roster` is every member of the group including this device — the dispatch
/// list is the same set minus self, and during an admission handover also
/// differs by channel, since a joiner sits on its ephemeral pairing channel
/// until it hydrates.
pub(in crate::protocol) fn build_secret(
    paired_helpers: &[(crate::protocol::types::HelperChannel, SharedKey)],
    roster: &[crate::protocol::types::ReplicaMember],
    secrets: Vec<UserSecret>,
    group_channel: Option<ChannelId>,
    group_key: Option<SharedKey>,
) -> Result<Secret> {
    let helper_infos: Vec<HelperInfo> = paired_helpers
        .iter()
        .map(|(channel, shared_key)| HelperInfo {
            channel_id: channel.channel_id.0,
            transports: channel.transports.clone(),
            shared_key: shared_key.to_vec(),
            communication_info: channel.communication_info.clone(),
        })
        .collect();

    Ok(Secret {
        helpers: helper_infos,
        secrets,
        replicas: build_replicas(roster, group_channel, group_key)?,
    })
}

/// The group's channel: the one on this device's **own** member row.
///
/// A joiner admitted since the last round is still on its ephemeral pairing
/// channel, so the group's id cannot be read off an arbitrary row — and
/// publishing an ephemeral id as the group's would strand every other member.
/// This device's own row always names the group: it is written once, at the
/// first replica pairing, and never moved.
///
/// `Ok(None)` when there is no group at all.
fn group_channel_of(
    local: &Local<'_>,
    roster: &[crate::protocol::types::ReplicaMember],
) -> Result<Option<ChannelId>> {
    if roster.is_empty() {
        return Ok(None);
    }
    let own = local.replica_id.ok_or(Error::ReplicaIdNotConfigured)?;
    roster
        .iter()
        .find(|m| m.replica_id.0 == own)
        .map(|m| Some(m.channel_id))
        .ok_or(Error::Invariant(
            "replica group has members but this device holds no row of its own",
        ))
}

/// Project the group onto the wire roster.
fn build_replicas(
    roster: &[crate::protocol::types::ReplicaMember],
    group_channel: Option<ChannelId>,
    group_key: Option<SharedKey>,
) -> Result<Option<crate::protocol::types::Replicas>> {
    let (Some(group_channel), Some(group_key)) = (group_channel, group_key) else {
        return Ok(None);
    };

    let members: Vec<crate::protocol::types::ReplicaInfo> = roster
        .iter()
        // A member told to leave is already out of the group as far as the
        // published roster is concerned. Its absence here is what completes
        // the removal on every recipient.
        .filter(|member| member.status != crate::protocol::types::ChannelStatus::Unpairing)
        .map(|member| crate::protocol::types::ReplicaInfo {
            replica_id: member.replica_id.0,
            transports: member.transports.clone(),
            role: member.role as i32,
            communication_info: member.communication_info.clone(),
        })
        .collect();

    Ok(Some(crate::protocol::types::Replicas {
        channel_id: group_channel.0,
        members,
        shared_key: group_key.to_vec(),
    }))
}

fn build_replica_composite(
    secret: &Secret,
    split_result: Option<&crate::primitives::sharing::request::SplitResult>,
) -> crate::protocol::types::ReplicaSecretPayload {
    let shares: Vec<crate::protocol::types::ChannelShare> = split_result
        .map(|r| {
            r.shares
                .iter()
                .map(|(ch_id, committed)| crate::protocol::types::ChannelShare {
                    channel_id: ch_id.0,
                    committed_share: committed.encode_to_vec(),
                })
                .collect()
        })
        .unwrap_or_default();

    crate::protocol::types::ReplicaSecretPayload {
        secret: Some(secret.clone()),
        shares,
        shared_key: Vec::new(),
    }
}

fn wrap_for_helper_split(secret: &Secret, threshold: usize) -> Vec<u8> {
    let derec_secret = DeRecSecret {
        secret_data: secret.encode(),
        creation_time: None,
        helper_threshold_for_recovery: threshold as i64,
        helper_threshold_for_confirming_share_receipt: threshold as i64,
        helpers: Vec::new(),
    };
    derec_secret.encode_to_vec()
}

#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = round.trace_id, secret_id = local.secret_id)))]
#[allow(clippy::too_many_arguments)]
async fn distribute_shares<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    paired_helpers: &[(crate::protocol::types::HelperChannel, SharedKey)],
    split_result: &crate::primitives::sharing::request::SplitResult,
    keep_versions_count: usize,
    version: u32,
    description: &str,
    round: &Round<'_>,
) -> Vec<(ChannelId, Result<()>)> {
    let keep_list: Vec<u32> = {
        let start = version
            .saturating_sub(keep_versions_count as u32 - 1)
            .max(1);
        (start..=version).collect()
    };

    let mut results: Vec<(ChannelId, Result<()>)> = Vec::with_capacity(paired_helpers.len());
    for (channel, shared_key) in paired_helpers {
        let Some(committed_share) = split_result.shares.get(&channel.channel_id) else {
            continue;
        };

        let outcome = dispatch_share_to_helper(
            stores,
            local,
            channel,
            shared_key,
            committed_share,
            &keep_list,
            version,
            description,
            round,
        )
        .await;

        #[cfg(feature = "logging")]
        match &outcome {
            Ok(()) => tracing::debug!(
                channel_id = channel.channel_id.0,
                secret_id = local.secret_id,
                version = version,
                "share envelope sent"
            ),
            Err(e) => tracing::warn!(
                channel_id = channel.channel_id.0,
                secret_id = local.secret_id,
                version = version,
                error = %e,
                "share envelope dispatch failed"
            ),
        }

        results.push((channel.channel_id, outcome));
    }

    #[cfg(feature = "logging")]
    tracing::info!(
        secret_id = local.secret_id,
        version = version,
        "secret distributed to helpers"
    );

    results
}
#[allow(clippy::too_many_arguments)]
async fn dispatch_share_to_helper<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel: &crate::protocol::types::HelperChannel,
    shared_key: &SharedKey,
    committed_share: &derec_proto::CommittedDeRecShare,
    keep_list: &[u32],
    version: u32,
    description: &str,
    round: &Round<'_>,
) -> Result<()> {
    let secret_id = local.secret_id;
    let msg = produce_store_share_request_message(
        channel.channel_id,
        version,
        secret_id,
        committed_share,
        keep_list,
        description,
        shared_key,
        round.reply_to,
    )?;
    let envelope = crate::derec_message::apply_trace_id(&msg.envelope, round.trace_id)?;
    stores.transport.send(&channel.transports, envelope).await?;

    stores
        .shares
        .save(
            secret_id,
            channel.channel_id,
            Share {
                secret_id,
                version,
                bytes: committed_share.encode_to_vec(),
            },
        )
        .await?;
    Ok(())
}

#[cfg_attr(feature = "logging", tracing::instrument(skip_all, fields(trace_id = round.trace_id, secret_id = local.secret_id)))]
#[allow(clippy::too_many_arguments)]
async fn distribute_composite_to_destinations<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    replicas: &[(crate::protocol::types::ReplicaMember, SharedKey)],
    composite: &crate::protocol::types::ReplicaSecretPayload,
    k_group: Option<SharedKey>,
    version: u32,
    description: &str,
    round: &Round<'_>,
) -> Vec<(crate::types::ReplicaId, Result<()>)> {
    let mut results: Vec<(crate::types::ReplicaId, Result<()>)> =
        Vec::with_capacity(replicas.len());
    for (channel, channel_key) in replicas {
        let outcome = dispatch_composite_to_destination(
            stores,
            local,
            channel,
            channel_key,
            composite,
            k_group.as_ref(),
            version,
            description,
            round,
        )
        .await;

        #[cfg(feature = "logging")]
        match &outcome {
            Ok(()) => tracing::debug!(
                channel_id = channel.channel_id.0,
                secret_id = local.secret_id,
                version = version,
                "replica secret envelope sent"
            ),
            Err(e) => tracing::warn!(
                channel_id = channel.channel_id.0,
                secret_id = local.secret_id,
                version = version,
                error = %e,
                "replica secret envelope dispatch failed"
            ),
        }

        results.push((channel.replica_id, outcome));
    }

    #[cfg(feature = "logging")]
    tracing::info!(
        secret_id = local.secret_id,
        version = version,
        count = replicas.len(),
        "secret distributed to replicas"
    );

    results
}
#[allow(clippy::too_many_arguments)]
async fn dispatch_composite_to_destination<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    channel: &crate::protocol::types::ReplicaMember,
    channel_key: &SharedKey,
    composite: &crate::protocol::types::ReplicaSecretPayload,
    k_group: Option<&SharedKey>,
    version: u32,
    description: &str,
    round: &Round<'_>,
) -> Result<()> {
    let needs_handover = match k_group {
        Some(g) => channel_key != g,
        None => false,
    };

    let mut per_channel = composite.clone();
    if needs_handover {
        per_channel.shared_key = k_group.expect("handover implies k_group set").to_vec();
    }
    let composite_bytes = per_channel.encode_to_vec();

    let timestamp = current_timestamp();
    let (legacy_reply_to, reply_to_transports) =
        crate::extensions::advertised_endpoints::split_reply_to(round.reply_to);
    // Populating the deprecated singular field is the compatibility
    // path that keeps peers predating `replyToTransports`
    // answerable, so the warning is expected here.
    #[allow(deprecated)]
    let msg = StoreShareRequestMessage {
        share: composite_bytes,
        share_algorithm: SHARE_ALGORITHM_REPLICA_SECRET,
        version,
        keep_list: Vec::new(),
        version_description: description.to_owned(),
        timestamp: Some(timestamp),
        secret_id: local.secret_id,
        reply_to: legacy_reply_to,
        reply_to_transports,
        replica_id: local.replica_id,
    };

    let envelope_bytes = DeRecMessageBuilder::channel()
        .channel_id(channel.channel_id)
        .timestamp(timestamp)
        .message_body(MessageBody::StoreShareRequest(msg))
        .encrypt(channel_key)?
        .build()?
        .encode_to_vec();
    let envelope = crate::derec_message::apply_trace_id(&envelope_bytes, round.trace_id)?;
    stores.transport.send(&channel.transports, envelope).await?;

    if needs_handover {
        let new_key = k_group.expect("handover implies k_group set");
        stores
            .secrets
            .save(
                local.secret_id,
                channel.channel_id,
                SecretValue::SharedKey(*new_key),
            )
            .await
            .map_err(crate::Error::SecretStore)?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use crate::primitives::sharing::request;
    use crate::protocol::context::Exchange;
    use crate::protocol::test::LocalFixture;
    use crate::protocol::test::{InMemChannelStore, NoopTransport, StoreRig, run_async};
    use crate::types::{ChannelId, SharedKey};
    use derec_proto::{Protocol, TransportProtocol};
    use prost::Message as _;

    /// A Helper stores each incoming share partitioned under *its own*
    /// `secret_id`, but the persisted `Share` record must carry the
    /// *Owner's* `secret_id` (from the wire request). Discovery groups a
    /// Helper's shares by `Share::secret_id` to report which Owner secrets
    /// it holds; recording the Helper's own partition id instead would
    /// mislabel every held share as belonging to the Helper. The two ids
    /// are only distinguishable when they differ — so this test drives
    /// `accept` with an Owner id that is not the Helper's.
    #[test]
    fn accept_records_owner_secret_id_not_helper_partition() {
        run_async(async {
            let lf = LocalFixture::new(HELPER_SECRET_ID);
            const OWNER_SECRET_ID: u64 = 0xA11CE;
            const HELPER_SECRET_ID: u64 = 0xB0B;
            let channel_id = ChannelId(11);
            let shared_key: SharedKey = [42u8; 32];

            // Owner: split a secret across two channels and build the
            // store-share request bound to OWNER_SECRET_ID.
            let split = request::split(
                &[channel_id, ChannelId(12)],
                OWNER_SECRET_ID,
                1,
                b"correct horse battery staple",
                2,
            )
            .expect("split secret");
            let committed = split.shares.get(&channel_id).expect("share for channel");
            let produced = request::produce(
                channel_id,
                1,
                OWNER_SECRET_ID,
                committed,
                &[],
                "",
                &shared_key,
                std::slice::from_ref(&TransportProtocol {
                    uri: "https://owner.example".to_owned(),
                    protocol: Protocol::Https as i32,
                }),
            )
            .expect("produce store-share request");

            // Helper: recover the request and confirm it carries the
            // Owner's id, then run the accept handler under the Helper's
            // own (different) partition id.
            let request = request::extract(&produced.envelope, &shared_key)
                .expect("extract request")
                .request;
            assert_eq!(request.secret_id, OWNER_SECRET_ID);

            let mut rig = StoreRig::with_transport(NoopTransport);
            super::accept(
                &mut rig.stores(),
                &lf.local(),
                &Exchange {
                    channel_id,
                    shared_key: &shared_key,
                    trace_id: 1,
                },
                &request,
            )
            .await
            .expect("accept stores share");

            // The record is keyed under the Helper's partition id, but the
            // `secret_id` field Discovery groups by must be the Owner's.
            let stored = rig
                .shares
                .data
                .lock()
                .unwrap()
                .get(&(HELPER_SECRET_ID, channel_id.0, 1))
                .cloned()
                .expect("share persisted under helper partition");
            assert_eq!(
                stored.secret_id, OWNER_SECRET_ID,
                "Discovery groups shares by Share.secret_id; it must be the owner's id"
            );
        });
    }

    /// A version has exactly one writer. Re-sending the *identical*
    /// envelope is an idempotent retry — the recipient acknowledges it
    /// and leaves the stored bytes untouched, so a lost ack costs
    /// nothing.
    #[test]
    fn accept_treats_an_identical_resend_as_an_idempotent_retry() {
        run_async(async {
            let lf = LocalFixture::new(SECRET_ID);
            const SECRET_ID: u64 = 0xA11CE;
            let channel_id = ChannelId(11);
            let shared_key: SharedKey = [42u8; 32];

            let split = request::split(
                &[channel_id, ChannelId(12)],
                SECRET_ID,
                1,
                b"correct horse battery staple",
                2,
            )
            .expect("split secret");
            let committed = split.shares.get(&channel_id).expect("share for channel");
            let produced = request::produce(
                channel_id,
                1,
                SECRET_ID,
                committed,
                &[],
                "",
                &shared_key,
                &[],
            )
            .expect("produce request");
            let request = request::extract(&produced.envelope, &shared_key)
                .expect("extract request")
                .request;

            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_owner_channel(&mut rig.channels, SECRET_ID, channel_id).await;

            for _ in 0..2 {
                let events = super::accept(
                    &mut rig.stores(),
                    &lf.local(),
                    &Exchange {
                        channel_id,
                        shared_key: &shared_key,
                        trace_id: 1,
                    },
                    &request,
                )
                .await
                .expect("identical re-send is accepted");
                assert!(
                    matches!(
                        events.as_slice(),
                        [crate::protocol::DeRecEvent::ShareStored { .. }]
                    ),
                    "an idempotent retry is still acknowledged as stored"
                );
            }

            assert_eq!(
                rig.shares.data.lock().unwrap().len(),
                1,
                "the retry must not create a second entry"
            );
        });
    }

    /// A second writer publishing different content at a version that is
    /// already taken is refused. A single writer derives `version` as
    /// `latest + 1` and so can never reach this path, which is what makes
    /// differing bytes at one version a reliable signal of concurrent
    /// publishers.
    #[test]
    fn accept_refuses_a_second_writer_at_an_existing_version() {
        run_async(async {
            let lf = LocalFixture::new(SECRET_ID);
            const SECRET_ID: u64 = 0xA11CE;
            let channel_id = ChannelId(11);
            let shared_key: SharedKey = [42u8; 32];

            let build = |payload: &[u8]| {
                let split = request::split(&[channel_id, ChannelId(12)], SECRET_ID, 1, payload, 2)
                    .expect("split secret");
                let committed = split.shares.get(&channel_id).expect("share").clone();
                let produced = request::produce(
                    channel_id,
                    1,
                    SECRET_ID,
                    &committed,
                    &[],
                    "",
                    &shared_key,
                    &[],
                )
                .expect("produce request");
                request::extract(&produced.envelope, &shared_key)
                    .expect("extract request")
                    .request
            };

            let first = build(b"written by alice");
            let second = build(b"written by alice-2");
            assert_ne!(
                first.share, second.share,
                "the two writers must differ for this to be a conflict"
            );

            let mut rig = StoreRig::with_transport(NoopTransport);
            seed_owner_channel(&mut rig.channels, SECRET_ID, channel_id).await;

            super::accept(
                &mut rig.stores(),
                &lf.local(),
                &Exchange {
                    channel_id,
                    shared_key: &shared_key,
                    trace_id: 1,
                },
                &first,
            )
            .await
            .expect("first writer stores");

            let events = super::accept(
                &mut rig.stores(),
                &lf.local(),
                &Exchange {
                    channel_id,
                    shared_key: &shared_key,
                    trace_id: 1,
                },
                &second,
            )
            .await
            .expect("the conflict is reported to the peer, not raised locally");

            assert!(
                matches!(events.as_slice(), [crate::protocol::DeRecEvent::NoOp]),
                "a refused write stores nothing and reports no ShareStored"
            );

            let stored = rig
                .shares
                .data
                .lock()
                .unwrap()
                .get(&(SECRET_ID, channel_id.0, 1))
                .cloned()
                .expect("the first writer's share survives");
            assert_eq!(
                stored.bytes,
                first.encode_to_vec(),
                "the first writer wins; the second never overwrites"
            );
        });
    }

    /// Both conflict tests need a channel record so `accept` can resolve
    /// a response endpoint.
    async fn seed_owner_channel(
        channels: &mut InMemChannelStore,
        secret_id: u64,
        channel_id: ChannelId,
    ) {
        use crate::protocol::DeRecChannelStore;
        channels
            .save(
                secret_id,
                crate::protocol::types::ChannelRecord::Helper(
                    crate::protocol::types::HelperChannel {
                        channel_id,
                        transports: vec![TransportProtocol {
                            uri: "https://owner.example".to_owned(),
                            protocol: Protocol::Https as i32,
                        }],
                        communication_info: std::collections::HashMap::new(),
                        status: crate::protocol::types::ChannelStatus::Paired,
                        created_at: 0,
                        peer_role: derec_proto::SenderKind::Owner,
                    },
                ),
            )
            .await
            .expect("seed channel");
    }
}

/// Group-model conformance checks (T1–T3, T6 of the replica-group spec).
///
/// These pin the properties that a shared group channel makes easy to get
/// wrong: who a publish addresses, which channel the group is on, and what a
/// non-source member is allowed to do.
#[cfg(test)]
mod group_conformance_tests {
    use crate::protocol::DeRecChannelStore;
    use crate::protocol::test::LocalFixture;
    use crate::protocol::test::StoreRig;
    use crate::protocol::test::{InMemChannelStore, InMemSecretStore, run_async};
    use crate::protocol::types::{
        ChannelRecord, ChannelStatus, ReplicaMember, ReplicaRole, SecretValue,
    };
    use crate::types::{ChannelId, ReplicaId};
    use derec_proto::{Protocol, TransportProtocol};

    const SECRET_ID: u64 = 0xC0FFEE;
    const GROUP_CHANNEL: ChannelId = ChannelId(5001);

    fn endpoint(uri: &str) -> TransportProtocol {
        TransportProtocol {
            uri: uri.to_owned(),
            protocol: Protocol::Https as i32,
        }
    }

    async fn seed_member(
        channels: &mut InMemChannelStore,
        replica_id: u64,
        role: ReplicaRole,
        uri: &str,
    ) {
        channels
            .save(
                SECRET_ID,
                ChannelRecord::Replica(ReplicaMember {
                    channel_id: GROUP_CHANNEL,
                    replica_id: ReplicaId(replica_id),
                    transports: vec![endpoint(uri)],
                    communication_info: std::collections::HashMap::new(),
                    role,
                    status: ChannelStatus::Paired,
                    created_at: 0,
                }),
            )
            .await
            .expect("seed member");
    }

    async fn seed_group_key(secrets: &mut InMemSecretStore) {
        use crate::protocol::DeRecSecretStore;
        secrets
            .save(SECRET_ID, GROUP_CHANNEL, SecretValue::SharedKey([0x42; 32]))
            .await
            .expect("seed group key");
    }

    /// T1 — a member never addresses itself.
    ///
    /// The roster deliberately includes this device, so the exclusion has to
    /// happen when the dispatch list is built. A self-addressed target would
    /// have the device encrypt a payload to its own endpoint and wait for an
    /// acknowledgement that can never arrive.
    #[test]
    fn a_member_is_never_a_target_of_its_own_publish() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1002);
            let mut rig = StoreRig::new();
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                "https://alice",
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                "https://alice-2",
            )
            .await;
            seed_member(
                &mut rig.channels,
                1003,
                ReplicaRole::Destination,
                "https://alice-3",
            )
            .await;
            seed_group_key(&mut rig.secrets).await;

            let (_, targets) = super::load_all_paired_targets(&mut rig.stores(), &lf.local())
                .await
                .expect("targets load");

            let ids: Vec<u64> = targets.iter().map(|(m, _)| m.replica_id.0).collect();
            assert_eq!(
                ids.len(),
                2,
                "the roster has three members; the writer is not one of its own targets"
            );
            assert!(
                !ids.contains(&1002),
                "a member must never address itself, got {ids:?}"
            );
        });
    }

    /// T2 — three members on one channel are three distinct targets.
    ///
    /// The case that exposed the original collision: keyed by `channel_id`
    /// they would collapse into a single target, because the group shares one
    /// channel.
    #[test]
    fn three_members_on_one_channel_are_three_targets() {
        run_async(async {
            let lf = LocalFixture::with_replica(SECRET_ID, 1001);
            let mut rig = StoreRig::new();
            for (id, role) in [
                (1001, ReplicaRole::Source),
                (1002, ReplicaRole::Destination),
                (1003, ReplicaRole::Destination),
                (1004, ReplicaRole::Destination),
            ] {
                seed_member(&mut rig.channels, id, role, "https://peer").await;
            }
            seed_group_key(&mut rig.secrets).await;

            let (_, targets) = super::load_all_paired_targets(&mut rig.stores(), &lf.local())
                .await
                .expect("targets load");

            assert_eq!(targets.len(), 3, "one target per member, not per channel");
            let channels_used: std::collections::HashSet<ChannelId> =
                targets.iter().map(|(m, _)| m.channel_id).collect();
            assert_eq!(
                channels_used.len(),
                1,
                "all three sit on the one group channel"
            );
        });
    }

    /// T3 — a destination can publish.
    ///
    /// After hydrating, a destination holds the same state as the source and
    /// must be able to build a payload. Nothing in the roster projection may
    /// gate on the writer being the `Source`.
    #[test]
    fn a_destination_can_build_the_roster() {
        run_async(async {
            let lf = LocalFixture::with_replica(0, 1002);
            let mut rig = StoreRig::new();
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                "https://alice",
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                "https://alice-2",
            )
            .await;
            seed_group_key(&mut rig.secrets).await;

            // Publishing as the destination, not the source.
            let roster = rig
                .channels
                .replicas(SECRET_ID, crate::protocol::types::ReplicaFilter::default())
                .await
                .expect("roster");
            let group_channel =
                super::group_channel_of(&lf.local(), &roster).expect("group channel resolves");
            assert_eq!(group_channel, Some(GROUP_CHANNEL));

            let secret =
                super::build_secret(&[], &roster, Vec::new(), group_channel, Some([0x42; 32]))
                    .expect("a destination must be able to build the payload");

            let group = secret.replicas.expect("roster is present");
            assert_eq!(group.members.len(), 2, "the roster still names everyone");
            let sources: Vec<u64> = group
                .members
                .iter()
                .filter(|m| m.role == ReplicaRole::Source as i32)
                .map(|m| m.replica_id)
                .collect();
            assert_eq!(
                sources,
                vec![1001],
                "the source is unchanged by who published"
            );
        });
    }

    /// T6 — a joiner mid-handover does not redefine the group channel.
    ///
    /// The admitter's own row names the group; a member still on its ephemeral
    /// pairing channel must not drag the group id onto that channel, which
    /// would strand every other member.
    #[test]
    fn a_joiner_on_an_ephemeral_channel_does_not_move_the_group() {
        run_async(async {
            let lf = LocalFixture::with_replica(0, 1002);
            let mut rig = StoreRig::new();
            seed_member(
                &mut rig.channels,
                1001,
                ReplicaRole::Source,
                "https://alice",
            )
            .await;
            seed_member(
                &mut rig.channels,
                1002,
                ReplicaRole::Destination,
                "https://alice-2",
            )
            .await;
            // A joiner admitted since the last round, still on Cā‚‚.
            rig.channels
                .save(
                    SECRET_ID,
                    ChannelRecord::Replica(ReplicaMember {
                        channel_id: ChannelId(7001),
                        replica_id: ReplicaId(1003),
                        transports: vec![endpoint("https://alice-3")],
                        communication_info: std::collections::HashMap::new(),
                        role: ReplicaRole::Destination,
                        status: ChannelStatus::Paired,
                        created_at: 0,
                    }),
                )
                .await
                .expect("seed joiner");

            let roster = rig
                .channels
                .replicas(SECRET_ID, crate::protocol::types::ReplicaFilter::default())
                .await
                .expect("roster");
            let group_channel = super::group_channel_of(&lf.local(), &roster)
                .expect("group channel resolves")
                .expect("a group exists");
            assert_eq!(
                group_channel, GROUP_CHANNEL,
                "the group id comes from this device's own row, not the joiner's"
            );
        });
    }
}

/// Build the payload a catch-up request is answered with.
///
/// The same composite a publish sends — whole secret, whole roster — so the
/// asker's hydration path is identical whether the state arrived unsolicited
/// or was pulled. `None` when this device holds no snapshot and therefore has
/// nothing to serve.
pub(in crate::protocol) async fn build_catch_up_payload<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
) -> Result<Option<crate::protocol::types::ReplicaSecretPayload>> {
    let secret_id = local.secret_id;
    let Some(snapshot) = stores.user_secrets.load_latest(secret_id).await? else {
        return Ok(None);
    };

    let (helpers, _) = load_all_paired_targets(stores, local).await?;
    let roster = stores
        .channels
        .replicas_matching(secret_id, crate::protocol::types::ReplicaFilter::default())
        .await?;
    let group_channel = group_channel_of(local, &roster)?;
    let group_key = match group_channel {
        Some(channel_id) => match stores
            .secrets
            .load(secret_id, channel_id, SecretKind::SharedKey)
            .await?
        {
            Some(SecretValue::SharedKey(key)) => Some(key),
            _ => None,
        },
        None => None,
    };

    let secret = build_secret(
        &helpers,
        &roster,
        snapshot.secrets,
        group_channel,
        group_key,
    )?;

    // No share map: shares are derived per publishing round from the helper
    // set, and a member does not persist them. A catch-up carries the secret,
    // which is what the asker needs to become current.
    Ok(Some(crate::protocol::types::ReplicaSecretPayload {
        secret: Some(secret),
        shares: Vec::new(),
        shared_key: Vec::new(),
    }))
}

/// Hydrate a payload pulled by a catch-up, reporting install or update.
pub(in crate::protocol) async fn hydrate_catch_up<S: StoreSet>(
    stores: &mut Stores<'_, S>,
    local: &Local<'_>,
    from_replica_id: u64,
    version: u32,
    payload: &[u8],
) -> Result<Vec<DeRecEvent>> {
    let secret_id = local.secret_id;
    let composite = crate::protocol::types::ReplicaSecretPayload::decode(payload)
        .map_err(crate::Error::ProtobufDecode)?;
    let secret = composite.secret.ok_or(crate::Error::InvalidInput(
        "catch-up payload missing `secret` field",
    ))?;

    let is_install = stores.user_secrets.load_latest(secret_id).await?.is_none();

    replica::hydrate(stores, local, version, &secret, String::new()).await?;

    let event = if is_install {
        DeRecEvent::ReplicaSecretInstalled {
            channel_id: ChannelId(secret.replicas.as_ref().map_or(0, |g| g.channel_id)),
            from_replica_id,
            secret_id,
            version,
            secret,
            shares: composite.shares,
        }
    } else {
        DeRecEvent::ReplicaSecretReceived {
            channel_id: ChannelId(secret.replicas.as_ref().map_or(0, |g| g.channel_id)),
            from_replica_id,
            secret_id,
            version,
            secret,
            shares: composite.shares,
        }
    };
    Ok(vec![event])
}