x0x 0.33.0

Agent-to-agent gossip network for AI systems — no winners, no losers, just cooperation
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
//! High-level group management for x0x.
//!
//! A Group ties together:
//! - An MLS group (encryption, membership)
//! - A KvStore (group metadata, display names, settings)
//! - Gossip topics (chat rooms, notifications)
//! - CRDT task lists (kanban boards)
//! - A [`GroupPolicy`](crate::groups::policy::GroupPolicy) that governs discovery/admission/read/write
//!
//! Groups are the primary collaboration primitive for agents and humans.

pub mod card;
pub mod diagnostics;
pub mod directory;
pub mod discovery;
pub mod invite;
pub mod kem_envelope;
pub mod member;
pub mod policy;
pub mod public_message;
pub mod request;
pub mod state_commit;

use crate::identity::{AgentId, AgentKeypair};
use crate::mls::SecureGroupPlane;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

pub use self::diagnostics::{
    GroupCounters, GroupDiagnostic, GroupsDiagnostics, GroupsDiagnosticsSnapshot,
};
pub use self::directory::GroupCard;
pub use self::discovery::{
    may_publish_to_public_shards, name_words, normalize_tag, shard_of, shards_for_public,
    topic_for, DigestEntry, DirectoryMessage, DirectoryShardCache, ListedToContactsCard,
    ListedToContactsDigest, ListedToContactsPull, ShardKind, SubscriptionRecord, SubscriptionSet,
    DEFAULT_MAX_ENTRIES_PER_SHARD, DEFAULT_MAX_SUBSCRIPTIONS, DIRECTORY_TOPIC_PREFIX,
    MAX_NAME_WORDS, MAX_TAGS_PER_GROUP, SHARD_COUNT,
};
pub use self::member::{GroupMember, GroupMemberState, GroupRole};
pub use self::policy::{
    GroupAdmission, GroupConfidentiality, GroupDiscoverability, GroupPolicy, GroupPolicyPreset,
    GroupPolicySummary, GroupReadAccess, GroupWriteAccess,
};
pub use self::public_message::{
    public_topic_for, validate_public_message, GroupPublicMessage, GroupPublicMessageKind,
    IngestError as PublicMessageIngestError, PublicIngestContext, MAX_PUBLIC_MESSAGE_BYTES,
    PUBLIC_GROUP_TOPIC_PREFIX, PUBLIC_MESSAGE_DOMAIN,
};
pub use self::request::{JoinRequest, JoinRequestStatus};
pub use self::state_commit::{
    compute_policy_hash, compute_public_meta_hash, compute_roster_root, compute_state_hash,
    enforce_last_admin_invariant, roster_projection, roster_root_of_projection, ActionKind,
    ApplyContext, ApplyError, GroupGenesis, GroupPublicMeta, GroupStateCommit, RetainedCommit,
    RosterMemberSnapshot, CARD_SIGNATURE_DOMAIN, DEFAULT_CARD_TTL_SECS, EVENT_SIGNATURE_DOMAIN,
    STATE_COMMIT_DOMAIN,
};

fn now_millis() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

/// Locally-issued invite record used to authenticate joiner-authored
/// `MemberJoined` requests at the original inviter.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IssuedInviteRecord {
    /// Unix seconds when the invite was minted.
    #[serde(default)]
    pub created_at_secs: u64,
    /// Unix seconds after which the invite is no longer accepted. `0` means
    /// no expiry, matching [`invite::SignedInvite`].
    #[serde(default)]
    pub expires_at_secs: u64,
    /// Maximum role this invite may grant. Invite-join v1 uses `Member`.
    #[serde(default = "default_invite_max_role")]
    pub max_role: GroupRole,
    /// Agent that consumed this one-time invite, if any.
    #[serde(default)]
    pub consumed_by: Option<String>,
    /// Unix milliseconds when the invite was consumed locally.
    #[serde(default)]
    pub consumed_at_ms: Option<u64>,
}

fn default_invite_max_role() -> GroupRole {
    GroupRole::Member
}

/// Metadata for a group.
///
/// Persisted as JSON. The legacy v1 layout used a flat `members: BTreeSet`
/// plus a parallel `display_names: HashMap`. The v2 layout uses a structured
/// `members_v2: BTreeMap<String, GroupMember>`. For migration, the v1 fields
/// are deserialised (`#[serde(default)]`) but never written back
/// (`skip_serializing`). Call [`GroupInfo::migrate_from_v1`] at load time to
/// fold any v1 data into v2.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupInfo {
    // ── v1 compat (read-only) ───────────────────────────────────────────
    #[serde(default, skip_serializing)]
    pub members: BTreeSet<String>,
    #[serde(default, skip_serializing)]
    pub display_names: HashMap<String, String>,
    #[serde(default, skip_serializing)]
    pub membership_revision: u64,

    // ── v2 identity + topics ────────────────────────────────────────────
    pub name: String,
    pub description: String,
    pub creator: AgentId,
    pub created_at: u64,
    #[serde(default)]
    pub updated_at: u64,
    pub mls_group_id: String,
    pub metadata_topic: String,
    pub chat_topic_prefix: String,

    // ── v2 policy + roster ──────────────────────────────────────────────
    #[serde(default)]
    pub policy: GroupPolicy,
    #[serde(default)]
    pub policy_revision: u64,
    #[serde(default)]
    pub roster_revision: u64,
    #[serde(default)]
    pub members_v2: BTreeMap<String, GroupMember>,
    #[serde(default)]
    pub join_requests: BTreeMap<String, JoinRequest>,
    #[serde(default)]
    pub discovery_card_topic: Option<String>,

    // ── Phase D.2: Group Shared Secret (GSS) for cross-daemon encrypted
    //    content delivery. This is a symmetric-key layer distributed via
    //    welcomes, NOT full MLS TreeKEM. It gives:
    //      - cross-daemon encrypt/decrypt (proven from the correct peer)
    //      - rekey-on-ban semantics (banned peer loses future access)
    //    It does NOT give per-message forward secrecy within an epoch.
    //    Full TreeKEM cross-daemon join is blocked on saorsa-mls upstream
    //    providing a `from_welcome` constructor.
    /// 32-byte random secret for MlsEncrypted groups. None for SignedPublic or
    /// for stub entries created via card import (importer isn't a member yet).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub shared_secret: Option<Vec<u8>>,
    /// Monotonic epoch for the shared secret. Incremented on rekey (ban/remove).
    #[serde(default)]
    pub secret_epoch: u64,
    /// Which secure-group crypto plane this group runs on (ADR-0012).
    /// Defaults to [`SecureGroupPlane::Gss`] when absent so every
    /// already-persisted group — all created before TreeKEM existed — is
    /// correctly grandfathered onto the legacy GSS plane. New `MlsEncrypted`
    /// groups are created on [`SecureGroupPlane::TreeKem`] (set explicitly at
    /// creation time, not by this default).
    #[serde(default = "secure_plane_legacy_default")]
    pub secure_plane: SecureGroupPlane,

    // ── Phase D.3: Stable identity + evolving validity ──────────────────
    /// Stable genesis record — establishes the group's permanent `group_id`.
    /// Reconstructed from `mls_group_id` + creator + created_at when
    /// migrating pre-D.3 blobs (see [`GroupInfo::migrate_from_v1`]).
    #[serde(default)]
    pub genesis: Option<state_commit::GroupGenesis>,
    /// Monotonic revision of the signed state-commit chain. 0 = genesis
    /// (no authority-signed commits yet); bumped on every accepted event.
    #[serde(default)]
    pub state_revision: u64,
    /// Current `state_hash` — commitment to (group_id, revision, prev_hash,
    /// roster_root, policy_hash, public_meta_hash, security_binding,
    /// withdrawn). Recomputed by `recompute_state_hash()` after every
    /// mutation.
    #[serde(default)]
    pub state_hash: String,
    /// Previous `state_hash` so receivers can verify chain linking. None
    /// at genesis.
    #[serde(default)]
    pub prev_state_hash: Option<String>,
    /// Current security binding — for `MlsEncrypted` groups, a string of
    /// the form `"gss:epoch=N"` so roster/policy/epoch changes cannot
    /// silently drift apart. `None` for `SignedPublic`.
    #[serde(default)]
    pub security_binding: Option<String>,
    /// Optional tags for public discovery (Phase C.2 will hash these into
    /// shard topics). Only meaningful for `PublicDirectory` groups.
    #[serde(default)]
    pub tags: Vec<String>,
    /// Optional avatar URL for public cards.
    #[serde(default)]
    pub avatar_url: Option<String>,
    /// Optional banner URL for public cards.
    #[serde(default)]
    pub banner_url: Option<String>,
    /// Withdrawal/hidden supersession marker. Once set by a higher-revision
    /// signed commit, no further non-withdrawal actions may apply and
    /// subsequent public cards must carry the withdrawal flag.
    #[serde(default)]
    pub withdrawn: bool,

    /// Retained, applied state-commit history (issue #111, follow-up to
    /// ADR-0016). Each entry pairs a signed
    /// [`state_commit::GroupStateCommit`] with the roster projection it
    /// effected, so "what did the signed roster say at revision N" is
    /// answerable and independently verifiable long after the fact — the
    /// head-only chain fields above cannot do this. Appended by
    /// [`GroupInfo::seal_commit`] (local authorship),
    /// [`GroupInfo::finalize_applied_commit`] (peer non-terminal commits), and
    /// [`GroupInfo::finalize_applied_terminal_commit`] (peer terminal commits);
    /// it therefore captures every commit this daemon applied, from either
    /// path, with no per-call-site wiring. Bounded by [`COMMIT_LOG_CAP`]: past
    /// the cap the oldest entries are dropped and the loss is logged (never
    /// silent).
    /// History begins at the first retaining release and each daemon retains
    /// only the suffix it witnessed.
    #[serde(default)]
    pub commit_log: Vec<state_commit::RetainedCommit>,

    /// Legacy pre-v1.1 invite-secret set. Retained for JSON compatibility
    /// with already-persisted group blobs, but new admission checks use
    /// `issued_invites` so expiry, role cap, and one-time consumption can be
    /// enforced.
    #[serde(default)]
    pub issued_invite_secrets: HashSet<String>,
    /// Structured one-time invite records issued by this local node for this
    /// group. Populated by `POST /groups/:id/invite` and consumed by the
    /// original inviter when accepting a joiner-authored `MemberJoined`
    /// request. Third-party receivers do not apply `MemberJoined` directly;
    /// they wait for the inviter's authority-signed `MemberAdded` commit.
    #[serde(default)]
    pub issued_invites: HashMap<String, IssuedInviteRecord>,
}

/// Serde default for [`GroupInfo::secure_plane`]: groups persisted before the
/// field existed were all created on the legacy GSS plane, so a missing field
/// must deserialize to [`SecureGroupPlane::Gss`] (NOT the enum's own
/// `TreeKem` default) to avoid silently relabelling a grandfathered group as
/// FS/PCS-capable when it has no TreeKEM state.
fn secure_plane_legacy_default() -> SecureGroupPlane {
    SecureGroupPlane::Gss
}

/// Hard cap on retained state-commits per group (issue #111). Private-group
/// roster churn is low-frequency, so this bounds `named_groups.json` growth
/// while keeping a deep history. Past the cap the oldest entries are dropped
/// (checkpoint-and-truncate is deferred — see issue #111); the drop is logged
/// so history loss can never be silent.
pub const COMMIT_LOG_CAP: usize = 4096;

/// Exact ADR-0016 §3 REST error string for acts that would leave a live
/// group with zero active admins. Fixed verbatim by the Phase 1 spec.
pub const LAST_ADMIN_PRECHECK_ERROR: &str =
    "a group must always have at least one admin; make another member an admin first";

/// Exact ADR-0016 §3 REST error string for last-admin self-leave attempts.
/// Fixed verbatim by the Phase 1 spec.
pub const LAST_ADMIN_SELF_LEAVE_PRECHECK_ERROR: &str =
    "a group must always have at least one admin; make another member an admin before leaving";

/// Return the ADR-0016 last-admin REST pre-check error for a proposed
/// post-mutation group state.
///
/// Callers provide the same mutation they are about to author/apply; this
/// helper runs it on a clone and maps the shared invariant to the exact §3
/// user-facing string. It is a UX pre-check only — the authoritative guard
/// remains [`state_commit::enforce_last_admin_invariant`] at the commit
/// authoring/apply choke-points.
#[must_use]
pub fn last_admin_precheck_error(
    info: &GroupInfo,
    apply: impl FnOnce(&mut GroupInfo),
) -> Option<&'static str> {
    let mut proposed = info.clone();
    apply(&mut proposed);
    state_commit::enforce_last_admin_invariant(&proposed.members_v2, proposed.withdrawn)
        .err()
        .map(|_| LAST_ADMIN_PRECHECK_ERROR)
}

/// Return the ADR-0016 last-admin REST pre-check error for a proposed
/// self-leave by `leaver_hex`.
///
/// This is the self-leave variant of [`last_admin_precheck_error`], with the
/// separate §3 user-facing recovery hint. It deliberately evaluates the removal
/// on a clone so rejected leaves cannot mutate live group state before the
/// authoritative commit-time invariant rejects them.
#[must_use]
pub fn last_admin_self_leave_precheck_error(
    info: &GroupInfo,
    leaver_hex: &str,
) -> Option<&'static str> {
    let mut proposed = info.clone();
    proposed.remove_member(leaver_hex, None);
    state_commit::enforce_last_admin_invariant(&proposed.members_v2, proposed.withdrawn)
        .err()
        .map(|_| LAST_ADMIN_SELF_LEAVE_PRECHECK_ERROR)
}

impl GroupInfo {
    /// Create a new `GroupInfo` with the given policy (defaults to `private_secure`).
    #[must_use]
    pub fn new(name: String, description: String, creator: AgentId, mls_group_id: String) -> Self {
        Self::with_policy(
            name,
            description,
            creator,
            mls_group_id,
            GroupPolicy::default(),
        )
    }

    /// Create a new `GroupInfo` with an explicit policy.
    #[must_use]
    pub fn with_policy(
        name: String,
        description: String,
        creator: AgentId,
        mls_group_id: String,
        policy: GroupPolicy,
    ) -> Self {
        let now = now_millis();
        let metadata_topic = format!(
            "x0x.group.{}.meta",
            &mls_group_id[..16.min(mls_group_id.len())]
        );
        let chat_topic_prefix = format!(
            "x0x.group.{}.chat",
            &mls_group_id[..16.min(mls_group_id.len())]
        );
        let discovery_card_topic = if policy.discoverability != GroupDiscoverability::Hidden {
            Some(format!(
                "x0x.group.{}.card",
                &mls_group_id[..16.min(mls_group_id.len())]
            ))
        } else {
            None
        };

        let creator_hex = hex::encode(creator.as_bytes());
        let mut members_v2 = BTreeMap::new();
        members_v2.insert(
            creator_hex.clone(),
            GroupMember::new_admin(creator_hex.clone(), None, now),
        );

        // Generate a fresh shared secret for MlsEncrypted groups. SignedPublic
        // groups don't need one — their content is signed but not encrypted.
        let shared_secret = if policy.confidentiality == GroupConfidentiality::MlsEncrypted {
            use rand::RngCore;
            let mut secret = vec![0u8; 32];
            rand::thread_rng().fill_bytes(&mut secret);
            Some(secret)
        } else {
            None
        };

        // All groups are MLS groups — the MLS group id IS the stable group id.
        // The genesis record is retained for audit (creator + creation timestamp),
        // but its `group_id` is pinned to the MLS group id so every id surface
        // (owner named_groups key, card.group_id, metadata_topic) converges on
        // a single value. Prior to this, genesis.group_id was a separately
        // derived BLAKE3 hash which caused cross-daemon lookup drift.
        let genesis = state_commit::GroupGenesis::with_existing_id(
            mls_group_id.clone(),
            creator_hex.clone(),
            now,
            String::new(),
        );

        let confidentiality = policy.confidentiality;
        let mut info = Self {
            members: BTreeSet::new(),
            display_names: HashMap::new(),
            membership_revision: 0,

            name,
            description,
            creator,
            created_at: now,
            updated_at: now,
            mls_group_id,
            metadata_topic,
            chat_topic_prefix,
            policy,
            policy_revision: 0,
            roster_revision: 0,
            members_v2,
            join_requests: BTreeMap::new(),
            discovery_card_topic,
            commit_log: Vec::new(),
            shared_secret,
            secret_epoch: 0,
            // Generic constructor stays on the legacy GSS plane (matching the
            // shared_secret generated above). The secure-by-default TreeKEM
            // routing is applied explicitly in the daemon's create-group path
            // (ADR-0012 Phase 2), not here, so card-import stubs and other
            // constructors are not silently relabelled.
            secure_plane: SecureGroupPlane::Gss,

            genesis: Some(genesis),
            state_revision: 0,
            state_hash: String::new(),
            prev_state_hash: None,
            security_binding: match confidentiality {
                GroupConfidentiality::MlsEncrypted => Some("gss:epoch=0".into()),
                GroupConfidentiality::SignedPublic => None,
            },
            tags: Vec::new(),
            avatar_url: None,
            banner_url: None,
            withdrawn: false,
            issued_invite_secrets: HashSet::new(),
            issued_invites: HashMap::new(),
        };
        info.recompute_state_hash();
        info
    }

    /// Rotate the group's shared secret (called on ban/remove in MlsEncrypted
    /// groups). Returns the new secret and new epoch. Previous-epoch content
    /// encrypted by members still in the group is NOT decryptable at the new
    /// epoch — that's forward secrecy across epochs.
    ///
    /// Callers must arrange to distribute the new secret to remaining members
    /// (never to the departed/banned peer).
    ///
    /// Phase D.3: also refreshes `security_binding` so the next state commit
    /// incorporates the new epoch into `state_hash`.
    #[must_use]
    pub fn rotate_shared_secret(&mut self) -> (Vec<u8>, u64) {
        use rand::RngCore;
        let mut new_secret = vec![0u8; 32];
        rand::thread_rng().fill_bytes(&mut new_secret);
        self.secret_epoch = self.secret_epoch.saturating_add(1);
        self.shared_secret = Some(new_secret.clone());
        self.security_binding = Some(format!("gss:epoch={}", self.secret_epoch));
        (new_secret, self.secret_epoch)
    }

    // ── Phase D.3: state-commit chain ──────────────────────────────────

    /// The stable `group_id` (Phase D.3). Falls back to `mls_group_id` for
    /// pre-D.3 groups where genesis has not yet been reconstructed.
    #[must_use]
    pub fn stable_group_id(&self) -> &str {
        self.genesis
            .as_ref()
            .map(|g| g.group_id.as_str())
            .unwrap_or(self.mls_group_id.as_str())
    }

    /// Snapshot of the public metadata that contributes to the state hash.
    #[must_use]
    pub fn public_meta(&self) -> state_commit::GroupPublicMeta {
        state_commit::GroupPublicMeta {
            name: self.name.clone(),
            description: self.description.clone(),
            tags: self.tags.clone(),
            avatar_url: self.avatar_url.clone(),
            banner_url: self.banner_url.clone(),
        }
    }

    /// Recompute and store `state_hash` from the current fields. Called
    /// after every mutation; also called by constructors and the v1
    /// migration path so new and migrated groups have a valid hash.
    pub fn recompute_state_hash(&mut self) {
        let roster_root = state_commit::compute_roster_root(&self.members_v2);
        let policy_hash = state_commit::compute_policy_hash(&self.policy);
        let meta_hash = state_commit::compute_public_meta_hash(&self.public_meta());
        self.state_hash = state_commit::compute_state_hash(
            self.stable_group_id(),
            self.state_revision,
            self.prev_state_hash.as_deref(),
            &roster_root,
            &policy_hash,
            &meta_hash,
            self.security_binding.as_deref(),
            self.withdrawn,
        );
    }

    /// Seal the current (already-mutated) state into a signed commit.
    ///
    /// - bumps `state_revision` by 1,
    /// - records `prev_state_hash = self.state_hash` (pre-bump hash),
    /// - recomputes the new `state_hash`,
    /// - returns a signed [`state_commit::GroupStateCommit`].
    ///
    /// Callers must mutate the group first (e.g. `add_member`, `ban_member`,
    /// policy update) **and then** call `seal_commit` to produce the
    /// authority-signed commit that can be published and verified by peers.
    pub fn seal_commit(
        &mut self,
        keypair: &AgentKeypair,
        now_ms: u64,
    ) -> Result<state_commit::GroupStateCommit, state_commit::ApplyError> {
        // ADR-0016 R2: never author a commit whose post-mutation,
        // non-withdrawn state has zero active admins. `self` already holds
        // the caller's domain mutations, so this evaluates the proposed
        // post-mutation roster before any chain field is touched.
        state_commit::enforce_last_admin_invariant(&self.members_v2, self.withdrawn)?;
        if self.withdrawn {
            let signer_hex = hex::encode(keypair.agent_id().as_bytes());
            if !state_commit::active_signer_is_admin_or_higher(&self.members_v2, &signer_hex) {
                return Err(state_commit::ApplyError::Unauthorized {
                    signer: signer_hex,
                    action: state_commit::ActionKind::AdminOrHigher.name(),
                });
            }
        }
        // Ensure the genesis record is present — callers may reach here via
        // migrated paths that didn't set it yet.
        if self.genesis.is_none() {
            let creator_hex = hex::encode(self.creator.as_bytes());
            self.genesis = Some(state_commit::GroupGenesis::with_existing_id(
                self.mls_group_id.clone(),
                creator_hex,
                self.created_at,
                // Deterministic nonce from mls_group_id so migration is
                // idempotent across daemon restarts.
                hex::encode(blake3::hash(self.mls_group_id.as_bytes()).as_bytes()),
            ));
        }
        // NOTE: do NOT recompute here. `self.state_hash` reflects the
        // *last committed* state; that is what the new commit's
        // `prev_state_hash` must link to. Mutations the caller made
        // since the last commit are intentionally not yet reflected in
        // `self.state_hash` — the recompute below folds them in under
        // the new revision.
        let prev = self.state_hash.clone();
        self.state_revision = self.state_revision.saturating_add(1);
        self.prev_state_hash = Some(prev.clone());
        self.updated_at = now_ms;
        self.recompute_state_hash();

        let roster_root = state_commit::compute_roster_root(&self.members_v2);
        let policy_hash = state_commit::compute_policy_hash(&self.policy);
        let meta_hash = state_commit::compute_public_meta_hash(&self.public_meta());

        let commit = state_commit::GroupStateCommit::sign(
            self.stable_group_id().to_string(),
            self.state_revision,
            Some(prev),
            roster_root,
            policy_hash,
            meta_hash,
            self.security_binding.clone(),
            self.withdrawn,
            now_ms,
            keypair,
        )?;
        // issue #111: retain the locally-authored commit + the roster it
        // committed. `self` already reflects the committed state here.
        self.retain_commit(&commit);
        Ok(commit)
    }

    /// Append a retained commit for the just-committed state and enforce
    /// [`COMMIT_LOG_CAP`]. `self` must already reflect the committed roster
    /// (callers mutate then seal/finalize, so this holds). The single
    /// chokepoint both commit-production paths route through, so retention
    /// cannot be forgotten at an individual apply site.
    fn retain_commit(&mut self, commit: &state_commit::GroupStateCommit) {
        self.commit_log.push(state_commit::RetainedCommit::capture(
            commit.clone(),
            &self.members_v2,
        ));
        if self.commit_log.len() > COMMIT_LOG_CAP {
            let overflow = self.commit_log.len() - COMMIT_LOG_CAP;
            self.commit_log.drain(0..overflow);
            tracing::warn!(
                group_id = %self.stable_group_id(),
                dropped = overflow,
                cap = COMMIT_LOG_CAP,
                "commit_log exceeded cap; dropped oldest retained commits",
            );
        }
    }

    /// Mark the group as withdrawn and seal the terminal higher-revision
    /// commit. A withdrawn group is superseded immediately for public
    /// discovery purposes — peers holding stale public cards must drop them
    /// on receipt of this commit regardless of TTL. Successful withdrawal also
    /// clears local GSS key material; `GroupDeleted` carries the signed commit,
    /// not encrypted group content.
    ///
    /// Withdrawal is admin-authored; authorization is checked before the local
    /// state is marked withdrawn so rejected calls leave the group untouched.
    pub fn seal_withdrawal(
        &mut self,
        keypair: &AgentKeypair,
        now_ms: u64,
    ) -> Result<state_commit::GroupStateCommit, state_commit::ApplyError> {
        let signer_hex = hex::encode(keypair.agent_id().as_bytes());
        if !state_commit::active_signer_is_admin_or_higher(&self.members_v2, &signer_hex) {
            return Err(state_commit::ApplyError::Unauthorized {
                signer: signer_hex,
                action: state_commit::ActionKind::AdminOrHigher.name(),
            });
        }

        let original = self.clone();
        self.withdrawn = true;
        match self.seal_commit(keypair, now_ms) {
            Ok(commit) => {
                self.shared_secret = None;
                Ok(commit)
            }
            Err(err) => {
                *self = original;
                Err(err)
            }
        }
    }

    /// Accept a peer-authored signed non-terminal commit on the apply-side.
    ///
    /// Performs [`state_commit::validate_apply`] with the given action kind
    /// and, on success, updates the local chain fields (`state_revision`,
    /// `state_hash`, `prev_state_hash`) to mirror the commit. Domain-specific
    /// mutations (roster/policy/meta) are the caller's responsibility and must
    /// be performed **before** calling this method, so the post-mutation
    /// recomputed hash matches `commit.state_hash`.
    ///
    /// A live -> withdrawn transition is intentionally rejected here: terminal
    /// withdrawal must arrive through explicit terminal event handling so the
    /// withdrawn marker and key wipe stay one atomic act.
    pub fn apply_commit(
        &mut self,
        commit: &state_commit::GroupStateCommit,
        action_kind: state_commit::ActionKind,
    ) -> Result<(), state_commit::ApplyError> {
        let ctx = state_commit::ApplyContext {
            current_state_hash: &self.state_hash,
            current_revision: self.state_revision,
            current_withdrawn: self.withdrawn,
            members_v2: &self.members_v2,
            group_id: self.stable_group_id(),
        };
        state_commit::validate_apply(&ctx, commit, action_kind)?;
        self.finalize_applied_commit(commit)
    }

    fn finalize_applied_commit_with_terminal_mode(
        &mut self,
        commit: &state_commit::GroupStateCommit,
        allow_live_withdrawal: bool,
    ) -> Result<(), state_commit::ApplyError> {
        if self.withdrawn && !commit.withdrawn {
            return Err(state_commit::ApplyError::Withdrawn);
        }

        let live_to_withdrawn = !self.withdrawn && commit.withdrawn;
        if live_to_withdrawn && !allow_live_withdrawal {
            return Err(state_commit::ApplyError::Invariant(
                "live withdrawal commit requires terminal finalization".to_string(),
            ));
        }

        self.state_revision = commit.revision;
        self.prev_state_hash = commit.prev_state_hash.clone();
        self.withdrawn = commit.withdrawn;
        self.recompute_state_hash();
        if self.state_hash != commit.state_hash {
            return Err(state_commit::ApplyError::StateHashMismatch {
                expected: commit.state_hash.clone(),
                got: self.state_hash.clone(),
            });
        }
        // ADR-0016 R2: reject any applied commit whose post-mutation,
        // non-withdrawn state has zero active admins. Runs after the hash
        // check so the roster being validated is provably the roster the
        // signed commit's `roster_root` committed to.
        state_commit::enforce_last_admin_invariant(&self.members_v2, self.withdrawn)?;
        if live_to_withdrawn {
            self.shared_secret = None;
        }
        // issue #111: retain the peer-authored commit only after it has
        // validated and applied cleanly (post hash-match + invariants), so
        // rejected commits never enter the history.
        self.retain_commit(commit);
        Ok(())
    }

    /// Finalize a non-terminal commit **after** the caller has already performed
    /// any action-specific pre-validation and mirrored the payload
    /// mutation into `self`.
    ///
    /// This is the second half of D.4 apply-side handling: callers may
    /// need the pre-mutation roster view to validate signer authority
    /// (e.g. self-leave), then mutate local state, then verify the
    /// recomputed post-mutation hash matches the signed commit. This default
    /// finalizer deliberately rejects live -> withdrawn commits; use
    /// [`GroupInfo::finalize_applied_terminal_commit`] only from explicit
    /// terminal event handling.
    pub fn finalize_applied_commit(
        &mut self,
        commit: &state_commit::GroupStateCommit,
    ) -> Result<(), state_commit::ApplyError> {
        self.finalize_applied_commit_with_terminal_mode(commit, false)
    }

    /// Finalize an explicitly terminal, already-authorized withdrawal commit.
    ///
    /// This is the terminal counterpart to [`GroupInfo::finalize_applied_commit`]:
    /// callers must first run [`state_commit::validate_apply_terminal`] from the
    /// appropriate terminal event context (currently server `GroupDeleted`) and
    /// mirror any terminal metadata fields into `self`. On a live -> withdrawn
    /// transition this method clears GSS key material before retaining the
    /// terminal commit; the daemon's `GroupDeleted` path additionally tombstones
    /// the record and wipes local MLS/TreeKEM material.
    pub fn finalize_applied_terminal_commit(
        &mut self,
        commit: &state_commit::GroupStateCommit,
    ) -> Result<(), state_commit::ApplyError> {
        if !commit.withdrawn {
            return Err(state_commit::ApplyError::Invariant(
                "terminal finalization requires withdrawn commit".to_string(),
            ));
        }
        self.finalize_applied_commit_with_terminal_mode(commit, true)
    }

    /// Derive the per-message AEAD key from the group's current shared secret.
    /// Returns None if the group has no shared secret (e.g., SignedPublic, or
    /// the caller hasn't received a welcome yet).
    #[must_use]
    pub fn secure_message_key(&self) -> Option<Vec<u8>> {
        let secret = self.shared_secret.as_ref()?;
        Some(Self::derive_message_key(
            secret,
            self.secret_epoch,
            self.stable_group_id(),
        ))
    }

    /// Pure helper so both encryptor and decryptor derive the same key from
    /// (secret, epoch, group_id).
    #[must_use]
    pub fn derive_message_key(secret: &[u8], epoch: u64, group_id: &str) -> Vec<u8> {
        let mut material = Vec::with_capacity(secret.len() + 48);
        material.extend_from_slice(b"x0x.group.secure\0");
        material.extend_from_slice(secret);
        material.extend_from_slice(&epoch.to_le_bytes());
        material.extend_from_slice(group_id.as_bytes());
        let hash = blake3::hash(&material);
        hash.as_bytes()[..32].to_vec()
    }

    /// Migrate v1 (BTreeSet + display_names) data into v2 structured members.
    /// Also backfills Phase D.3 stable-genesis + state-hash fields for
    /// blobs written before D.3 landed. Idempotent: may be called multiple
    /// times.
    pub fn migrate_from_v1(&mut self) {
        if self.members_v2.is_empty() {
            let now = now_millis();
            let creator_hex = hex::encode(self.creator.as_bytes());
            let mut all_ids: BTreeSet<String> = self.members.clone();
            all_ids.insert(creator_hex.clone());
            for id in self.display_names.keys() {
                all_ids.insert(id.clone());
            }
            for id in all_ids {
                let display_name = self.display_names.get(&id).cloned();
                let member = if id == creator_hex {
                    GroupMember::new_admin(id.clone(), display_name, now)
                } else {
                    GroupMember::new_member(
                        id.clone(),
                        display_name,
                        Some(creator_hex.clone()),
                        now,
                    )
                };
                self.members_v2.insert(id, member);
            }
            if self.roster_revision == 0 {
                self.roster_revision = self.membership_revision;
            }
            if self.updated_at == 0 {
                self.updated_at = self.created_at;
            }
        }
        // Phase D.3: backfill stable-genesis deterministically from the
        // existing mls_group_id so migrated blobs carry the same
        // `stable_group_id` across restarts.
        if self.genesis.is_none() {
            let creator_hex = hex::encode(self.creator.as_bytes());
            let nonce = hex::encode(blake3::hash(self.mls_group_id.as_bytes()).as_bytes());
            self.genesis = Some(state_commit::GroupGenesis::with_existing_id(
                self.mls_group_id.clone(),
                creator_hex,
                self.created_at,
                nonce,
            ));
        }
        // Phase D.3: if security_binding is unset on an MlsEncrypted group,
        // derive it from the current secret_epoch.
        if self.security_binding.is_none()
            && self.policy.confidentiality == GroupConfidentiality::MlsEncrypted
        {
            self.security_binding = Some(format!("gss:epoch={}", self.secret_epoch));
        }
        // Phase D.3: recompute state_hash if absent.
        if self.state_hash.is_empty() {
            self.recompute_state_hash();
        }
    }

    /// Record an invite minted by this local authority. Invite-join v1 is
    /// deliberately one-time and role-capped to prevent replay and privilege
    /// escalation from joiner-authored metadata events.
    pub fn record_issued_invite(
        &mut self,
        secret: String,
        created_at_secs: u64,
        expires_at_secs: u64,
        max_role: GroupRole,
    ) {
        self.issued_invite_secrets.insert(secret.clone());
        self.issued_invites.insert(
            secret,
            IssuedInviteRecord {
                created_at_secs,
                expires_at_secs,
                max_role,
                consumed_by: None,
                consumed_at_ms: None,
            },
        );
    }

    /// Consume a previously-recorded one-time invite for `member_agent_id`.
    ///
    /// Returns `Ok(())` only if the secret exists, has not already been
    /// consumed, has not expired, and the requested role is within the
    /// invite's role cap.
    pub fn consume_issued_invite(
        &mut self,
        secret: &str,
        member_agent_id: &str,
        requested_role: GroupRole,
        event_ts_ms: u64,
        now_ms: u64,
    ) -> Result<(), &'static str> {
        let Some(record) = self.issued_invites.get_mut(secret) else {
            return Err("invite_secret_unknown");
        };
        if record.consumed_by.is_some() {
            return Err("invite_secret_consumed");
        }
        if !record.max_role.at_least(requested_role) {
            return Err("invite_role_exceeds_cap");
        }
        let event_secs = event_ts_ms / 1_000;
        if event_secs.saturating_add(300) < record.created_at_secs {
            return Err("invite_event_before_creation");
        }
        if record.expires_at_secs != 0 {
            let now_secs = now_ms / 1_000;
            if event_secs > record.expires_at_secs || now_secs > record.expires_at_secs {
                return Err("invite_expired");
            }
        }
        record.consumed_by = Some(member_agent_id.to_string());
        record.consumed_at_ms = Some(now_ms);
        self.issued_invite_secrets.remove(secret);
        Ok(())
    }

    /// Add or update a member. If the member already exists, updates state to Active.
    pub fn add_member(
        &mut self,
        agent_id_hex: String,
        role: GroupRole,
        added_by: Option<String>,
        display_name: Option<String>,
    ) {
        self.add_member_with_kem(agent_id_hex, role, added_by, display_name, None);
    }

    /// Add or update a member, optionally recording their ML-KEM-768 public
    /// key for future secure-share delivery. If `kem_public_key_b64` is
    /// `Some`, it overwrites any previously-recorded value; `None` preserves
    /// the existing one.
    pub fn add_member_with_kem(
        &mut self,
        agent_id_hex: String,
        role: GroupRole,
        added_by: Option<String>,
        display_name: Option<String>,
        kem_public_key_b64: Option<String>,
    ) {
        let now = now_millis();
        self.members_v2
            .entry(agent_id_hex.clone())
            .and_modify(|m| {
                m.role = role;
                m.state = GroupMemberState::Active;
                m.updated_at = now;
                if let Some(dn) = display_name.clone() {
                    m.display_name = Some(dn);
                }
                if added_by.is_some() {
                    m.added_by = added_by.clone();
                }
                if let Some(ref k) = kem_public_key_b64 {
                    m.kem_public_key_b64 = Some(k.clone());
                }
            })
            .or_insert_with(|| GroupMember {
                agent_id: agent_id_hex,
                user_id: None,
                role,
                state: GroupMemberState::Active,
                display_name,
                joined_at: now,
                updated_at: now,
                added_by,
                removed_by: None,
                kem_public_key_b64,
                treekem_key_package_b64: None,
                treekem_key_package_hash: None,
            });
    }

    /// Record a member's ML-KEM-768 public key without changing any other
    /// state. Used when we learn a key for an existing member via a later
    /// event (e.g. `JoinRequestCreated` after a stub was already seeded).
    pub fn set_member_kem_public_key(&mut self, agent_id_hex: &str, kem_public_key_b64: String) {
        if let Some(m) = self.members_v2.get_mut(agent_id_hex) {
            m.kem_public_key_b64 = Some(kem_public_key_b64);
            m.updated_at = now_millis();
        }
    }

    /// Record the TreeKEM KeyPackage that binds a roster member to a ratchet
    /// tree leaf. Receivers use this before removal to avoid trusting a stale
    /// best-effort `AgentId -> leaf` map.
    pub fn set_member_treekem_key_package(
        &mut self,
        agent_id_hex: &str,
        treekem_key_package_b64: String,
    ) {
        if let Some(m) = self.members_v2.get_mut(agent_id_hex) {
            m.treekem_key_package_hash = Some(
                blake3::hash(treekem_key_package_b64.as_bytes())
                    .to_hex()
                    .to_string(),
            );
            m.treekem_key_package_b64 = Some(treekem_key_package_b64);
            m.updated_at = now_millis();
        }
    }
    /// Record only the committed KeyPackage hash when the package bytes are
    /// intentionally absent from an invite-derived roster.
    pub fn set_member_treekem_key_package_hash(
        &mut self,
        agent_id_hex: &str,
        treekem_key_package_hash: String,
    ) {
        if let Some(member) = self.members_v2.get_mut(agent_id_hex) {
            if member.treekem_key_package_hash.as_deref() != Some(&treekem_key_package_hash) {
                member.treekem_key_package_b64 = None;
            }
            member.treekem_key_package_hash = Some(treekem_key_package_hash);
            member.updated_at = now_millis();
        }
    }

    /// Mark a member as Removed (soft delete — entry retained for audit).
    pub fn remove_member(&mut self, agent_id_hex: &str, removed_by: Option<String>) {
        if let Some(m) = self.members_v2.get_mut(agent_id_hex) {
            m.state = GroupMemberState::Removed;
            m.updated_at = now_millis();
            m.removed_by = removed_by;
        }
    }

    /// Mark a member as Banned.
    pub fn ban_member(&mut self, agent_id_hex: &str, banned_by: Option<String>) {
        let now = now_millis();
        self.members_v2
            .entry(agent_id_hex.to_string())
            .and_modify(|m| {
                m.state = GroupMemberState::Banned;
                m.updated_at = now;
                m.removed_by = banned_by.clone();
            })
            .or_insert_with(|| GroupMember {
                agent_id: agent_id_hex.to_string(),
                user_id: None,
                role: GroupRole::Guest,
                state: GroupMemberState::Banned,
                display_name: None,
                joined_at: now,
                updated_at: now,
                added_by: None,
                removed_by: banned_by,
                kem_public_key_b64: None,
                treekem_key_package_b64: None,
                treekem_key_package_hash: None,
            });
    }

    /// Unban — transition Banned → Active (keeps current role).
    pub fn unban_member(&mut self, agent_id_hex: &str) {
        if let Some(m) = self.members_v2.get_mut(agent_id_hex) {
            if m.state == GroupMemberState::Banned {
                m.state = GroupMemberState::Active;
                m.updated_at = now_millis();
                m.removed_by = None;
            }
        }
    }

    /// Change a member's role. Caller must verify caller's authority first.
    pub fn set_member_role(&mut self, agent_id_hex: &str, role: GroupRole) {
        if let Some(m) = self.members_v2.get_mut(agent_id_hex) {
            m.role = role;
            m.updated_at = now_millis();
        }
    }

    /// Check that a member is present and Active.
    #[must_use]
    pub fn has_active_member(&self, agent_id_hex: &str) -> bool {
        self.members_v2
            .get(agent_id_hex)
            .is_some_and(GroupMember::is_active)
    }

    /// Legacy compat: true if active (matches old `has_member` semantics).
    #[must_use]
    pub fn has_member(&self, agent_id_hex: &str) -> bool {
        self.has_active_member(agent_id_hex)
    }

    /// Returns the caller's effective role if they are an active member.
    #[must_use]
    pub fn caller_role(&self, agent_id_hex: &str) -> Option<GroupRole> {
        self.members_v2
            .get(agent_id_hex)
            .filter(|m| m.is_active())
            .map(|m| m.role)
    }

    /// Returns true if the agent is currently banned.
    #[must_use]
    pub fn is_banned(&self, agent_id_hex: &str) -> bool {
        self.members_v2
            .get(agent_id_hex)
            .is_some_and(GroupMember::is_banned)
    }

    /// Set a display name for a member. Member must exist.
    pub fn set_display_name(&mut self, agent_id_hex: &str, name: String) {
        if let Some(m) = self.members_v2.get_mut(agent_id_hex) {
            m.display_name = Some(name);
            m.updated_at = now_millis();
        }
    }

    /// Get a member's display name, falling back to truncated agent ID.
    #[must_use]
    pub fn display_name(&self, agent_id_hex: &str) -> String {
        if let Some(m) = self.members_v2.get(agent_id_hex) {
            if let Some(dn) = &m.display_name {
                return dn.clone();
            }
        }
        if agent_id_hex.len() >= 8 {
            format!("{}", &agent_id_hex[..8])
        } else {
            agent_id_hex.to_string()
        }
    }

    /// Iterator over currently active members.
    pub fn active_members(&self) -> impl Iterator<Item = &GroupMember> {
        self.members_v2.values().filter(|m| m.is_active())
    }

    /// Count of currently active members.
    #[must_use]
    pub fn active_member_count(&self) -> usize {
        self.active_members().count()
    }

    /// Count of currently active Admins (including legacy Owner).
    #[must_use]
    pub fn active_admin_count(&self) -> usize {
        self.members_v2
            .values()
            .filter(|m| m.is_active() && m.role.at_least(GroupRole::Admin))
            .count()
    }

    /// Active legacy Owner's agent hex, if one exists.
    #[must_use]
    pub fn owner_agent_id(&self) -> Option<String> {
        self.members_v2
            .values()
            .find(|m| m.is_active() && m.role == GroupRole::Owner)
            .map(|m| m.agent_id.clone())
    }

    /// Default chat topic for the group ("general" room).
    #[must_use]
    pub fn general_chat_topic(&self) -> String {
        format!("{}/general", self.chat_topic_prefix)
    }

    /// Build a shareable discoverable `GroupCard` from this group's state.
    /// Returns None if the group is `Hidden`.
    ///
    /// The returned card carries the Phase D.3 state-commit binding
    /// (`revision`, `state_hash`, `prev_state_hash`, `issued_at`,
    /// `expires_at`, `withdrawn`) but is **unsigned**. Callers with the
    /// authority's keypair should call `GroupCard::sign` before
    /// publishing to turn it into a verifiable public artifact.
    #[must_use]
    pub fn to_group_card(&self) -> Option<GroupCard> {
        if self.policy.discoverability == GroupDiscoverability::Hidden && !self.withdrawn {
            return None;
        }
        let owner = self
            .owner_agent_id()
            .unwrap_or_else(|| hex::encode(self.creator.as_bytes()));
        let issued_at = now_millis();
        let expires_at =
            issued_at.saturating_add(state_commit::DEFAULT_CARD_TTL_SECS.saturating_mul(1_000));
        Some(GroupCard {
            group_id: self.stable_group_id().to_string(),
            name: self.name.clone(),
            description: self.description.clone(),
            avatar_url: self.avatar_url.clone(),
            banner_url: self.banner_url.clone(),
            tags: self.tags.clone(),
            policy_summary: GroupPolicySummary::from(&self.policy),
            owner_agent_id: owner,
            admin_count: self.active_admin_count() as u32,
            member_count: self.active_member_count() as u32,
            created_at: self.created_at,
            updated_at: self.updated_at,
            request_access_enabled: self.policy.admission == GroupAdmission::RequestAccess,
            metadata_topic: Some(self.metadata_topic.clone()),
            revision: self.state_revision,
            state_hash: self.state_hash.clone(),
            prev_state_hash: self.prev_state_hash.clone(),
            issued_at,
            expires_at,
            authority_agent_id: String::new(),
            authority_public_key: String::new(),
            withdrawn: self.withdrawn,
            signature: String::new(),
        })
    }

    /// Build and sign a `GroupCard` in one step.
    ///
    /// Returns None if the group is `Hidden` AND not withdrawn. Callers
    /// publishing a withdrawal card must call `seal_withdrawal()` first to
    /// advance the state chain, then this helper to emit the terminal
    /// signed card.
    pub fn to_signed_group_card(
        &self,
        keypair: &AgentKeypair,
    ) -> Result<Option<GroupCard>, state_commit::ApplyError> {
        let Some(mut card) = self.to_group_card() else {
            return Ok(None);
        };
        card.sign(keypair)?;
        Ok(Some(card))
    }
}

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

    fn agent(n: u8) -> AgentId {
        AgentId([n; 32])
    }

    #[test]
    fn test_group_info_new_seeds_admin() {
        let info = GroupInfo::new(
            "Test Group".to_string(),
            "A test".to_string(),
            agent(1),
            "aabb".repeat(8),
        );
        let creator_hex = hex::encode([1u8; 32]);
        let admin = info.members_v2.get(&creator_hex).unwrap();
        assert_eq!(admin.role, GroupRole::Admin);
        assert!(admin.is_active());
        assert_eq!(info.policy, GroupPolicy::default());
        assert_eq!(info.active_member_count(), 1);
    }

    #[test]
    fn seal_commit_retains_verifiable_history() {
        // issue #111: every locally-authored commit is retained in-struct,
        // paired with a roster projection that re-derives its signed root.
        let mut info = GroupInfo::new("Test".into(), String::new(), agent(1), "aabb".repeat(8));
        let kp = crate::identity::AgentKeypair::generate().unwrap();
        assert!(
            info.commit_log.is_empty(),
            "fresh group has no retained commits"
        );

        let c1 = info.seal_commit(&kp, 1_000).unwrap();
        info.add_member(
            hex::encode([2u8; 32]),
            GroupRole::Member,
            Some("alice".into()),
            None,
        );
        let c2 = info.seal_commit(&kp, 2_000).unwrap();

        assert_eq!(
            info.commit_log.len(),
            2,
            "each seal retains exactly one entry"
        );
        assert_eq!(info.commit_log[0].commit.revision, c1.revision);
        assert_eq!(info.commit_log[1].commit.revision, c2.revision);
        assert!(c2.revision > c1.revision, "revisions are monotonic");

        for entry in &info.commit_log {
            assert!(
                entry.roster_root_consistent(),
                "retained entry must re-derive its signed roster_root"
            );
        }
        assert!(
            info.commit_log[1]
                .roster
                .contains_key(&hex::encode([2u8; 32])),
            "newly added member must appear in the latest retained projection"
        );
    }

    #[test]
    fn seal_withdrawal_rejects_non_admin_without_mutating_local_state() {
        let admin = crate::identity::AgentKeypair::generate().unwrap();
        let outsider = crate::identity::AgentKeypair::generate().unwrap();
        let mut info = GroupInfo::with_policy(
            "Test".into(),
            String::new(),
            admin.agent_id(),
            "aabb".repeat(8),
            GroupPolicyPreset::PublicRequestSecure.to_policy(),
        );
        let before = serde_json::to_string(&info).expect("snapshot serializes");

        let err = info.seal_withdrawal(&outsider, 1_000).unwrap_err();

        assert!(matches!(err, state_commit::ApplyError::Unauthorized { .. }));
        assert_eq!(
            serde_json::to_string(&info).expect("snapshot serializes"),
            before,
            "failed withdrawal authorization must leave local group state untouched"
        );
        assert!(!info.withdrawn);
    }

    #[test]
    fn seal_withdrawal_success_clears_shared_secret() {
        let admin = crate::identity::AgentKeypair::generate().unwrap();
        let mut info = GroupInfo::with_policy(
            "Test".into(),
            String::new(),
            admin.agent_id(),
            "aabb".repeat(8),
            GroupPolicyPreset::PublicRequestSecure.to_policy(),
        );
        assert!(
            info.shared_secret.is_some(),
            "secure group starts with GSS key material"
        );

        let commit = info.seal_withdrawal(&admin, 1_000).unwrap();

        assert!(commit.withdrawn);
        assert!(info.withdrawn);
        assert_eq!(info.state_hash, commit.state_hash);
        assert!(
            info.shared_secret.is_none(),
            "successful withdrawal must leave the terminal GroupInfo keyless"
        );
        assert!(info.secure_message_key().is_none());
    }

    #[test]
    fn test_display_name_fallback() {
        let mut info = GroupInfo::new(
            "Test".to_string(),
            String::new(),
            agent(1),
            "aabb".repeat(8),
        );
        let creator_hex = hex::encode([1u8; 32]);
        let name = info.display_name(&creator_hex);
        assert!(name.ends_with(''));

        info.set_display_name(&creator_hex, "Alice".to_string());
        assert_eq!(info.display_name(&creator_hex), "Alice");
    }

    #[test]
    fn test_add_and_remove_member() {
        let mut info = GroupInfo::new(
            "Test".to_string(),
            String::new(),
            agent(1),
            "aabb".repeat(8),
        );
        let bob_hex = hex::encode([2u8; 32]);
        info.add_member(
            bob_hex.clone(),
            GroupRole::Member,
            Some("alice".into()),
            None,
        );
        assert!(info.has_active_member(&bob_hex));
        assert_eq!(info.active_member_count(), 2);

        info.remove_member(&bob_hex, Some("alice".into()));
        assert!(!info.has_active_member(&bob_hex));
        assert_eq!(info.active_member_count(), 1);
    }

    #[test]
    fn test_ban_unban() {
        let mut info = GroupInfo::new("T".into(), "".into(), agent(1), "aa".repeat(16));
        let hex_b = hex::encode([2u8; 32]);
        info.add_member(hex_b.clone(), GroupRole::Member, None, None);
        info.ban_member(&hex_b, Some("alice".into()));
        assert!(info.is_banned(&hex_b));
        assert!(!info.has_active_member(&hex_b));
        info.unban_member(&hex_b);
        assert!(info.has_active_member(&hex_b));
        assert!(!info.is_banned(&hex_b));
    }

    #[test]
    fn test_migrate_from_v1() {
        // Simulate a v1 blob missing v2 fields
        let bob_key = hex::encode([2u8; 32]);
        let charlie_key = hex::encode([3u8; 32]);
        let creator_bytes: Vec<u8> = vec![1u8; 32];
        let v1_json = serde_json::json!({
            "members": [bob_key.clone(), charlie_key],
            "display_names": { bob_key.clone(): "Bob" },
            "membership_revision": 5,
            "name": "Old",
            "description": "",
            "creator": creator_bytes,
            "created_at": 1000,
            "mls_group_id": "aa".repeat(16),
            "metadata_topic": "x0x.group.aa.meta",
            "chat_topic_prefix": "x0x.group.aa.chat",
        });
        let mut info: GroupInfo = serde_json::from_value(v1_json).unwrap();
        assert!(info.members_v2.is_empty());
        info.migrate_from_v1();
        // creator + 2 members = 3 entries
        assert_eq!(info.members_v2.len(), 3);
        let creator_hex = hex::encode([1u8; 32]);
        let bob_hex = hex::encode([2u8; 32]);
        assert_eq!(info.members_v2[&creator_hex].role, GroupRole::Admin);
        assert_eq!(info.members_v2[&bob_hex].role, GroupRole::Member);
        assert_eq!(
            info.members_v2[&bob_hex].display_name.as_deref(),
            Some("Bob")
        );
        assert_eq!(info.roster_revision, 5);

        // Idempotent
        let count = info.members_v2.len();
        info.migrate_from_v1();
        assert_eq!(info.members_v2.len(), count);
    }

    #[test]
    fn legacy_group_without_plane_field_grandfathers_to_gss() {
        // ADR-0012: every group persisted before `secure_plane` existed was
        // created on the GSS plane. A blob missing the field MUST load as Gss,
        // never the enum's own TreeKem default — relabelling a grandfathered
        // group as FS/PCS-capable when it has no TreeKEM state would be a lie.
        let json = serde_json::json!({
            "name": "Old",
            "description": "",
            "creator": vec![1u8; 32],
            "created_at": 1000,
            "mls_group_id": "aa".repeat(16),
            "metadata_topic": "x0x.group.aa.meta",
            "chat_topic_prefix": "x0x.group.aa.chat",
            "shared_secret": vec![7u8; 32],
            "secret_epoch": 3,
        });
        let info: GroupInfo = serde_json::from_value(json).expect("deserialize legacy blob");
        assert_eq!(
            info.secure_plane,
            SecureGroupPlane::Gss,
            "a group blob without secure_plane must grandfather to GSS"
        );
    }

    #[test]
    fn with_policy_constructor_stays_on_gss_plane() {
        // The generic constructor must not flip groups to TreeKem — that
        // decision is made explicitly in the daemon's create path so stubs and
        // other callers are not silently relabelled (ADR-0012 Phase 2).
        let info = GroupInfo::new("T".into(), "".into(), agent(1), "aa".repeat(16));
        assert_eq!(info.secure_plane, SecureGroupPlane::Gss);
    }

    #[test]
    fn secure_plane_survives_json_roundtrip() {
        let mut info = GroupInfo::new("T".into(), "".into(), agent(1), "aa".repeat(16));
        info.secure_plane = SecureGroupPlane::TreeKem;
        let json = serde_json::to_string(&info).expect("serialize");
        let restored: GroupInfo = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(restored.secure_plane, SecureGroupPlane::TreeKem);
    }

    #[test]
    fn test_to_group_card_hidden_returns_none() {
        let info = GroupInfo::new("T".into(), "".into(), agent(1), "aa".repeat(16));
        assert!(info.to_group_card().is_none());
    }

    #[test]
    fn test_to_group_card_public() {
        let info = GroupInfo::with_policy(
            "T".into(),
            "d".into(),
            agent(1),
            "aa".repeat(16),
            GroupPolicyPreset::PublicRequestSecure.to_policy(),
        );
        let card = info.to_group_card().unwrap();
        assert_eq!(card.name, "T");
        assert_eq!(card.member_count, 1);
        assert!(card.request_access_enabled);
    }

    #[test]
    fn test_caller_role() {
        let info = GroupInfo::new("T".into(), "".into(), agent(1), "aa".repeat(16));
        let creator_hex = hex::encode([1u8; 32]);
        assert_eq!(info.caller_role(&creator_hex), Some(GroupRole::Admin));
        let stranger_hex = hex::encode([9u8; 32]);
        assert_eq!(info.caller_role(&stranger_hex), None);
    }

    #[test]
    fn default_invite_max_role_is_member() {
        assert_eq!(default_invite_max_role(), GroupRole::Member);
    }
}