Skip to main content

vector_core/community/v2/
service.rs

1//! Concord v2 service — the stateful orchestration binding the pure v2 modules
2//! to storage + transport. Free functions, `SessionGuard`-gated at every write
3//! (a `swap_session` can land at any await — see CLAUDE.md), mirroring the v1
4//! service's discipline.
5//!
6//! Signing + NIP-44 flow through the active [`VectorSigner`] (`active_signer()`):
7//! the live client's signer for a NIP-46 bunker / NIP-55 offline account, else the
8//! local vault. Every identity op in v2 is `sign_event` / `nip44_encrypt` /
9//! `nip44_decrypt` — a remote signer's whole surface — so create, send, join,
10//! invite, moderate, rotate, and refound all work keylessly (CORD-06 D1/D5 made the
11//! rekey locator public + its blobs pairwise NIP-44, so unlike v1 there is no
12//! raw-ECDH exception).
13
14use nostr_sdk::prelude::{Event, Keys, PublicKey, Timestamp};
15
16use super::super::transport::{Query, Transport};
17use super::super::{version, ChannelId, Epoch};
18use super::chat::{self, ChatEvent};
19use super::community::{ChannelV2, CommunityV2};
20use super::control;
21use super::derive::{base_rekey_group_key, channel_group_key, channel_rekey_group_key, control_group_key, GroupKey};
22use super::invite::{self, CommunityInvite};
23use super::rekey::{self, Continuity, RekeyScope};
24use super::{guestbook, stream, vsk};
25use crate::community::edition::ParsedEdition;
26use crate::state::SessionGuard;
27
28/// The active signer for v2 authority actions: the live client's signer — which
29/// covers a NIP-46 bunker / NIP-55 offline signer — falling back to the local
30/// vault keys when there is no client or no signer attached (local accounts,
31/// headless/CLI paths, and tests). Every v2 seal, rekey blob, and control edition
32/// signs / NIP-44-wraps through this, so a keyless account can create AND
33/// administer a community. v2's rekey locator is public + its blobs are pairwise
34/// NIP-44 (CORD-06 D1/D5), so unlike v1 there is no raw-ECDH exception.
35/// The active identity's public key for addressing/tags — authoritative (set at
36/// login), no signer round-trip. Used everywhere v2 needs "who am I" so a keyless
37/// account (empty vault) still resolves its own identity.
38fn me_pk() -> Result<PublicKey, String> {
39    crate::state::my_public_key().ok_or_else(|| "no active identity".to_string())
40}
41
42fn now_ms() -> u64 {
43    std::time::SystemTime::now()
44        .duration_since(std::time::UNIX_EPOCH)
45        .map(|d| d.as_millis() as u64)
46        .unwrap_or(0)
47}
48
49/// Create a fresh v2 community owned by the local identity: mint the genesis
50/// (self-certifying id + the two owner editions), persist, publish the genesis
51/// control editions, and announce the owner's Guestbook Join. Returns the saved
52/// community.
53pub async fn create_community<T: Transport + ?Sized>(
54    transport: &T,
55    name: &str,
56    relays: Vec<String>,
57    description: Option<String>,
58) -> Result<CommunityV2, String> {
59    let session = SessionGuard::capture();
60    let signer = crate::signer::active_signer()?;
61    let owner_pk = me_pk()?;
62    let at_ms = now_ms();
63
64    let meta = control::CommunityMetadata {
65        name: name.to_string(),
66        description: description.clone(),
67        relays: relays.clone(),
68        ..Default::default()
69    };
70    let genesis = control::genesis_signed(owner_pk, &signer, meta, at_ms / 1000).await.map_err(|e| e.to_string())?;
71    let community = CommunityV2::from_genesis(&genesis, name, description, relays.clone(), at_ms);
72
73    // Save-before-publish (like v1 create): no peers exist yet so there's no
74    // shared view to diverge from, and the fresh-random keys are irrecoverable
75    // if a publish hiccup rolled them back. Re-check the session after the genesis
76    // signing await (a bunker signs over the network) before the DB write.
77    if !session.is_valid() {
78        return Err("account changed during community creation".to_string());
79    }
80    // Seed the genesis edition heads (v1) as the owner's refuse-downgrade floor, so a
81    // later edit can't be rolled back by a relay serving only the genesis prefix. The
82    // live control sub is replay-free (limit 0), so the owner won't re-fold its own
83    // genesis to seed the floor otherwise. Floors land BEFORE the community row
84    // (floors-then-state ordering).
85    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
86    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
87    for wrap in &genesis.wraps {
88        if let Ok((ed, _)) = control::open_control_edition(wrap, &control) {
89            let entity_hex = crate::simd::hex::bytes_to_hex_32(&ed.entity_id);
90            crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, community.root_epoch.0)?;
91        }
92    }
93    crate::db::community::save_community_v2(&community)?;
94    // Archive the genesis root at epoch 0, so a later Refounding leaves this epoch's
95    // Public-channel history readable (CORD-03 §3 multi-epoch read).
96    let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch.0, &community.community_root);
97
98    // Publish the two genesis control editions at the epoch-0 control plane.
99    // Durable, not single-shot: over a slow transport (Tor) one attempt is a coin
100    // flip, and a lost genesis leaves a community that exists only locally. Durable
101    // races every relay, returns on the first ACK, then heals stragglers in the bg.
102    for wrap in &genesis.wraps {
103        transport.publish_durable(wrap, &community.relays).await?;
104    }
105
106    // Announce the owner's Guestbook Join so they appear in the memberlist. Relays are
107    // proven-alive by the genesis ACK above, so durable here just guarantees the owner's
108    // own join lands (member count) without a real block risk.
109    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
110    let join_rumor = guestbook::build_join_rumor(owner_pk, None, at_ms);
111    if let Ok((join_wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, owner_pk, &join_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
112        let _ = transport.publish_durable(&join_wrap, &community.relays).await;
113    }
114
115    // Sync the new membership across devices (CORD-02 §8), durably — see the join path.
116    match republish_community_list(transport, Some(community.id())).await {
117        Ok(true) => {}
118        Ok(false) => republish_community_list_durable(Some(*community.id())),
119        Err(e) => {
120            crate::log_warn!("[CommunityList] failed to record this community across devices ({}) — retrying", e);
121            republish_community_list_durable(Some(*community.id()));
122        }
123    }
124    Ok(community)
125}
126
127/// Mint a v2 migration TWIN whose primary channel REUSES the v1 primary channel id (§migration)
128/// so chat history stitches through the flip. Same owner identity, fresh salt/root. Additional
129/// v1 channels are added by the wizard via `create_*_channel_with_id`. Mirrors
130/// [`create_community`]'s persist-before-publish + floor seeding.
131pub async fn create_migration_twin<T: Transport + ?Sized>(
132    transport: &T,
133    name: &str,
134    relays: Vec<String>,
135    description: Option<String>,
136    primary: (ChannelId, String),
137) -> Result<CommunityV2, String> {
138    let session = SessionGuard::capture();
139    let signer = crate::signer::active_signer()?;
140    let owner_pk = me_pk()?;
141    let at_ms = now_ms();
142
143    let meta = control::CommunityMetadata {
144        name: name.to_string(),
145        description: description.clone(),
146        relays: relays.clone(),
147        ..Default::default()
148    };
149    let primary_name = primary.1.clone();
150    let genesis = control::genesis_signed_with_primary(owner_pk, &signer, meta, at_ms / 1000, Some(primary))
151        .await
152        .map_err(|e| e.to_string())?;
153    let mut community = CommunityV2::from_genesis(&genesis, name, description, relays.clone(), at_ms);
154    // from_genesis hard-names the primary "general"; carry the v1 name (the wire edition
155    // already carries it, so this only keeps the owner's immediate local view correct).
156    if let Some(ch) = community.channels.first_mut() {
157        ch.name = primary_name;
158    }
159    if !session.is_valid() {
160        return Err("account changed during twin creation".to_string());
161    }
162    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
163    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
164    for wrap in &genesis.wraps {
165        if let Ok((ed, _)) = control::open_control_edition(wrap, &control) {
166            let entity_hex = crate::simd::hex::bytes_to_hex_32(&ed.entity_id);
167            crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, community.root_epoch.0)?;
168        }
169    }
170    crate::db::community::save_community_v2(&community)?;
171    let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch.0, &community.community_root);
172    for wrap in &genesis.wraps {
173        transport.publish_durable(wrap, &community.relays).await?;
174    }
175    // Owner Guestbook Join so they appear in the twin's memberlist.
176    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
177    let join_rumor = guestbook::build_join_rumor(owner_pk, None, at_ms);
178    if let Ok((join_wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, owner_pk, &join_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
179        let _ = transport.publish_durable(&join_wrap, &community.relays).await;
180    }
181    Ok(community)
182}
183
184/// Clone a v1 banlist onto the v2 twin (§migration Phase 1.3): the join-time ban gate needs
185/// the v2 banlist to name every v1-banned npub, else a banned-but-never-cut member who can
186/// open `m` would walk in. Owner-signed on the twin's control plane.
187pub async fn clone_banlist_to_twin<T: Transport + ?Sized>(
188    transport: &T,
189    twin: &CommunityV2,
190    banned: &[String],
191) -> Result<(), String> {
192    if banned.is_empty() {
193        return Ok(());
194    }
195    set_banlist(transport, twin, banned).await
196}
197
198/// Clone v1 governance onto the twin (§migration Phase 1.3): every v1 member who was a FULL
199/// admin (effective permissions ⊇ ADMIN_ALL) is re-granted @admin on the twin (mapping v1's
200/// Admin onto v2's deterministic admin role id, CORD-04 §2). The owner is supreme by
201/// identity (never a grant) and banned members are skipped (a banned author's editions fold
202/// out anyway, and re-granting would spring them back to admin on a future unban).
203///
204/// NON-ESCALATION: only a full admin maps to v2 @admin (which holds ADMIN_ALL). A
205/// partial-management v1 role holder (e.g. CREATE_INVITE only — never minted by the v1 UI,
206/// but reachable via the SDK) degrades to a plain member rather than being ESCALATED to full
207/// admin. Bespoke non-admin custom roles are not carried — a documented, non-security gap.
208pub async fn clone_governance_to_twin<T: Transport + ?Sized>(
209    transport: &T,
210    twin: &CommunityV2,
211    v1_roles: &crate::community::roles::CommunityRoles,
212    banned: &[String],
213) -> Result<(), String> {
214    use crate::community::roles::Permissions;
215    let owner = twin.owner()?;
216    for grant in &v1_roles.grants {
217        if !v1_roles.effective_permissions(&grant.member).contains(Permissions::ADMIN_ALL) {
218            continue; // not a full admin → plain member on v2 (never escalated)
219        }
220        if banned.contains(&grant.member) {
221            continue; // banned → no authority on v2, don't re-arm a future unban
222        }
223        let Ok(member) = PublicKey::parse(&grant.member) else { continue };
224        if member == owner {
225            continue; // supreme by identity — never needs a grant
226        }
227        grant_admin(transport, twin, &member).await?;
228    }
229    Ok(())
230}
231
232/// The twin's JoinMaterial — the membership subset sealed into the migration `m`.
233pub fn twin_join_material(twin: &CommunityV2) -> super::list::JoinMaterial {
234    join_material(twin)
235}
236
237/// Send a text message to a channel. Derives the channel's Chat-Plane group key
238/// (community_root for a Public channel, the channel key for a Private one),
239/// seals it encrypted, and publishes. Returns the message's rumor id (hex).
240pub async fn send_message<T: Transport + ?Sized>(
241    transport: &T,
242    community: &CommunityV2,
243    channel_id: &ChannelId,
244    content: &str,
245) -> Result<String, String> {
246    send_chat_message(transport, community, channel_id, content, None, &[], vec![]).await
247}
248
249/// Full chat send: threaded reply (NIP-C7 `q`, the parent's `(rumor_id, author)`
250/// hex pair), NIP-30 custom-emoji pairs, and verbatim extra tags (NIP-92 `imeta`
251/// attachments). Returns the message's rumor id (hex).
252pub async fn send_chat_message<T: Transport + ?Sized>(
253    transport: &T,
254    community: &CommunityV2,
255    channel_id: &ChannelId,
256    content: &str,
257    reply_to: Option<(&str, &str)>,
258    emoji: &[(&str, &str)],
259    extra_tags: Vec<nostr_sdk::prelude::Tag>,
260) -> Result<String, String> {
261    send_chat_message_at(transport, community, channel_id, content, reply_to, emoji, extra_tags, now_ms()).await
262}
263
264/// [`send_chat_message`] with an explicit event time. The rumor id is a pure
265/// function of its inputs, so a GUI that picks `at_ms` can precompute the id for
266/// its optimistic pending row — the in-process echo and the finalize then key
267/// the SAME id (the exact v1 pending → sent contract).
268#[allow(clippy::too_many_arguments)]
269pub async fn send_chat_message_at<T: Transport + ?Sized>(
270    transport: &T,
271    community: &CommunityV2,
272    channel_id: &ChannelId,
273    content: &str,
274    reply_to: Option<(&str, &str)>,
275    emoji: &[(&str, &str)],
276    extra_tags: Vec<nostr_sdk::prelude::Tag>,
277    at_ms: u64,
278) -> Result<String, String> {
279    let (author_pk, group, epoch, session) = chat_send_context(community, channel_id)?;
280    let rumor = chat::build_message_rumor(author_pk, channel_id, epoch, content, reply_to, emoji, extra_tags, at_ms);
281    publish_chat(transport, community, &session, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
282}
283
284/// React to a channel message (kind 7, NIP-25 shape). `target_id_hex` /
285/// `target_author_hex` name the reacted-to message; `target_kind` is its rumor
286/// kind (`kind::MESSAGE`, or `kind::COMMENT` for a threaded reply); `emoji`
287/// carries the NIP-30 pair when `emoji_content` is a custom `:shortcode:`.
288#[allow(clippy::too_many_arguments)]
289pub async fn send_reaction<T: Transport + ?Sized>(
290    transport: &T,
291    community: &CommunityV2,
292    channel_id: &ChannelId,
293    target_id_hex: &str,
294    target_author_hex: &str,
295    target_kind: u16,
296    emoji_content: &str,
297    emoji: Option<(&str, &str)>,
298) -> Result<String, String> {
299    let (author_pk, group, epoch, session) = chat_send_context(community, channel_id)?;
300    let at_ms = now_ms();
301    let rumor =
302        chat::build_reaction_rumor(author_pk, channel_id, epoch, target_id_hex, target_author_hex, target_kind, emoji_content, emoji, at_ms);
303    publish_chat(transport, community, &session, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
304}
305
306/// Edit one of your own messages (kind 3302): peers re-render `target_id_hex`
307/// with the replacement text. Author-enforced on the read side — only the
308/// original author's edit folds.
309pub async fn send_edit<T: Transport + ?Sized>(
310    transport: &T,
311    community: &CommunityV2,
312    channel_id: &ChannelId,
313    target_id_hex: &str,
314    new_content: &str,
315) -> Result<String, String> {
316    let (author_pk, group, epoch, session) = chat_send_context(community, channel_id)?;
317    let at_ms = now_ms();
318    let rumor = chat::build_edit_rumor(author_pk, channel_id, epoch, target_id_hex, new_content, at_ms);
319    publish_chat(transport, community, &session, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
320}
321
322/// Cooperative in-plane delete (kind 5, NIP-09 semantics): peers stop rendering
323/// `target_id_hex`. The wrap ciphertext on relays is scrubbed separately via the
324/// retained per-message stream key (see `publish_chat`).
325pub async fn send_delete<T: Transport + ?Sized>(
326    transport: &T,
327    community: &CommunityV2,
328    channel_id: &ChannelId,
329    target_id_hex: &str,
330    target_kind: u16,
331) -> Result<String, String> {
332    let (author_pk, group, epoch, session) = chat_send_context(community, channel_id)?;
333    let at_ms = now_ms();
334    let rumor = chat::build_delete_rumor(author_pk, channel_id, epoch, target_id_hex, target_kind, at_ms, None);
335    publish_chat(transport, community, &session, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
336}
337
338/// Moderation-hide: remove SOMEONE ELSE's message under `MANAGE_MESSAGES`
339/// (CORD-04 §3/§5). Same kind-5 the author's own delete uses — CORD defines no
340/// separate hide, the authority is what differs, and every reader re-derives it
341/// from the seal's real npub against the folded Roster.
342///
343/// Gated locally against the same predicate peers enforce, so the button can't
344/// promise what the plane will refuse; a non-owner cites the Grant it acts under.
345/// `target_author` comes from the caller's resident copy — you can only moderate
346/// a message you can see.
347pub async fn moderation_delete<T: Transport + ?Sized>(
348    transport: &T,
349    community: &CommunityV2,
350    channel_id: &ChannelId,
351    target_id_hex: &str,
352    target_kind: u16,
353    target_author: &PublicKey,
354) -> Result<String, String> {
355    let (author_pk, group, epoch, session) = chat_send_context(community, channel_id)?;
356    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
357    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
358        return Err("this community is dissolved — it accepts no new moderation actions".to_string());
359    }
360    let owner_hex = community.owner()?.to_hex();
361    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
362    if !crate::community::moderation::can_hide(
363        Some(&owner_hex),
364        &roster,
365        &author_pk.to_hex(),
366        &target_author.to_hex(),
367    ) {
368        return Err("you can't hide a message from a member who outranks you (or the owner)".to_string());
369    }
370    let at_ms = now_ms();
371    let citation = required_authority_citation(community, &author_pk)?;
372    let rumor = chat::build_delete_rumor(author_pk, channel_id, epoch, target_id_hex, target_kind, at_ms, citation.as_ref());
373    publish_chat(transport, community, &session, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
374}
375
376/// WebXDC realtime peer signal (kind 3310) — the v2 twin of v1's
377/// `publish_webxdc_signal`: the same shared content shape, sealed on the
378/// channel's chat plane, DURABLE (a reopening peer backfills a recent ad).
379/// Signed by the member's real identity — a member can't forge another
380/// player's presence. Failure is non-fatal to callers (the next re-advertise
381/// covers a missed ad).
382pub async fn send_webxdc_signal<T: Transport + ?Sized>(
383    transport: &T,
384    community: &CommunityV2,
385    channel_id: &ChannelId,
386    topic_id: &str,
387    node_addr: Option<&str>,
388) -> Result<(), String> {
389    let (author_pk, group, epoch, session) = chat_send_context(community, channel_id)?;
390    let at_ms = now_ms();
391    let content = crate::webxdc::peer_signal_content(topic_id, node_addr);
392    let rumor = chat::build_webxdc_rumor(author_pk, channel_id, epoch, &content, vec![], at_ms);
393    publish_chat(transport, community, &session, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await.map(|_| ())
394}
395
396/// Ephemeral typing indicator (kind 23311 in a 21059 wrap — relays never store it).
397pub async fn send_typing<T: Transport + ?Sized>(
398    transport: &T,
399    community: &CommunityV2,
400    channel_id: &ChannelId,
401) -> Result<(), String> {
402    let (author_pk, group, epoch, session) = chat_send_context(community, channel_id)?;
403    let at_ms = now_ms();
404    let rumor = chat::build_typing_rumor(author_pk, channel_id, epoch, at_ms);
405    publish_chat(transport, community, &session, &group, author_pk, channel_id, epoch, rumor, at_ms, true).await.map(|_| ())
406}
407
408/// Everything a chat-plane send needs: local keys, the channel's group key +
409/// epoch, and the session snapshot taken BEFORE any await. Refuses a dissolved
410/// community (every honest member sealed it read-only) and a keyless Private
411/// channel — deriving from the root would post to the public plane; its key
412/// arrives over the rekey plane.
413fn chat_send_context(community: &CommunityV2, channel_id: &ChannelId) -> Result<(PublicKey, GroupKey, Epoch, SessionGuard), String> {
414    let session = SessionGuard::capture();
415    let author_pk = me_pk()?;
416    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
417    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
418        return Err("this community has been dissolved".to_string());
419    }
420    // A self-ban: every honest peer drops our events (CORD-04 §4) and the send
421    // echo would silently no-op, so fail loudly instead of a message that seems
422    // to send but shows up nowhere.
423    if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&author_pk.to_hex()) {
424        return Err("you are banned from this community".to_string());
425    }
426    let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
427    if ch.private && ch.key.is_none() {
428        return Err("this private channel has no key yet (awaiting rekey delivery)".to_string());
429    }
430    let (secret, epoch) = community.channel_secret(ch);
431    Ok((author_pk, channel_group_key(&secret, channel_id, epoch), epoch, session))
432}
433
434/// Seal one chat rumor, re-check the session, publish, and echo the send into the
435/// shared store. Returns the rumor id (hex).
436#[allow(clippy::too_many_arguments)]
437async fn publish_chat<T: Transport + ?Sized>(
438    transport: &T,
439    community: &CommunityV2,
440    session: &SessionGuard,
441    group: &GroupKey,
442    author_pk: PublicKey,
443    channel_id: &ChannelId,
444    epoch: Epoch,
445    rumor: nostr_sdk::prelude::UnsignedEvent,
446    at_ms: u64,
447    ephemeral: bool,
448) -> Result<String, String> {
449    let rumor_id = rumor.id.ok_or("rumor has no id")?.to_hex();
450    let signer = crate::signer::active_signer()?;
451    let (wrap, _p_tag_keys) = chat::seal_chat_rumor_signed(&signer, author_pk, &rumor, group, Timestamp::from_secs(at_ms / 1000), ephemeral).await
452        .map_err(|e| e.to_string())?;
453    if !session.is_valid() {
454        return Err("account changed before send".to_string());
455    }
456    transport.publish(&wrap, &community.relays).await?;
457    // Retain the wrap's signing key (the group stream key) keyed by rumor id so a
458    // full delete can NIP-09 this exact wrap off relays (same-author rule, honored
459    // everywhere — the discarded p-tag pair only works on recipient-delete relays).
460    // Frozen per-message so later rekeys can't strand it. Session-gated: the publish
461    // straddled network I/O.
462    if !ephemeral {
463        if !session.is_valid() {
464            return Ok(rumor_id);
465        }
466        crate::db::community::store_message_key(&rumor_id, &wrap.id.to_hex(), group.keys(), &community.relays)?;
467    }
468    // Local echo (v1 parity): open our OWN wrap through the exact inbound path so
469    // send-then-read works with no listen loop, and the relay's re-delivery dedups
470    // against this row instead of re-firing callbacks. Best-effort — the publish
471    // already succeeded. Ephemeral kinds (typing) apply to nothing and skip out.
472    if !ephemeral {
473        if let Ok(event) = chat::open_chat_event(&wrap, group, channel_id, epoch) {
474            let channel_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
475            let outcome = {
476                let mut st = crate::state::STATE.lock().await;
477                if !session.is_valid() {
478                    return Ok(rumor_id); // swapped on the lock await — never echo into another account.
479                }
480                super::inbound::apply_chat_to_state(&mut st, &event, &channel_hex, &author_pk)
481            };
482            if let Some(outcome) = outcome {
483                if !session.is_valid() {
484                    return Ok(rumor_id);
485                }
486                super::inbound::persist_chat(&channel_hex, &outcome).await;
487            }
488        }
489    }
490    Ok(rumor_id)
491}
492
493/// A chat event opened from a channel fetch, tagged with the epoch its key
494/// decrypted under.
495pub struct FetchedEvent {
496    pub event: ChatEvent,
497    pub epoch: Epoch,
498}
499
500/// Self-heal scrub-key retention for an OWN rumor seen during a history open:
501/// pre-retention and other-device sends stay fully deletable, because the wrap's
502/// signing key is the derivable group stream key — only this rumor→wrap mapping
503/// was ever missing locally. No-op for foreign authors, kinds the UI can't
504/// delete, and already-retained rows. Best-effort: a store failure never breaks
505/// the fetch.
506fn heal_own_wrap_key(event: &ChatEvent, group: &GroupKey, relays: &[String]) {
507    if !matches!(event, ChatEvent::Message { .. } | ChatEvent::Reaction { .. }) {
508        return;
509    }
510    let opened = event.opened();
511    if crate::state::my_public_key() != Some(opened.author) {
512        return;
513    }
514    let rumor_hex = opened.rumor_id.to_hex();
515    // Only fill a confirmed gap — never clobber a send-time row, never write
516    // when the store can't be read.
517    if !matches!(crate::db::community::get_message_key(&rumor_hex), Ok(None)) {
518        return;
519    }
520    if crate::db::community::store_message_key(&rumor_hex, &opened.wrapper_id.to_hex(), group.keys(), relays).is_ok() {
521        // The UI caches full-vs-limited delete verdicts per message; tell it this
522        // one just flipped so it re-resolves without an app restart.
523        crate::traits::emit_event("message_delete_meta_changed", &serde_json::json!({ "id": rumor_hex }));
524    }
525}
526
527/// Fetch a channel's newest messages — one page of [`fetch_channel_history`].
528/// `limit` is one relay-side bound across the whole epoch-author OR-set, not
529/// per epoch; deeper history pages backwards via the walk.
530pub async fn fetch_channel<T: Transport + ?Sized>(
531    transport: &T,
532    community: &CommunityV2,
533    channel_id: &ChannelId,
534    limit: usize,
535) -> Result<Vec<FetchedEvent>, String> {
536    fetch_channel_history(transport, community, channel_id, limit, 1, None, crate::community::transport::Evidence::Quorum, |_| true).await
537}
538
539/// Walk a channel's history newest-first (CORD-03 §3 "clients load a Channel
540/// newest-first and paginate backwards"), querying every held epoch's Chat-Plane
541/// address one `page`-sized query at a time until `max_pages`, a drained relay,
542/// or `keep_paging` returns false for a page (the caller's "I already hold
543/// these" early stop — consulted only on pages that opened something, so junk
544/// at the address can't fake exhaustion). Pages step by INCLUSIVE `until` with
545/// wrap-id dedup, so a page boundary landing mid-second can't skip siblings; a
546/// full page of only-already-seen wraps is a same-second WALL (relay filters
547/// are second-granular) and steps past it accepting that unseen same-second
548/// siblings beyond the relay cap are unreachable — logged, and a protocol-level
549/// limitation (the `ms` tag can't be filtered server-side).
550///
551/// Returns everything opened, deduped by rumor id, oldest→newest.
552pub async fn fetch_channel_history<T: Transport + ?Sized>(
553    transport: &T,
554    community: &CommunityV2,
555    channel_id: &ChannelId,
556    page: usize,
557    max_pages: usize,
558    since: Option<u64>,
559    evidence: crate::community::transport::Evidence,
560    mut keep_paging: impl FnMut(&[FetchedEvent]) -> bool,
561) -> Result<Vec<FetchedEvent>, String> {
562    // Guards the opportunistic scrub-key heals below — the fetch loop straddles
563    // network I/O, and an account swap must not write into the new account's DB.
564    let session = SessionGuard::capture();
565    let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
566    // A Public channel reads across EVERY held base-root epoch, and a Private one
567    // across its OWN held epochs (CORD-03 §3), so history spanning a rotation stays
568    // continuous either way. A keyless Private channel is unreadable — never derived
569    // from the root (that would address the public plane).
570    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
571    let coords: Vec<([u8; 32], Epoch)> = if ch.private {
572        let Some(current) = ch.key else {
573            return Ok(Vec::new());
574        };
575        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
576        let mut held = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default();
577        if !held.iter().any(|(ep, _)| *ep == ch.epoch) {
578            held.push((ch.epoch, current));
579        }
580        // Only real grants are archived, but keep the invariant local: a private
581        // plane is never read with the root value.
582        held.into_iter().filter(|(_, k)| *k != community.community_root).map(|(ep, k)| (k, ep)).collect()
583    } else {
584        let mut roots = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default();
585        if !roots.iter().any(|(ep, _)| *ep == community.root_epoch) {
586            roots.push((community.root_epoch, community.community_root));
587        }
588        roots.into_iter().map(|(ep, root)| (root, ep)).collect()
589    };
590    if coords.is_empty() {
591        return Ok(Vec::new());
592    }
593
594    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
595    let mut seen_rumors = std::collections::HashSet::new();
596    let mut out: Vec<(u64, FetchedEvent)> = Vec::new();
597    let mut until: Option<u64> = None;
598    let mut oldest: Option<u64> = None;
599    for _ in 0..max_pages {
600        // Fetch each held epoch's Chat-Plane AUTHED AS that plane key. AUTH-gating
601        // relays (Ditto) require the connection authed as the author queried and
602        // reject a multi-author REQ ("all authors must be authenticated"), so a
603        // single merged fetch returns nothing there — the latest messages under a
604        // freshly-adopted epoch never load. Per-plane authed fetches + union.
605        let mut wraps: Vec<Event> = Vec::new();
606        let mut wrap_ids: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
607        for (secret, epoch) in &coords {
608            let plane = channel_group_key(secret, channel_id, *epoch);
609            let q = Query {
610                kinds: vec![stream::KIND_WRAP],
611                authors: vec![plane.pk_hex()],
612                since,
613                until,
614                limit: Some(page),
615                evidence,
616                ..Default::default()
617            };
618            if let Ok(evs) = transport.fetch_plane(plane.keys(), &q, &community.relays).await {
619                for e in evs {
620                    if wrap_ids.insert(e.id) {
621                        wraps.push(e);
622                    }
623                }
624            }
625        }
626        if wraps.is_empty() {
627            break;
628        }
629        let mut fresh = 0usize;
630        let mut page_events: Vec<FetchedEvent> = Vec::new();
631        for wrap in &wraps {
632            if !seen_wraps.insert(wrap.id) {
633                continue;
634            }
635            fresh += 1;
636            let at = wrap.created_at.as_secs();
637            if oldest.is_none_or(|o| at < o) {
638                oldest = Some(at);
639            }
640            // Select the epoch whose group key authored this wrap (no trial decrypt).
641            for (secret, epoch) in &coords {
642                let group = channel_group_key(secret, channel_id, *epoch);
643                if wrap.pubkey != group.pk() {
644                    continue;
645                }
646                if let Ok(event) = chat::open_chat_event(wrap, &group, channel_id, *epoch) {
647                    let id = event.opened().rumor_id;
648                    if seen_rumors.insert(id) {
649                        if session.is_valid() {
650                            heal_own_wrap_key(&event, &group, &community.relays);
651                        }
652                        page_events.push(FetchedEvent { event, epoch: *epoch });
653                    }
654                }
655                break;
656            }
657        }
658        if fresh == 0 {
659            if wraps.len() < page {
660                break; // drained — the relay has nothing older.
661            }
662            // A full page of already-seen wraps: a same-second WALL. Step past it;
663            // same-second siblings beyond the relay's cap are unreachable by a
664            // second-granular filter.
665            let Some(o) = oldest else { break };
666            if o == 0 {
667                break;
668            }
669            crate::log_warn!("v2: same-second history wall at {o} — stepping past it (messages beyond the relay page cap in that second are unreachable)");
670            until = Some(o - 1);
671            continue;
672        }
673        let stop = !page_events.is_empty() && !keep_paging(&page_events);
674        out.extend(page_events.into_iter().map(|e| (e.event.opened().at_ms, e)));
675        if stop {
676            break; // the caller holds everything from here back.
677        }
678        until = oldest; // inclusive — wrap-id dedup absorbs the boundary overlap.
679    }
680    out.sort_by_key(|(ms, _)| *ms);
681    Ok(out.into_iter().map(|(_, e)| e).collect())
682}
683
684// ── Invites (CORD-05) ────────────────────────────────────────────────────────
685
686/// Who an invite bundle is FOR — which decides the Private-Channel keys it may
687/// carry (CORD-05 §1 vs §2).
688///
689/// A **Link** has no recipient: "anyone the link reaches can join", so its
690/// audience holds no Role by construction and is entitled to no Private Channel
691/// at all. A **Member** is a specific npub whose entitlement is computable.
692#[derive(Debug, Clone, Copy, PartialEq, Eq)]
693pub enum BundleAudience {
694    /// A public link (33301 bundle event): public channels only.
695    Link,
696    /// A direct invite (3313) to this npub: may carry Private-Channel keys.
697    Member(PublicKey),
698}
699
700/// Build the §1 invite bundle for this community, scoped to `audience`. A
701/// Public channel carries the `community_root` as its "key" (the joiner derives
702/// the real secret from the root); a Private one its own key — and only for a
703/// Member the folded roster shows entitled. The bundle self-certifies the owner,
704/// so the inviter's identity is irrelevant to trust.
705pub fn bundle_of(
706    community: &CommunityV2,
707    audience: BundleAudience,
708    creator: Option<PublicKey>,
709    expires_at_ms: Option<u64>,
710    label: Option<String>,
711) -> CommunityInvite {
712    bundle_of_with_overlay(community, audience, creator, expires_at_ms, label, &[], &[])
713}
714
715/// [`bundle_of`] settling entitlement against a Grant this client JUST published
716/// (`with`/`without` role ids), since the fold lags its own publish. This is the
717/// grant-vend path (CORD-03 "delivered on grant").
718pub fn bundle_of_with_overlay(
719    community: &CommunityV2,
720    audience: BundleAudience,
721    creator: Option<PublicKey>,
722    expires_at_ms: Option<u64>,
723    label: Option<String>,
724    with: &[String],
725    without: &[String],
726) -> CommunityInvite {
727    let hex = crate::simd::hex::bytes_to_hex_32;
728    let cid_hex = hex(&community.identity.community_id.0);
729    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
730    let owner_hex = community.owner().ok().map(|o| o.to_hex());
731    let recipient_hex = match audience {
732        BundleAudience::Link => None,
733        BundleAudience::Member(pk) => Some(pk.to_hex()),
734    };
735    let channels = community
736        .vendable_channels(&roster, owner_hex.as_deref(), recipient_hex.as_deref(), with, without)
737        .into_iter()
738        .map(|c| invite::ChannelGrant {
739            id: hex(&c.id.0),
740            key: hex(&c.key.unwrap_or(community.community_root)),
741            epoch: c.epoch.0,
742            name: c.name.clone(),
743        })
744        .collect();
745    CommunityInvite {
746        community_id: hex(&community.identity.community_id.0),
747        owner: hex(&community.identity.owner_xonly),
748        owner_salt: hex(&community.identity.owner_salt),
749        community_root: hex(&community.community_root),
750        root_epoch: community.root_epoch.0,
751        channels,
752        relays: community.relays.clone(),
753        name: community.name.clone(),
754        // Mint-time snapshot so a parked invite renders the real logo before any
755        // fold; the Control Plane stays the authority after joining.
756        icon: community.icon.clone(),
757        expires_at: expires_at_ms,
758        creator_npub: creator.map(|p| p.to_hex()),
759        label,
760        extra: Default::default(),
761    }
762}
763
764/// Gift-wrap a Direct Invite (kind 3313) of this community straight to `recipient`
765/// and publish it to the community relays. `expires_at_ms` (unix ms) optionally
766/// bounds its shelf life; `label` is echoed in the joiner's Guestbook Join. The
767/// bundle hands over the keys; the recipient consents by accepting (nothing joins
768/// on receipt). Returns the wrap.
769pub async fn send_direct_invite<T: Transport + ?Sized>(
770    transport: &T,
771    community: &CommunityV2,
772    recipient: &PublicKey,
773    expires_at_ms: Option<u64>,
774    label: Option<String>,
775) -> Result<Event, String> {
776    let session = SessionGuard::capture();
777    // A stale bundle is worse than a stale edit: it hands the joiner keys to a
778    // buried epoch, and their client later self-evicts on the rekey exclusion.
779    assert_current_root(community)?;
780    let signer = crate::signer::active_signer()?;
781    let inviter_pk = me_pk()?;
782    let bundle = bundle_of(community, BundleAudience::Member(*recipient), Some(inviter_pk), expires_at_ms, label);
783    let wrap = invite::build_direct_invite_signed(&signer, inviter_pk, recipient, &bundle).await.map_err(|e| e.to_string())?;
784    if !session.is_valid() {
785        return Err("account changed before sending invite".to_string());
786    }
787    transport.publish(&wrap, &community.relays).await?;
788    Ok(wrap)
789}
790
791/// A minted public link: the shareable URL plus the addressable bundle event to
792/// publish and the link keypair to retain (in the Invite List) for later refresh
793/// or revocation.
794pub struct MintedLink {
795    pub url: String,
796    pub bundle_event: Event,
797    pub link_signer: Keys,
798    pub token: [u8; super::derive::TOKEN_LEN],
799    /// Unix ms, mirrored from the bundle. The Invite List is the creator's only
800    /// record of it, and the Registry prunes on it — the coordinate a member
801    /// folds carries no expiry, so a lapsed link the creator never pruned reads
802    /// as a live door forever (CORD-05 §4/§5).
803    pub expires_at_ms: Option<u64>,
804    pub label: Option<String>,
805}
806
807/// Mint a public invite link for this community: a fresh token + link keypair, the
808/// bundle encrypted under the token key and published at `(33301, link_signer,
809/// "")`, and the `base/invite/<naddr>#<fragment>` URL. `base` is the deep-link
810/// domain (e.g. `https://vectorapp.io`); the fragment carries the token + bootstrap
811/// relays and never reaches a server.
812pub async fn mint_public_link<T: Transport + ?Sized>(
813    transport: &T,
814    community: &CommunityV2,
815    base: &str,
816    expires_at_ms: Option<u64>,
817    label: Option<String>,
818) -> Result<MintedLink, String> {
819    let session = SessionGuard::capture();
820    let mut token = [0u8; super::derive::TOKEN_LEN];
821    token.copy_from_slice(&super::super::random_32()[..super::derive::TOKEN_LEN]);
822    let link_signer = Keys::generate();
823    let bundle = bundle_of(community, BundleAudience::Link, Some(me_pk()?), expires_at_ms, label.clone());
824    let bundle_key = super::derive::invite_bundle_key(&token);
825    let bundle_event = invite::build_bundle_event(&link_signer, &bundle, &bundle_key).map_err(|e| e.to_string())?;
826    let url = invite::build_invite_url(base, &link_signer.public_key(), &token, &community.relays).map_err(|e| e.to_string())?;
827
828    if !session.is_valid() {
829        return Err("account changed before minting link".to_string());
830    }
831    transport.publish_durable(&bundle_event, &community.relays).await?;
832    let minted = MintedLink { url, bundle_event, link_signer, token, expires_at_ms, label: label.clone() };
833    // Sync the link across the creator's devices (13303) + publish the Registry
834    // (vsk-8) so members see the community is Public. Best-effort — the link works
835    // without the sync.
836    let _ = record_minted_link(transport, community, &minted).await;
837    // Local mirror so `list_public_invites` stays a sync local read (v1 parity);
838    // the 13303 list remains the cross-device record. Re-check the session: the
839    // publishes above straddled awaits, and this write must not land account A's
840    // link (secret token included) in a swapped-in account's DB.
841    if session.is_valid() {
842        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
843        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
844        let _ = crate::db::community::save_public_invite(&token_hex, &cid_hex, &minted.url, expires_at_ms.map(|e| e as i64), label.as_deref());
845    }
846    Ok(minted)
847}
848
849// ── The Invite Registry (vsk 8) + Invite List (13303), CORD-05 §4/§5 ──────────
850
851/// Fetch the creator's own 13303 Invite List from `relays` (newest wins; a
852/// decrypt/parse failure is "no news", never a clobber of the local mirror).
853/// Transport failure is Err, NOT None: the 13303 is REPLACEABLE, so a caller
854/// that mistakes "couldn't reach the relays" for "no list yet" and publishes a
855/// fresh one wipes every link minted on other devices. Full evidence for the
856/// same reason — this read feeds replaceable-event writes.
857async fn fetch_invite_list<T: Transport + ?Sized>(
858    transport: &T,
859    relays: &[String],
860) -> Result<Option<invite::InviteList>, String> {
861    let signer = crate::signer::active_signer()?;
862    let my_pk = me_pk()?;
863    let query = Query {
864        kinds: vec![super::kind::INVITE_LIST],
865        authors: vec![my_pk.to_hex()],
866        limit: Some(4),
867        evidence: crate::community::transport::Evidence::Full,
868        ..Default::default()
869    };
870    let events = transport.fetch(&query, relays).await?;
871    let mut best: Option<(u64, invite::InviteList)> = None;
872    for e in events {
873        if let Ok(l) = invite::parse_invite_list_event_signed(&signer, my_pk, &e).await {
874            let at = e.created_at.as_secs();
875            if best.as_ref().map(|(b, _)| at > *b).unwrap_or(true) {
876                best = Some((at, l));
877            }
878        }
879    }
880    Ok(best.map(|(_, l)| l))
881}
882
883/// The creator's LIVE link-signer pubkeys for one community — the Registry's
884/// content (CORD-05 §5), derived from the stored link secrets.
885///
886/// Live means neither tombstoned nor EXPIRED. An expired link cannot be joined
887/// (`InviteBundle::expired`, CORD-05 §1), so leaving it in the Registry states
888/// a door that isn't there: the aggregate never empties, the community reads
889/// Public forever, and every gate hanging off that reading silently inverts.
890fn live_signers_for(list: &invite::InviteList, community_id_hex: &str, now_ms: u64) -> Vec<PublicKey> {
891    let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
892    list.entries
893        .iter()
894        .filter(|e| e.community_id == community_id_hex && !dead.contains(e.token.as_str()))
895        .filter(|e| !e.expires_at.is_some_and(|exp| now_ms > exp))
896        .filter_map(|e| Keys::parse(&e.signer_sk).ok().map(|k| k.public_key()))
897        .collect()
898}
899
900/// Publish the creator's Registry (vsk-8) edition — their live link signers for this
901/// community — so members fold it into the Public/Private source of truth (a
902/// non-empty aggregate = Public).
903async fn publish_invite_registry<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, session: &SessionGuard, live_signers: &[PublicKey]) -> Result<(), String> {
904    let my_pk = me_pk()?;
905    let eid = super::derive::invite_links_locator(community.id(), &my_pk.to_bytes());
906    let content = invite::build_registry_content(live_signers);
907    publish_control_edition(transport, community, session, vsk::INVITE_LINKS, &eid, &content).await?;
908    // Refresh the cache from the PLANE, not from `live_signers`: the column aggregates
909    // every creator, so writing only mine would clobber theirs, and a union could never
910    // shrink — retiring the last link would leave the community reading Public forever.
911    refresh_invite_registry_cache(transport, community, session).await;
912    Ok(())
913}
914
915/// Re-fold the whole invite Registry and cache it, so Public/Private stays a sync
916/// LOCAL read. Silent no-op when the plane can't be read whole — a partial fold
917/// would under-state Public, leaving a live link open behind a ban.
918async fn refresh_invite_registry_cache<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, session: &SessionGuard) {
919    let Ok(owner) = community.owner() else { return };
920    let Some(editions) = fetch_control_plane_whole(transport, community).await else { return };
921    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
922    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
923        .unwrap_or_default()
924        .into_iter()
925        .filter(|(_, f)| f.0 == community.root_epoch.0)
926        .map(|(entity, f)| (entity, (f.1, f.2, f.3)))
927        .collect();
928    let authority = fold_authority(community, &editions, &floors);
929    let sets = live_invite_link_sets(community.id(), &owner.to_hex(), &editions, &authority, &floors);
930    if session.is_valid() {
931        let _ = crate::db::community::set_community_invite_registry(&cid_hex, &flatten_link_sets(&sets));
932        let _ = crate::db::community::replace_invite_link_sets(&cid_hex, &sets);
933    }
934}
935
936/// Record a freshly-minted public link across the creator's devices: append it to the
937/// 13303 Invite List and refresh the Registry (CORD-05 §4/§5).
938async fn record_minted_link<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, minted: &MintedLink) -> Result<(), String> {
939    let session = SessionGuard::capture();
940    let signer = crate::signer::active_signer()?;
941    let my_pk = me_pk()?;
942    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
943    let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
944    // Err aborts the sync half (the link's bundle already published durably;
945    // a retry re-records it) — an unreachable relay set must never be mistaken
946    // for "no list yet" and clobber the replaceable 13303. Ok(None) IS a fresh
947    // creator's honest first list.
948    let mut list = fetch_invite_list(transport, &community.relays).await?.unwrap_or_default();
949    if !list.entries.iter().any(|e| e.token == token_hex) {
950        list.entries.push(invite::InviteEntry {
951            token: token_hex,
952            signer_sk: minted.link_signer.secret_key().to_secret_hex(),
953            community_id: cid_hex.clone(),
954            url: minted.url.clone(),
955            label: minted.label.clone(),
956            created_at: now_ms() / 1000,
957            expires_at: minted.expires_at_ms,
958            extra: Default::default(),
959        });
960    }
961    if !session.is_valid() {
962        return Err("account changed during link record".to_string());
963    }
964    let event = invite::build_invite_list_event_signed(&signer, my_pk, &list).await.map_err(|e| e.to_string())?;
965    transport.publish(&event, &community.relays).await?;
966    let signers = live_signers_for(&list, &cid_hex, now_ms());
967    publish_invite_registry(transport, community, &session, &signers).await
968}
969
970/// Revoke a public link by its token hex (CORD-05 §2/§5): re-post its coordinate as a
971/// revocation tombstone (retiring the bundle behind the URL, so a fetcher finds the
972/// grave), tombstone the Invite List entry, and refresh the Registry. Retiring the
973/// LAST live link empties the Registry → the community reads Private (a Refounding is
974/// the owner's separate read-cut).
975pub async fn revoke_public_link<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, token_hex: &str) -> Result<(), String> {
976    let session = SessionGuard::capture();
977    let signer = crate::signer::active_signer()?;
978    let my_pk = me_pk()?;
979    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
980    let mut list = fetch_invite_list(transport, &community.relays).await?.ok_or("no invite list found to revoke from")?;
981    let entry = list
982        .entries
983        .iter()
984        .find(|e| e.token == token_hex && e.community_id == cid_hex)
985        .cloned()
986        .ok_or("no such link in the invite list")?;
987    // Re-post the bundle coordinate as a revocation tombstone (creator-signed).
988    let link_signer = Keys::parse(&entry.signer_sk).map_err(|_| "malformed link signer")?;
989    let revocation = invite::build_revocation(&link_signer).map_err(|e| e.to_string())?;
990    if !session.is_valid() {
991        return Err("account changed during revoke".to_string());
992    }
993    transport.publish_durable(&revocation, &community.relays).await?;
994    // Tombstone the Invite List entry (permanent — a stale device can't resurrect it).
995    list.tombstones.push(invite::InviteTombstone { token: token_hex.to_string(), community_id: cid_hex.clone(), extra: Default::default() });
996    list.entries.retain(|e| e.token != token_hex);
997    let event = invite::build_invite_list_event_signed(&signer, my_pk, &list).await.map_err(|e| e.to_string())?;
998    transport.publish(&event, &community.relays).await?;
999    let signers = live_signers_for(&list, &cid_hex, now_ms());
1000    publish_invite_registry(transport, community, &session, &signers).await?;
1001    // Drop the local mirror row (sibling of the mint-time save) — only if still our session.
1002    if session.is_valid() {
1003        let _ = crate::db::community::delete_public_invite(token_hex);
1004    }
1005    Ok(())
1006}
1007
1008/// Refresh every live public link's bundle behind its stable URL (CORD-05 §2) — e.g.
1009/// after a Rekey/Refounding rolled the keys — by re-posting the bundle at the same
1010/// coordinate with the CURRENT community state, so a link shared once keeps working
1011/// across rotations. Best-effort.
1012pub async fn refresh_public_links<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
1013    let session = SessionGuard::capture();
1014    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1015    // Fetch inline (not via fetch_invite_list) so a TRANSPORT FAILURE propagates as
1016    // Err — the caller (a post-refounding refresh) must be able to retry, or live
1017    // links keep serving the PRE-refound root and new joiners land on the dead
1018    // epoch. A genuinely-empty list is Ok (nothing to refresh).
1019    let signer = crate::signer::active_signer()?;
1020    let my_pk = me_pk()?;
1021    let query = Query {
1022        kinds: vec![super::kind::INVITE_LIST],
1023        authors: vec![my_pk.to_hex()],
1024        limit: Some(4),
1025        ..Default::default()
1026    };
1027    let events = transport.fetch(&query, &community.relays).await?;
1028    let mut best: Option<(u64, invite::InviteList)> = None;
1029    for e in events {
1030        if let Ok(l) = invite::parse_invite_list_event_signed(&signer, my_pk, &e).await {
1031            let at = e.created_at.as_secs();
1032            if best.as_ref().map(|(b, _)| at > *b).unwrap_or(true) {
1033                best = Some((at, l));
1034            }
1035        }
1036    }
1037    let Some((_, list)) = best else {
1038        return Ok(());
1039    };
1040    let creator = my_pk;
1041    let now = now_ms();
1042    let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
1043    for entry in &list.entries {
1044        if entry.community_id != cid_hex || dead.contains(entry.token.as_str()) || entry.token.len() != 2 * super::derive::TOKEN_LEN {
1045            continue;
1046        }
1047        // An expired link can't be joined, so refreshing it just re-states a
1048        // door that isn't there (CORD-05 §1/§5).
1049        if entry.expires_at.is_some_and(|exp| now > exp) {
1050            continue;
1051        }
1052        let Ok(link_signer) = Keys::parse(&entry.signer_sk) else { continue };
1053        let token = crate::simd::hex::hex_to_bytes_16(&entry.token);
1054        let bundle = bundle_of(community, BundleAudience::Link, Some(creator), entry.expires_at, entry.label.clone());
1055        let bundle_key = super::derive::invite_bundle_key(&token);
1056        if let Ok(event) = invite::build_bundle_event(&link_signer, &bundle, &bundle_key) {
1057            if !session.is_valid() {
1058                return Err("account changed during link refresh".to_string());
1059            }
1060            let _ = transport.publish_durable(&event, &community.relays).await;
1061        }
1062    }
1063    // Republish the Registry from the same pruned view. Expiry is the one way a
1064    // link dies with no user action, so without a heal point here the aggregate
1065    // never empties and the community reads Public long after its last door
1066    // shut (CORD-05 §5). Idempotent when nothing lapsed.
1067    //
1068    // Only for a creator who actually minted here: one Invite List spans every
1069    // community, so a member holding links ELSEWHERE would otherwise publish an
1070    // empty Registry edition into this one on every rotation they adopt — a
1071    // control-plane write, and a version bump, for a coordinate they never owned.
1072    let mine_here = list.entries.iter().any(|e| e.community_id == cid_hex);
1073    if !mine_here {
1074        return Ok(());
1075    }
1076    let signers = live_signers_for(&list, &cid_hex, now);
1077    if !session.is_valid() {
1078        return Err("account changed during link refresh".to_string());
1079    }
1080    let _ = publish_invite_registry(transport, community, &session, &signers).await;
1081    Ok(())
1082}
1083
1084/// Whether this community is PUBLIC (CORD-05 §5): fold every creator's Registry
1085/// (vsk-8) that its author is authorized for (`CREATE_INVITE`, bound to their
1086/// coordinate) into an aggregate live-link set — non-empty ⇒ a live link exists ⇒
1087/// Public; empty ⇒ Private. Retiring the last link is what flips it back.
1088pub async fn community_is_public<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> bool {
1089    let Ok(owner) = community.owner() else { return false };
1090    // Truncation fails toward Public: over-stating it only makes a caller take the
1091    // stronger remedy (privatise + re-found + reissue), while under-stating it
1092    // leaves a live link open behind a ban.
1093    let Some(editions) = fetch_control_plane_whole(transport, community).await else { return true };
1094    let cid = community.id();
1095    let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
1096    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
1097        .unwrap_or_default()
1098        .into_iter()
1099        .filter(|(_, f)| f.0 == community.root_epoch.0)
1100        .map(|(entity, f)| (entity, (f.1, f.2, f.3)))
1101        .collect();
1102    let authority = fold_authority(community, &editions, &floors);
1103    !live_invite_link_sets(cid, &owner.to_hex(), &editions, &authority, &floors).is_empty()
1104}
1105
1106/// Page the WHOLE control plane, not the newest window: a registry pushed out of a
1107/// single page reads as retired, and any member can push it out since the plane key
1108/// comes from the community root they hold. `None` = it could NOT be read whole
1109/// (transport failure, same-second wall, pager depth), so a caller must not mistake
1110/// an empty fold for absence.
1111async fn fetch_control_plane_whole<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Option<Vec<ParsedEdition>> {
1112    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
1113    let mut editions: Vec<ParsedEdition> = Vec::new();
1114    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
1115    let mut oldest: Option<u64> = None;
1116    let mut until: Option<u64> = None;
1117    for page in 0..COMPACT_MAX_PAGES {
1118        // Quorum, DECLARED (the until→Full transport floor is gone): these
1119        // control reads tolerate a partial union — their fold semantics are
1120        // fail-safe on gaps (seeded banlists, withheld roster cache).
1121        let query = Query {
1122            kinds: vec![stream::KIND_WRAP],
1123            authors: vec![control.pk_hex()],
1124            until,
1125            limit: Some(FOLLOW_PAGE),
1126            evidence: crate::community::transport::Evidence::Quorum,
1127            ..Default::default()
1128        };
1129        let Ok(wraps) = transport.fetch(&query, &community.relays).await else { return None };
1130        let mut fresh = 0usize;
1131        for w in &wraps {
1132            if !seen_wraps.insert(w.id) {
1133                continue;
1134            }
1135            fresh += 1;
1136            let at = w.created_at.as_secs();
1137            if oldest.is_none_or(|o| at < o) {
1138                oldest = Some(at);
1139            }
1140            if let Ok((ed, _)) = control::open_control_edition(w, &control) {
1141                editions.push(ed);
1142            }
1143        }
1144        if fresh == 0 {
1145            if wraps.len() >= FOLLOW_PAGE {
1146                return None; // same-second wall: the plane can't be read whole
1147            }
1148            return Some(editions);
1149        }
1150        until = oldest;
1151        if page + 1 == COMPACT_MAX_PAGES {
1152            return None;
1153        }
1154    }
1155    Some(editions)
1156}
1157
1158/// The live link coordinates PER AUTHORISED CREATOR across every Registry (vsk-8);
1159/// non-empty ⇒ the Community is Public, and the per-creator split is what drives
1160/// "X has N active invite links". Pure over an already-fetched edition set so the
1161/// on-demand probe and the control follow fold it identically.
1162fn live_invite_link_sets(
1163    cid: &crate::community::CommunityId,
1164    owner_hex: &str,
1165    editions: &[ParsedEdition],
1166    authority: &AuthoritySet,
1167    floors: &Floors,
1168) -> Vec<crate::db::community::InviteLinkSetRow> {
1169    use crate::community::roles::Permissions;
1170    use std::collections::BTreeMap;
1171    let mut by_eid: BTreeMap<[u8; 32], Vec<&ParsedEdition>> = BTreeMap::new();
1172    for e in editions {
1173        if e.vsk == vsk::INVITE_LINKS {
1174            by_eid.entry(e.entity_id).or_default().push(e);
1175        }
1176    }
1177    let mut sets: Vec<crate::db::community::InviteLinkSetRow> = Vec::new();
1178    for (eid, group) in &by_eid {
1179        // Authority BEFORE the fold, matching `apply_control_fold`. `fold_head`
1180        // picks an equal-version winner author-blind (lowest inner id, which an
1181        // author can grind), so folding first would let any member occupy the head
1182        // slot and have the whole registry dropped by the check below — silently
1183        // retiring a live invite link, i.e. flipping the community to Private.
1184        let authed: Vec<&ParsedEdition> = group
1185            .iter()
1186            .copied()
1187            .filter(|p| {
1188                let author = p.author.to_hex();
1189                // The creator must hold CREATE_INVITE, not be banned, AND own this coordinate.
1190                !authority.banned.contains(&author)
1191                    && authority.roles.is_authorized(&author, Some(owner_hex), Permissions::CREATE_INVITE)
1192                    && super::derive::invite_links_locator(cid, &p.author.to_bytes()) == *eid
1193            })
1194            .collect();
1195        if authed.is_empty() {
1196            continue;
1197        }
1198        let fold_eds: Vec<version::Edition> = authed.iter().map(|p| p.to_fold_edition()).collect();
1199        let (Some(hi), _) = fold_head(&fold_eds, floors.get(&crate::simd::hex::bytes_to_hex_32(eid))) else { continue };
1200        if let Ok(signers) = invite::parse_registry_content(&authed[hi].content) {
1201            if signers.is_empty() {
1202                continue; // a creator who retired every link is absent, not a zero row
1203            }
1204            sets.push(crate::db::community::InviteLinkSetRow {
1205                creator_hex: authed[hi].author.to_hex(),
1206                locators: signers.iter().map(|p| p.to_hex()).collect(),
1207            });
1208        }
1209    }
1210    sets
1211}
1212
1213/// Flatten per-creator sets into the aggregate the `invite_registry` column holds.
1214fn flatten_link_sets(sets: &[crate::db::community::InviteLinkSetRow]) -> Vec<String> {
1215    let mut flat: Vec<String> = sets.iter().flat_map(|s| s.locators.iter().cloned()).collect();
1216    flat.sort();
1217    flat.dedup();
1218    flat
1219}
1220
1221/// Accept an already-unwrapped bundle: verify the owner commitment AND that the
1222/// delivered community_root is genuinely the owner's, persist the community, and
1223/// announce a Guestbook Join (with invite attribution). Shared tail of both accept
1224/// paths. Takes the caller's `SessionGuard` (captured BEFORE any network fetch the
1225/// caller did) so the `is_valid()` gate straddles that I/O.
1226async fn accept_bundle<T: Transport + ?Sized>(
1227    transport: &T,
1228    session: &SessionGuard,
1229    bundle: &CommunityInvite,
1230    invited_by: Option<PublicKey>,
1231    announce_join: bool,
1232) -> Result<CommunityV2, String> {
1233    let signer = crate::signer::active_signer()?;
1234    let my_pk = me_pk()?;
1235    let at_ms = now_ms();
1236    // Expiry gate: a past invite still previews but must not join (CORD-05 §1).
1237    if bundle.expired(at_ms) {
1238        return Err("this invite has expired".to_string());
1239    }
1240    // `from_bundle` re-validates bounds + the owner commitment fail-closed.
1241    let community = CommunityV2::from_bundle(bundle, at_ms)?;
1242    // Captured before the save below: a re-accept of a held community must not
1243    // re-announce a membership this account already declared.
1244    let already_held = crate::db::community::load_community_v2(community.id()).ok().flatten().is_some();
1245
1246    // Authenticate the delivered community_root before trusting it. The owner
1247    // commitment proves WHO the owner is, but community_root (and channel keys) are
1248    // NOT in that commitment, so a forged invite can pair a real (id, owner, salt)
1249    // with an attacker-chosen root and silently partition the joiner onto planes
1250    // only the attacker controls. Requiring the owner's genesis to open under the
1251    // delivered root closes that eclipse; also reconciles channel classification.
1252    // A preview verified the SAME (id, root) moments ago → reuse its fold instead
1253    // of re-walking the plane (the bundle re-fetch above kept the revocation gate).
1254    let handoff = VERIFIED_PREVIEW.lock().unwrap().take().filter(|v| {
1255        v.session.is_valid()
1256            && v.at.elapsed() < VERIFIED_PREVIEW_TTL
1257            && v.community_id == community.id().0
1258            && v.community_root == community.community_root
1259    });
1260    let (community, join_heads, join_banlist) = match handoff {
1261        Some(v) => {
1262            let mut c = v.folded;
1263            // The preview holds no acquisition time — stamp the JOIN's.
1264            c.created_at_ms = at_ms;
1265            (c, v.heads, v.banned)
1266        }
1267        None => verify_owner_root_and_reconcile(transport, community).await?,
1268    };
1269
1270    // A dissolved community is a grave (CORD-02 §9): refuse to join it.
1271    if is_dissolved(transport, &community).await {
1272        return Err("this community has been dissolved".to_string());
1273    }
1274
1275    // Join-time ban gate (CORD-04 §4, Armada parity): an honest client refuses to join a
1276    // community whose authorized banlist names it — before the Guestbook Join publishes
1277    // and before any local write. Every door funnels through here (direct invite, parked,
1278    // public link, migration), so none of them needs its own exclusion.
1279    if join_banlist.contains(&my_pk.to_hex()) {
1280        return Err("you are banned from this community".to_string());
1281    }
1282
1283    // The account must not have swapped since the guard was captured (which was
1284    // before any fetch the caller / the verify above performed) — else we'd write
1285    // A's join into B.
1286    if !session.is_valid() {
1287        return Err("account changed during join".to_string());
1288    }
1289    // Seed the verified heads as the initial refuse-downgrade floor BEFORE the
1290    // community row lands (floors-then-state, so a mid-seed error can't leave saved
1291    // state outrunning its floor); the first post-join follow then can't persist a
1292    // state below what this join already showed.
1293    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1294    for h in &join_heads {
1295        crate::db::community::set_edition_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, community.root_epoch.0)?;
1296    }
1297    crate::db::community::save_community_v2(&community)?;
1298    // Archive the joined root at its epoch, so this member reads Public-channel
1299    // history from their join epoch onward across later Refoundings (CORD-03 §3).
1300    let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch.0, &community.community_root);
1301    // Same for each granted Private-channel key: the archive is what lets its
1302    // history stay readable after the channel rotates away from this key.
1303    for ch in &community.channels {
1304        if let (true, Some(key)) = (ch.private, ch.key) {
1305            let _ = crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.id.0), ch.epoch.0, &key);
1306        }
1307    }
1308
1309    // Announce our Guestbook Join, echoing the invite attribution when present.
1310    // Only an ACTUAL join speaks: a re-accept of a held community, or a
1311    // cross-device key sync (announce_join=false), is not a membership event —
1312    // the account's original Join already stands in the guestbook, and every
1313    // re-publish renders as "<user> has joined" spam for the whole community.
1314    if announce_join && !already_held {
1315        let attribution = invited_by
1316            .map(|p| p.to_hex())
1317            .or_else(|| bundle.creator_npub.clone())
1318            .zip(Some(bundle.label.clone().unwrap_or_default()));
1319        let attr_ref = attribution.as_ref().map(|(c, l)| (c.as_str(), l.as_str()));
1320        let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
1321        let join_rumor = guestbook::build_join_rumor(my_pk, attr_ref, at_ms);
1322        if let Ok((join_wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &join_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
1323            let _ = transport.publish(&join_wrap, &community.relays).await;
1324        }
1325    }
1326
1327    // Record the membership across devices (CORD-02 §8). The inline attempt covers the
1328    // happy path; anything else hands off to the durable retry, because an unrecorded
1329    // join is what strands a community behind a stale tombstone.
1330    match republish_community_list(transport, Some(community.id())).await {
1331        Ok(true) => {}
1332        Ok(false) => republish_community_list_durable(Some(*community.id())),
1333        Err(e) => {
1334            crate::log_warn!("[CommunityList] failed to record this join across devices ({}) — retrying", e);
1335            republish_community_list_durable(Some(*community.id()));
1336        }
1337    }
1338    Ok(community)
1339}
1340
1341/// Prove the delivered `community_root` is genuinely the owner's, and reconcile
1342/// channel classification from the owner's editions. `community_id` commits only
1343/// to `(owner_xonly, owner_salt)` — both semi-public (they ride every bundle and
1344/// every synced Community List) — so a forged invite can present a real community's
1345/// id/owner/salt with an attacker-chosen root; every plane then derives from that
1346/// root, silently eclipsing the joiner onto attacker-controlled addresses while the
1347/// owner commitment still "verifies". The defense: the owner's genesis metadata
1348/// edition (vsk-0, `eid == community_id`) only opens under the AUTHENTIC root — an
1349/// attacker can't forge the owner's seal — so its presence on the control plane
1350/// derived from the delivered root proves that root. On a ROTATED plane (epoch > 0)
1351/// the compaction may have carried an admin-signed metadata head instead (CORD-06
1352/// re-wraps heads with their original signatures), so the anchor there is the
1353/// community-bound metadata head plus any owner-signed edition under the same root.
1354/// Fail-closed: no anchor (forged invite, or relays unreachable) → refuse to join.
1355/// On success, folds the owner's authoritative editions to heal a bundle that
1356/// misclassified a channel.
1357async fn verify_owner_root_and_reconcile<T: Transport + ?Sized>(
1358    transport: &T,
1359    community: CommunityV2,
1360) -> Result<(CommunityV2, Vec<FoldedHead>, std::collections::BTreeSet<String>), String> {
1361    let owner = community.owner()?;
1362    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
1363    let control_pk = control.pk_hex();
1364
1365    // AUTH-gating relays (ditto-relay's default gates kind-1059) serve a plane's
1366    // wraps ONLY to a connection authenticated AS the stream key — Concord's
1367    // group-addressed wraps aren't p-tagged to the joiner, so the login alone can't
1368    // satisfy the gate and the control plane reads back empty. Register this
1369    // community's stream keys + start the challenge responder so the fetch below
1370    // (whose REQ triggers the relay's AUTH challenge) reads the plane after auth.
1371    super::streamauth::prime(&community);
1372
1373    // Authenticity = the owner's GENESIS metadata edition (vsk-0, `eid ==
1374    // community_id`) at the root-derived control plane. The genesis eid pins it to
1375    // THIS community, and it lives ONLY under the real root — so a forged root can't
1376    // produce one: an edition's seal carries no community binding, but another
1377    // community's genesis has a different eid, and this community's own genesis is
1378    // unreadable without its real root (which the forger lacks). ("Any owner edition"
1379    // is NOT sound: an owner sig from any co-owned community, rewrapped onto the fake
1380    // plane, would pass — reopening the eclipse.) The residual — a T-member replaying
1381    // T's genesis onto a fake root to MITM another T-joiner — is closed only by
1382    // binding the root into community_id (protocol, deferred).
1383    //
1384    // Seed `until` with a FAR-FUTURE constant (NOT now-based), and request
1385    // Evidence::Full EXPLICITLY below: this walk draws an ABSENCE verdict (no
1386    // owner-signed genesis ⇒ reject), which trusts only the completest union —
1387    // an open partial window misses a genesis on a lagging relay (routine over
1388    // Tor). A constant beyond any real created_at clips NOTHING — so neither
1389    // a clock-skewed future-dated genesis nor a >1h-slow-clock joiner is excluded (a
1390    // now-based bound could clip either). Break on an EMPTY page (a short page is a
1391    // relay cap). A forged root walks to exhaustion and rejects; a flood/deep plane
1392    // that buries the genesis past the walk is the deferred protocol residual.
1393    const PAGE: usize = 500;
1394    const MAX_PAGES: usize = 4;
1395    const FAR_FUTURE_SECS: u64 = 4_102_444_800; // ~year 2100 — above any real edition, safe as a relay `until`.
1396    let mut editions: Vec<ParsedEdition> = Vec::new();
1397    let mut all_editions: Vec<ParsedEdition> = Vec::new();
1398    let mut found_genesis = false;
1399    // Rotated planes (CORD-06): compaction re-wraps each entity's CURRENT head with
1400    // its ORIGINAL signature, so if an admin last edited the metadata the plane holds
1401    // no owner-signed vsk-0 at all — the strict genesis anchor is unsatisfiable there.
1402    // Fallback pair for epoch > 0: the community-bound metadata head (any signer) PLUS
1403    // at least one owner-signed edition opened under this root. A non-member forger
1404    // can produce neither; the sibling-community rewrap residual this reopens is the
1405    // same class the spec defers to root-in-id binding.
1406    let mut compacted_metadata = false;
1407    crate::log_debug!(
1408        "[JoinVerify] control_pk={} root_epoch={:?} relays={:?}",
1409        &control_pk[..12], community.root_epoch, community.relays
1410    );
1411    let anchored = |found_genesis: bool, compacted_metadata: bool, owner_editions: usize, epoch: Epoch| {
1412        found_genesis || (epoch.0 > 0 && compacted_metadata && owner_editions > 0)
1413    };
1414    for attempt in 0..2 {
1415        editions.clear();
1416        all_editions.clear();
1417        compacted_metadata = false;
1418        let mut until: Option<u64> = Some(FAR_FUTURE_SECS);
1419        let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
1420        for page_no in 0..MAX_PAGES {
1421            let query = Query {
1422                kinds: vec![stream::KIND_WRAP],
1423                authors: vec![control_pk.clone()],
1424                until,
1425                limit: Some(PAGE),
1426                evidence: crate::community::transport::Evidence::Full,
1427                ..Default::default()
1428            };
1429            let wraps = transport.fetch(&query, &community.relays).await?;
1430            crate::log_trace!(
1431                "[JoinVerify] attempt {} page {}: fetched {} wraps",
1432                attempt, page_no, wraps.len()
1433            );
1434            // INCLUSIVE `until` + wrap-id dedup: a `-1` step can skip same-second
1435            // siblings at a page boundary (and the genesis with them); re-served
1436            // boundary events are free, and no-new-events means exhausted.
1437            let mut oldest = u64::MAX;
1438            let mut fresh = 0usize;
1439            for w in &wraps {
1440                if !seen_wraps.insert(w.id) {
1441                    continue;
1442                }
1443                fresh += 1;
1444                oldest = oldest.min(w.created_at.as_secs());
1445                if let Ok((ed, _)) = control::open_control_edition(w, &control) {
1446                    crate::log_trace!(
1447                        "[JoinVerify] edition vsk={} eid={} owner={} at={}",
1448                        ed.vsk, crate::simd::hex::bytes_to_hex_32(&ed.entity_id)[..12].to_string(),
1449                        ed.author == owner, w.created_at.as_secs()
1450                    );
1451                    if ed.vsk == vsk::COMMUNITY_METADATA && ed.entity_id == community.id().0 {
1452                        if ed.author == owner {
1453                            found_genesis = true;
1454                        } else {
1455                            compacted_metadata = true;
1456                        }
1457                    }
1458                    if ed.author == owner {
1459                        editions.push(ed.clone());
1460                    }
1461                    // Any-author set for the join-time authority fold below: the banlist head
1462                    // may be admin-signed, and its authority chains to the owner regardless.
1463                    all_editions.push(ed);
1464                }
1465            }
1466            crate::log_debug!(
1467                "[JoinVerify] attempt {} page {}: fresh={} opened_owner={} opened_any={} genesis={} compacted={}",
1468                attempt, page_no, fresh, editions.len(), all_editions.len(), found_genesis, compacted_metadata
1469            );
1470            if anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) || fresh == 0 {
1471                break; // authenticated, or the relay is exhausted.
1472            }
1473            until = Some(oldest);
1474        }
1475        if anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) {
1476            break;
1477        }
1478        if attempt == 0 {
1479            // AUTH-gating relays: the first walk's REQ triggers the NIP-42 challenge,
1480            // but nostr-sdk's own retry re-auths as the USER key — which doesn't
1481            // satisfy a stream-authors gate — and can land before the responder's
1482            // stream-key auth settles, reading the plane back EMPTY. Replay the
1483            // remembered challenges for every registered stream key, then walk once
1484            // more on the settled connection.
1485            if let Some(client) = crate::state::nostr_client() {
1486                super::streamauth::prime_auth(&client, &community.relays).await;
1487            }
1488        }
1489    }
1490    if !anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) {
1491        return Err(
1492            "could not verify this community from its relays (the invite may be forged, the relays are unreachable, or the control plane is being flooded); not joining"
1493                .to_string(),
1494        );
1495    }
1496    // Join-time reconcile: the joiner holds no floors yet (empty map → bootstrap per
1497    // entity). The heads this fold verified are returned for the caller to SEED as
1498    // the initial floor once the community row is saved — without that, the first
1499    // post-join follow would bootstrap floor-less and could persist a state BELOW
1500    // what this join already verified and showed.
1501    // Join-time reconcile folds only the owner's editions (genesis-authenticated
1502    // above), and the owner is supreme — so owner-only authority suffices. The full
1503    // roster (admins) folds on the first post-join follow_control.
1504    let empty_floors = Floors::new();
1505    let authority = AuthoritySet::owner_only();
1506    let fold = apply_control_fold(&community, &editions, &empty_floors, &authority);
1507    // Join-time banlist: fold authority over the ANY-author edition set (roles/grants
1508    // chain to the genesis-verified owner; the banlist head is honored only if its signer
1509    // held BAN). Returned so the accept path can refuse a banned self BEFORE it publishes
1510    // a Guestbook Join — the gate every join door shares (Armada parity, CORD-04 §4).
1511    let join_banlist = fold_authority(&community, &all_editions, &empty_floors).banned;
1512    Ok((fold.updated.unwrap_or(community), fold.heads, join_banlist))
1513}
1514
1515/// Accept a Direct Invite: unwrap the 3313 giftwrap (Schnorr-verifying the seal),
1516/// then run the shared accept path. The recipient's consent IS this call. No
1517/// network await precedes the accept, so the guard captured here suffices.
1518pub async fn accept_direct_invite<T: Transport + ?Sized>(transport: &T, wrap: &Event) -> Result<CommunityV2, String> {
1519    let session = SessionGuard::capture();
1520    let signer = crate::signer::active_signer()?;
1521    let (inviter, bundle) = invite::unwrap_direct_invite_signed(&signer, wrap).await.map_err(|e| e.to_string())?;
1522    accept_bundle(transport, &session, &bundle, Some(inviter), true).await
1523}
1524
1525/// Accept a PARKED Direct Invite from its stored bundle JSON (the wrap was already
1526/// unwrapped + owner-verified at park time). Re-parses through the same fail-closed
1527/// bundle validation, then runs the shared accept path (which re-verifies the owner
1528/// root over the network). `inviter_hex` is the parked seal signer, for Guestbook
1529/// Join attribution.
1530pub async fn accept_parked_invite<T: Transport + ?Sized>(
1531    transport: &T,
1532    bundle_json: &str,
1533    inviter_hex: Option<&str>,
1534) -> Result<CommunityV2, String> {
1535    let session = SessionGuard::capture();
1536    let bundle = CommunityInvite::from_bundle_json(bundle_json).map_err(|e| e.to_string())?;
1537    let invited_by = inviter_hex.and_then(|h| PublicKey::parse(h).ok());
1538    accept_bundle(transport, &session, &bundle, invited_by, true).await
1539}
1540
1541/// Accept v2 JoinMaterial recovered from a v1→v2 migration dissolution payload (`m`). The
1542/// material IS a bundle's membership subset — rebuild the invite and run the SHARED accept
1543/// path, which re-verifies the owner root over the network and enforces the join-time ban
1544/// gate (a banned-never-cut v1 member who can open `m` is refused here, fail-closed). No
1545/// giftwrap to unwrap: the dissolution already authenticated the owner via its signature.
1546pub async fn accept_migration_material<T: Transport + ?Sized>(
1547    transport: &T,
1548    jm: &super::list::JoinMaterial,
1549) -> Result<CommunityV2, String> {
1550    let session = SessionGuard::capture();
1551    let bundle = material_to_invite(jm);
1552    accept_bundle(transport, &session, &bundle, None, true).await
1553}
1554
1555/// Fetch + decrypt the newest Live bundle at a public link's coordinate
1556/// (`(33301, link_signer, "")`). **Revocation is authoritative-if-present**: if
1557/// ANY signer-valid tombstone is among the fetched events, refuse — never trust
1558/// fetch ordering (a cross-relay union has no global newest-first sort, so a
1559/// stale Live could otherwise win a partial-propagation race). Otherwise pick
1560/// the newest valid Live by `created_at`. Read-only.
1561pub async fn fetch_public_bundle<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityInvite, String> {
1562    let parsed = invite::parse_invite_link(url).map_err(|e| e.to_string())?;
1563    // NO `#d` filter, even though the coordinate's `d` is empty (CORD-05 §2). Relays disagree on
1564    // indexing an empty tag value: some answer the REQ and then never EOSE, so the fetch burns its
1565    // whole union grace on every invite. The per-link signer pins the coordinate on its own (it
1566    // signs nothing else), and `parse_bundle_event` re-checks the empty `d` locally.
1567    let query = Query {
1568        kinds: vec![super::kind::INVITE_BUNDLE],
1569        authors: vec![parsed.link_signer.to_hex()],
1570        ..Default::default()
1571    };
1572    let relays = if parsed.bootstrap_relays.is_empty() {
1573        invite::stock_relays()
1574    } else {
1575        parsed.bootstrap_relays.clone()
1576    };
1577    // One bounded retry: a join fired while the pool is still warming (bootstrap
1578    // relays mid-handshake, routine during boot contention) reads back a transport
1579    // error, not an absent bundle. The pool add already happened on the first try,
1580    // so wait for a socket rather than guessing with a fixed sleep.
1581    let events = match transport.fetch(&query, &relays).await {
1582        Ok(evs) => evs,
1583        Err(_) => {
1584            wait_for_bootstrap_relay(&relays).await;
1585            transport.fetch(&query, &relays).await?
1586        }
1587    };
1588    let bundle_key = super::derive::invite_bundle_key(&parsed.token);
1589
1590    // Scan EVERY event: a tombstone beats a Live unconditionally (order-independent).
1591    let mut newest_live: Option<(u64, CommunityInvite)> = None;
1592    for event in &events {
1593        match invite::parse_bundle_event(event, &parsed.link_signer, &bundle_key) {
1594            Ok(invite::BundleState::Revoked) => return Err("this invite link has been revoked".to_string()),
1595            Ok(invite::BundleState::Live(bundle)) => {
1596                let at = event.created_at.as_secs();
1597                if newest_live.as_ref().is_none_or(|(t, _)| at > *t) {
1598                    newest_live = Some((at, *bundle));
1599                }
1600            }
1601            Err(_) => {} // a foreign/garbage event at the coordinate — ignore.
1602        }
1603    }
1604    newest_live.map(|(_, b)| b).ok_or_else(|| "invite bundle not found on relays".to_string())
1605}
1606
1607/// Wait — bounded — for ANY of the targets to report Connected before a retry:
1608/// the fetch's own warm path bounds its connect wait tighter than a cold TLS
1609/// handshake takes under boot contention.
1610async fn wait_for_bootstrap_relay(relays: &[String]) {
1611    let Some(client) = crate::state::nostr_client() else { return };
1612    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(8);
1613    loop {
1614        for url in relays {
1615            if let Ok(Some(relay)) = client.relay(url).await {
1616                if relay.status() == nostr_sdk::prelude::RelayStatus::Connected {
1617                    return;
1618                }
1619            }
1620        }
1621        if tokio::time::Instant::now() >= deadline {
1622            return;
1623        }
1624        tokio::time::sleep(std::time::Duration::from_millis(400)).await;
1625    }
1626}
1627
1628/// The most recent owner-root verification a PREVIEW completed, handed to a join
1629/// so accepting seconds later doesn't re-walk the control plane. Single-slot,
1630/// short-lived, session-guarded, and keyed on `(community_id, community_root)` —
1631/// a different delivered root never matches. The join's own bundle re-fetch is
1632/// untouched, so the revocation gate always runs live.
1633struct VerifiedPreview {
1634    session: SessionGuard,
1635    at: std::time::Instant,
1636    community_id: [u8; 32],
1637    community_root: [u8; 32],
1638    folded: CommunityV2,
1639    heads: Vec<FoldedHead>,
1640    /// The join-time authorized banlist from the SAME verified walk — carried so the
1641    /// handoff path keeps the ban gate (a preview-then-join must not skip it).
1642    banned: std::collections::BTreeSet<String>,
1643}
1644static VERIFIED_PREVIEW: std::sync::Mutex<Option<VerifiedPreview>> = std::sync::Mutex::new(None);
1645const VERIFIED_PREVIEW_TTL: std::time::Duration = std::time::Duration::from_secs(120);
1646
1647/// Read-only rich preview of a public link: the decrypted bundle plus the LATEST
1648/// display metadata folded live from the Control Plane (a v2 bundle deliberately
1649/// carries no icon — the fold is the authority). Owner-root verification rides
1650/// the fold, so a forged-root link can't render a convincing preview; on a
1651/// fold/transport failure the bundle snapshot is the fallback. Nothing persists
1652/// — the caller hasn't joined.
1653pub async fn preview_public_link<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityV2, String> {
1654    let bundle = fetch_public_bundle(transport, url).await?;
1655    preview_bundle(transport, &bundle).await
1656}
1657
1658/// The fold half of [`preview_public_link`], over an already-fetched bundle. Split out so a caller
1659/// that only needs the community's IDENTITY can read it off the bundle (it is self-certifying) and
1660/// skip the Control-Plane walk entirely — the walk is the join gate, and `accept_public_link` runs
1661/// it again regardless.
1662pub async fn preview_bundle<T: Transport + ?Sized>(transport: &T, bundle: &CommunityInvite) -> Result<CommunityV2, String> {
1663    let community = CommunityV2::from_bundle(bundle, 0)?;
1664    match verify_owner_root_and_reconcile(transport, community.clone()).await {
1665        Ok((folded, heads, banned)) => {
1666            *VERIFIED_PREVIEW.lock().unwrap() = Some(VerifiedPreview {
1667                session: SessionGuard::capture(),
1668                at: std::time::Instant::now(),
1669                community_id: folded.id().0,
1670                community_root: folded.community_root,
1671                folded: folded.clone(),
1672                heads,
1673                banned,
1674            });
1675            Ok(folded)
1676        }
1677        Err(_) => Ok(community),
1678    }
1679}
1680
1681/// Accept a public invite link: fetch its bundle (revocation-aware) and join.
1682pub async fn accept_public_link<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityV2, String> {
1683    // Capture BEFORE the network fetch so the join's is_valid() gate straddles it.
1684    let session = SessionGuard::capture();
1685    let bundle = fetch_public_bundle(transport, url).await?;
1686    if !session.is_valid() {
1687        return Err("account changed during join".to_string());
1688    }
1689    accept_bundle(transport, &session, &bundle, None, true).await
1690}
1691
1692/// Leave a community: publish a Guestbook Leave and tear down the local hold.
1693pub async fn leave_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
1694    let session = SessionGuard::capture();
1695    let signer = crate::signer::active_signer()?;
1696    let my_pk = me_pk()?;
1697    let at_ms = now_ms();
1698    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
1699    let leave_rumor = guestbook::build_leave_rumor(my_pk, at_ms);
1700    if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &leave_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
1701        let _ = transport.publish(&wrap, &community.relays).await;
1702    }
1703    if !session.is_valid() {
1704        return Err("account changed during leave".to_string());
1705    }
1706    // Tombstone the membership across devices (CORD-02 §8) BEFORE the local delete,
1707    // to the leaving community's own relays (it's about to be gone locally) —
1708    // best-effort.
1709    let _ = tombstone_community_list(transport, community.id(), &community.relays).await;
1710    // The tombstone publish straddled an await — never delete from a swapped-in DB.
1711    if !session.is_valid() {
1712        return Err("account changed during leave".to_string());
1713    }
1714    crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
1715    Ok(())
1716}
1717
1718/// Cooperative Kick (CORD-04 §6, Guestbook plane): name the target; every reader
1719/// honors it iff the signer holds KICK and strictly outranks them (the coalesce's
1720/// `can_kick`), so publishing without authority is inert. A kicked member may
1721/// rejoin with a fresh invite — cryptographic severance is the ban/refound path.
1722pub async fn kick_member<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, target: &PublicKey) -> Result<(), String> {
1723    let session = SessionGuard::capture();
1724    assert_current_root(community)?;
1725    let signer = crate::signer::active_signer()?;
1726    let my_pk = me_pk()?;
1727    // Fast local pre-check; readers re-verify independently.
1728    let authority = fetch_authority(transport, community).await;
1729    let owner_hex = community.owner()?.to_hex();
1730    if !authority.roles.can_act_on_member(
1731        &my_pk.to_hex(),
1732        Some(&owner_hex),
1733        &target.to_hex(),
1734        crate::community::roles::Permissions::KICK,
1735    ) {
1736        return Err("not authorized to kick this member".to_string());
1737    }
1738    // CORD-04 §6 composition: a Kick is Role Removal THEN the directive — strip
1739    // first, so the target's rank is gone before the departure lands. Without it a
1740    // kicked admin leaves the memberlist still holding every management bit, and
1741    // every client keeps honoring their control editions.
1742    //
1743    // SKIPPED (not refused) when the strip isn't ours to make: a revoke needs
1744    // MANAGE_ROLES + strict outrank, and a KICK-only moderator still kicks — the
1745    // target just keeps their rank until an authorized strip lands. Each layer
1746    // validates on its own rule, so a missing one is a weaker removal, never a
1747    // broken one. A strip we DO attempt and lose is a hard error: proceeding would
1748    // publish a directive we know leaves rank behind.
1749    let target_hex = target.to_hex();
1750    let holds_roles = authority.roles.grants.iter().any(|g| g.member == target_hex && !g.role_ids.is_empty());
1751    let may_strip = authority.roles.can_act_on_member(
1752        &my_pk.to_hex(),
1753        Some(&owner_hex),
1754        &target_hex,
1755        crate::community::roles::Permissions::MANAGE_ROLES,
1756    );
1757    if holds_roles && may_strip {
1758        grant_roles(transport, community, target, Vec::new())
1759            .await
1760            .map_err(|e| format!("could not strip this member's roles before kicking: {e}"))?;
1761        if !session.is_valid() {
1762            return Err("account changed during kick".to_string());
1763        }
1764    }
1765    let at_ms = now_ms();
1766    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
1767    // A Kick is an authority action, so it cites its Grant like any other
1768    // (CORD-02 §5 / CORD-04 §5).
1769    let citation = required_authority_citation(community, &my_pk)?;
1770    let rumor = guestbook::build_kick_rumor(my_pk, *target, citation.as_ref(), at_ms);
1771    let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await
1772        .map_err(|e| e.to_string())?;
1773    if !session.is_valid() {
1774        return Err("account changed before send".to_string());
1775    }
1776    transport.publish(&wrap, &community.relays).await?;
1777    Ok(())
1778}
1779
1780/// A community's folded, delegation-authorized authority — the on-demand read
1781/// view (a paged control-plane fetch + fold, nothing persisted). `roles` is the
1782/// owner-seeded authorized roster (shared algebra with v1); `banned` the
1783/// enforced banlist. `floored`/`head_entities` let a writer detect a WITHHELD
1784/// entity (floored locally but no head folded) before replacing it blind.
1785pub struct AuthorityView {
1786    pub roles: crate::community::roles::CommunityRoles,
1787    pub banned: std::collections::BTreeSet<String>,
1788    /// Any authority entity's fold hit a floor gap (withheld / evicted link).
1789    pub gapped: bool,
1790    /// Entity hexes holding a persisted floor at this epoch (all vsk kinds).
1791    pub floored: std::collections::BTreeSet<String>,
1792    /// Authority entities (role/grant/banlist) that folded a head this fetch.
1793    pub head_entities: std::collections::BTreeSet<String>,
1794    /// Ban history (npub hex → secs), outliving the ban so an un-ban raises no phantom.
1795    pub banned_at: std::collections::BTreeMap<String, u64>,
1796}
1797
1798/// Fetch + fold the community's current authority (CORD-04), paging older like
1799/// `follow_control` while the fold is gapped so a busy control plane can't push
1800/// the roster off the newest window. A fetch failure degrades fail-safe:
1801/// owner-only authority plus the PERSISTED banlist — nobody gains standing from
1802/// an outage, and a ban never lifts on withheld data.
1803pub async fn fetch_authority<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> AuthorityView {
1804    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1805    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
1806        .unwrap_or_default()
1807        .into_iter()
1808        .filter(|(_, f)| f.0 == community.root_epoch.0)
1809        .map(|(entity, f)| (entity, (f.1, f.2, f.3)))
1810        .collect();
1811    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
1812
1813    let mut editions: Vec<ParsedEdition> = Vec::new();
1814    let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
1815    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
1816    let mut oldest: Option<u64> = None;
1817    let mut until: Option<u64> = None;
1818    // Seed from an EMPTY fold, not owner_only(): a fold over zero editions yields
1819    // owner-only roles AND retains the PERSISTED banlist. So a first-page transport
1820    // error returns the stored bans (fail-safe), never an empty banlist that would
1821    // silently un-ban on withheld data.
1822    let mut a = fold_authority(community, &[], &floors);
1823    for _ in 0..FOLLOW_MAX_PAGES {
1824        // Quorum, DECLARED (the until→Full transport floor is gone): these
1825        // control reads tolerate a partial union — their fold semantics are
1826        // fail-safe on gaps (seeded banlists, withheld roster cache).
1827        let query = Query {
1828            kinds: vec![stream::KIND_WRAP],
1829            authors: vec![control.pk_hex()],
1830            until,
1831            limit: Some(FOLLOW_PAGE),
1832            evidence: crate::community::transport::Evidence::Quorum,
1833            ..Default::default()
1834        };
1835        let Ok(wraps) = transport.fetch(&query, &community.relays).await else { break };
1836        let mut fresh = 0usize;
1837        for w in &wraps {
1838            if !seen_wraps.insert(w.id) {
1839                continue;
1840            }
1841            fresh += 1;
1842            let at = w.created_at.as_secs();
1843            if oldest.is_none_or(|o| at < o) {
1844                oldest = Some(at);
1845            }
1846            if let Ok((ed, _)) = control::open_control_edition(w, &control) {
1847                if seen.insert(ed.inner_id) {
1848                    editions.push(ed);
1849                }
1850            }
1851        }
1852        a = fold_authority(community, &editions, &floors);
1853        if !a.gapped || fresh == 0 {
1854            break;
1855        }
1856        until = oldest;
1857    }
1858    AuthorityView {
1859        roles: a.roles,
1860        banned: a.banned,
1861        gapped: a.gapped,
1862        floored: floors.keys().cloned().collect(),
1863        head_entities: a.heads.iter().map(|h| h.entity_hex.clone()).collect(),
1864        banned_at: a.banned_at,
1865    }
1866}
1867
1868/// Page the Guestbook plane newest-to-oldest, stopping once a page's oldest wrap
1869/// falls below `since_secs` (everything older is already held) or the plane is
1870/// exhausted. Returns the parsed events at/after the window plus the newest wrap
1871/// time seen (the caller's next cursor; `since_secs` when nothing newer arrived).
1872///
1873/// PAGE bound rationale: a single 500-window silently drops a member whose Join
1874/// aged out (organic growth, or an insider flooding throwaway Joins), and
1875/// `refound_community` consumes the fold as its rekey recipient set — a dropped
1876/// member is SEVERED. Beyond this depth a community needs sharding (documented);
1877/// the granted-member union in [`fold_members`] is the consensus-complete
1878/// backstop regardless of Guestbook depth.
1879async fn fetch_guestbook_events<T: Transport + ?Sized>(
1880    transport: &T,
1881    community: &CommunityV2,
1882    since_secs: u64,
1883) -> Result<(Vec<guestbook::GuestbookEvent>, u64), String> {
1884    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
1885    const GB_PAGE: usize = 500;
1886    const GB_MAX_PAGES: usize = 12;
1887    let mut events = Vec::new();
1888    let mut newest: u64 = since_secs;
1889    let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
1890    let mut until: Option<u64> = None;
1891    let mut oldest: Option<u64> = None;
1892    for _ in 0..GB_MAX_PAGES {
1893        // Full: this set becomes the refound's recipient list — a member's
1894        // Join visible only on a minority relay must not be severed.
1895        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb_group.pk_hex()], until, limit: Some(GB_PAGE), evidence: crate::community::transport::Evidence::Full, ..Default::default() };
1896        let wraps = transport.fetch(&query, &community.relays).await?;
1897        let mut fresh = 0usize;
1898        for wrap in &wraps {
1899            if !seen.insert(wrap.id) {
1900                continue;
1901            }
1902            fresh += 1;
1903            let at = wrap.created_at.as_secs();
1904            if oldest.is_none_or(|o| at < o) {
1905                oldest = Some(at);
1906            }
1907            if at > newest {
1908                newest = at;
1909            }
1910            // Older than the cursor window — already held; skip the decrypt.
1911            if at < since_secs {
1912                continue;
1913            }
1914            if let Ok(opened) = stream::open_wrap(wrap, &gb_group) {
1915                if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
1916                    events.push(ev);
1917                }
1918            }
1919        }
1920        if fresh == 0 || wraps.len() < GB_PAGE || oldest.is_some_and(|o| o < since_secs) {
1921            break;
1922        }
1923        match oldest {
1924            Some(o) if o > 0 => until = Some(o),
1925            _ => break,
1926        }
1927    }
1928    Ok((events, newest))
1929}
1930
1931/// The shared membership fold: coalesce Guestbook events under the community's
1932/// authority (owner-supreme kicks, refounder snapshots), union observed authors
1933/// plus every roster grantee, subtract the banlist, and pin the proven owner.
1934/// One implementation, so the live and stored reads can't drift.
1935fn fold_members(
1936    community: &CommunityV2,
1937    events: &[guestbook::GuestbookEvent],
1938    mut observed: std::collections::BTreeMap<PublicKey, u64>,
1939    roles: &crate::community::roles::CommunityRoles,
1940    banlist: &std::collections::BTreeSet<PublicKey>,
1941    banned_at: &std::collections::BTreeMap<PublicKey, u64>,
1942) -> Result<Vec<PublicKey>, String> {
1943    let owner = community.owner()?;
1944    let owner_hex = owner.to_hex();
1945    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1946
1947    // CONSENSUS-COMPLETE backstop: every member the folded roster GRANTS a role to
1948    // is provably a member (a Grant binds member_xonly, CORD-02 A.6) — count them
1949    // even if their Join aged out of the Guestbook entirely and they never posted.
1950    // This is what keeps a Refounding from severing a lurking admin. `observed`
1951    // carries them at ts 0 (presence, not recency); the banlist subtraction below
1952    // still removes a banned grantee whose grant wasn't yet stripped.
1953    for g in &roles.grants {
1954        if let Some(pk) = PublicKey::from_hex(&g.member).ok().filter(|_| !g.role_ids.is_empty()) {
1955            observed.entry(pk).or_insert(0);
1956        }
1957    }
1958
1959    // Snapshot authority (CORD-02 §5): a refounding rolls `root_epoch` and re-seeds the
1960    // new epoch's Guestbook with a 3312 snapshot of the survivors. Only the OWNER's snapshot is
1961    // honored here, so a silent survivor stays in the memberlist across an owner refound
1962    // without re-posting. A genesis community (root_epoch 0) has no refounder, hence no
1963    // snapshot power. KNOWN GAP (do not "fix" unilaterally — CORD-04/06 + Armada): the refound
1964    // send/receive gates authorize any BAN-holder to refound, but their snapshot is NOT honored
1965    // here, so a non-owner admin's refound drops silent survivors (incl. migration roster seeds)
1966    // until they re-post. Binding the minting rotator into snapshot authority is a spec change.
1967    let snapshot_authority = (community.root_epoch.0 > 0).then_some(&owner);
1968    // Kick authority (CORD-04 §5/§6): the signer must cite a Grant we've synced AND
1969    // hold KICK AND strictly outrank the target (the owner is supreme; equal cannot
1970    // kick equal).
1971    let can_kick = |actor: &PublicKey, target: &PublicKey, citation: Option<&crate::community::edition::AuthorityCitation>| {
1972        let actor_hex = actor.to_hex();
1973        citation_is_synced(&cid_hex, &owner_hex, &actor_hex, citation)
1974            && roles.can_act_on_member(&actor_hex, Some(&owner_hex), &target.to_hex(), crate::community::roles::Permissions::KICK)
1975    };
1976    let coalesced = guestbook::coalesce(events, now_ms(), snapshot_authority, &can_kick);
1977    let mut members = guestbook::complete_memberlist(&coalesced, &observed, banlist, banned_at);
1978    // The owner is a member by definition, independent of any fetched Join.
1979    if !banlist.contains(&owner) {
1980        members.insert(owner);
1981    }
1982    Ok(members.into_iter().collect())
1983}
1984
1985/// Did the AUTHORIZED Guestbook coalesce rule `member` KICKED, per the stored plane?
1986///
1987/// This is the only sound basis for acting on a kick against ourselves. The
1988/// memberlist is the wrong question: it also folds the banlist, the ban marks and
1989/// observed authors, so a member whose Guestbook hasn't caught up yet — a REJOIN,
1990/// where the store starts empty while the control fold has already re-derived their
1991/// old ban mark — is absent from it while being perfectly joined. Coalescing asks
1992/// only "what is the latest authorized entry for this npub", so a fresh Join
1993/// supersedes an old Kick and an empty store yields no verdict at all.
1994pub fn stored_kick_verdict(community: &CommunityV2, member: &PublicKey) -> bool {
1995    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
1996    let Ok((events, _cursor)) = crate::db::community::get_guestbook(&cid_hex) else {
1997        return false;
1998    };
1999    let Ok(owner) = community.owner() else { return false };
2000    let owner_hex = owner.to_hex();
2001    let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
2002    let snapshot_authority = (community.root_epoch.0 > 0).then_some(&owner);
2003    let can_kick = |actor: &PublicKey, target: &PublicKey, citation: Option<&crate::community::edition::AuthorityCitation>| {
2004        let actor_hex = actor.to_hex();
2005        citation_is_synced(&cid_hex, &owner_hex, &actor_hex, citation)
2006            && roles.can_act_on_member(&actor_hex, Some(&owner_hex), &target.to_hex(), crate::community::roles::Permissions::KICK)
2007    };
2008    matches!(
2009        guestbook::coalesce(&events, now_ms(), snapshot_authority, &can_kick).get(member),
2010        Some(st) if st.verdict == guestbook::Verdict::Kicked
2011    )
2012}
2013
2014/// Catch the persisted Guestbook up from its stored cursor (a fresh hold seeds
2015/// from zero). The fetch straddles the network, so the session re-checks before
2016/// the store writes. Returns the events that were NEW to the store — the caller
2017/// surfaces them (presence lines) and refreshes on non-empty.
2018pub async fn sync_guestbook<T: Transport + ?Sized>(
2019    transport: &T,
2020    community: &CommunityV2,
2021    session: &SessionGuard,
2022) -> Result<Vec<guestbook::GuestbookEvent>, String> {
2023    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2024    let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex)?;
2025    // Overlap one second so a same-second boundary event can't slip the cursor;
2026    // the rumor-id merge below dedups the re-fetched edge.
2027    let since = cursor.saturating_sub(1);
2028    let (fresh, newest) = fetch_guestbook_events(transport, community, since).await?;
2029    if !session.is_valid() {
2030        return Err("account changed during guestbook sync".to_string());
2031    }
2032    let known: std::collections::HashSet<[u8; 32]> = events.iter().map(|e| e.rumor_id).collect();
2033    let mut added = Vec::new();
2034    for ev in fresh {
2035        if !known.contains(&ev.rumor_id) {
2036            events.push(ev.clone());
2037            added.push(ev);
2038        }
2039    }
2040    if !added.is_empty() || newest > cursor {
2041        crate::db::community::set_guestbook(&cid_hex, &events, newest.max(cursor))?;
2042    }
2043    Ok(added)
2044}
2045
2046/// Fold ONE live guestbook event into the store (the realtime path — no fetch).
2047/// Returns whether it was new.
2048pub fn ingest_guestbook_event(community: &CommunityV2, ev: guestbook::GuestbookEvent, wrap_secs: u64) -> Result<bool, String> {
2049    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2050    let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex)?;
2051    if events.iter().any(|e| e.rumor_id == ev.rumor_id) {
2052        return Ok(false);
2053    }
2054    events.push(ev);
2055    crate::db::community::set_guestbook(&cid_hex, &events, cursor.max(wrap_secs))?;
2056    Ok(true)
2057}
2058
2059/// The memberlist from LOCAL state only: the persisted Guestbook, plus locally
2060/// observed authors (the synced events DB), plus roster grantees, minus the
2061/// banlist. Instant and offline-correct; [`sync_guestbook`] (post-join, boot,
2062/// reconnect, live ingest) keeps the store current. The live [`memberlist`]
2063/// remains the authoritative walk — a refounding's rekey recipient set must
2064/// never trust a possibly-stale store.
2065pub fn stored_memberlist(community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
2066    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
2067    let (events, _cursor) = crate::db::community::get_guestbook(&cid_hex)?;
2068    let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
2069    for (npub, last_active_secs) in crate::db::community::community_member_activity(&cid_hex).unwrap_or_default() {
2070        if let Ok(pk) = PublicKey::parse(&npub) {
2071            observed.insert(pk, last_active_secs.saturating_mul(1000));
2072        }
2073    }
2074    let roles = crate::db::community::get_community_roles(&cid_hex)?;
2075    let banlist: std::collections::BTreeSet<PublicKey> = crate::db::community::get_community_banlist(&cid_hex)
2076        .unwrap_or_default()
2077        .iter()
2078        .filter_map(|h| PublicKey::from_hex(h).ok())
2079        .collect();
2080    // Ban history outlives the banlist itself — see [`fold_members`]. Read from the store,
2081    // since this path never folds editions.
2082    let banned_at: std::collections::BTreeMap<PublicKey, u64> = crate::db::community::get_community_ban_marks(&cid_hex)
2083        .unwrap_or_default()
2084        .into_iter()
2085        .filter_map(|(h, at)| PublicKey::from_hex(&h).ok().map(|pk| (pk, at)))
2086        .collect();
2087    fold_members(community, &events, observed, &roles, &banlist, &banned_at)
2088}
2089
2090/// Fold the Complete Memberlist from the Guestbook plane. The proven owner is
2091/// ALWAYS a member (derived from the self-certifying community_id — no network,
2092/// so a lost/evicted genesis Join can't drop them). Observed authors — anyone
2093/// seen publishing on a channel — are folded in FORWARD-only per CORD-02 §5, so a
2094/// member whose Join was lost still counts.
2095pub async fn memberlist<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
2096    let (events, _newest) = fetch_guestbook_events(transport, community, 0).await?;
2097    // Observed authors: fold each held channel's recent authorship (real author +
2098    // newest ms), so a member who posted but whose Join was lost is still counted.
2099    let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
2100    for ch in &community.channels {
2101        if let Ok(page) = fetch_channel(transport, community, &ch.id, 200).await {
2102            for f in &page {
2103                let e = observed.entry(f.event.opened().author).or_insert(0);
2104                *e = (*e).max(f.event.opened().at_ms);
2105            }
2106        }
2107    }
2108
2109    // Fold the Control Plane roster + banlist (CORD-04) for Kick authority and the
2110    // ban subtraction. A control fetch failure degrades to owner-only authority + no
2111    // bans (fail-open on availability is safe here: a Kick still needs a real signer,
2112    // and a missed ban only fails to HIDE, never to wrongly admit authority).
2113    let authority = fetch_authority(transport, community).await;
2114    // The authorized banlist, as pubkeys (a malformed hex entry is simply dropped).
2115    let banlist: std::collections::BTreeSet<PublicKey> =
2116        authority.banned.iter().filter_map(|h| PublicKey::from_hex(h).ok()).collect();
2117    // Union the live fold's ban history with the stored marks: the fetch only reaches the
2118    // editions still in its window, and a ban that aged out is exactly the one whose
2119    // pre-ban Join would phantom.
2120    let mut banned_at: std::collections::BTreeMap<PublicKey, u64> = crate::db::community::get_community_ban_marks(
2121        &crate::simd::hex::bytes_to_hex_32(&community.id().0),
2122    )
2123    .unwrap_or_default()
2124    .into_iter()
2125    .filter_map(|(h, at)| PublicKey::from_hex(&h).ok().map(|pk| (pk, at)))
2126    .collect();
2127    for (h, at) in &authority.banned_at {
2128        if let Ok(pk) = PublicKey::from_hex(h) {
2129            let slot = banned_at.entry(pk).or_insert(0);
2130            *slot = (*slot).max(*at);
2131        }
2132    }
2133    fold_members(community, &events, observed, &authority.roles, &banlist, &banned_at)
2134}
2135
2136// ── Dissolution (CORD-02 §9) ─────────────────────────────────────────────────
2137
2138/// Owner dissolution / "Delete Community" (CORD-02 §9): publish the terminal
2139/// tombstone at the dissolved plane (`community_id`-derived, epoch-free, so every
2140/// past or present member resolves the same grave and a Refounding can never strand
2141/// it). The tombstone's presence IS the state; only the owner's seal counts.
2142/// Irreversible — on success the local hold is sealed read-only.
2143pub async fn dissolve_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
2144    let session = SessionGuard::capture();
2145    let signer = crate::signer::active_signer()?;
2146    let my_pk = me_pk()?;
2147    if community.owner()? != my_pk {
2148        return Err("only the owner can dissolve a community".to_string());
2149    }
2150    let at = now_ms() / 1000;
2151    let rumor = super::dissolution::dissolved_tombstone_rumor(my_pk, community.id(), at);
2152    let wrap = super::dissolution::seal_dissolved_signed(&signer, my_pk, &rumor, community.id(), Timestamp::from_secs(at)).await.map_err(|e| e.to_string())?;
2153    if !session.is_valid() {
2154        return Err("account changed during dissolve".to_string());
2155    }
2156    // Durable broadcast: death must propagate (a rekey racing a dissolution loses).
2157    transport.publish_durable(&wrap, &community.relays).await?;
2158    crate::db::community::set_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
2159    Ok(())
2160}
2161
2162/// Whether a valid owner-signed dissolution tombstone exists for this community on
2163/// its relays (CORD-02 §9). A join refuses a dead community, and a live follow seals
2164/// on sight. Fail-OPEN on a fetch error (absence of proof is not death), but any
2165/// owner-verified tombstone found is authoritative.
2166pub async fn is_dissolved<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> bool {
2167    let group = super::derive::dissolved_group_key(community.id());
2168    let query = Query {
2169        kinds: vec![stream::KIND_WRAP],
2170        authors: vec![group.pk_hex()],
2171        limit: Some(20),
2172        ..Default::default()
2173    };
2174    let Ok(wraps) = transport.fetch(&query, &community.relays).await else {
2175        return false;
2176    };
2177    wraps.iter().any(|w| super::dissolution::verify_dissolved(w, &community.identity))
2178}
2179
2180// ── Refounding (CORD-06 §3) ──────────────────────────────────────────────────
2181
2182/// Owner/admin Refounding (CORD-06 §3): roll the `community_root` to
2183/// cryptographically remove `removed` from a Private community (a Ban's read-cut).
2184/// Compacts the Control Plane under the new root (re-wraps each head VERBATIM — the
2185/// inner owner/actor signatures survive, so no re-authoring), rekeys the base plus
2186/// every Private channel (each sealed under the PRIOR root, D2, so a base-fork loser
2187/// can still open them), and seeds the new epoch's Guestbook snapshot. Requires BAN.
2188///
2189/// **Acquire-before-commit:** the compaction is fetched + re-sealed BEFORE any
2190/// publish, and a head we can't fetch ABORTS with ZERO published state — so a
2191/// transient miss never strands a published rekey with a half-anchored plane.
2192pub async fn refound_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, removed: &[PublicKey]) -> Result<CommunityV2, String> {
2193    let session = SessionGuard::capture();
2194    let cid = community.id();
2195    let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
2196    // Death wins every race: a dissolved community never re-founds (CORD-02 §9).
2197    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
2198        return Err("this community has been dissolved; it cannot be re-founded".to_string());
2199    }
2200    let signer = crate::signer::active_signer()?;
2201    let my_pk = me_pk()?;
2202    // Serialize with the follow worker for the whole rotation: the commit tail
2203    // whole-row-saves, and an unserialized concurrent follow could otherwise be
2204    // rolled back (or adopt a half-published sibling of this very rotation).
2205    let lock = super::realtime::follow_lock(cid);
2206    let _guard = lock.lock().await;
2207    // Reload the FRESHEST base state: a stale caller struct would address the rotation
2208    // under a superseded root (a base fork with no heal). The community_id is
2209    // self-certifying + stable, so re-loading by it is safe.
2210    let fresh = crate::db::community::load_community_v2(cid)?.ok_or("community gone before re-founding")?;
2211    let community = &fresh;
2212    let owner = community.owner()?;
2213
2214    // CORD-06 §Authority: a Refounding requires the BAN permission and the rotator
2215    // must strictly OUTRANK every removed target — the owner is supreme (BAN ⊂
2216    // owner). Mirrors the receive counterpart (`advance_scope::base_rotator_ok`)
2217    // and the banlist authority fold: any admin holding BAN may re-found, checked
2218    // against the folded Roster. Fail-closed — an empty/unauthorized roster leaves
2219    // only the owner able to re-found.
2220    {
2221        let owner_hex = owner.to_hex();
2222        let me_hex = my_pk.to_hex();
2223        // Persisted (last-folded) roster — the receive side is authoritative, so
2224        // this is a belt-and-suspenders gate. Fail-closed: a stale/empty roster
2225        // collapses to owner-only, which can only OVER-restrict a fresh admin whose
2226        // grant hasn't folded into their own DB (the caller's ban flow folds control
2227        // first). It can never grant authority no one has.
2228        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
2229        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
2230        let authorized = my_pk == owner
2231            || (!banned.contains(&me_hex)
2232                && roster.is_authorized(&me_hex, Some(&owner_hex), crate::community::roles::Permissions::BAN)
2233                && removed.iter().all(|t| {
2234                    roster.can_act_on_member(&me_hex, Some(&owner_hex), &t.to_hex(), crate::community::roles::Permissions::BAN)
2235                }));
2236        if !authorized {
2237            return Err("re-founding requires the BAN permission and outranking every removed member".to_string());
2238        }
2239    }
2240
2241    // Fold the current roster: the opened editions are reused for the compaction (their
2242    // seals re-wrap under the new epoch), and the roster gates which admin-authored
2243    // heads carry forward.
2244    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
2245        .into_iter()
2246        .filter(|(_, f)| f.0 == community.root_epoch.0)
2247        .map(|(entity, f)| (entity, (f.1, f.2, f.3)))
2248        .collect();
2249    let current_control = control_group_key(&community.community_root, cid, community.root_epoch);
2250    // Page the ENTIRE control plane, not just the newest window: the compaction MUST
2251    // carry EVERY committed (floored) entity to the new epoch, so a head buried under a
2252    // flood of newer editions (100 roles + 400 grants already exceeds one page) or a
2253    // head a relay withholds can't silently drop. CORD-06 §3 mandates aborting if the
2254    // Refounder cannot fold all Control Events — a dropped Banlist would unban a member
2255    // at the new epoch a fresh joiner bootstraps.
2256    let mut opened: Vec<(ParsedEdition, super::stream::OpenedStream)> = Vec::new();
2257    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
2258    let mut oldest: Option<u64> = None;
2259    let mut until: Option<u64> = None;
2260    // Read to EXHAUSTION, not to coverage: an entity with no floor yet (a
2261    // first-ever Banlist published while we were away) is invisible to a
2262    // coverage test, so stopping there could compact it away.
2263    let mut truncated = false;
2264    for page in 0..COMPACT_MAX_PAGES {
2265        // Full: compaction re-wraps the head set it can SEE — a control
2266        // edition (a ban head) reachable only on a minority relay must not be
2267        // compacted away by a partial union.
2268        let query = Query {
2269            kinds: vec![stream::KIND_WRAP],
2270            authors: vec![current_control.pk_hex()],
2271            until,
2272            limit: Some(FOLLOW_PAGE),
2273            evidence: crate::community::transport::Evidence::Full,
2274            ..Default::default()
2275        };
2276        let wraps = transport.fetch(&query, &community.relays).await?;
2277        let mut fresh = 0usize;
2278        for w in &wraps {
2279            if !seen_wraps.insert(w.id) {
2280                continue;
2281            }
2282            fresh += 1;
2283            let at = w.created_at.as_secs();
2284            if oldest.is_none_or(|o| at < o) {
2285                oldest = Some(at);
2286            }
2287            if let Ok(parsed) = control::open_control_edition(w, &current_control) {
2288                opened.push(parsed);
2289            }
2290        }
2291        if fresh == 0 {
2292            // `until` is inclusive: a FULL page with nothing new is a same-second
2293            // wall no cursor steps past, so older editions stay unreachable. A
2294            // short page is simply the end of the plane.
2295            truncated = wraps.len() >= FOLLOW_PAGE;
2296            break;
2297        }
2298        until = oldest;
2299        if page + 1 == COMPACT_MAX_PAGES {
2300            truncated = true;
2301        }
2302    }
2303    if truncated {
2304        return Err(
2305            "The community's control plane is too deep to read in full right now; re-founding stopped so no member is left behind.".to_string(),
2306        );
2307    }
2308
2309    let prev_epoch = community.root_epoch;
2310    let new_epoch = Epoch(prev_epoch.0.checked_add(1).ok_or("root epoch overflow")?);
2311    let prev_commit = super::derive::epoch_key_commitment(prev_epoch, &community.community_root);
2312    // Mint-or-REUSE the new root, keyed by (scope, new_epoch) and archived BEFORE any
2313    // publish: a retried Refounding re-delivers the SAME root at this epoch/address, so
2314    // it can't double-mint two roots a receiver's correlation dedup would collapse into
2315    // a permanent fork (CORD-06 §3 idempotency). The compaction fetch above straddled
2316    // this DB write — re-check so a mid-fetch swap can't archive into another account.
2317    if !session.is_valid() {
2318        return Err("account changed during re-founding compaction".to_string());
2319    }
2320    let new_root = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, new_epoch.0)?;
2321    let new_control = control_group_key(&new_root, cid, new_epoch);
2322    let at = now_ms();
2323    let at_secs = at / 1000;
2324
2325    // ACQUIRE + COVERAGE GATE (CORD-06 §3 MUST): re-wrap the head of EVERY committed
2326    // (floored) entity under the new epoch — FLOOR-driven, so nothing silently drops,
2327    // including entities the metadata/roster folds don't touch (the invite Registry
2328    // vsk-8, whose coordinate survives the rekey per CORD-05 §5). A floor whose head
2329    // can't be folded (buried past the pager / withheld) ABORTS before any publish.
2330    use std::collections::BTreeMap;
2331    let mut by_eid: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2332    for (i, (e, _)) in opened.iter().enumerate() {
2333        by_eid.entry(crate::simd::hex::bytes_to_hex_32(&e.entity_id)).or_default().push(i);
2334    }
2335    let mut carried: Vec<(FoldedHead, Event)> = Vec::new();
2336    for (floor_key, floor) in &floors {
2337        // Re-wrap the AUTHORIZED head — the exact edition the persisted floor commits to
2338        // (its self_hash). The floor advances ONLY to authorized heads (author-aware fold),
2339        // so matching it is authority-correct across EVERY entity type. `fold_head`'s
2340        // version-chain TIP is author-BLIND: a member can seal a forged higher-version
2341        // edition chaining onto the floor, which the tip would carry and honest folders
2342        // then DROP as unauthorized — silently suppressing that role/grant/banlist across
2343        // the refounding. Abort if the committed head isn't served (fail-closed).
2344        let head_idx = by_eid
2345            .get(floor_key)
2346            .and_then(|v| v.iter().copied().find(|&i| opened[i].0.self_hash == floor.1));
2347        let Some(head_idx) = head_idx else {
2348            return Err(format!("re-founding aborted: the committed head of control entity {floor_key} (v{}) was not served; no state published", floor.0));
2349        };
2350        let (head_ed, head_os) = &opened[head_idx];
2351        let h = FoldedHead { entity_hex: floor_key.clone(), version: head_ed.version, self_hash: head_ed.self_hash, inner_id: head_ed.inner_id };
2352        let (rewrapped, _) = super::stream::rewrap_seal(&head_os.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
2353        carried.push((h, rewrapped));
2354    }
2355    if !session.is_valid() {
2356        return Err("account changed during re-founding acquire".to_string());
2357    }
2358
2359    // Recipients: the current members minus `removed`, plus me (multi-device).
2360    let members = memberlist(transport, community).await?;
2361    let removed_set: std::collections::HashSet<[u8; 32]> = removed.iter().map(|p| p.to_bytes()).collect();
2362    let mut recipients: Vec<PublicKey> = members.into_iter().filter(|m| !removed_set.contains(&m.to_bytes())).collect();
2363    if !recipients.iter().any(|p| *p == my_pk) {
2364        recipients.push(my_pk);
2365    }
2366
2367    // Base rekey blobs (the new root to each recipient), sealed under the PRIOR root.
2368    let mut base_blobs = Vec::new();
2369    for r in &recipients {
2370        base_blobs.push(
2371            super::rekey::build_blob(&signer, &my_pk.to_bytes(), r, super::rekey::RekeyScope::Root, new_epoch, &new_root)
2372                .await
2373                .map_err(|e| e.to_string())?,
2374        );
2375    }
2376    let base_group = super::derive::base_rekey_group_key(&community.community_root, cid, new_epoch);
2377    let base_chunks =
2378        super::rekey::build_rekey_chunks(&signer, my_pk, &base_group, super::rekey::RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &base_blobs, at_secs, my_authority_citation(community, &my_pk).as_ref())
2379            .await
2380            .map_err(|e| e.to_string())?;
2381
2382    // Private-channel rekeys: each mints a fresh key at its next channel-epoch, sealed
2383    // under the PRIOR root (D2). Public channels ride the base — no per-channel rekey.
2384    //
2385    // Each private channel goes only to ITS entitled set, never the base recipient
2386    // list: a Refounding that re-broadcast every private key to every member would
2387    // undo the access lists on every rotation (CORD-03).
2388    // Entitlement must come from a CURRENT roster, not the last-folded cache: the
2389    // base recipients above are a fresh network fold, and mixing the two strands
2390    // anyone granted since this client last folded — they keep a dead key and the
2391    // new epoch's rekey plane carries no blob for them. Fetched, then merged over
2392    // the cache so a role we published ourselves survives too.
2393    let mut roster_for_channels = fetch_authority(transport, community).await.roles;
2394    {
2395        let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
2396        for r in cached.roles {
2397            if !roster_for_channels.roles.iter().any(|x| x.role_id == r.role_id) {
2398                roster_for_channels.roles.push(r);
2399            }
2400        }
2401        for g in cached.grants {
2402            if !roster_for_channels.grants.iter().any(|x| x.member == g.member) {
2403                roster_for_channels.grants.push(g);
2404            }
2405        }
2406    }
2407    if !session.is_valid() {
2408        return Err("account changed during re-founding entitlement fetch".to_string());
2409    }
2410    let owner_hex_for_channels = community.owner().ok().map(|o| o.to_hex());
2411    let mut channel_updates: Vec<(ChannelId, [u8; 32], Epoch)> = Vec::new();
2412    let mut channel_chunk_sets: Vec<Vec<Event>> = Vec::new();
2413    for ch in &community.channels {
2414        let (Some(old_key), true) = (ch.key, ch.private) else { continue };
2415        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
2416        let entitled: Vec<PublicKey> = recipients
2417            .iter()
2418            .copied()
2419            .filter(|r| {
2420                *r == my_pk
2421                    || roster_for_channels.is_entitled(owner_hex_for_channels.as_deref(), &r.to_hex(), &ch_hex, &[], &[])
2422            })
2423            .collect();
2424        let ch_new_epoch = Epoch(ch.epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
2425        // Mint-or-reuse per channel too, keyed by (channel_id, next epoch) — same
2426        // retry-idempotency as the base root. The base-rekey signing above is a bunker
2427        // round-trip; re-check before this per-channel DB write straddles it.
2428        if !session.is_valid() {
2429            return Err("account changed during re-founding channel prepare".to_string());
2430        }
2431        let ch_new_key = mint_or_reuse_rotation_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.id.0), ch_new_epoch.0)?;
2432        let ch_prev_commit = super::derive::epoch_key_commitment(ch.epoch, &old_key);
2433        let mut ch_blobs = Vec::new();
2434        for r in &entitled {
2435            ch_blobs.push(
2436                super::rekey::build_blob(&signer, &my_pk.to_bytes(), r, super::rekey::RekeyScope::Channel(ch.id), ch_new_epoch, &ch_new_key)
2437                    .await
2438                    .map_err(|e| e.to_string())?,
2439            );
2440        }
2441        let ch_group = super::derive::channel_rekey_group_key(&community.community_root, &ch.id, ch_new_epoch);
2442        let ch_chunks = super::rekey::build_rekey_chunks(&signer, my_pk, &ch_group, super::rekey::RekeyScope::Channel(ch.id), ch_new_epoch, ch.epoch, &ch_prev_commit, &ch_blobs, at_secs, my_authority_citation(community, &my_pk).as_ref())
2443            .await
2444            .map_err(|e| e.to_string())?;
2445        channel_updates.push((ch.id, ch_new_key, ch_new_epoch));
2446        channel_chunk_sets.push(ch_chunks);
2447    }
2448    if !session.is_valid() {
2449        return Err("account changed during re-founding prepare".to_string());
2450    }
2451
2452    // COMMIT (durable publishes only — all fetching is done). Base rekey first
2453    // (delivers the new root), then channel rekeys, then the compacted control.
2454    for c in &base_chunks {
2455        transport.publish_durable(c, &community.relays).await?;
2456    }
2457    for set in &channel_chunk_sets {
2458        for c in set {
2459            transport.publish_durable(c, &community.relays).await?;
2460        }
2461    }
2462    for (_, wrap) in &carried {
2463        transport.publish_durable(wrap, &community.relays).await?;
2464    }
2465    // Guestbook snapshot at the new epoch — best-effort (a Refounding succeeds without
2466    // it; an omitted member heals by publishing their own Join).
2467    let gb_group = super::derive::guestbook_group_key(&new_root, cid, new_epoch);
2468    let snap_id = crate::community::random_32();
2469    for rumor in guestbook::build_snapshot_rumors(my_pk, &recipients, snap_id, at) {
2470        if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
2471            let _ = transport.publish(&wrap, &community.relays).await;
2472        }
2473    }
2474
2475    // COMMIT locally, only now that the new root + compacted plane are on relays.
2476    if !session.is_valid() {
2477        return Err("account changed during re-founding commit".to_string());
2478    }
2479    if crate::db::community::community_protocol(cid)?.is_none() {
2480        return Ok(community.clone()); // left/deleted mid-rotation — don't resurrect.
2481    }
2482    // Save the new root/epoch + rekeyed channel keys in ONE tx FIRST, so a crash can
2483    // never leave the base root advanced while the channel keys lag (which would
2484    // re-derive the channel rekey address under the wrong root and orphan them).
2485    let mut updated = community.clone();
2486    updated.community_root = new_root;
2487    updated.root_epoch = new_epoch;
2488    for (id, key, ep) in &channel_updates {
2489        if let Some(c) = updated.channels.iter_mut().find(|c| c.id.0 == id.0) {
2490            c.key = Some(*key);
2491            c.epoch = *ep;
2492        }
2493    }
2494    crate::db::community::save_community_v2(&updated)?;
2495    // Archive the new epoch key + confirm the monotonic base head (the root was already
2496    // archived by mint_or_reuse, so this is idempotent). Record the carried heads at
2497    // the NEW epoch; if a crash skips this, the epoch-filtered floors bootstrap the
2498    // compacted control on the next follow, so they self-heal.
2499    crate::db::community::advance_server_root_epoch(&cid_hex, new_epoch.0, &new_root)?;
2500    for (h, _) in &carried {
2501        crate::db::community::set_edition_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, new_epoch.0)?;
2502    }
2503    // Re-subscribe NOW: the rotation changed every plane author, and the live sub
2504    // still carries the OLD epoch's set. Members adopt via the follow worker
2505    // (which refreshes); the REFOUNDER has no such path — without this, the very
2506    // client that performed the ban goes deaf to the new epoch (a rejoin lands on
2507    // the relays and never arrives live).
2508    if let Some(client) = crate::state::nostr_client() {
2509        super::realtime::refresh_subscription(&client).await;
2510    }
2511    // Refresh any live public links so their bundles carry the NEW root behind the
2512    // same URL (a link shared once survives the rotation, CORD-05 §2). Idempotent,
2513    // so retry a transient failure — a stranded link lands a new joiner on the dead
2514    // pre-refound epoch, and there's no other trigger to heal it before the next
2515    // refounding. A persistent failure is logged (refound already succeeded).
2516    for attempt in 0..3u8 {
2517        match refresh_public_links(transport, &updated).await {
2518            Ok(()) => break,
2519            Err(_) if !session.is_valid() => break, // swapped — stop touching this account
2520            Err(e) if attempt == 2 => {
2521                crate::log_warn!("v2: post-refounding public-link refresh failed after retries ({e}); live links may serve the prior root until the next refresh");
2522            }
2523            Err(_) => continue,
2524        }
2525    }
2526    Ok(updated)
2527}
2528
2529/// BIRTH refound (§migration Phase 1.4): roll a freshly-minted migration twin from epoch 0
2530/// to epoch 1 so it can carry an owner-signed Guestbook SNAPSHOT of the full v1 memberlist —
2531/// genesis (epoch 0) has no snapshot authority (`fold_members` gates on `root_epoch > 0`), so
2532/// this is the ONLY way to seed a roster every honest client folds. UNLIKE [`refound_community`]
2533/// the two sets are DECOUPLED:
2534///
2535/// - **Rekey recipients = {owner} ONLY.** Members do NOT get the epoch-1 root via birth blobs
2536///   — they get it from the migration carrier's `m` (sealed AFTER this returns). Keeping the
2537///   set at {owner} also dodges the 120-blob rotation cap for large communities.
2538/// - **Snapshot members = the EXPLICIT full v1 list** (`snapshot_members`, display/roster only,
2539///   no keys). Chunked at SNAPSHOT_CHUNK (400)/rumor, no cap — a 10k-member community seeds fine.
2540///
2541/// The SAFEST refound possible: the owner authored 100% of the control plane seconds ago and
2542/// holds every edition locally, so the fold-all-or-abort discipline is trivially met (a flaky
2543/// relay just fires the abort → the wizard retries). Returns the epoch-1 community.
2544pub async fn refound_at_birth<T: Transport + ?Sized>(
2545    transport: &T,
2546    community: &CommunityV2,
2547    snapshot_members: &[PublicKey],
2548) -> Result<CommunityV2, String> {
2549    let session = SessionGuard::capture();
2550    let cid = community.id();
2551    let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
2552    // Death wins every race: a dissolved community never re-founds (CORD-02 §9, parity with
2553    // refound_community). A migration twin should never be dissolved mid-build, but fail-closed.
2554    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
2555        return Err("this community has been dissolved; it cannot be birth-refounded".to_string());
2556    }
2557    let signer = crate::signer::active_signer()?;
2558    let my_pk = me_pk()?;
2559    if my_pk != community.owner()? {
2560        return Err("only the owner can birth-refound the migration twin".to_string());
2561    }
2562    let lock = super::realtime::follow_lock(cid);
2563    let _guard = lock.lock().await;
2564    let community = crate::db::community::load_community_v2(cid)?.ok_or("twin gone before birth refound")?;
2565    // RESUME IDEMPOTENCE: if the refound already committed locally (epoch 1) but crashed
2566    // before its ledger write, the wizard re-calls this. The epoch advance + compaction only
2567    // commit AFTER the snapshot published durably + verified back (below), so an epoch-1 twin
2568    // means the snapshot already landed and is readable — return it. A twin past epoch 1 is
2569    // unexpected (nothing else rotates a mid-migration twin).
2570    if community.root_epoch.0 == 1 {
2571        return Ok(community);
2572    }
2573    if community.root_epoch.0 != 0 {
2574        return Err("birth refound only rolls a genesis (epoch 0) twin".to_string());
2575    }
2576    let community = &community;
2577
2578    // Compact the epoch-0 control plane onto epoch 1: re-wrap the committed head of every
2579    // floored entity VERBATIM (inner owner/admin signatures survive). The owner holds every
2580    // edition locally (authored seconds ago), so this fold-all-or-abort is trivially met.
2581    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
2582        .into_iter()
2583        .filter(|(_, f)| f.0 == community.root_epoch.0)
2584        .map(|(entity, f)| (entity, (f.1, f.2, f.3)))
2585        .collect();
2586    let current_control = control_group_key(&community.community_root, cid, community.root_epoch);
2587    let mut opened: Vec<(ParsedEdition, super::stream::OpenedStream)> = Vec::new();
2588    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
2589    let mut oldest: Option<u64> = None;
2590    let mut until: Option<u64> = None;
2591    // Exhaustion, not coverage — see the sibling read in `refound_community`.
2592    let mut truncated = false;
2593    for page in 0..COMPACT_MAX_PAGES {
2594        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![current_control.pk_hex()], until, limit: Some(FOLLOW_PAGE), evidence: crate::community::transport::Evidence::Full, ..Default::default() };
2595        let wraps = transport.fetch(&query, &community.relays).await?;
2596        let mut fresh = 0usize;
2597        for w in &wraps {
2598            if !seen_wraps.insert(w.id) { continue; }
2599            fresh += 1;
2600            let at = w.created_at.as_secs();
2601            if oldest.is_none_or(|o| at < o) { oldest = Some(at); }
2602            if let Ok(parsed) = control::open_control_edition(w, &current_control) {
2603                opened.push(parsed);
2604            }
2605        }
2606        if fresh == 0 {
2607            truncated = wraps.len() >= FOLLOW_PAGE;
2608            break;
2609        }
2610        until = oldest;
2611        if page + 1 == COMPACT_MAX_PAGES { truncated = true; }
2612    }
2613    if truncated {
2614        return Err(
2615            "The community's control plane is too deep to read in full right now; re-founding stopped so no member is left behind.".to_string(),
2616        );
2617    }
2618
2619    let prev_epoch = community.root_epoch; // 0
2620    let new_epoch = Epoch(1);
2621    let prev_commit = super::derive::epoch_key_commitment(prev_epoch, &community.community_root);
2622    if !session.is_valid() {
2623        return Err("account changed during birth-refound compaction".to_string());
2624    }
2625    let new_root = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, new_epoch.0)?;
2626    let new_control = control_group_key(&new_root, cid, new_epoch);
2627    let at = now_ms();
2628    let at_secs = at / 1000;
2629
2630    use std::collections::BTreeMap;
2631    let mut by_eid: BTreeMap<String, Vec<usize>> = BTreeMap::new();
2632    for (i, (e, _)) in opened.iter().enumerate() {
2633        by_eid.entry(crate::simd::hex::bytes_to_hex_32(&e.entity_id)).or_default().push(i);
2634    }
2635    let mut carried: Vec<(FoldedHead, Event)> = Vec::new();
2636    for (floor_key, floor) in &floors {
2637        let head_idx = by_eid.get(floor_key).and_then(|v| v.iter().copied().find(|&i| opened[i].0.self_hash == floor.1));
2638        let Some(head_idx) = head_idx else {
2639            return Err(format!("birth refound aborted: committed head of entity {floor_key} (v{}) not served; no state published", floor.0));
2640        };
2641        let (head_ed, head_os) = &opened[head_idx];
2642        let h = FoldedHead { entity_hex: floor_key.clone(), version: head_ed.version, self_hash: head_ed.self_hash, inner_id: head_ed.inner_id };
2643        let (rewrapped, _) = super::stream::rewrap_seal(&head_os.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
2644        carried.push((h, rewrapped));
2645    }
2646    if !session.is_valid() {
2647        return Err("account changed during birth-refound acquire".to_string());
2648    }
2649
2650    // Base rekey: the epoch-1 root to the OWNER ONLY (members key up via the carrier's `m`).
2651    let base_blobs = vec![
2652        super::rekey::build_blob(&signer, &my_pk.to_bytes(), &my_pk, super::rekey::RekeyScope::Root, new_epoch, &new_root)
2653            .await
2654            .map_err(|e| e.to_string())?,
2655    ];
2656    let base_group = super::derive::base_rekey_group_key(&community.community_root, cid, new_epoch);
2657    let base_chunks =
2658        super::rekey::build_rekey_chunks(&signer, my_pk, &base_group, super::rekey::RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &base_blobs, at_secs, my_authority_citation(community, &my_pk).as_ref())
2659            .await
2660            .map_err(|e| e.to_string())?;
2661    if !session.is_valid() {
2662        return Err("account changed during birth-refound prepare".to_string());
2663    }
2664
2665    // COMMIT to the wire: base rekey (owner's new root), then the compacted control.
2666    for c in &base_chunks {
2667        transport.publish_durable(c, &community.relays).await?;
2668    }
2669    for (_, wrap) in &carried {
2670        transport.publish_durable(wrap, &community.relays).await?;
2671    }
2672    // The Guestbook SNAPSHOT — the WHOLE POINT of the birth refound, so publish it DURABLY
2673    // and FAIL the refound if any chunk doesn't land. Unlike `refound_community` (where
2674    // live members heal via their own Join if a chunk drops), a seeded-never-landed member
2675    // CANNOT heal — omitted → absent from `memberlist()` → excluded from every future rotation
2676    // → permanently stranded. So the snapshot is load-bearing, not best-effort. The publishes
2677    // precede the local commit, so a `?`-abort leaves epoch 0 and a retry re-runs idempotently
2678    // (mint_or_reuse gives the same epoch-1 root; snapshot chunks coalesce commutatively).
2679    let gb_group = super::derive::guestbook_group_key(&new_root, cid, new_epoch);
2680    let snap_id = crate::community::random_32();
2681    let snapshot_wraps: Vec<Event> = {
2682        let mut out = Vec::new();
2683        for rumor in guestbook::build_snapshot_rumors(my_pk, snapshot_members, snap_id, at) {
2684            let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs))
2685                .await
2686                .map_err(|e| format!("seal birth snapshot: {e}"))?;
2687            out.push(wrap);
2688        }
2689        out
2690    };
2691    for wrap in &snapshot_wraps {
2692        transport.publish_durable(wrap, &community.relays).await?;
2693    }
2694    // Verify-back (design §4 Phase 1.5): fetch the snapshot at the new epoch and confirm every
2695    // seeded member folds, before we commit locally. A relay that ACKed a durable publish but
2696    // won't serve it back (or a partial landing) aborts here with ZERO local state — the retry
2697    // re-publishes. A seed that is (legitimately) in the folded banlist is EXPECTED to be
2698    // absent from the memberlist (`memberlist` subtracts the banlist, so requiring a
2699    // banned seed to "fold" would wedge the retry forever) — so subtract the wire-folded
2700    // banlist from the expected set. The real caller never seeds a banned member, but the
2701    // arbitrary-`snapshot_members` API must not be able to wedge on one.
2702    let verify_view = {
2703        let mut v = community.clone();
2704        v.community_root = new_root;
2705        v.root_epoch = new_epoch;
2706        v
2707    };
2708    let expected: Vec<PublicKey> = {
2709        let banlist = fetch_authority(transport, &verify_view).await.banned;
2710        snapshot_members.iter().copied()
2711            .filter(|m| *m != my_pk && !banlist.contains(&m.to_hex()))
2712            .collect()
2713    };
2714    if !expected.is_empty() {
2715        let folded = memberlist(transport, &verify_view).await.unwrap_or_default();
2716        let missing = expected.iter().filter(|m| !folded.contains(m)).count();
2717        if missing > 0 {
2718            return Err(format!("birth snapshot verify-back: {missing} seeded member(s) not readable from relays; not committing"));
2719        }
2720    }
2721
2722    // COMMIT locally, only now that the new root + compacted plane + snapshot are on relays.
2723    if !session.is_valid() {
2724        return Err("account changed during birth-refound commit".to_string());
2725    }
2726    if crate::db::community::community_protocol(cid)?.is_none() {
2727        return Ok(community.clone());
2728    }
2729    let mut updated = community.clone();
2730    updated.community_root = new_root;
2731    updated.root_epoch = new_epoch;
2732    crate::db::community::save_community_v2(&updated)?;
2733    crate::db::community::advance_server_root_epoch(&cid_hex, new_epoch.0, &new_root)?;
2734    for (h, _) in &carried {
2735        crate::db::community::set_edition_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, new_epoch.0)?;
2736    }
2737    Ok(updated)
2738}
2739
2740/// Mint a fresh 32-byte rotation key for `(scope, new_epoch)`, or REUSE the one
2741/// already archived from a prior (aborted) attempt — so a retried Refounding re-
2742/// delivers the SAME key at the same epoch/address instead of double-minting two roots
2743/// a receiver's correlation dedup would collapse into a permanent fork (CORD-06 §3
2744/// idempotency). Archived BEFORE the first publish; `scope` is the all-zero server-root
2745/// sentinel for a base rotation, else the channel_id hex.
2746fn mint_or_reuse_rotation_key(community_id_hex: &str, scope_hex: &str, new_epoch: u64) -> Result<[u8; 32], String> {
2747    if let Some(existing) = crate::db::community::held_epoch_key(community_id_hex, scope_hex, new_epoch)? {
2748        return Ok(existing);
2749    }
2750    let fresh = crate::community::random_32();
2751    crate::db::community::store_epoch_key(community_id_hex, scope_hex, new_epoch, &fresh)?;
2752    Ok(fresh)
2753}
2754
2755// ── The Community List (kind 13302, CORD-02 §8) ──────────────────────────────
2756
2757/// This community's MEMBERSHIP subset for the 13302 list (CORD-02 §8): never the
2758/// icon (a rehydrating device folds it from the Control Plane), never the link
2759/// fields. Only PRIVATE channel keys ride — public channels derive from the root.
2760fn join_material(community: &CommunityV2) -> super::list::JoinMaterial {
2761    let hex = crate::simd::hex::bytes_to_hex_32;
2762    let channels = community
2763        .channels
2764        .iter()
2765        .filter(|c| c.private)
2766        // Keyed channels ONLY. A keyless entry is readable by this build but is
2767        // rejected outright by shipped ones (their `key` is a required String),
2768        // so emitting one would strand every older client on a stale list.
2769        .filter_map(|c| {
2770            c.key.map(|k| super::list::ChannelKeyRef { id: hex(&c.id.0), key: Some(hex(&k)), epoch: c.epoch.0, name: c.name.clone() })
2771        })
2772        .collect();
2773    super::list::JoinMaterial {
2774        community_id: hex(&community.identity.community_id.0),
2775        owner: hex(&community.identity.owner_xonly),
2776        owner_salt: hex(&community.identity.owner_salt),
2777        community_root: hex(&community.community_root),
2778        root_epoch: community.root_epoch.0,
2779        channels,
2780        relays: community.relays.clone(),
2781        name: community.name.clone(),
2782        extra: Default::default(),
2783    }
2784}
2785
2786/// Rebuild an invite bundle from list join material, for a cross-device rehydrate
2787/// (the material IS the membership subset of a bundle). The owner root is still
2788/// verified over the network before the community is trusted (accept_bundle).
2789fn material_to_invite(jm: &super::list::JoinMaterial) -> CommunityInvite {
2790    // A keyless listing records that the channel EXISTS, not a grant — there is
2791    // nothing to seat, and it keys up when access is granted.
2792    let channels = jm
2793        .channels
2794        .iter()
2795        .filter_map(|c| {
2796            c.key.as_ref().map(|k| invite::ChannelGrant { id: c.id.clone(), key: k.clone(), epoch: c.epoch, name: c.name.clone() })
2797        })
2798        .collect();
2799    CommunityInvite {
2800        community_id: jm.community_id.clone(),
2801        owner: jm.owner.clone(),
2802        owner_salt: jm.owner_salt.clone(),
2803        community_root: jm.community_root.clone(),
2804        root_epoch: jm.root_epoch,
2805        channels,
2806        relays: jm.relays.clone(),
2807        name: jm.name.clone(),
2808        icon: None,
2809        expires_at: None,
2810        creator_npub: None,
2811        label: None,
2812        extra: Default::default(),
2813    }
2814}
2815
2816/// The union of every held v2 community's relays — where this account's 13302 list
2817/// lives (a fresh device that opens any held community reaches the same set).
2818fn held_v2_relays() -> Vec<String> {
2819    let mut set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
2820    if let Ok(ids) = crate::db::community::list_community_ids() {
2821        for id in ids {
2822            if matches!(crate::db::community::community_protocol(&id), Ok(Some(crate::community::ConcordProtocol::V2))) {
2823                if let Ok(Some(c)) = crate::db::community::load_community_v2(&id) {
2824                    set.extend(c.relays);
2825                }
2826            }
2827        }
2828    }
2829    set.into_iter().collect()
2830}
2831
2832/// Fetch this account's own 13302 Community List from `relays` (the newest wins;
2833/// a decrypt/parse failure is "no news", never a clobber of the local mirror).
2834/// Fetch this account's newest 13302 list. `Err` = the transport FAILED (a caller
2835/// must NOT drive a replaceable-event write from a failed read — it would clobber
2836/// the live list); `Ok(None)` = genuinely no list yet; `Ok(Some)` = the list.
2837async fn fetch_community_list<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<Option<super::list::CommunityList>, String> {
2838    let signer = crate::signer::active_signer()?;
2839    let my_pk = me_pk()?;
2840    let query = Query {
2841        kinds: vec![super::kind::COMMUNITY_LIST],
2842        authors: vec![my_pk.to_hex()],
2843        limit: Some(4),
2844        ..Default::default()
2845    };
2846    let events = transport.fetch(&query, relays).await?;
2847    let seen = events.len();
2848    // Which copy won matters: relays disagree (one may hold a stale replaceable),
2849    // and a list near the NIP-44 ceiling stops accepting joins — both are invisible
2850    // without saying so.
2851    let mut undecryptable = 0usize;
2852    let mut unreadable: Option<(u64, String, usize, String)> = None;
2853    let mut best: Option<(u64, String, super::list::CommunityList)> = None;
2854    for e in events {
2855        let at = e.created_at.as_secs();
2856        let id_hex = e.id.to_hex();
2857        let content_len = e.content.len();
2858        match super::list::parse_list_event_signed(&signer, my_pk, &e).await {
2859            Ok(l) => {
2860                if best.as_ref().map(|(b, _, _)| at > *b).unwrap_or(true) {
2861                    best = Some((at, id_hex, l));
2862                }
2863            }
2864            Err(err) => {
2865                undecryptable += 1;
2866                if unreadable.as_ref().map(|(a, _, _, _)| at > *a).unwrap_or(true) {
2867                    unreadable = Some((at, id_hex, content_len, err.to_string()));
2868                }
2869            }
2870        }
2871    }
2872    // Only the case that costs data is worth a warning: a copy we could not read
2873    // that was NEWER than the one we settled for. That silently pins the account
2874    // to stale membership, and the parse error is the only clue to why.
2875    if let Some((at, id, len, err)) = &unreadable {
2876        if best.as_ref().map(|(b, _, _)| at > b).unwrap_or(true) {
2877            crate::log_net_fail!(
2878                "[CommunityList] IGNORED a newer copy {} created_at={at} ({len} content bytes) — falling back to stale membership: {err}",
2879                &id[..8]
2880            );
2881        }
2882    }
2883    if let Some((at, id, l)) = &best {
2884        let bytes = serde_json::to_string(l).map(|s| s.len()).unwrap_or(0);
2885        crate::log_debug!(
2886            "[CommunityList] using {} created_at={at} ({bytes}/{} bytes) of {seen} copies, {undecryptable} unreadable",
2887            &id[..8],
2888            super::stream::NIP44_MAX_PLAINTEXT
2889        );
2890    }
2891    Ok(best.map(|(_, _, l)| l))
2892}
2893
2894/// Rebuild this account's 13302 from its held v2 communities, MERGE with the remote
2895/// copy (preserving tombstones, other-device entries, unknown fields), and publish.
2896/// `just_joined` is the community THIS call is recording a create/join for — the
2897/// ONLY community whose entry is (re)stamped `now`, so it beats any prior tombstone
2898/// (a deliberate re-join resurrects). Every OTHER held community that the remote
2899/// has tombstoned is left tombstoned (a sibling device's leave is NOT undone just
2900/// because we joined something else — the W1 resurrection hole). Idempotent;
2901/// best-effort — a list-publish failure never fails the membership change itself.
2902/// Returns `Ok(true)` when the list was PUBLISHED, `Ok(false)` when the attempt was
2903/// skipped without failing the caller (a failed remote fetch — see below). Callers that
2904/// need the membership to actually land use [`republish_community_list_durable`].
2905pub async fn republish_community_list<T: Transport + ?Sized>(transport: &T, just_joined: Option<&crate::community::CommunityId>) -> Result<bool, String> {
2906    let session = SessionGuard::capture();
2907    let signer = crate::signer::active_signer()?;
2908    let my_pk = me_pk()?;
2909    let relays = held_v2_relays();
2910    if relays.is_empty() {
2911        return Ok(false); // nothing held → nothing to sync
2912    }
2913    // A FAILED remote fetch must not drive this replaceable-event write: publishing
2914    // a list built without the remote seeds would drop older-epoch backfill anchors
2915    // and re-stamp add-times (the W2 seed-regression + a resurrection window).
2916    let remote = match fetch_community_list(transport, &relays).await {
2917        Ok(r) => r.unwrap_or_default(),
2918        Err(e) => {
2919            // SILENT-SKIP HAZARD: bailing is correct (publishing a list built without the
2920            // remote seeds drops backfill anchors), but the membership this call was meant
2921            // to record is now simply unrecorded. A join that lands here leaves a community
2922            // held locally with no list entry — and if it also carries an older tombstone,
2923            // nothing ever out-ranks it again. Say so loudly; `Ok(())` keeps it non-fatal.
2924            crate::log_warn!(
2925                "[CommunityList] republish SKIPPED (remote fetch failed: {}){}",
2926                e,
2927                just_joined
2928                    .map(|c| format!(" — the join of {} is NOT recorded across devices", &crate::simd::hex::bytes_to_hex_32(&c.0)[..8]))
2929                    .unwrap_or_default()
2930            );
2931            return Ok(false);
2932        }
2933    };
2934    let just_joined_hex = just_joined.map(|c| crate::simd::hex::bytes_to_hex_32(&c.0));
2935    let now = now_ms();
2936    let mut local = super::list::CommunityList::default();
2937    for id in crate::db::community::list_community_ids()? {
2938        if !matches!(crate::db::community::community_protocol(&id), Ok(Some(crate::community::ConcordProtocol::V2))) {
2939            continue;
2940        }
2941        let Some(c) = crate::db::community::load_community_v2(&id)? else { continue };
2942        let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
2943        let is_join = just_joined_hex.as_deref() == Some(cid_hex.as_str());
2944        // A held community the remote has tombstoned (a sibling device left it) that
2945        // we are NOT currently (re)joining stays LEFT — don't re-add it, or joining a
2946        // different community would silently undo the leave everywhere.
2947        //
2948        // UNLESS our hold POST-DATES the removal. A rejoin whose membership never
2949        // reached the list (this publish is best-effort — a failed remote fetch
2950        // silently skips it) leaves a tombstone with no entry, and nothing can ever
2951        // out-rank it again: every boot the list sync reads "removed", tears the
2952        // community down, the rejoin re-adds it, and it loops forever. Our own hold
2953        // is first-hand evidence of membership, so let it settle the tie by the same
2954        // add-vs-remove rule the list already uses everywhere else.
2955        let tombstoned_at = remote
2956            .tombstones
2957            .iter()
2958            .find(|t| t.community_id == cid_hex)
2959            .map(|t| t.removed_at)
2960            .unwrap_or(0);
2961        let held_since = c.created_at_ms;
2962        if !is_join && !remote.is_live(&cid_hex) && tombstoned_at > 0 && held_since <= tombstoned_at {
2963            crate::log_warn!(
2964                "[CommunityList] holding {} but NOT recording it: a tombstone at {} post-dates our hold ({}) — treated as a leave from another device",
2965                &cid_hex[..8], tombstoned_at, held_since
2966            );
2967            continue;
2968        }
2969        // Keep an already-live entry's add time (no churn); the joined community (or a
2970        // genuinely-new one) stamps `now` so a re-join beats a stale tombstone. A hold
2971        // that outlived a tombstone re-asserts itself at its own join time, which is
2972        // already newer than the removal.
2973        let added_at = if remote.is_live(&cid_hex) && !is_join {
2974            remote.entries.iter().find(|e| e.community_id == cid_hex).map(|e| e.added_at).unwrap_or(now)
2975        } else if !is_join && tombstoned_at > 0 {
2976            held_since
2977        } else {
2978            now
2979        };
2980        let jm = join_material(&c);
2981        local.entries.push(super::list::CommunityListEntry { community_id: cid_hex, seed: jm.clone(), current: jm, added_at, extra: Default::default() });
2982    }
2983    let merged = remote.merge(&local);
2984    merged.assert_fits().map_err(|e| e.to_string())?;
2985    let event = super::list::build_list_event_signed(&signer, my_pk, &merged).await.map_err(|e| e.to_string())?;
2986    if !session.is_valid() {
2987        return Err("account changed during community-list publish".to_string());
2988    }
2989    if let Err(e) = transport.publish(&event, &relays).await {
2990        crate::log_warn!("[CommunityList] publish FAILED ({}) — memberships stay local-only until the next edit", e);
2991        return Err(e);
2992    }
2993    Ok(true)
2994}
2995
2996/// Retry budget for [`republish_community_list_durable`]. An unrecorded membership is
2997/// invisible to the user and self-heals only on their NEXT join, so ride out a relay
2998/// blip rather than a single shot. Bounded: a permanently dead relay set gives up
2999/// instead of spinning.
3000const LIST_REPUBLISH_BACKOFF_SECS: [u64; 6] = [2, 5, 15, 45, 120, 300];
3001
3002/// Record a membership across devices DURABLY: retry in the background until the list
3003/// actually lands.
3004///
3005/// [`republish_community_list`] must never fail a join, and it deliberately publishes
3006/// NOTHING when the remote fetch fails (a list built without the remote seeds would drop
3007/// other devices' entries). One shot at that means a relay blip during a join leaves the
3008/// membership unrecorded until the user happens to join something else — and if a stale
3009/// tombstone out-ranks it, the community is stranded until a manual leave+rejoin.
3010///
3011/// Non-blocking. Skipped entirely without a live client (headless/unit tests drive the
3012/// generic fn directly). The `SessionGuard` is captured BEFORE the spawn and re-checked
3013/// before every attempt, so an account swap mid-backoff can't publish A's list from B.
3014pub fn republish_community_list_durable(just_joined: Option<crate::community::CommunityId>) {
3015    if crate::state::nostr_client().is_none() {
3016        return;
3017    }
3018    let session = SessionGuard::capture();
3019    tokio::spawn(async move {
3020        for (attempt, wait) in LIST_REPUBLISH_BACKOFF_SECS.iter().enumerate() {
3021            if !session.is_valid() {
3022                return;
3023            }
3024            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
3025            match republish_community_list(&transport, just_joined.as_ref()).await {
3026                Ok(true) => {
3027                    if attempt > 0 {
3028                        crate::log_info!("[CommunityList] membership recorded on retry #{}", attempt);
3029                    }
3030                    return;
3031                }
3032                Ok(false) => {} // skipped (remote fetch failed) — already logged; retry
3033                Err(e) => crate::log_warn!("[CommunityList] republish attempt #{} failed: {}", attempt, e),
3034            }
3035            tokio::time::sleep(std::time::Duration::from_secs(*wait)).await;
3036        }
3037        crate::log_warn!(
3038            "[CommunityList] gave up recording membership after {} attempts — it will re-record on the next join/leave",
3039            LIST_REPUBLISH_BACKOFF_SECS.len()
3040        );
3041    });
3042}
3043
3044/// Record a permanent leave tombstone for `community_id` in the 13302, published to
3045/// `relays` (the leaving community's own, since it's about to be deleted locally).
3046async fn tombstone_community_list<T: Transport + ?Sized>(transport: &T, community_id: &crate::community::CommunityId, relays: &[String]) -> Result<(), String> {
3047    let signer = crate::signer::active_signer()?;
3048    let my_pk = me_pk()?;
3049    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);
3050    // A failed fetch here would drop other communities' entries (only the
3051    // tombstone would survive); preserve them by bailing — the leave re-records
3052    // on the next attempt, and the local teardown already happened.
3053    let mut doc = match fetch_community_list(transport, relays).await {
3054        Ok(d) => d.unwrap_or_default(),
3055        Err(e) => return Err(e),
3056    };
3057    let now = now_ms();
3058    doc.tombstones.retain(|t| t.community_id != cid_hex);
3059    doc.tombstones.push(super::list::Tombstone { community_id: cid_hex, removed_at: now, extra: Default::default() });
3060    doc.assert_fits().map_err(|e| e.to_string())?;
3061    let event = super::list::build_list_event_signed(&signer, my_pk, &doc).await.map_err(|e| e.to_string())?;
3062    transport.publish(&event, relays).await
3063}
3064
3065/// Sync memberships from the 13302 across devices: fetch this account's list from
3066/// `bootstrap_relays` (its held communities' relays plus any caller-supplied set for
3067/// a fresh device), and JOIN every live entry not already held — reconstructing the
3068/// community from its join material and re-verifying the owner root. Returns the
3069/// newly-rehydrated communities (so the caller can subscribe + notify).
3070/// What one Community-List sync changed locally.
3071pub struct ListSyncOutcome {
3072    /// Communities newly adopted from the list (already persisted + chat-registered).
3073    pub joined: Vec<CommunityV2>,
3074    /// Communities a sibling device LEFT, as `(community_id_hex, channel_id_hexes)`.
3075    ///
3076    /// The rows are already gone here, so the ids are captured BEFORE deletion: the caller
3077    /// still has to finish the local teardown (chat rows, STATE, the live subscription),
3078    /// and it can't look them up afterwards. Deleting the community while leaving its chat
3079    /// row behind is what produces a ghost "0 Members" room pointing at nothing.
3080    pub removed: Vec<(String, Vec<String>)>,
3081}
3082
3083pub async fn sync_community_list<T: Transport + ?Sized>(transport: &T, bootstrap_relays: &[String]) -> Result<ListSyncOutcome, String> {
3084    let session = SessionGuard::capture();
3085    let mut relays = held_v2_relays();
3086    relays.extend(bootstrap_relays.iter().cloned());
3087    relays.sort();
3088    relays.dedup();
3089    if relays.is_empty() {
3090        return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
3091    }
3092    // A cross-device sync that finds nothing is indistinguishable from one that
3093    // never ran, so every exit says why — this path is only ever debugged after
3094    // the fact, from a user's log.
3095    let list = match fetch_community_list(transport, &relays).await {
3096        Ok(Some(l)) => {
3097            crate::log_debug!(
3098                "[CommunityList] fetched: {} entries, {} tombstones, across {} relays",
3099                l.entries.len(),
3100                l.tombstones.len(),
3101                relays.len()
3102            );
3103            l
3104        }
3105        Ok(None) => {
3106            // Transient by nature: boot runs many concurrent passes and a relay that
3107            // times out under that load returns nothing. Only persistent absence
3108            // matters, and that shows up as "adopted nothing" anyway.
3109            crate::log_debug!("[CommunityList] no kind-13302 across {} relays", relays.len());
3110            return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
3111        }
3112        Err(e) => {
3113            crate::log_net_fail!("[CommunityList] fetch failed across {} relays: {e}", relays.len());
3114            return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
3115        }
3116    };
3117    // Receive-side teardown (the counterpart to the republish tombstone guard):
3118    // a community this device still holds but the synced list shows TOMBSTONED (a
3119    // sibling device left it) and NOT live gets torn down here, so a leave on one
3120    // device propagates to the others. A re-join would have re-added it live
3121    // (beating the tombstone), so is_live short-circuits the honest case.
3122    let mut removed: Vec<(String, Vec<String>)> = Vec::new();
3123    for t in &list.tombstones {
3124        if list.is_live(&t.community_id) {
3125            continue;
3126        }
3127        let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&t.community_id) else { continue };
3128        let id = crate::community::CommunityId(cid);
3129        let Some(held) = crate::db::community::load_community_v2(&id).ok().flatten() else {
3130            continue; // not held — nothing to tear down
3131        };
3132        // `is_live` above assumes a rejoin re-added an entry, but recording that entry is
3133        // best-effort: a relay blip at join time leaves the tombstone unopposed forever, and
3134        // this would then delete the community on every sync. So let the LOCAL hold break the
3135        // tie too — a hold created after the removal IS the rejoin, whether or not its entry
3136        // ever reached the list. Same rule the v1 sweep uses.
3137        if held.created_at_ms > t.removed_at {
3138            crate::log_warn!(
3139                "[CommunityList] {} is tombstoned at {} but our hold ({}) post-dates it — treating as a rejoin, not tearing down",
3140                &t.community_id[..8], t.removed_at, held.created_at_ms
3141            );
3142            continue;
3143        }
3144        if !session.is_valid() {
3145            return Err("account changed during community-list sync".to_string());
3146        }
3147        let channel_ids: Vec<String> = held.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
3148        let _ = crate::db::community::delete_community(&t.community_id);
3149        removed.push((t.community_id.clone(), channel_ids));
3150    }
3151    let mut joined = Vec::new();
3152    for entry in list.live_entries() {
3153        let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&entry.community_id) else { continue };
3154        if crate::db::community::load_community_v2(&crate::community::CommunityId(cid)).ok().flatten().is_some() {
3155            continue; // already held
3156        }
3157        if !session.is_valid() {
3158            return Err("account changed during community-list sync".to_string());
3159        }
3160        // The material IS a bundle; accept_bundle re-verifies the owner root, saves,
3161        // and seeds floors. NO Guestbook Join: this device is receiving keys the
3162        // account already holds elsewhere — the membership was announced when it
3163        // actually joined, and a key sync is not a membership event.
3164        let bundle = material_to_invite(&entry.current);
3165        match accept_bundle(transport, &session, &bundle, None, false).await {
3166            Ok(community) => joined.push(community),
3167            // A listed-but-unadoptable entry is the failure mode that reads as
3168            // "cross-device sync is broken": the community never appears and any
3169            // parked invite for it is never retired.
3170            Err(e) => crate::log_net_fail!(
3171                "[CommunityList] {} is listed but adoption failed: {e}",
3172                &entry.community_id[..entry.community_id.len().min(8)]
3173            ),
3174        }
3175    }
3176    Ok(ListSyncOutcome { joined, removed })
3177}
3178
3179// ── Control edition authoring (CORD-04 roles / CORD-02 §6 / CORD-03 §2) ──────
3180
3181/// Publish one control edition (a role, grant, banlist, community-metadata, or
3182/// channel-metadata edit) at the next version for its entity, chaining `prev` from
3183/// our held head, and advance our local floor. Authority is enforced by every
3184/// reader's roster fold (CORD-04 §5: authority is rejection, not prevention), so this
3185/// requires only a valid local signer; a well-behaved client checks its own rank
3186/// first, but a reader drops an unauthorized edition regardless.
3187/// This actor's authority citation for a control edition (CORD-04 §5): the head
3188/// of their OWN Grant entity, pinned by coordinate + version + edition hash.
3189///
3190/// A SYNC FLOOR, not a verdict — a verifier refuses to act until it has synced
3191/// at least this Grant, then resolves rank against its CURRENT roster, so a
3192/// demoted admin is never grandfathered by an old-but-once-valid citation.
3193///
3194/// `None` for the owner (supreme, rank comes from the community id) and `None`
3195/// when no Grant head is held — an actor who cannot cite has no rank to claim,
3196/// and the edition is dropped by a conforming reader either way.
3197/// The verify half of [`my_authority_citation`] (CORD-04 §5): does the actor's
3198/// cited Grant prove authority we have actually SYNCED? The owner is supreme and
3199/// cites nothing. A non-owner MUST cite, and we must hold that Grant at ≥ the
3200/// cited version with the cited hash at the tip — else fail closed, because
3201/// honoring an action whose authority we can't confirm is exactly how a demoted
3202/// moderator keeps moderating.
3203///
3204/// Completeness only: the permission + outrank is the separate roster check, so a
3205/// since-demoted actor is refused there (refuse-superseded). An action citing a
3206/// version we haven't synced parks and is re-judged on the next roster sync — the
3207/// sync path can't escalate to a blocking fetch.
3208pub(super) fn citation_is_synced(
3209    cid_hex: &str,
3210    owner_hex: &str,
3211    actor_hex: &str,
3212    citation: Option<&crate::community::edition::AuthorityCitation>,
3213) -> bool {
3214    if owner_hex == actor_hex {
3215        return true;
3216    }
3217    if citation.is_none() {
3218        return false;
3219    }
3220    let cid_bytes = crate::simd::hex::hex_to_bytes_32(cid_hex);
3221    let actor_bytes = crate::simd::hex::hex_to_bytes_32(actor_hex);
3222    let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(
3223        &crate::community::CommunityId(cid_bytes),
3224        &actor_bytes,
3225    ));
3226    let head: Vec<crate::community::roster::EntityHead> =
3227        crate::db::community::get_edition_head(cid_hex, &grant_hex)
3228            .ok()
3229            .flatten()
3230            .map(|(version, self_hash)| crate::community::roster::EntityHead {
3231                entity_hex: grant_hex.clone(),
3232                version,
3233                self_hash,
3234                inner_id: [0u8; 32],
3235                citation: None,
3236            })
3237            .into_iter()
3238            .collect();
3239    crate::community::roster::authority_citation_satisfied(&head, Some(owner_hex), actor_hex, &grant_hex, citation)
3240}
3241
3242/// [`my_authority_citation`], but refusing to emit an action every reader will
3243/// drop (CORD-04 §5: an uncited non-owner action is not honored).
3244///
3245/// The citation is built from PERSISTED heads, which only `follow_control` writes
3246/// — so an admin who hasn't folded yet (just promoted, or freshly restored) would
3247/// otherwise publish uncited and have the action silently vanish on every client,
3248/// with nothing shown locally. Failing here turns that into one retryable error.
3249fn required_authority_citation(
3250    community: &CommunityV2,
3251    actor: &PublicKey,
3252) -> Result<Option<crate::community::edition::AuthorityCitation>, String> {
3253    if community.owner().ok().as_ref() == Some(actor) {
3254        return Ok(None); // supreme, cites nothing
3255    }
3256    my_authority_citation(community, actor).map(Some).ok_or_else(|| {
3257        "your admin rights aren't synced on this device yet — reopen the community and retry".to_string()
3258    })
3259}
3260
3261fn my_authority_citation(
3262    community: &CommunityV2,
3263    actor: &PublicKey,
3264) -> Option<crate::community::edition::AuthorityCitation> {
3265    if community.owner().ok().as_ref() == Some(actor) {
3266        return None;
3267    }
3268    let entity_id = super::derive::grant_locator(community.id(), &actor.to_bytes());
3269    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3270    let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
3271    crate::db::community::get_edition_head(&cid_hex, &entity_hex)
3272        .ok()
3273        .flatten()
3274        .map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
3275}
3276
3277/// Refuse a root-derived write whose in-hand struct predates a rotation.
3278///
3279/// A Ban's refound buries the old root while the caller's `CommunityV2` still
3280/// points at it; publishing there lands on a plane nobody folds — the action
3281/// "succeeds" and silently never happened (an unban that doesn't unban, an
3282/// invite that strands its joiner on a dead epoch). Failing loudly instead lets
3283/// the caller reload and retry against the living root.
3284fn assert_current_root(community: &CommunityV2) -> Result<(), String> {
3285    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3286    match crate::db::community::get_server_root_epoch(&cid_hex)? {
3287        Some(held) if held != community.root_epoch.0 => Err(format!(
3288            "the community re-founded mid-action (epoch {} -> {held}); retry",
3289            community.root_epoch.0
3290        )),
3291        _ => Ok(()), // no row = a not-yet-persisted create; nothing newer to defer to
3292    }
3293}
3294
3295async fn publish_control_edition<T: Transport + ?Sized>(
3296    transport: &T,
3297    community: &CommunityV2,
3298    session: &SessionGuard,
3299    vsk: &str,
3300    entity_id: &[u8; 32],
3301    content: &str,
3302) -> Result<(), String> {
3303    assert_current_root(community)?;
3304    let signer = crate::signer::active_signer()?;
3305    let my_pk = me_pk()?;
3306    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
3307    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3308    let entity_hex = crate::simd::hex::bytes_to_hex_32(entity_id);
3309    let (version, prev) = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
3310        Some((v, h)) => (v + 1, Some(h)),
3311        None => (1, None),
3312    };
3313    // CORD-04 §5: a non-owner names the exact Grant edition it claims its rank
3314    // under. Computed here rather than passed in — the citation is a property of
3315    // WHO IS ACTING, identical for every entity kind, so deciding it per call
3316    // site is nine chances to forget (and nine were, silently: every site passed
3317    // None). The owner cites nothing; their rank is the community id itself.
3318    let citation = required_authority_citation(community, &my_pk)?;
3319    let at = now_ms() / 1000;
3320    let rumor = control::build_edition_rumor(my_pk, vsk, entity_id, version, prev.as_ref(), content, at, citation.as_ref());
3321    let (wrap, _) = control::seal_control_edition_signed(&signer, my_pk, &rumor, &control, Timestamp::from_secs(at)).await.map_err(|e| e.to_string())?;
3322    if !session.is_valid() {
3323        return Err("account changed before control publish".to_string());
3324    }
3325    transport.publish(&wrap, &community.relays).await?;
3326    // Advance our own floor so a follow-up edit chains from this head and refuse-
3327    // downgrade holds; open our own wrap to recover the self_hash + inner_id.
3328    // Re-check the session AFTER the publish await: a swap mid-publish means the
3329    // pool now points at another account's DB — skipping is safe (the next own
3330    // edit rebuilds the same head from the relay's copy).
3331    if !session.is_valid() {
3332        return Ok(());
3333    }
3334    if let Ok((ed, _)) = control::open_control_edition(&wrap, &control) {
3335        crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, community.root_epoch.0)?;
3336    }
3337    Ok(())
3338}
3339
3340/// Merge our OWN just-published Role/Grant into the locally stored roster.
3341///
3342/// v2 persists the roster only inside `follow_control`, so a role or grant we
3343/// just published is invisible to every sync local read (entitlement, capability
3344/// gates, the next grant) until the next fold. This writes what we are already
3345/// authorized to have written; the next fold recomputes from the plane and
3346/// converges. Mirrors the fold's own write, so the stored `roles_at` is left
3347/// alone — a real edition always outranks this optimistic merge.
3348fn merge_local_roster(cid_hex: &str, role: Option<&crate::community::roles::Role>, grant: Option<&crate::community::roles::MemberGrant>) {
3349    let mut roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3350    if let Some(r) = role {
3351        match roster.roles.iter_mut().find(|x| x.role_id == r.role_id) {
3352            Some(slot) => *slot = r.clone(),
3353            None => roster.roles.push(r.clone()),
3354        }
3355    }
3356    if let Some(g) = grant {
3357        match roster.grants.iter_mut().find(|x| x.member == g.member) {
3358            Some(slot) => *slot = g.clone(),
3359            None => roster.grants.push(g.clone()),
3360        }
3361    }
3362    let at = crate::db::community::get_community_roles_at(cid_hex).unwrap_or(0);
3363    if let Err(e) = crate::db::community::set_community_roles(cid_hex, &roster, at) {
3364        crate::log_warn!("v2: local roster merge failed (heals on the next control fold): {e}");
3365    }
3366}
3367
3368/// Create or edit a Role (vsk 1, CORD-04 §2). `role.role_id` is the coordinate; a
3369/// rename or permission change is a versioned edit of the same id. Gated on the
3370/// reader side by `MANAGE_ROLES` + outrank.
3371pub async fn set_role<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role: &crate::community::roles::Role) -> Result<(), String> {
3372    let session = SessionGuard::capture();
3373    super::roles::validate_role(role)?;
3374    let content = super::roles::role_content_json(role)?;
3375    let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).ok_or("role_id must be 32-byte hex")?;
3376    publish_control_edition(transport, community, &session, vsk::ROLE, &role_id, &content).await
3377}
3378
3379/// Grant or revoke a member's Roles (vsk 3, CORD-04 §2). Empty `role_ids` is a
3380/// revoke. Gated on the reader side by `MANAGE_ROLES` + outrank of every role + the
3381/// member.
3382pub async fn grant_roles<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey, role_ids: Vec<String>) -> Result<(), String> {
3383    let session = SessionGuard::capture();
3384    let grant = crate::community::roles::MemberGrant { member: member.to_hex(), role_ids };
3385    let content = super::roles::grant_content_json(&grant)?;
3386    let eid = super::derive::grant_locator(community.id(), &member.to_bytes());
3387    publish_control_edition(transport, community, &session, vsk::GRANT, &eid, &content).await
3388}
3389
3390/// The community's @admin role id: the folded Server-scope ADMIN_ALL role when one
3391/// exists, else (with `create_if_missing`) a DETERMINISTIC mint — the same id on
3392/// every device, so concurrent grants converge as editions of ONE entity instead
3393/// of forking two Admin roles.
3394pub async fn ensure_admin_role<T: Transport + ?Sized>(
3395    transport: &T,
3396    community: &CommunityV2,
3397    view: &AuthorityView,
3398    create_if_missing: bool,
3399) -> Result<Option<String>, String> {
3400    use crate::community::roles::{Permissions, Role, RoleScope};
3401    if let Some(r) = view
3402        .roles
3403        .roles
3404        .iter()
3405        .find(|r| matches!(r.scope, RoleScope::Server) && r.permissions.contains(Permissions::ADMIN_ALL))
3406    {
3407        return Ok(Some(r.role_id.clone()));
3408    }
3409    if !create_if_missing {
3410        return Ok(None);
3411    }
3412    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3413    let role_id = crate::crypto::sha256_hex(format!("vector/v2/role/admin/{cid_hex}").as_bytes());
3414    set_role(transport, community, &Role::admin(role_id.clone())).await?;
3415    Ok(Some(role_id))
3416}
3417
3418/// Grant the @admin role (minting it deterministically when absent), MERGED into
3419/// the member's existing grant — a grant entity replaces whole (CORD-04 §2), so a
3420/// blind push would erase their other roles. Owner-only: the position-1 Admin is
3421/// manageable only by position 0 (an equal never outranks it), and refusing
3422/// before any publish keeps an unauthorized edition of the DETERMINISTIC admin
3423/// entity from advancing this device's own floor onto a head readers reject.
3424pub async fn grant_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
3425    // Guard spans the multi-page fetch below: a swap mid-fetch must not let the
3426    // downstream publish's own (post-swap) guard write account A's floor into B.
3427    let session = SessionGuard::capture();
3428    let my_pk = me_pk()?;
3429    if my_pk != community.owner()? {
3430        return Err("only the community owner can grant @admin".to_string());
3431    }
3432    let view = fetch_authority(transport, community).await;
3433    if !session.is_valid() {
3434        return Err("account changed during grant".to_string());
3435    }
3436    let member_hex = member.to_hex();
3437    require_grant_head(community, &view, &member_hex)?;
3438    let role_id = ensure_admin_role(transport, community, &view, true)
3439        .await?
3440        .expect("create_if_missing yields an id");
3441    let mut role_ids = view
3442        .roles
3443        .grants
3444        .iter()
3445        .find(|g| g.member == member_hex)
3446        .map(|g| g.role_ids.clone())
3447        .unwrap_or_default();
3448    if role_ids.contains(&role_id) {
3449        return Ok(()); // already admin — don't bump the grant edition for nothing.
3450    }
3451    role_ids.push(role_id);
3452    grant_roles(transport, community, member, role_ids).await
3453}
3454
3455/// Strip the @admin role from the member's grant, preserving their other roles.
3456/// A no-op when they don't hold it. Owner-only, like [`grant_admin`].
3457pub async fn revoke_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
3458    let session = SessionGuard::capture();
3459    let my_pk = me_pk()?;
3460    if my_pk != community.owner()? {
3461        return Err("only the community owner can revoke @admin".to_string());
3462    }
3463    let view = fetch_authority(transport, community).await;
3464    if !session.is_valid() {
3465        return Err("account changed during revoke".to_string());
3466    }
3467    let member_hex = member.to_hex();
3468    require_grant_head(community, &view, &member_hex)?;
3469    let Some(role_id) = ensure_admin_role(transport, community, &view, false).await? else {
3470        return Ok(()); // no admin role exists — nothing to revoke.
3471    };
3472    let mut role_ids = view
3473        .roles
3474        .grants
3475        .iter()
3476        .find(|g| g.member == member_hex)
3477        .map(|g| g.role_ids.clone())
3478        .unwrap_or_default();
3479    let before = role_ids.len();
3480    role_ids.retain(|r| r != &role_id);
3481    if role_ids.len() == before {
3482        return Ok(());
3483    }
3484    grant_roles(transport, community, member, role_ids).await
3485}
3486
3487/// A grant replaces whole — refuse the merge when this member's grant is FLOORED
3488/// locally but no head folded (withheld / evicted): a blind push at that point
3489/// would erase their other roles at a higher version.
3490fn require_grant_head(community: &CommunityV2, view: &AuthorityView, member_hex: &str) -> Result<(), String> {
3491    let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(member_hex) else {
3492        return Err("malformed member key".to_string());
3493    };
3494    let eid_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &member));
3495    if view.floored.contains(&eid_hex) && !view.head_entities.contains(&eid_hex) {
3496        return Err("this member's current grant could not be fetched; try again once relays serve the control plane".to_string());
3497    }
3498    Ok(())
3499}
3500
3501/// Replace the Banlist (vsk 4, CORD-04 §4) with `banned` (lowercase-hex npubs), the
3502/// whole list on every edit. Gated on the reader side by `BAN`.
3503pub async fn set_banlist<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, banned: &[String]) -> Result<(), String> {
3504    let session = SessionGuard::capture();
3505    super::roles::validate_banlist(banned)?;
3506    let content = super::roles::banlist_content_json(banned)?;
3507    let eid = super::derive::banlist_locator(community.id());
3508    publish_control_edition(transport, community, &session, vsk::BANLIST, &eid, &content).await
3509}
3510
3511/// Edit the community metadata (vsk 0, CORD-02 §6). Gated on the reader side by
3512/// `MANAGE_METADATA`.
3513pub async fn edit_community_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, meta: &control::CommunityMetadata) -> Result<(), String> {
3514    let session = SessionGuard::capture();
3515    control::validate_community_metadata(meta).map_err(|e| e.to_string())?;
3516    let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
3517    publish_control_edition(transport, community, &session, vsk::COMMUNITY_METADATA, &community.id().0, &content).await
3518}
3519
3520/// Persist a freshly-published icon/banner onto the held row and return the fresh
3521/// row. Reloads under the community's follow lock: `save_community_v2` is a
3522/// whole-row save that prunes channels absent from the passed struct, so writing
3523/// a stale pre-upload copy would drop rows a concurrent fold just landed.
3524pub async fn persist_community_image(
3525    id: &crate::community::CommunityId,
3526    img: control::ImageRef,
3527    is_banner: bool,
3528    session: &SessionGuard,
3529) -> Option<CommunityV2> {
3530    let lock = super::realtime::follow_lock(id);
3531    let _guard = lock.lock().await;
3532    if !session.is_valid() {
3533        return None;
3534    }
3535    let mut fresh = crate::db::community::load_community_v2(id).ok()??;
3536    if is_banner {
3537        fresh.banner = Some(img);
3538    } else {
3539        fresh.icon = Some(img);
3540    }
3541    crate::db::community::save_community_v2(&fresh).ok()?;
3542    Some(fresh)
3543}
3544
3545/// Add or edit a channel's metadata (vsk 2, CORD-03 §2). `channel_id` is the
3546/// coordinate. Gated on the reader side by `MANAGE_CHANNELS`.
3547pub async fn edit_channel_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata) -> Result<(), String> {
3548    let session = SessionGuard::capture();
3549    let my_pk = me_pk()?;
3550    ensure_channel_manager(community, &my_pk)?;
3551    let old_name = community.channel(channel_id).map(|c| c.name.clone());
3552    // Public → private CONVERSION is a key rotation (CORD-03 §2) this build doesn't
3553    // mint yet — refuse the flag flip rather than publish an edition no reader can
3554    // key (members would keep posting on the root-derived plane, splitting the
3555    // channel). Private → public works (readers heal to the root derivation).
3556    if meta.private {
3557        if let Some(held) = community.channel(channel_id) {
3558            if !held.private {
3559                return Err("converting a public channel to private is not supported yet".to_string());
3560            }
3561        }
3562    }
3563    control::validate_channel_metadata(meta).map_err(|e| e.to_string())?;
3564    let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
3565    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
3566    // Apply locally too. The fold is the authority but runs later, so without this
3567    // an edit we just made reads back stale until some future control pass — the
3568    // rename appears to have silently failed.
3569    if !session.is_valid() {
3570        return Ok(());
3571    }
3572    if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
3573        if let Some(ch) = held.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
3574            ch.name = meta.name.clone();
3575            ch.private = meta.private;
3576            ch.voice = meta.voice;
3577            ch.meta_custom = meta.custom.clone();
3578            ch.meta_extra = meta.extra.clone();
3579            crate::db::community::save_community_v2(&held)?;
3580        }
3581    }
3582    // Keep the companion access role's label in step with the channel it gates.
3583    if meta.private {
3584        if let Some(old) = old_name.filter(|o| *o != meta.name) {
3585            rename_channel_access_role(transport, community, channel_id, &old, &meta.name, &session).await;
3586        }
3587    }
3588    Ok(())
3589}
3590
3591/// Rename a private channel's companion access role to follow the channel (CORD-04 §2).
3592/// Best-effort and never fatal: the channel rename has already published, and a role's
3593/// name is cosmetic — entitlement is carried by the scope, not the label.
3594///
3595/// Only renames a label still equal to the channel's OLD name, so a deliberately
3596/// customised role name survives a channel rename untouched.
3597async fn rename_channel_access_role<T: Transport + ?Sized>(
3598    transport: &T,
3599    community: &CommunityV2,
3600    channel_id: &ChannelId,
3601    old_name: &str,
3602    new_name: &str,
3603    session: &SessionGuard,
3604) {
3605    let (Ok(my_pk), Ok(owner)) = (me_pk(), community.owner()) else {
3606        return;
3607    };
3608    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3609    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
3610    // Fetched, not cached: `set_role` republishes the WHOLE role body, so a stale
3611    // cache would clobber a permission edit this client has not folded yet.
3612    let mut roster = fetch_authority(transport, community).await.roles;
3613    let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3614    for r in cached.roles {
3615        if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
3616            roster.roles.push(r);
3617        }
3618    }
3619    if !session.is_valid() {
3620        return;
3621    }
3622    // MANAGE_CHANNELS got us the rename; the role edition needs MANAGE_ROLES + outrank
3623    // of its own. Publishing one readers reject would wedge our later, legitimate role
3624    // edits behind a rejected chain, so verify before publishing rather than after.
3625    let (me_hex, owner_hex) = (my_pk.to_hex(), owner.to_hex());
3626    if !roster.is_authorized_in(&me_hex, Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
3627        return;
3628    }
3629    // Same selector `grant_channel_access` vends: the permission-less scoped role. A
3630    // per-channel moderator role sharing the scope is NOT the access list.
3631    let Some(mut role) = roster
3632        .channel_roles(&chan_hex)
3633        .into_iter()
3634        .find(|r| r.permissions == crate::community::roles::Permissions::empty() && r.name == old_name)
3635        .cloned()
3636    else {
3637        return;
3638    };
3639    if !roster.can_act_on_position(&me_hex, Some(&owner_hex), role.position, crate::community::roles::Permissions::MANAGE_ROLES) {
3640        return;
3641    }
3642    role.name = new_name.to_string();
3643    if let Err(e) = set_role(transport, community, &role).await {
3644        crate::log_warn!("v2: channel renamed but its access role did not follow: {e}");
3645        return;
3646    }
3647    if session.is_valid() {
3648        merge_local_roster(&cid_hex, Some(&role), None);
3649    }
3650}
3651
3652/// The local mirror of the reader's `MANAGE_CHANNELS` fold gate (CORD-03 §2): the
3653/// owner, or a roster-authorized manager who isn't banned. Refusing BEFORE any
3654/// publish keeps an unauthorized device from advancing its own edition floor onto
3655/// a head every reader rejects (wedging its later, legitimately-authorized edits
3656/// behind a rejected chain).
3657fn ensure_channel_manager(community: &CommunityV2, me: &PublicKey) -> Result<(), String> {
3658    let owner = community.owner()?;
3659    if *me == owner {
3660        return Ok(());
3661    }
3662    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3663    let me_hex = me.to_hex();
3664    if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&me_hex) {
3665        return Err("you are banned from this community".to_string());
3666    }
3667    let roster = crate::db::community::get_community_roles(&cid_hex)?;
3668    if roster.is_authorized(&me_hex, Some(&owner.to_hex()), crate::community::roles::Permissions::MANAGE_CHANNELS) {
3669        Ok(())
3670    } else {
3671        Err("managing channels here needs the MANAGE_CHANNELS permission".to_string())
3672    }
3673}
3674
3675/// Create a new PUBLIC channel (CORD-03 §2): mint a fresh id, publish its metadata
3676/// edition (vsk 2), and add it to the held community. A Public channel derives its Chat
3677/// Plane from the `community_root` (no per-channel key), so other members fold it in on
3678/// their next control follow with nothing to distribute. Returns the new channel id.
3679/// Reader-gated by `MANAGE_CHANNELS`.
3680pub async fn create_public_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
3681    let channel_id = ChannelId(super::super::random_32());
3682    create_public_channel_with_id(transport, community, name, channel_id).await?;
3683    Ok(channel_id)
3684}
3685
3686/// [`create_public_channel`] with a CALLER-CHOSEN id — the migration-only entry point
3687/// (§migration) that reuses a v1 channel's id so chat history stitches through the flip.
3688/// Asserts the id isn't already live in a DIFFERENT held v2 community before minting.
3689pub async fn create_public_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
3690    let session = SessionGuard::capture();
3691    // Serialize with the follow worker: the save below writes the WHOLE community
3692    // row from this caller's struct, so an unserialized concurrent follow adopting
3693    // a rotation would be rolled back to a stale root (a deaf community).
3694    let lock = super::realtime::follow_lock(community.id());
3695    let _guard = lock.lock().await;
3696    let my_pk = me_pk()?;
3697    ensure_channel_manager(community, &my_pk)?;
3698    assert_channel_id_free(&channel_id, community.id())?;
3699    let meta = control::ChannelMetadata { name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() };
3700    control::validate_channel_metadata(&meta).map_err(|e| e.to_string())?;
3701    let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
3702    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
3703    if !session.is_valid() {
3704        return Err("account changed during channel create".to_string());
3705    }
3706    // Add locally + persist so the creator can post immediately (peers fold it in).
3707    let mut updated = community.clone();
3708    updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: false, key: None, epoch: updated.root_epoch, voice: None, meta_custom: None, meta_extra: Default::default() });
3709    crate::db::community::save_community_v2(&updated)?;
3710    Ok(())
3711}
3712
3713/// Refuse a channel id already live in a DIFFERENT held v2 community — the same
3714/// cross-community hijack the `save_community_v2` guard forecloses, checked up front so a
3715/// migration twin never adopts an id it doesn't own. A collision with a v1-owned row is
3716/// fine (that's the whole point — the flip re-parents it); only a foreign v2 owner blocks.
3717fn assert_channel_id_free(channel_id: &ChannelId, community_id: &crate::community::CommunityId) -> Result<(), String> {
3718    let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
3719    if let Ok(Some(existing)) = crate::db::community::community_id_for_channel(&ch_hex) {
3720        let mine = crate::simd::hex::bytes_to_hex_32(&community_id.0);
3721        let existing_id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&existing));
3722        if existing != mine
3723            && matches!(crate::db::community::community_protocol(&existing_id), Ok(Some(crate::community::ConcordProtocol::V2)))
3724        {
3725            return Err("channel id is already live in another v2 community".to_string());
3726        }
3727    }
3728    Ok(())
3729}
3730
3731/// Create a new PRIVATE channel (CORD-03 §2): mint a fresh id + an independent
3732/// random key at channel-epoch 1, mint a companion channel-scoped Role that is
3733/// the channel's access list (CORD-04 §2), deliver the key to the entitled over
3734/// the rekey plane (CORD-06 §1), then announce the channel (vsk 2, `private`).
3735/// Epoch 0 is the root generation ("the first privatisation is epoch 1"), so the
3736/// delivery commits its continuity to `(0, community_root)` — verifiable by every
3737/// member and bound to THIS community's root. The key ships BEFORE the
3738/// announcement: an aborted attempt leaves only an unannounced crate (invisible),
3739/// and a retry mints a fresh id, so there is no same-coordinate double-mint to
3740/// fork on. Live public links are refreshed; they carry no private key, so this
3741/// only re-states the public set.
3742pub async fn create_private_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
3743    let channel_id = ChannelId(super::super::random_32());
3744    create_private_channel_with_id(transport, community, name, channel_id).await?;
3745    Ok(channel_id)
3746}
3747
3748/// The companion Role minted alongside a Private channel — the channel's access
3749/// list (CORD-04 §2 `scope: {"kind":"channel"}`). Same name as the channel, and
3750/// **no permission bits**: it confers read access, which is key possession, never
3751/// authority. Position sits below every management role for the same reason.
3752pub fn channel_access_role(channel_id: &ChannelId, name: &str) -> crate::community::roles::Role {
3753    use crate::community::roles::{Permissions, Role, RoleScope};
3754    Role {
3755        role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
3756        name: name.to_string(),
3757        position: u32::MAX - 1,
3758        permissions: Permissions::empty(),
3759        scope: RoleScope::Channel(crate::simd::hex::bytes_to_hex_32(&channel_id.0)),
3760        color: 0,
3761    }
3762}
3763
3764/// [`create_private_channel`] with a CALLER-CHOSEN id — the migration-only entry point
3765/// (§migration) reusing a v1 private channel's id so history stitches through the flip.
3766pub async fn create_private_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
3767    let session = SessionGuard::capture();
3768    // Serialize with the follow worker across the whole fetch→publish→save span
3769    // (the memberlist fetch is seconds long; an unserialized follow adopting a
3770    // rotation meanwhile would be rolled back by the whole-row save below).
3771    let lock = super::realtime::follow_lock(community.id());
3772    let _guard = lock.lock().await;
3773    let signer = crate::signer::active_signer()?;
3774    let my_pk = me_pk()?;
3775    ensure_channel_manager(community, &my_pk)?;
3776    assert_channel_id_free(&channel_id, community.id())?;
3777    let meta = control::ChannelMetadata { name: name.to_string(), private: true, voice: None, deleted: None, custom: None, extra: Default::default() };
3778    control::validate_channel_metadata(&meta).map_err(|e| e.to_string())?;
3779    let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
3780
3781    let channel_key = super::super::random_32();
3782    let epoch = Epoch(1);
3783
3784    // The channel's access list: a companion channel-scoped Role (CORD-04 §2),
3785    // granted to me so the creator is entitled from the first edition.
3786    let access_role = channel_access_role(&channel_id, name);
3787    let access_role_ids = vec![access_role.role_id.clone()];
3788
3789    // Recipients are the ENTITLED, not the memberlist: CORD-03's private channel
3790    // is "readable only by granted role-holders". At create that is me (plus the
3791    // owner, who is always entitled) — everyone else keys up when granted.
3792    let owner = community.owner()?;
3793    let mut recipients = vec![my_pk];
3794    if owner != my_pk {
3795        recipients.push(owner);
3796    }
3797    let prev_commit = super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
3798    let mut blobs = Vec::with_capacity(recipients.len());
3799    for r in &recipients {
3800        blobs.push(
3801            rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(channel_id), epoch, &channel_key)
3802                .await
3803                .map_err(|e| e.to_string())?,
3804        );
3805    }
3806    let group = channel_rekey_group_key(&community.community_root, &channel_id, epoch);
3807    let at_secs = now_ms() / 1000;
3808    let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(channel_id), epoch, Epoch(0), &prev_commit, &blobs, at_secs, my_authority_citation(community, &my_pk).as_ref())
3809        .await
3810        .map_err(|e| e.to_string())?;
3811    if !session.is_valid() {
3812        return Err("account changed during channel create".to_string());
3813    }
3814    for c in &chunks {
3815        transport.publish_durable(c, &community.relays).await?;
3816    }
3817    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
3818    if !session.is_valid() {
3819        return Err("account changed during channel create".to_string());
3820    }
3821    // Publish the access list AFTER the channel exists, so a peer folding the
3822    // Role always resolves the channel it scopes to. A failure here leaves a
3823    // channel only its creator can read — recoverable by re-granting, never a
3824    // leak.
3825    set_role(transport, community, &access_role).await?;
3826    grant_roles(transport, community, &my_pk, access_role_ids.clone()).await?;
3827    if !session.is_valid() {
3828        return Err("account changed during channel create".to_string());
3829    }
3830    // The fold is the authority but runs later; without this the creator is not
3831    // yet entitled to their own channel and the next grant finds no access role.
3832    merge_local_roster(
3833        &crate::simd::hex::bytes_to_hex_32(&community.id().0),
3834        Some(&access_role),
3835        Some(&crate::community::roles::MemberGrant { member: my_pk.to_hex(), role_ids: access_role_ids }),
3836    );
3837    // A leave/delete raced the create: saving would resurrect the community row.
3838    if crate::db::community::community_protocol(community.id())?.is_none() {
3839        return Err("community removed during channel create".to_string());
3840    }
3841    let mut updated = community.clone();
3842    updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: true, key: Some(channel_key), epoch, voice: None, meta_custom: None, meta_extra: Default::default() });
3843    crate::db::community::save_community_v2(&updated)?;
3844    // Archive the epoch-1 key so this channel's history stays readable across its
3845    // future rotations (CORD-03 §3).
3846    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3847    crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&channel_id.0), epoch.0, &channel_key)?;
3848    // Re-state live links. They carry no private key (CORD-05 §2 — a link's
3849    // audience holds no Role), so this only refreshes the public set.
3850    let _ = refresh_public_links(transport, &updated).await;
3851    Ok(())
3852}
3853
3854/// Tombstone a channel (CORD-03 §2, `deleted: true`) + drop it locally. Reader-gated by
3855// ── Receiving a key vend (CORD-03 "delivered on grant") ──────────────────────
3856
3857/// What a client should do with a vended Private-Channel key right now.
3858#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3859pub enum VendVerdict {
3860    /// Every rule passed — adopt the key.
3861    Accept,
3862    /// Cannot judge YET: our fold lags the grant it delivers. Park quietly and
3863    /// re-judge after the next control follow. NOT an anomaly — a lagging fold
3864    /// is the normal case for a vend that races its own Grant.
3865    Park(&'static str),
3866    /// Judged invalid against evidence that cannot become true later. Alarm-worthy.
3867    Refuse(&'static str),
3868}
3869
3870/// Judge a vended Private-Channel key against our OWN folded state.
3871///
3872/// The Grant is the authority half and rides the owner-rooted control plane, so
3873/// it cannot be forged; the vend is only delivery. Acceptance therefore rests
3874/// entirely on what our own fold proves — a bundle can never introduce a channel
3875/// our control plane doesn't define, which is what closes the hidden-channel
3876/// injection class.
3877///
3878/// `community` must already be the held (self-certified) community: the caller
3879/// resolves it by `community_id`, so a bundle naming a community we're not in is
3880/// never judged here at all.
3881pub fn judge_channel_key_vend(
3882    community: &CommunityV2,
3883    roster: &crate::community::roles::CommunityRoles,
3884    channel_id: &ChannelId,
3885    epoch: Epoch,
3886    sender_hex: &str,
3887) -> VendVerdict {
3888    let me = match me_pk() {
3889        Ok(pk) => pk.to_hex(),
3890        Err(_) => return VendVerdict::Park("no active identity"),
3891    };
3892    let owner_hex = match community.owner() {
3893        Ok(o) => o.to_hex(),
3894        Err(_) => return VendVerdict::Refuse("community has no resolvable owner"),
3895    };
3896    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
3897
3898    // (2) The channel must exist in OUR fold, and be private there. The bundle's
3899    // own claims are ignored: a vend may deliver a key, never define a channel.
3900    let Some(ch) = community.channel(channel_id) else {
3901        return VendVerdict::Park("channel not in our fold yet");
3902    };
3903    if !ch.private {
3904        // Never heals: our owner-rooted fold says this channel is public, so a
3905        // "private key" for it is a spoof, not a lagging view.
3906        return VendVerdict::Refuse("vend names a channel our fold says is public");
3907    }
3908
3909    // (5) Epoch sanity, BOTH directions. Below is superseded by the rotation that
3910    // produced our copy. Above matters more: the channel head is monotonic, so a
3911    // wildly-ahead epoch is not merely wrong, it is PERMANENT — every genuine
3912    // rotation afterwards lands at `head + 1`, is refused as stale, and the
3913    // channel dies for us with no heal path at all (not a rekey, not a re-grant,
3914    // not a refound). Rotations advance one epoch at a time, so a lead this large
3915    // is never a delivery we could place.
3916    if ch.key.is_some() && epoch.0 <= ch.epoch.0 {
3917        return VendVerdict::Refuse("superseded: we already hold this epoch or newer");
3918    }
3919    if epoch.0 > ch.epoch.0.saturating_add(MAX_VEND_EPOCH_LEAD) {
3920        return VendVerdict::Refuse("vend epoch is implausibly far ahead of the channel head");
3921    }
3922
3923    // (3) OUR fold must show US granted a role scoped to this channel. This is
3924    // the rule that kills the spoof class: an attacker cannot forge the Grant,
3925    // so they cannot make us accept a key for a channel we were never granted.
3926    if !roster.is_entitled(Some(&owner_hex), &me, &chan_hex, &[], &[]) {
3927        return VendVerdict::Park("our grant for this channel has not folded yet");
3928    }
3929
3930    // (4) The vendor must be entitled too — they hold the real key, so a wrong
3931    // key from them costs isolation, never confidentiality.
3932    if sender_hex != owner_hex && !roster.is_entitled(Some(&owner_hex), sender_hex, &chan_hex, &[], &[]) {
3933        return VendVerdict::Park("vendor's entitlement has not folded yet");
3934    }
3935
3936    VendVerdict::Accept
3937}
3938
3939/// How long an unprovable parked vend is kept. Deliberately long: the fallback
3940/// heal is the channel's next rotation, which may never come.
3941const PARKED_VEND_TTL_SECS: u64 = 30 * 24 * 3600;
3942
3943/// How far above our channel head a vend may claim to be. Generous — a keyless
3944/// cursor can lag a busy channel by many rotations — but bounded, because the
3945/// head is monotonic and an over-advance can never be walked back.
3946const MAX_VEND_EPOCH_LEAD: u64 = 1024;
3947
3948/// Re-judge every parked key vend for this community and adopt the ones that now
3949/// pass. Runs after a control follow (the fold moved, so verdicts can change) and
3950/// on the boot sweep.
3951///
3952/// Returns the channels newly keyed up.
3953pub fn absorb_parked_channel_keys(community: &CommunityV2, session: &SessionGuard) -> Vec<ChannelId> {
3954    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3955    let parked = match crate::db::community::get_pending_channel_keys(&cid_hex) {
3956        Ok(p) if !p.is_empty() => p,
3957        _ => return Vec::new(),
3958    };
3959    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3960    let mut adopted = Vec::new();
3961    let now = now_ms() / 1000;
3962    for p in parked {
3963        // Several candidates may name one channel (parking is open to any sender,
3964        // so a stranger can never suppress the entitled vendor's key by holding a
3965        // slot). Once one is seated the rest are moot.
3966        if adopted.iter().any(|c: &ChannelId| crate::simd::hex::bytes_to_hex_32(&c.0) == p.channel_id) {
3967            let _ = crate::db::community::drop_pending_channel_key(p.id);
3968            continue;
3969        }
3970        // A vend we were never able to prove is not kept forever: an admin who
3971        // adds then immediately removes someone leaves a row nothing will ever
3972        // discharge. Generous by design — the alternative heal (the channel's
3973        // next rotation) can be arbitrarily far away, so this is hygiene, not a
3974        // deadline.
3975        if now.saturating_sub(p.received_at.max(0) as u64) > PARKED_VEND_TTL_SECS {
3976            let _ = crate::db::community::drop_pending_channel_key(p.id);
3977            continue;
3978        }
3979        let Some(id_bytes) = crate::simd::hex::hex_to_bytes_32_checked(&p.channel_id) else {
3980            let _ = crate::db::community::drop_pending_channel_key(p.id);
3981            continue;
3982        };
3983        let channel_id = ChannelId(id_bytes);
3984        match judge_channel_key_vend(community, &roster, &channel_id, Epoch(p.epoch), &p.sender) {
3985            VendVerdict::Accept => {
3986                if !session.is_valid() {
3987                    return adopted;
3988                }
3989                // First delivery vs rotation. A keyless channel must bypass the
3990                // monotonic guard: it sits at the epoch-0 cursor, and a peer that
3991                // mints born-private channels at epoch 0 vends that same epoch, so
3992                // `new > current` would refuse the only key on offer.
3993                let keyless = community.channel(&channel_id).is_some_and(|c| c.key.is_none());
3994                let seated = if keyless {
3995                    crate::db::community::seat_channel_key(&cid_hex, &p.channel_id, p.epoch, &p.key)
3996                } else {
3997                    crate::db::community::advance_channel_epoch(&cid_hex, &p.channel_id, p.epoch, &p.key).map(|_| ())
3998                };
3999                if let Err(e) = seated {
4000                    crate::log_warn!("v2: adopting a vended channel key failed: {e}");
4001                    continue;
4002                }
4003                // The key landed — every other candidate for this channel is moot.
4004                let _ = crate::db::community::drop_pending_channel_keys_for(&cid_hex, &p.channel_id);
4005                adopted.push(channel_id);
4006            }
4007            VendVerdict::Refuse(why) => {
4008                crate::log_warn!("v2: refused a vended channel key for {}: {why}", p.channel_id);
4009                // Only THIS candidate — a sibling may still be the genuine vend.
4010                let _ = crate::db::community::drop_pending_channel_key(p.id);
4011            }
4012            // Quiet by design: the fold simply hasn't caught up.
4013            VendVerdict::Park(_) => {}
4014        }
4015    }
4016    adopted
4017}
4018
4019/// Grant `member` read access to a Private channel (CORD-03 "delivered on
4020/// grant"): publish a Grant adding the channel's access role, then vend the key
4021/// as a CORD-05 §6 Direct Invite whose bundle carries exactly the channels they
4022/// are now entitled to.
4023///
4024/// The Grant is the authority half and rides the owner-rooted control plane, so
4025/// it cannot be forged; the vend is only delivery. A recipient accepts the key
4026/// solely on the strength of their OWN fold showing this grant — the bundle can
4027/// never introduce a channel their control plane doesn't define.
4028pub async fn grant_channel_access<T: Transport + ?Sized>(
4029    transport: &T,
4030    community: &CommunityV2,
4031    channel_id: &ChannelId,
4032    member: &PublicKey,
4033) -> Result<(), String> {
4034    let session = SessionGuard::capture();
4035    let my_pk = me_pk()?;
4036    let ch = community.channel(channel_id).ok_or("unknown channel")?;
4037    if !ch.private {
4038        return Err("channel is public — every member already reads it".to_string());
4039    }
4040    if ch.key.is_none() {
4041        return Err("we hold no key for this channel, so we cannot vend it".to_string());
4042    }
4043    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
4044    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
4045    let owner_hex = community.owner()?.to_hex();
4046    // A Grant REPLACES the member's role set, so the union it is built from must
4047    // be CURRENT: a stale local roster would silently strip every role this
4048    // client hasn't folded yet. Fetch the authority fresh rather than trusting
4049    // the cache, and merge the local view on top so a role we just published
4050    // ourselves (which the plane has but no fold has read back) survives too.
4051    let mut roster = fetch_authority(transport, community).await.roles;
4052    let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
4053    for r in cached.roles {
4054        if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
4055            roster.roles.push(r);
4056        }
4057    }
4058    for g in cached.grants {
4059        if !roster.grants.iter().any(|x| x.member == g.member) {
4060            roster.grants.push(g);
4061        }
4062    }
4063    if !session.is_valid() {
4064        return Err("account changed during grant".to_string());
4065    }
4066    // Reader-gated by MANAGE_ROLES, like any Grant; narrowed to this channel so
4067    // a channel-scoped manager can run its own access list.
4068    if !roster.is_authorized_in(&my_pk.to_hex(), Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
4069        return Err("not authorized to manage this channel's access".to_string());
4070    }
4071    // The channel's roles are ordered by AUTHORITY, so `.first()` is the most
4072    // privileged — granting read access must never hand out a per-channel
4073    // moderator role that happens to share the scope. Pick the permission-less
4074    // one: conferring read access is exactly what carries no authority.
4075    let role_id = roster
4076        .channel_roles(&chan_hex)
4077        .into_iter()
4078        .find(|r| r.permissions == crate::community::roles::Permissions::empty())
4079        .map(|r| r.role_id.clone())
4080        .ok_or("channel has no permission-less access role to grant")?;
4081
4082    let mut role_ids: Vec<String> = roster.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
4083    if !role_ids.contains(&role_id) {
4084        role_ids.push(role_id.clone());
4085    }
4086    grant_roles(transport, community, member, role_ids.clone()).await?;
4087    if !session.is_valid() {
4088        return Err("account changed during grant".to_string());
4089    }
4090    merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids }));
4091    // Settle the vend against the Grant we JUST published — the fold lags it.
4092    let bundle = bundle_of_with_overlay(
4093        community,
4094        BundleAudience::Member(*member),
4095        Some(my_pk),
4096        None,
4097        None,
4098        std::slice::from_ref(&role_id),
4099        &[],
4100    );
4101    let signer = crate::signer::active_signer()?;
4102    let wrap = invite::build_direct_invite_signed(&signer, my_pk, member, &bundle).await.map_err(|e| e.to_string())?;
4103    if !session.is_valid() {
4104        return Err("account changed before vending the key".to_string());
4105    }
4106    transport.publish(&wrap, &community.relays).await?;
4107    Ok(())
4108}
4109
4110/// Revoke `member`'s read access to a Private channel (CORD-03 "rekeyed on
4111/// removal"): drop the channel's access role from their Grant, then rotate the
4112/// channel to its next epoch delivering the fresh key to everyone still
4113/// entitled (CORD-06). The revoked member keeps whatever history they already
4114/// read — a rekey protects the future, never the past.
4115pub async fn revoke_channel_access<T: Transport + ?Sized>(
4116    transport: &T,
4117    community: &CommunityV2,
4118    channel_id: &ChannelId,
4119    member: &PublicKey,
4120) -> Result<(), String> {
4121    let session = SessionGuard::capture();
4122    let my_pk = me_pk()?;
4123    let ch = community.channel(channel_id).ok_or("unknown channel")?;
4124    if !ch.private {
4125        return Err("channel is public — there is no access to revoke".to_string());
4126    }
4127    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
4128    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
4129    let owner_hex = community.owner()?.to_hex();
4130    // Same replace-not-merge hazard as the grant: the retained set must be built
4131    // from a CURRENT roster or this revoke strips roles we simply hadn't folded.
4132    let mut roster = fetch_authority(transport, community).await.roles;
4133    let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
4134    for r in cached.roles {
4135        if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
4136            roster.roles.push(r);
4137        }
4138    }
4139    for g in cached.grants {
4140        if !roster.grants.iter().any(|x| x.member == g.member) {
4141            roster.grants.push(g);
4142        }
4143    }
4144    if !session.is_valid() {
4145        return Err("account changed during revoke".to_string());
4146    }
4147    if !roster.is_authorized_in(&my_pk.to_hex(), Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
4148        return Err("not authorized to manage this channel's access".to_string());
4149    }
4150    if *member == community.owner()? {
4151        return Err("the owner is supreme and cannot be removed".to_string());
4152    }
4153    let access_ids = roster.channel_role_ids(&chan_hex);
4154    // Without the access list this revoke is a no-op that still ROTATES, and the
4155    // rotation's recipient filter would match nobody — cutting off every
4156    // legitimately entitled member. Refuse rather than mass-evict.
4157    if access_ids.is_empty() {
4158        return Err("this channel's access role has not folded yet — retry once the control plane serves it".to_string());
4159    }
4160    let remaining: Vec<String> = roster
4161        .roles_of(&member.to_hex())
4162        .map(|r| r.role_id.clone())
4163        .filter(|id| !access_ids.contains(id))
4164        .collect();
4165    grant_roles(transport, community, member, remaining.clone()).await?;
4166    if !session.is_valid() {
4167        return Err("account changed during revoke".to_string());
4168    }
4169    merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids: remaining }));
4170    // Rotate so the removal actually severs them (CORD-06 §1). The revoked
4171    // member is excluded from the recipient set by the overlay, since the fold
4172    // has not yet caught the Grant we just published.
4173    rekey_channel_excluding(transport, community, channel_id, &roster, &access_ids, member).await
4174}
4175
4176/// Rotate one Private channel to its next epoch, delivering the fresh key to
4177/// everyone entitled EXCEPT `removed` (CORD-06 §1 single-channel rekey).
4178///
4179/// `roster` must be the caller's CURRENT view (fetched, not the local cache):
4180/// the recipient set is built from it, so a cached roster silently drops every
4181/// member granted since this client last folded — they keep a dead key with no
4182/// heal path. `access_ids` is that roster's access-role set for this channel;
4183/// `removed` is excluded explicitly, since the revoking Grant was published
4184/// moments ago and no fold has caught it.
4185async fn rekey_channel_excluding<T: Transport + ?Sized>(
4186    transport: &T,
4187    community: &CommunityV2,
4188    channel_id: &ChannelId,
4189    roster: &crate::community::roles::CommunityRoles,
4190    access_ids: &[String],
4191    removed: &PublicKey,
4192) -> Result<(), String> {
4193    let session = SessionGuard::capture();
4194    // Whole-row save below — serialize with the follow worker (see create_*_channel).
4195    let lock = super::realtime::follow_lock(community.id());
4196    let _guard = lock.lock().await;
4197    let signer = crate::signer::active_signer()?;
4198    let my_pk = me_pk()?;
4199    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
4200    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
4201    let ch = community.channel(channel_id).ok_or("unknown channel")?.clone();
4202    let old_key = ch.key.ok_or("we hold no key for this channel, so we cannot rotate it")?;
4203    let new_epoch = Epoch(ch.epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
4204    let owner = community.owner()?;
4205    let owner_hex = owner.to_hex();
4206
4207    // Everyone still entitled: the owner (always), me (the rotator must be able
4208    // to read what it rekeys), and every member the roster shows holding an
4209    // access role — minus the removal.
4210    let removed_hex = removed.to_hex();
4211    let mut recipients: Vec<PublicKey> = vec![my_pk];
4212    if owner != my_pk {
4213        recipients.push(owner);
4214    }
4215    for g in &roster.grants {
4216        if g.member == removed_hex || g.member == owner_hex {
4217            continue;
4218        }
4219        if !g.role_ids.iter().any(|id| access_ids.contains(id)) {
4220            continue;
4221        }
4222        if let Ok(pk) = PublicKey::parse(&g.member) {
4223            if !recipients.contains(&pk) {
4224                recipients.push(pk);
4225            }
4226        }
4227    }
4228    // Mint-or-reuse keyed by (channel, next epoch) so a retry after a partial
4229    // publish re-uses the same key instead of forking the epoch.
4230    let new_key = mint_or_reuse_rotation_key(&cid_hex, &chan_hex, new_epoch.0)?;
4231    let prev_commit = super::derive::epoch_key_commitment(ch.epoch, &old_key);
4232    let mut blobs = Vec::with_capacity(recipients.len());
4233    for r in &recipients {
4234        blobs.push(
4235            rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(*channel_id), new_epoch, &new_key)
4236                .await
4237                .map_err(|e| e.to_string())?,
4238        );
4239    }
4240    let group = channel_rekey_group_key(&community.community_root, channel_id, new_epoch);
4241    let at_secs = now_ms() / 1000;
4242    let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(*channel_id), new_epoch, ch.epoch, &prev_commit, &blobs, at_secs, my_authority_citation(community, &my_pk).as_ref())
4243        .await
4244        .map_err(|e| e.to_string())?;
4245    if !session.is_valid() {
4246        return Err("account changed during channel rekey".to_string());
4247    }
4248    for c in &chunks {
4249        transport.publish_durable(c, &community.relays).await?;
4250    }
4251    if !session.is_valid() {
4252        return Err("account changed during channel rekey".to_string());
4253    }
4254    if crate::db::community::community_protocol(community.id())?.is_none() {
4255        return Err("community removed during channel rekey".to_string());
4256    }
4257    // Adopt locally + archive, so our own history reads across the rotation.
4258    crate::db::community::advance_channel_epoch(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;
4259    crate::db::community::store_epoch_key(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;
4260    Ok(())
4261}
4262
4263/// Tombstone a channel (CORD-03 §2, `deleted: true`) + drop it locally. Reader-gated by
4264/// `MANAGE_CHANNELS`; the coordinate stays folded as a grave so peers hide it.
4265pub async fn delete_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, name: &str) -> Result<(), String> {
4266    let session = SessionGuard::capture();
4267    // Whole-row save below — serialize with the follow worker (see create_*_channel).
4268    let lock = super::realtime::follow_lock(community.id());
4269    let _guard = lock.lock().await;
4270    let my_pk = me_pk()?;
4271    ensure_channel_manager(community, &my_pk)?;
4272    // The tombstone carries the FULL held document (deleted flag set): a strict
4273    // reader treats an edition as the entity, so even a deletion must not strip
4274    // fields it didn't touch (CORD-02 §6).
4275    let mut meta = community.channel(channel_id).map(|c| c.metadata()).unwrap_or_else(|| control::ChannelMetadata {
4276        name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default(),
4277    });
4278    meta.deleted = Some(true);
4279    let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
4280    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
4281    if !session.is_valid() {
4282        return Err("account changed during channel delete".to_string());
4283    }
4284    let mut updated = community.clone();
4285    updated.channels.retain(|c| c.id.0 != channel_id.0);
4286    crate::db::community::save_community_v2(&updated)?;
4287    Ok(())
4288}
4289
4290// ── Live control-follow (CORD-02 §6 / CORD-03 §2) ────────────────────────────
4291
4292/// Re-fold this community's Control Plane and apply the current metadata +
4293/// **public** channel set to the held community, persisting any change. Called
4294/// when a control-plane wrap arrives in realtime (a rename, a new channel, an
4295/// edited description) so a long-running bot tracks the community mid-session
4296/// instead of freezing at its join-time view.
4297///
4298/// **Authority (CORD-04 §5):** the roster (roles/grants/banlist) folds first into
4299/// the owner-seeded authorized set ([`fold_authority`]), then each metadata/channel
4300/// edition is eligible only if its signer CURRENTLY holds the entity's management
4301/// bit (`MANAGE_METADATA`/`MANAGE_CHANNELS`) — so an authorized admin's edits fold,
4302/// a demoted one's drop. The owner is supreme, proven by the self-certifying
4303/// community_id (no network trust).
4304///
4305/// **Private channels are skipped here:** a Private channel's Chat-Plane key is
4306/// delivered over the rekey plane (or an invite bundle), never derivable from a
4307/// control edition alone. A new Private channel therefore surfaces only once
4308/// [`follow_rekeys`] delivers its key. Public channels derive from the
4309/// community_root, so they fold in directly.
4310///
4311/// Returns the updated community iff something changed (so the caller can skip a
4312/// redundant re-subscribe + refresh notification).
4313pub async fn follow_control<T: Transport + ?Sized>(
4314    transport: &T,
4315    community: &CommunityV2,
4316    session: &SessionGuard,
4317) -> Result<Option<CommunityV2>, String> {
4318    community.owner()?; // fail fast if the community is somehow unproven.
4319    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
4320    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
4321
4322    // Per-entity refuse-downgrade floors for the CURRENT epoch only. A head recorded
4323    // under a prior epoch is excluded, so that entity auto-bootstraps after a
4324    // Refounding (Armada accepts a compacted head across a dangling prev — matched).
4325    // A read error FAILS CLOSED: an empty map would silently re-open the rollback
4326    // window the floor exists to shut.
4327    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
4328        .into_iter()
4329        .filter(|(_, f)| f.0 == community.root_epoch.0)
4330        .map(|(entity, f)| (entity, (f.1, f.2, f.3)))
4331        .collect();
4332
4333    // Newest window first; page OLDER only while a tracking entity is gapped (its
4334    // floor link evicted from the window — H1/M8 refetch), bounded like the join
4335    // verifier. A withholding relay still converges to fail-closed after the cap.
4336    let mut editions: Vec<ParsedEdition> = Vec::new();
4337    let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
4338    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
4339    let mut oldest: Option<u64> = None;
4340    let mut until: Option<u64> = None;
4341    let mut fold = ControlFold { updated: None, heads: Vec::new(), gapped: false };
4342    let mut authority = AuthoritySet::owner_only();
4343    // Whether this round gave up with editions still unread. The follow is
4344    // procedural by design — process what arrives, converge with everyone else —
4345    // so a short read never blocks reading, writing or epoch adoption. It only
4346    // withholds the ROSTER cache below: caching a partial authority as this
4347    // device's baseline is the one step that outlives the round.
4348    let mut truncated = true;
4349    for _ in 0..FOLLOW_MAX_PAGES {
4350        // Quorum, DECLARED (the until→Full transport floor is gone): these
4351        // control reads tolerate a partial union — their fold semantics are
4352        // fail-safe on gaps (seeded banlists, withheld roster cache).
4353        let query = Query {
4354            kinds: vec![stream::KIND_WRAP],
4355            authors: vec![control.pk_hex()],
4356            until,
4357            limit: Some(FOLLOW_PAGE),
4358            evidence: crate::community::transport::Evidence::Quorum,
4359            ..Default::default()
4360        };
4361        let wraps = transport.fetch(&query, &community.relays).await?;
4362        // The `until` cursor is INCLUSIVE (a `-1` step can skip same-second siblings
4363        // at a page boundary); the wrap-id dedup makes re-served boundary events
4364        // free, and a page with nothing new means the relay is exhausted.
4365        let mut fresh = 0usize;
4366        for w in &wraps {
4367            if !seen_wraps.insert(w.id) {
4368                continue;
4369            }
4370            fresh += 1;
4371            let at = w.created_at.as_secs();
4372            if oldest.is_none_or(|o| at < o) {
4373                oldest = Some(at);
4374            }
4375            // Open + seal-verify every edition; authority is resolved by the roster
4376            // fold (CORD-04 §5), not by a signer filter here — an admin's edits fold.
4377            if let Ok((ed, _)) = control::open_control_edition(w, &control) {
4378                if seen.insert(ed.inner_id) {
4379                    editions.push(ed);
4380                }
4381            }
4382        }
4383        // Roster first (roles/grants/banlist → authorized set), then the authority-
4384        // gated metadata/channel fold over the same edition set.
4385        authority = fold_authority(community, &editions, &floors);
4386        fold = apply_control_fold(community, &editions, &floors, &authority);
4387        if !(fold.gapped || authority.gapped) {
4388            truncated = false; // nothing is gapped: this view is coherent
4389            break;
4390        }
4391        if fresh == 0 {
4392            // A FULL page with nothing new is a same-second wall no `until` steps
4393            // past, so older editions stay unreachable; a short page is the end
4394            // of the plane, and a gap in THAT is the relay withholding, not us
4395            // giving up early.
4396            truncated = wraps.len() >= FOLLOW_PAGE;
4397            break;
4398        }
4399        until = oldest;
4400    }
4401
4402    // The fetches straddled awaits; a swap since the guard was captured must not
4403    // write account A's control state into B.
4404    if !session.is_valid() {
4405        return Err("account changed during control follow".to_string());
4406    }
4407    // A leave/delete raced this follow: writing now would resurrect the community
4408    // row and orphan floor rows past delete_community's wipe.
4409    if crate::db::community::community_protocol(community.id())?.is_none() {
4410        return Ok(None);
4411    }
4412    // Persist advanced floors BEFORE the state save (a failed floor write must not
4413    // let saved state outrun its floor), stamping the epoch this fold ran under —
4414    // not the row's write-time value, which a concurrent re-founding can bump. Both
4415    // the metadata/channel heads and the roster/banlist heads advance their floors;
4416    // run the advance (v+1) and same-version convergence (fork tiebreak) paths.
4417    for h in fold.heads.iter().chain(authority.heads.iter()) {
4418        crate::db::community::set_edition_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, community.root_epoch.0)?;
4419        crate::db::community::converge_edition_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, community.root_epoch.0)?;
4420    }
4421    // Persist the authorized banlist content (retained/withholding folds carry None,
4422    // so the stored banlist is left intact — an anti-roster never silently un-bans).
4423    let mut authority_changed = false;
4424    // Ban marks MERGE (never replace): they must outlive both the ban and this window,
4425    // so a later un-ban can't resurrect a pre-ban Join. Persisted even when the banlist
4426    // itself was retained — the history is what the suppression reads.
4427    let _ = crate::db::community::merge_community_ban_marks(&cid_hex, &authority.banned_at);
4428    if let Some((banned, version)) = &authority.banlist_persist {
4429        let mut before = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
4430        crate::db::community::set_community_banlist(&cid_hex, banned, *version as i64)?;
4431        let mut after = banned.clone();
4432        before.sort();
4433        after.sort();
4434        authority_changed |= before != after;
4435    }
4436    // Persist the authorized roster so capabilities/roles stay sync LOCAL reads
4437    // (v1 parity: the passive follow folds, reads never fetch). Guarded like v1's
4438    // fetch path: only an aggregate built from roster editions at least as new as
4439    // the stored one may replace it — a withholding relay serving NO roster
4440    // editions folds an empty-but-ungapped aggregate (absence raises no gap flag),
4441    // and that must RETAIN the stored roster, never wipe standing.
4442    let newest_roster_at: i64 = editions
4443        .iter()
4444        .filter(|e| e.vsk == vsk::ROLE || e.vsk == vsk::GRANT || e.vsk == vsk::BANLIST)
4445        .map(|e| e.created_at as i64)
4446        .max()
4447        .unwrap_or(0);
4448    // Completeness gate: the `gapped` flag only covers entities present in the window.
4449    // A role/grant floored on this device but with ZERO editions fetched (aged out of
4450    // the paging reach) folds absent yet raises no gap — persisting would silently drop
4451    // it. So if any CURRENTLY-STORED entity is floored but folded no head this round,
4452    // RETAIN. A real revoke still folds a head (see select_authorized), so it persists.
4453    let stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
4454    let head_ents: std::collections::HashSet<&str> = authority.heads.iter().map(|h| h.entity_hex.as_str()).collect();
4455    let stored_complete = stored.roles.iter().all(|r| !floors.contains_key(&r.role_id) || head_ents.contains(r.role_id.as_str()))
4456        && stored.grants.iter().all(|g| {
4457            crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
4458                let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &m));
4459                !floors.contains_key(&eid) || head_ents.contains(eid.as_str())
4460            })
4461        });
4462    // `truncated` covers the case the other three can't: a COLD device (no floors,
4463    // no stored roster) folding under a plane a member has inflated past the pager.
4464    // `stored_complete` is trivially true with nothing stored, so without this the
4465    // first sync would cache a partial authority as its own baseline.
4466    if !truncated && !authority.gapped && stored_complete && newest_roster_at >= crate::db::community::get_community_roles_at(&cid_hex)? {
4467        authority_changed |= stored != authority.roles;
4468        crate::db::community::set_community_roles(&cid_hex, &authority.roles, newest_roster_at)?;
4469    }
4470    // Cache the folded invite Registry so Public/Private stays a sync LOCAL read
4471    // (v1 parity — `invite_registry` is the column every caller reads). Gated like
4472    // the roster: a truncated or gapped window folds an empty registry out of mere
4473    // absence, and persisting that under-states Public — the unsafe direction, since
4474    // it leaves a live link open behind a ban.
4475    if !truncated && !authority.gapped && !fold.gapped {
4476        if let Ok(owner) = community.owner() {
4477            let sets = live_invite_link_sets(community.id(), &owner.to_hex(), &editions, &authority, &floors);
4478            let live = flatten_link_sets(&sets);
4479            let mut before = crate::db::community::get_community_invite_registry(&cid_hex).unwrap_or_default();
4480            before.sort();
4481            if before != live {
4482                crate::db::community::set_community_invite_registry(&cid_hex, &live)?;
4483                authority_changed = true;
4484            }
4485            // The per-creator split drives "X has N active invite links" and the
4486            // first-link-flips-Public confirm; it lives in its own table.
4487            crate::db::community::replace_invite_link_sets(&cid_hex, &sets)?;
4488        }
4489    }
4490    // Roster/banlist moves are invisible in the returned community (they live in
4491    // their own columns), so callers that key a refresh off `updated` would never
4492    // repaint a promote/demote/ban. Announce from the single fold point — it covers
4493    // realtime, boot catch-up and manual sync alike.
4494    if authority_changed {
4495        crate::emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
4496    }
4497    match fold.updated {
4498        Some(u) => {
4499            crate::db::community::save_community_v2(&u)?;
4500            Ok(Some(u))
4501        }
4502        None => Ok(None),
4503    }
4504}
4505
4506/// Control-follow paging bounds: enough depth to re-anchor a long-offline floor
4507/// (H1/M8 refetch) without letting a flooding relay stall the follow queue.
4508///
4509/// Nearly free to raise: both follow loops exit the moment the fold stops being
4510/// gapped, so the cap only binds when something is genuinely missing — exactly
4511/// when paging further is what's wanted. The old ceiling of 4 (~2k editions) sat
4512/// under a plane that 100 roles + 400 grants already outgrows before counting
4513/// superseded versions, which accumulate until a compaction retires them.
4514const FOLLOW_MAX_PAGES: usize = 32;
4515const FOLLOW_PAGE: usize = 500;
4516/// Page ceiling for a COMPACTION read (CORD-06 §3: a Refounder that cannot fold
4517/// every Control Event must abort). Far above any real plane, but plane depth is
4518/// attacker-controlled — any member holds the key that mints wraps — so the read
4519/// is bounded and reports coming up short rather than compacting a partial view.
4520const COMPACT_MAX_PAGES: usize = 512;
4521
4522/// A folded control head to persist as the per-entity refuse-downgrade floor.
4523#[derive(Clone)]
4524struct FoldedHead {
4525    entity_hex: String,
4526    version: u64,
4527    self_hash: [u8; 32],
4528    inner_id: [u8; 32],
4529}
4530
4531/// The outcome of a floor-aware control fold: the updated community (if content
4532/// changed), the heads to persist as the new floor (returned even when content is
4533/// unchanged, so the floor still seeds/advances), and whether any TRACKING entity
4534/// hit an unresolvable gap — the caller's signal to page older history and re-fold
4535/// (CORD-04 H1/M8's refetch).
4536struct ControlFold {
4537    updated: Option<CommunityV2>,
4538    heads: Vec<FoldedHead>,
4539    gapped: bool,
4540}
4541
4542/// Per-entity floor: `(version, self_hash, inner_id)` of the committed head.
4543type Floors = std::collections::HashMap<String, (u64, [u8; 32], Option<[u8; 32]>)>;
4544
4545/// Fold owner-authored control editions into an updated community using the
4546/// PERSISTED per-entity version floor (refuse-downgrade). Per entity, fold with
4547/// [`version::fold`]`(floor, floor_hash)`:
4548///   - ANCHORED: adopt the chain-verified head. A `gap` ABOVE it (withheld middles)
4549///     doesn't block the verified prefix — refuse-downgrade holds for everything
4550///     applied — but flags `gapped` so the caller pages for the rest.
4551///   - UNANCHORED under a held floor: one legitimate cause is a same-version owner
4552///     fork AT the floor whose deterministic winner (lower inner id; a NULL held id
4553///     is always replaceable, mirroring v1's `decide()`) isn't our held edition —
4554///     the floor CONVERGES to the winner and the chain re-anchors on it, so every
4555///     client lands on the same head where a hash-strict floor would wedge forever.
4556///     Anything else is withholding → fail closed + `gapped`.
4557///   - BOOTSTRAPPING (`floor == 0` — a fresh joiner, or a fresh epoch after a
4558///     Refounding, since the caller epoch-filters the floor) takes the highest
4559///     signed head (author already owner-filtered).
4560/// This matches CORD-04 §1 and mirrors v1's `fold_roster`. Epoch-filtering makes a
4561/// compaction at a new epoch auto-bootstrap, converging with Armada's acceptance of
4562/// a compacted head across a dangling `prev` (Armada doesn't persist a floor, so a
4563/// Vector floor only makes Vector STRICTER locally — no wire change, honest-case
4564/// convergence preserved).
4565fn apply_control_fold(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors, authority: &AuthoritySet) -> ControlFold {
4566    use crate::community::roles::Permissions;
4567    use std::collections::BTreeMap;
4568
4569    let owner_hex = community.owner().ok().map(|o| o.to_hex());
4570
4571    let mut groups: BTreeMap<(String, [u8; 32]), Vec<&ParsedEdition>> = BTreeMap::new();
4572    for e in editions {
4573        groups.entry((e.vsk.clone(), e.entity_id)).or_default().push(e);
4574    }
4575
4576    let mut out = community.clone();
4577    let mut changed = false;
4578    let mut heads = Vec::new();
4579    let mut gapped = false;
4580    for ((vsk_code, eid), group) in &groups {
4581        // This fold applies exactly two entities: community metadata (eid ==
4582        // community_id) and channel metadata. A vsk-2 whose eid equals the community
4583        // id is excluded — the floor row keys on the entity alone, so it would share
4584        // (and corrupt) the metadata chain's floor.
4585        let is_meta = vsk_code == vsk::COMMUNITY_METADATA && *eid == community.id().0;
4586        let is_channel = vsk_code == vsk::CHANNEL_METADATA && *eid != community.id().0;
4587        if !is_meta && !is_channel {
4588            continue;
4589        }
4590        // Authority gate (CORD-04 §5): only editions whose author CURRENTLY holds the
4591        // entity's management bit are eligible. Pre-filtering before the fold means a
4592        // demoted admin's (possibly higher-version) edition can't be the head; the
4593        // highest AUTHORIZED head wins. The owner is supreme.
4594        let required = if is_meta { Permissions::MANAGE_METADATA } else { Permissions::MANAGE_CHANNELS };
4595        let authed: Vec<&ParsedEdition> = group
4596            .iter()
4597            .copied()
4598            .filter(|e| {
4599                let author = e.author.to_hex();
4600                // A banned npub's edits are dropped (CORD-04 §4), even if they still
4601                // held a bit via a not-yet-stripped grant.
4602                !authority.banned.contains(&author)
4603                    && authority.roles.is_authorized(&author, owner_hex.as_deref(), required)
4604                    // …and the CORD-04 §5 sync floor. Resolved against the Grant heads
4605                    // this same fold settled, so it works on a bootstrap where no
4606                    // persisted head exists yet.
4607                    && citation_ok_in_fold(community.id(), &authority.heads, owner_hex.as_deref(), &e.author, e.authority.as_ref())
4608            })
4609            .collect();
4610        if authed.is_empty() {
4611            continue;
4612        }
4613        let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
4614        let fold_eds: Vec<version::Edition> = authed.iter().map(|p| p.to_fold_edition()).collect();
4615        let (hi, entity_gapped) = fold_head(&fold_eds, floors.get(&entity_hex));
4616        gapped |= entity_gapped;
4617        let Some(hi) = hi else { continue };
4618
4619        let head = authed[hi];
4620        heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id });
4621        if is_meta {
4622            if let Ok(meta) = serde_json::from_str::<control::CommunityMetadata>(&head.content) {
4623                changed |= apply_community_metadata(&mut out, meta);
4624            }
4625        } else if let Ok(meta) = serde_json::from_str::<control::ChannelMetadata>(&head.content) {
4626            // vsk-2 carries no community binding (shared v1 grammar); a same-owner
4627            // cross-community replay can inject a phantom PUBLIC channel (bounded:
4628            // root-scoped key, eids don't collide). Binding is a deferred wire change.
4629            changed |= apply_channel_metadata(&mut out, ChannelId(*eid), meta);
4630        }
4631    }
4632    ControlFold { updated: changed.then_some(out), heads, gapped }
4633}
4634
4635/// Fold one entity's editions against its persisted floor into a head index (into the
4636/// input slice) plus whether a TRACKING gap was hit (the caller pages older history).
4637/// Encapsulates the W2 refuse-downgrade policy: bootstrap at floor 0 (highest signed
4638/// head, what Armada shows across a compaction's dangling prev); adopt the chain-
4639/// anchored head, paging on an upper gap; converge a same-version fork at the floor to
4640/// the lower-inner-id winner; and fail closed otherwise.
4641fn fold_head(fold_eds: &[version::Edition], floor: Option<&(u64, [u8; 32], Option<[u8; 32]>)>) -> (Option<usize>, bool) {
4642    let floor_v = floor.map(|f| f.0).unwrap_or(0);
4643    if floor_v == 0 {
4644        return (version::bootstrap_head(fold_eds, 0), false);
4645    }
4646    let floor_hash = floor.map(|f| &f.1);
4647    let held_inner = floor.and_then(|f| f.2);
4648    let result = version::fold(fold_eds, floor_v, floor_hash);
4649    if result.anchored {
4650        return (result.head, result.gap); // verified prefix; page any upper gap.
4651    }
4652    if result.head.is_none() && !result.gap {
4653        return (None, false); // everything below floor — a stale relay, no paging.
4654    }
4655    // Unanchored under a held floor: converge a same-version fork at the floor to its
4656    // deterministic winner (lower inner id; a NULL held id is always replaceable),
4657    // else fail closed.
4658    let fork = fold_eds.iter().enumerate().filter(|(_, e)| e.version == floor_v).min_by_key(|(_, e)| e.tiebreak_id);
4659    let win_hash = match fork {
4660        Some((_, w)) if floor_hash != Some(&w.self_hash) && held_inner.is_none_or(|h| w.tiebreak_id < h) => w.self_hash,
4661        _ => return (None, true), // detached from our committed head → withholding.
4662    };
4663    let re = version::fold(fold_eds, floor_v, Some(&win_hash));
4664    if !re.anchored {
4665        return (None, true);
4666    }
4667    (re.head, re.gap)
4668}
4669
4670/// The folded, delegation-AUTHORIZED control-plane authority (CORD-04): the roster
4671/// (roles + grants, owner-seeded fixpoint), the enforced banlist, and the
4672/// role/grant/banlist heads to persist as refuse-downgrade floors. The owner is
4673/// recomputed from the self-certifying community_id at each use.
4674struct AuthoritySet {
4675    roles: crate::community::roles::CommunityRoles,
4676    banned: std::collections::BTreeSet<String>,
4677    heads: Vec<FoldedHead>,
4678    gapped: bool,
4679    /// The authorized banlist `(content, version)` to persist when an authorized head
4680    /// advanced the floor. `None` when the banlist was retained (no new authorized
4681    /// head) or is empty — the caller then leaves the stored banlist untouched.
4682    banlist_persist: Option<(Vec<String>, u64)>,
4683    /// Ban HISTORY: npub hex → `created_at` (secs) of the newest authorized edition that
4684    /// named them, across every edition in the window rather than just the head. Outlives
4685    /// the ban itself so an un-ban can't resurrect a phantom (see [`fold_members`]).
4686    banned_at: std::collections::BTreeMap<String, u64>,
4687}
4688
4689impl AuthoritySet {
4690    /// Bootstrap authority for a community with no roster editions folded yet: only
4691    /// the owner is authorized (supreme), nobody banned.
4692    fn owner_only() -> Self {
4693        AuthoritySet {
4694            roles: Default::default(),
4695            banned: Default::default(),
4696            heads: vec![],
4697            gapped: false,
4698            banlist_persist: None,
4699            banned_at: Default::default(),
4700        }
4701    }
4702}
4703
4704/// Fold the roster/banlist entities (vsk 1/3/4) from the control editions into the
4705/// delegation-AUTHORIZED roster + enforced banlist (CORD-04 §2-§5). Each entity binds
4706/// to its coordinate (role at role_id, grant at grant_locator(cid, member), banlist at
4707/// banlist_locator(cid)); a content whose coordinate doesn't match is dropped. Roles
4708/// cap at the 100 lowest role_ids, a member at 64 roles, the banlist at 500. The
4709/// banlist is enforced only if its head's signer held BAN in the authorized roster.
4710fn fold_authority(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors) -> AuthoritySet {
4711    use crate::community::roles::Permissions;
4712    use std::collections::BTreeMap;
4713
4714    let cid = community.id();
4715    let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
4716    let owner = community.owner().ok();
4717    let owner_hex = owner.map(|o| o.to_hex());
4718    let banlist_eid = super::derive::banlist_locator(cid);
4719    let banlist_hex = crate::simd::hex::bytes_to_hex_32(&banlist_eid);
4720
4721    let mut groups: BTreeMap<[u8; 32], Vec<&ParsedEdition>> = BTreeMap::new();
4722    for e in editions {
4723        if e.vsk == vsk::ROLE || e.vsk == vsk::GRANT || e.vsk == vsk::BANLIST {
4724            groups.entry(e.entity_id).or_default().push(e);
4725        }
4726    }
4727
4728    // Per-entity CANDIDATE lists — every ≥floor edition of a role/grant, highest
4729    // version first (lowest inner-id as the deterministic tiebreak). CORD-04 §1: an
4730    // edition whose signer isn't authorized is SIMPLY DROPPED and the fold continues
4731    // to the next candidate, so a forged higher-version edition can't suppress the
4732    // authorized head beneath it (the author-blind collapse-to-one-head it replaces
4733    // let any member vanish a role or a member's grant). `gapped` (drives older-
4734    // paging) stays fold_head's per-entity flag.
4735    let mut role_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
4736    let mut grant_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
4737    let mut gapped = false;
4738
4739    for (eid, group) in &groups {
4740        // The banlist is folded author-aware AFTER the roster is known (below).
4741        if *eid == banlist_eid {
4742            continue;
4743        }
4744        let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
4745        let fold_eds: Vec<version::Edition> = group.iter().map(|p| p.to_fold_edition()).collect();
4746        let (_hi, entity_gapped) = fold_head(&fold_eds, floors.get(&entity_hex));
4747        gapped |= entity_gapped;
4748        let floor_v = floors.get(&entity_hex).map(|f| f.0).unwrap_or(0);
4749
4750        for p in group {
4751            // Refuse-downgrade: never consider an edition below the persisted floor.
4752            if p.version < floor_v {
4753                continue;
4754            }
4755            let head = FoldedHead { entity_hex: entity_hex.clone(), version: p.version, self_hash: p.self_hash, inner_id: p.inner_id };
4756            match p.vsk.as_str() {
4757                vsk::ROLE => {
4758                    // Bind: the content's role_id IS the coordinate; position 0 is the owner's.
4759                    if let Some(role) = super::roles::parse_role_content(&p.content) {
4760                        if role.role_id == entity_hex && role.position != 0 {
4761                            role_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: Some(role), grant: None, author: p.author, head, citation: p.authority.clone() });
4762                        }
4763                    }
4764                }
4765                vsk::GRANT => {
4766                    if let Some(mut grant) = super::roles::parse_grant_content(&p.content) {
4767                        if let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(&grant.member) {
4768                            if super::derive::grant_locator(cid, &member) == *eid {
4769                                grant.role_ids.truncate(super::roles::MAX_ROLES_PER_MEMBER);
4770                                grant_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: None, grant: Some(grant), author: p.author, head, citation: p.authority.clone() });
4771                            }
4772                        }
4773                    }
4774                }
4775                _ => {}
4776            }
4777        }
4778    }
4779    for cands in role_cands.values_mut().chain(grant_cands.values_mut()) {
4780        cands.sort_by(|a, b| b.head.version.cmp(&a.head.version).then(a.head.inner_id.cmp(&b.head.inner_id)));
4781    }
4782
4783    let empty: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
4784    // Preliminary roster (bans not yet applied) — the authority view the banlist head
4785    // is judged against.
4786    let (prelim, prelim_heads) = select_authorized(cid, &role_cands, &grant_cands, owner_hex.as_deref(), &empty);
4787
4788    // Banlist (CORD-04 §4), folded AUTHORITY-aware so its two anti-roster hazards are
4789    // both closed:
4790    //   - head selection: the head is the highest version whose author CURRENTLY holds
4791    //     BAN — an unauthorized higher-version edition can't erase existing bans
4792    //     (fail-open), and the floor never advances to one;
4793    //   - per-target: each entry is kept only if the author STRICTLY OUTRANKS that
4794    //     target (`can_act_on_member` — an admin can't ban a peer/superior, and the
4795    //     owner is unbannable);
4796    //   - withholding: when no authorized head is served, the persisted banlist is
4797    //     RETAINED (an anti-roster must not un-ban on a relay withholding the ban).
4798    let persisted_banned: Vec<String> = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
4799    // An ALREADY-banned npub can't author the banlist (a banned member vanishes, §4), or
4800    // a BAN-holder whose grant-strip hasn't yet folded could publish a list omitting their
4801    // OWN ban to un-ban themselves (removals aren't outrank-checked). Exclude them from
4802    // head eligibility, not just from the roster.
4803    let banned_authors: std::collections::HashSet<&str> = persisted_banned.iter().map(String::as_str).collect();
4804    let banlist_authored: Vec<&ParsedEdition> = groups
4805        .get(&banlist_eid)
4806        .map(|g| {
4807            g.iter()
4808                .copied()
4809                .filter(|e| {
4810                    let ah = e.author.to_hex();
4811                    !banned_authors.contains(ah.as_str())
4812                        && prelim.is_authorized(&ah, owner_hex.as_deref(), Permissions::BAN)
4813                        && citation_ok_in_fold(cid, &prelim_heads, owner_hex.as_deref(), &e.author, e.authority.as_ref())
4814                })
4815                .collect()
4816        })
4817        .unwrap_or_default();
4818    // Ban history for phantom suppression: the newest AUTHORIZED edition naming each npub,
4819    // over EVERY candidate rather than only the head — an un-ban replaces the head, so the
4820    // head alone forgets the ban that the suppression exists to remember. The owner is
4821    // skipped: they are never bannable, and a moderator listing them must not durably
4822    // suppress them past the un-ban.
4823    let mut banned_at: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();
4824    for p in &banlist_authored {
4825        for t in super::roles::parse_banlist_content(&p.content).unwrap_or_default() {
4826            if owner_hex.as_deref() == Some(t.as_str()) {
4827                continue;
4828            }
4829            let slot = banned_at.entry(t).or_insert(0);
4830            *slot = (*slot).max(p.created_at);
4831        }
4832    }
4833    let mut banlist_persist: Option<(Vec<String>, u64)> = None;
4834    let mut banlist_head: Option<FoldedHead> = None;
4835    let banned: std::collections::BTreeSet<String> = if banlist_authored.is_empty() {
4836        persisted_banned.into_iter().collect()
4837    } else {
4838        let fold_eds: Vec<version::Edition> = banlist_authored.iter().map(|p| p.to_fold_edition()).collect();
4839        let (hi, g) = fold_head(&fold_eds, floors.get(&banlist_hex));
4840        gapped |= g;
4841        match hi {
4842            Some(hi) => {
4843                let head = banlist_authored[hi];
4844                let ah = head.author.to_hex();
4845                let list: Vec<String> = super::roles::parse_banlist_content(&head.content)
4846                    .unwrap_or_default()
4847                    .into_iter()
4848                    .filter(|t| prelim.can_act_on_member(&ah, owner_hex.as_deref(), t, Permissions::BAN))
4849                    .take(super::roles::MAX_BANLIST)
4850                    .collect();
4851                banlist_head = Some(FoldedHead { entity_hex: banlist_hex.clone(), version: head.version, self_hash: head.self_hash, inner_id: head.inner_id });
4852                banlist_persist = Some((list.clone(), head.version));
4853                list.into_iter().collect()
4854            }
4855            None => persisted_banned.into_iter().collect(),
4856        }
4857    };
4858
4859    // Final roster (CORD-04 §4: a banned npub vanishes — every edition it authored is
4860    // dropped, and a grant TO a banned member carries no rank). Re-run selection with
4861    // the banned set excluded so a banned admin loses authority.
4862    let (mut authorized, mut heads) = select_authorized(cid, &role_cands, &grant_cands, owner_hex.as_deref(), &banned);
4863    if let Some(bh) = banlist_head {
4864        heads.push(bh);
4865    }
4866
4867    // Cap the AUTHORIZED community at the 100 lowest role_ids — applied AFTER
4868    // authorization, so an attacker's unauthorized roles can't consume cap slots and
4869    // evict a legitimate one (the pre-authorize cap they replace let 100 forged low-id
4870    // roles empty the roster).
4871    if authorized.roles.len() > super::roles::MAX_ROLES_PER_COMMUNITY {
4872        authorized.roles.sort_by(|a, b| a.role_id.cmp(&b.role_id));
4873        authorized.roles.truncate(super::roles::MAX_ROLES_PER_COMMUNITY);
4874        let kept: std::collections::HashSet<&str> = authorized.roles.iter().map(|r| r.role_id.as_str()).collect();
4875        authorized.grants.iter_mut().for_each(|g| g.role_ids.retain(|rid| kept.contains(rid.as_str())));
4876        authorized.grants.retain(|g| !g.role_ids.is_empty());
4877    }
4878
4879    AuthoritySet { roles: authorized, banned, heads, gapped, banlist_persist, banned_at }
4880}
4881
4882/// One candidate edition of a role/grant entity — the pool [`select_authorized`]
4883/// draws the highest AUTHORIZED head from (exactly one of `role`/`grant` is set).
4884struct AuthorityCand {
4885    role: Option<crate::community::roles::Role>,
4886    grant: Option<crate::community::roles::MemberGrant>,
4887    author: PublicKey,
4888    head: FoldedHead,
4889    /// The `vac` this edition carried (CORD-04 §5). `None` for an owner edition
4890    /// (supreme, cites nothing) or an uncited one — the latter is refused.
4891    citation: Option<crate::community::edition::AuthorityCitation>,
4892}
4893
4894/// CORD-04 §5 sync floor, resolved against the heads THIS fold pass has accepted.
4895///
4896/// Deliberately not the persisted-head helper the kick/hide paths use: this IS the
4897/// pass that establishes those heads, so an external floor would refuse every
4898/// non-owner edition on a bootstrap and the roster could never fold. Same rule the
4899/// spec gives for a dangling `prev` across a Refounding — a fresh joiner takes the
4900/// authority-verified head as its baseline, a tracking client fails closed per
4901/// entity — applied to the citation instead of the chain link.
4902fn citation_ok_in_fold(
4903    cid: &crate::community::CommunityId,
4904    heads: &[FoldedHead],
4905    owner_hex: Option<&str>,
4906    author: &PublicKey,
4907    citation: Option<&crate::community::edition::AuthorityCitation>,
4908) -> bool {
4909    let actor_hex = author.to_hex();
4910    if owner_hex == Some(actor_hex.as_str()) {
4911        return true;
4912    }
4913    let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &author.to_bytes()));
4914    let as_entity: Vec<crate::community::roster::EntityHead> = heads
4915        .iter()
4916        .map(|h| crate::community::roster::EntityHead {
4917            entity_hex: h.entity_hex.clone(),
4918            version: h.version,
4919            self_hash: h.self_hash,
4920            inner_id: h.inner_id,
4921            citation: None,
4922        })
4923        .collect();
4924    crate::community::roster::authority_citation_satisfied(&as_entity, owner_hex, &actor_hex, &grant_hex, citation)
4925}
4926
4927/// The owner-seeded delegation fixpoint (CORD-04 §1/§2), author-AWARE: per entity it
4928/// takes the highest-version candidate whose author is authorized to author it under
4929/// the roster resolved SO FAR, dropping unauthorized higher versions rather than
4930/// vanishing the entity. Authority resolves outward from the owner (proven by
4931/// `community_id`, never a Role), and the strict-outrank rule (no edition at/above its
4932/// signer's own position) keeps the fixpoint monotone, so it converges. Returns the
4933/// authorized roster plus the per-entity heads of the SELECTED editions (the floor
4934/// advances only to authorized heads — an unauthorized forgery never poisons it).
4935fn select_authorized(
4936    cid: &crate::community::CommunityId,
4937    role_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
4938    grant_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
4939    owner_hex: Option<&str>,
4940    excluded: &std::collections::BTreeSet<String>,
4941) -> (crate::community::roles::CommunityRoles, Vec<FoldedHead>) {
4942    use crate::community::roles::{CommunityRoles, Permissions};
4943    let mut accepted = CommunityRoles::default();
4944    let mut heads: Vec<FoldedHead> = Vec::new();
4945    // Jacobi iteration: authority propagates one delegation level per round, so a
4946    // generous multiple of the entity count is an ample bound. Non-convergence (never
4947    // seen for an owner-rooted chain) falls through fail-safe: only authorized editions
4948    // are ever selected.
4949    let bound = 2 * (role_cands.len() + grant_cands.len()) + 8;
4950    for _ in 0..bound {
4951        let mut next = CommunityRoles::default();
4952        let mut next_heads: Vec<FoldedHead> = Vec::new();
4953
4954        for cands in role_cands.values() {
4955            // Two gates, not one (CORD-04 §2). Minting at a position you outrank
4956            // is necessary but not sufficient: an edition REPLACES the entity, so
4957            // the author must also outrank the position standing before it.
4958            // Without that, an admin at position 5 rewrites the position-1 role
4959            // to position 9 — every check passes, since 9 is beneath them — and
4960            // a role that outranked them is now beneath them, along with everyone
4961            // holding it. Rank inversion by republish.
4962            //
4963            // The chain is replayed ASCENDING so each version is judged against
4964            // the position its own predecessor established, then the highest
4965            // admissible version wins (candidates arrive version-DESC, forks
4966            // broken by lowest inner_id — preserved by walking version groups).
4967            let mut admissible: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
4968            let mut standing: Option<u32> = None;
4969            let mut i = cands.len();
4970            while i > 0 {
4971                let hi = i;
4972                let ver = cands[i - 1].head.version;
4973                while i > 0 && cands[i - 1].head.version == ver {
4974                    i -= 1;
4975                }
4976                // One winner per version: fork siblings can't sidestep the gate.
4977                for c in cands[i..hi].iter().rev() {
4978                    let Some(role) = &c.role else { continue };
4979                    let ah = c.author.to_hex();
4980                    if excluded.contains(&ah) || role.position == 0 {
4981                        continue;
4982                    }
4983                    if !accepted.can_act_on_position(&ah, owner_hex, role.position, Permissions::MANAGE_ROLES) {
4984                        continue;
4985                    }
4986                    if let Some(prev) = standing {
4987                        if !accepted.can_act_on_position(&ah, owner_hex, prev, Permissions::MANAGE_ROLES) {
4988                            continue;
4989                        }
4990                    }
4991                    if !citation_ok_in_fold(cid, &heads, owner_hex, &c.author, c.citation.as_ref()) {
4992                        continue;
4993                    }
4994                    admissible.insert(c.head.self_hash);
4995                    standing = Some(role.position);
4996                    break;
4997                }
4998            }
4999            for c in cands {
5000                let Some(role) = &c.role else { continue };
5001                if !admissible.contains(&c.head.self_hash) {
5002                    continue;
5003                }
5004                next.roles.push(role.clone());
5005                next_heads.push(c.head.clone());
5006                break; // highest admissible candidate for this entity
5007            }
5008        }
5009        for cands in grant_cands.values() {
5010            for c in cands {
5011                let Some(grant) = &c.grant else { continue };
5012                let ah = c.author.to_hex();
5013                if excluded.contains(&ah) || excluded.contains(&grant.member) {
5014                    continue;
5015                }
5016                // The granter must outrank every granted role (resolved against the
5017                // accepted roster) AND the member — the escalation defense (CORD-04 §2).
5018                let positions: Option<Vec<u32>> = grant.role_ids.iter().map(|rid| accepted.role(rid).map(|r| r.position)).collect();
5019                let Some(positions) = positions else { continue };
5020                if !citation_ok_in_fold(cid, &heads, owner_hex, &c.author, c.citation.as_ref()) {
5021                    continue;
5022                }
5023                if positions.iter().all(|p| accepted.can_act_on_position(&ah, owner_hex, *p, Permissions::MANAGE_ROLES))
5024                    && accepted.can_act_on_member(&ah, owner_hex, &grant.member, Permissions::MANAGE_ROLES)
5025                {
5026                    // Record the head even for an EMPTY grant (a revoke is a real chain
5027                    // advance a completeness check must see), but don't carry the husk
5028                    // into the roster.
5029                    next_heads.push(c.head.clone());
5030                    if !grant.role_ids.is_empty() {
5031                        next.grants.push(grant.clone());
5032                    }
5033                    break;
5034                }
5035            }
5036        }
5037
5038        let converged = next.roles == accepted.roles && next.grants == accepted.grants;
5039        accepted = next;
5040        heads = next_heads;
5041        if converged {
5042            break;
5043        }
5044    }
5045    (accepted, heads)
5046}
5047
5048/// Apply a folded community-metadata head. Relays only overwrite when the edition
5049/// carries a non-empty list (a metadata edition that omits relays must not blank
5050/// the working set). Returns whether anything changed.
5051fn apply_community_metadata(out: &mut CommunityV2, meta: control::CommunityMetadata) -> bool {
5052    let mut changed = false;
5053    if out.name != meta.name {
5054        out.name = meta.name;
5055        changed = true;
5056    }
5057    if out.description != meta.description {
5058        out.description = meta.description;
5059        changed = true;
5060    }
5061    // Icon/banner apply verbatim, None included — an edition is the full
5062    // document, so an absent image IS a removal (editors preserve via
5063    // `CommunityV2::metadata()`).
5064    if out.icon != meta.icon {
5065        out.icon = meta.icon;
5066        changed = true;
5067    }
5068    if out.banner != meta.banner {
5069        out.banner = meta.banner;
5070        changed = true;
5071    }
5072    // Client-extensible + unknown fields ride the fold verbatim so our own
5073    // editions can carry them forward (CORD-02 §6).
5074    if out.meta_custom != meta.custom {
5075        out.meta_custom = meta.custom;
5076        changed = true;
5077    }
5078    if out.meta_extra != meta.extra {
5079        out.meta_extra = meta.extra;
5080        changed = true;
5081    }
5082    // CAP on the way in. `cap_relays` is the truncate-on-read invariant for every
5083    // other construction boundary, and the fold is a boundary like any other: an
5084    // authorized editor is not a trusted one, and an oversize list costs every
5085    // member a fan-out on each publish and the slowest of N on each fetch
5086    // (CORD-02 §6 makes trimming explicitly a client's call). Compare against the
5087    // CAPPED list too — against the raw one, an oversize edition never compares
5088    // equal, so every fold would report a change and re-save forever.
5089    let relays = crate::community::cap_relays(meta.relays);
5090    if !relays.is_empty() && out.relays != relays {
5091        out.relays = relays;
5092        changed = true;
5093    }
5094    changed
5095}
5096
5097/// Apply a folded channel-metadata head: delete removes the channel, a rename
5098/// updates an existing one, a brand-new PUBLIC channel is added, and a brand-new
5099/// PRIVATE one is recorded KEYLESS (unreadable until its key arrives over the
5100/// rekey plane or a fresh bundle). Returns whether anything changed.
5101fn apply_channel_metadata(out: &mut CommunityV2, id: ChannelId, meta: control::ChannelMetadata) -> bool {
5102    let deleted = meta.deleted.unwrap_or(false);
5103    if deleted {
5104        let before = out.channels.len();
5105        out.channels.retain(|c| c.id.0 != id.0);
5106        return out.channels.len() != before;
5107    }
5108    match out.channels.iter_mut().find(|c| c.id.0 == id.0) {
5109        Some(existing) => {
5110            let mut changed = false;
5111            if existing.name != meta.name {
5112                existing.name = meta.name;
5113                changed = true;
5114            }
5115            // vsk-2 fields Vector doesn't drive still fold + persist, so a later
5116            // local edit republishes them instead of wiping (CORD-02 §6).
5117            if existing.voice != meta.voice {
5118                existing.voice = meta.voice;
5119                changed = true;
5120            }
5121            if existing.meta_custom != meta.custom {
5122                existing.meta_custom = meta.custom;
5123                changed = true;
5124            }
5125            if existing.meta_extra != meta.extra {
5126                existing.meta_extra = meta.extra;
5127                changed = true;
5128            }
5129            // The owner's edition authoritatively declares visibility. A channel the
5130            // owner marks PUBLIC must derive from the root (key = None) — this heals a
5131            // bundle-time misclassification where an attacker set a public channel's
5132            // grant key to their own, silently addressing it at a plane only they read.
5133            // Public → private CONVERSION is DEFERRED: the flip is IGNORED here (the
5134            // record stays public) until the convert flow (key mint + cursor rebase
5135            // to the conversion's channel epoch) lands — the send side refuses to
5136            // publish one, and a foreign client's conversion won't move us.
5137            if !meta.private && (existing.private || existing.key.is_some()) {
5138                existing.private = false;
5139                existing.key = None;
5140                changed = true;
5141            }
5142            changed
5143        }
5144        None if !meta.private => {
5145            // A public channel derives its Chat Plane from the community_root at the
5146            // current root epoch (key = None); its stored epoch mirrors the root.
5147            out.channels.push(ChannelV2 {
5148                id,
5149                name: meta.name,
5150                private: false,
5151                key: None,
5152                epoch: out.root_epoch,
5153                voice: meta.voice,
5154                meta_custom: meta.custom,
5155                meta_extra: meta.extra,
5156            });
5157            true
5158        }
5159        None => {
5160            // A brand-new PRIVATE channel: record it KEYLESS at epoch 0 (the root
5161            // generation — CORD-03 §2 numbers the first private key epoch 1). The
5162            // epoch then doubles as [`follow_rekeys`]' scan cursor. Until a rotation
5163            // delivers a key, every read/send/subscribe path skips the channel; the
5164            // root-fallback in `channel_secret` is never taken for it.
5165            out.channels.push(ChannelV2 {
5166                id,
5167                name: meta.name,
5168                private: true,
5169                key: None,
5170                epoch: Epoch(0),
5171                voice: meta.voice,
5172                meta_custom: meta.custom,
5173                meta_extra: meta.extra,
5174            });
5175            true
5176        }
5177    }
5178}
5179
5180// ── Live rekey-follow (CORD-06 §2/§3) ────────────────────────────────────────
5181
5182/// The outcome of a rekey-follow pass.
5183pub struct RekeyFollow {
5184    /// The community after adopting every rotation it could catch up on, or `None`
5185    /// if nothing advanced.
5186    pub updated: Option<CommunityV2>,
5187    /// A base rotation removed us — the caller tears the local hold down (the
5188    /// updated community is not persisted in that case).
5189    pub self_removed: bool,
5190    /// An owner tombstone sits on the dissolved plane (CORD-02 §9) — the local
5191    /// flag is already set; the caller surfaces the death and stops following.
5192    pub dissolved: bool,
5193}
5194
5195/// The most archived base roots a channel-rekey lookup fans across per step. A
5196/// standalone rekey rides the minter's then-current root and a removal's rides the
5197/// PRIOR root (CORD-06 §3), so a follower whose base already advanced must look
5198/// back. A channel stranded DEEPER than this (its next-epoch crate addressed under
5199/// an older root than the fan reaches) only heals via a fresh invite bundle — the
5200/// walk is strictly sequential, so a later rotation can't be reached either.
5201const MAX_ADDRESSING_ROOTS: usize = 8;
5202
5203/// The base roots a channel rekey may be addressed under, freshest first: the
5204/// current root plus the archived priors, capped at [`MAX_ADDRESSING_ROOTS`].
5205/// CORD-06 D2: a removal-forced channel rekey rides the PRIOR root — so the
5206/// follower's fetch fan ([`follow_rekeys`]) and the stream-auth registration
5207/// (`streamauth::register_community`) MUST cover the SAME set. A plane the
5208/// fetch addresses but auth never registered is invisible on an AUTH-gating
5209/// relay: the REQ is CLOSED, the rotation crate never arrives, and the channel
5210/// wedges at its old epoch while the base advances.
5211pub(crate) fn channel_rekey_addressing_roots(cur_root: [u8; 32], cid_hex: &str) -> Vec<[u8; 32]> {
5212    let mut roots: Vec<[u8; 32]> = vec![cur_root];
5213    let mut archived = crate::db::community::held_epoch_keys(cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
5214        .unwrap_or_default();
5215    archived.sort_by(|a, b| b.0 .0.cmp(&a.0 .0));
5216    for (_, r) in archived {
5217        if !roots.contains(&r) {
5218            roots.push(r);
5219        }
5220    }
5221    roots.truncate(MAX_ADDRESSING_ROOTS);
5222    roots
5223}
5224
5225/// Follow rekeys for a held community: advance the base (root) epoch and each
5226/// Private channel's epoch as far as authorized rotations allow, adopting the
5227/// fresh key we're still a recipient of at each step and dropping a scope we've
5228/// been removed from. Persists the result. Called when a rekey wrap arrives in
5229/// realtime so a long-running bot keeps decrypting after a rotation instead of
5230/// going silent.
5231///
5232/// **Authority (CORD-06 §Authority):** a BASE rotation is honored from the owner
5233/// only — the deliberate mirror of the owner-only Refounding send (a non-owner's
5234/// ban silences + strips; the read-cut is the owner's). A CHANNEL rotation is
5235/// honored from the owner or a `MANAGE_CHANNELS` holder under the PERSISTED
5236/// roster (folded + persisted by `follow_control`), minus the banlist — so an
5237/// admin-created private channel keys up on every member.
5238///
5239/// **Addressing fans across held base roots:** each channel step queries its
5240/// next-epoch rekey address under the current root AND the archived prior roots,
5241/// so a base adopt landing before a Refounding's prior-root-addressed channel
5242/// rekeys (or before a creation delivery minted under an older root) can't
5243/// strand the channel.
5244///
5245/// **Continuity + fork resolution are spec-strict:** a rotation must extend the
5246/// exact `(epoch, key)` I hold, one epoch at a time; a same-epoch fork resolves
5247/// by the lexicographically lowest new key ([`rekey::lowest_key_winner`]), so
5248/// every follower converges. An incomplete rotation (a missing chunk) never
5249/// concludes removal — it just waits. A KEYLESS channel (announced by vsk-2, key
5250/// not yet delivered) holds no chain, so continuity is vacuous for it (CORD-06
5251/// §2: "a convergence check, not a secrecy mechanism") — authority is its
5252/// boundary; its epoch is the scan cursor, advancing past complete rotations
5253/// that exclude us so the walk converges on the channel's current epoch.
5254/// Diagnostic: run the base-rotation fetch+parse pipeline for a wedged community
5255/// and report, per rotation found at the next-epoch base plane, WHY
5256/// `follow_rekeys` did or didn't adopt it — the exact `advance_scope` gate that
5257/// tripped. Read-only. Every rotator/owner is a PUBLIC key; no secret material
5258/// is returned.
5259#[cfg(debug_assertions)]
5260pub async fn debug_explain_base_rekey<T: Transport + ?Sized>(
5261    transport: &T,
5262    community: &CommunityV2,
5263) -> Result<serde_json::Value, String> {
5264    let my_xonly = me_pk()?.to_bytes();
5265    let owner = community.owner()?;
5266    let owner_hex = owner.to_hex();
5267    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
5268    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
5269    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
5270    let held_epoch = community.root_epoch;
5271    let held_key = community.community_root;
5272    let next = Epoch(held_epoch.0.saturating_add(1));
5273    let group = base_rekey_group_key(&held_key, community.id(), next);
5274    let chunks = fetch_rekey_chunks(transport, &community.relays, &group).await?;
5275    let rotations = rekey::collect_rotations(&chunks);
5276
5277    let reports: Vec<serde_json::Value> = rotations
5278        .iter()
5279        .map(|r| {
5280            let rotator_is_owner = r.rotator == owner;
5281            // CORD-06 §Authority: a Refounding is authorized by BAN in the folded
5282            // Roster, not owner-identity — report that gate, not just owner-equality.
5283            let rotator_authorized = rotator_is_owner
5284                || (!banned.contains(&r.rotator.to_hex())
5285                    && roster.is_authorized(&r.rotator.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN));
5286            let scope_ok = r.scope.id32() == rekey::RekeyScope::Root.id32();
5287            let epoch_ok = r.new_epoch.0 == next.0;
5288            let complete = r.is_complete();
5289            let continuity = format!("{:?}", r.continuity(held_epoch, &held_key));
5290            let has_my_blob = rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &my_xonly, r.scope, r.new_epoch).is_some();
5291            // Is the OWNER a recipient? A non-owner Refounding that drops the owner
5292            // is a takeover attempt — this tells whether an "owner must be kept"
5293            // adopt-block would be safe here (it would falsely reject a legitimate
5294            // rotation that happened to exclude the owner).
5295            let owner_kept = r.rotator == owner
5296                || rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &owner.to_bytes(), r.scope, r.new_epoch).is_some();
5297            // The exact reason follow_rekeys skipped/rejected this rotation, in gate order.
5298            let verdict = if !rotator_authorized {
5299                "REJECTED: rotator holds no BAN authority in the folded roster"
5300            } else if !scope_ok {
5301                "REJECTED: scope is not Root"
5302            } else if !epoch_ok {
5303                "REJECTED: new_epoch != held+1"
5304            } else if !complete {
5305                "WAIT: rotation incomplete (missing chunk) — never concludes removal"
5306            } else if continuity != "Extends" {
5307                "REJECTED: continuity does not extend my held root (FORK/GAP)"
5308            } else if has_my_blob {
5309                "ADOPT: authorized + complete + continuous + my blob present"
5310            } else {
5311                "REMOVED: complete authorized rotation with no blob for me"
5312            };
5313            serde_json::json!({
5314                "rotator": r.rotator.to_hex(),
5315                "rotator_is_recorded_owner": rotator_is_owner,
5316                "rotator_authorized_ban": rotator_authorized,
5317                "scope_is_root": scope_ok,
5318                "new_epoch": r.new_epoch.0,
5319                "prev_epoch": r.prev_epoch.0,
5320                "declared_chunks": r.declared_chunks,
5321                "held_chunks": r.held_chunks.iter().copied().collect::<Vec<_>>(),
5322                "is_complete": complete,
5323                "continuity_vs_held_root": continuity,
5324                "my_blob_present": has_my_blob,
5325                "owner_kept": owner_kept,
5326                "blob_count": r.blobs.len(),
5327                "verdict": verdict,
5328            })
5329        })
5330        .collect();
5331
5332    Ok(serde_json::json!({
5333        "recorded_owner": owner.to_hex(),
5334        "held_root_epoch": held_epoch.0,
5335        "probing_next_epoch": next.0,
5336        "base_plane_pk": group.pk_hex(),
5337        "raw_chunks_parsed": chunks.len(),
5338        "rotations_found": rotations.len(),
5339        "rotations": reports,
5340    }))
5341}
5342
5343pub async fn follow_rekeys<T: Transport + ?Sized>(
5344    transport: &T,
5345    community: &CommunityV2,
5346    session: &SessionGuard,
5347) -> Result<RekeyFollow, String> {
5348    // Death wins every race (CORD-02 §9): a dissolved community honors no epoch advance
5349    // past its tombstone — don't adopt a rotation into a grave.
5350    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
5351    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
5352        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: true });
5353    }
5354    // An offline member must also LEARN of a death: the tombstone rides its own
5355    // public plane, which the live sub watches but no catch-up fetch touched —
5356    // without this, a member who slept through a dissolution follows (and posts
5357    // into) a grave forever. Fail-open on transport failure: availability is
5358    // never death.
5359    if is_dissolved(transport, community).await {
5360        if session.is_valid() {
5361            let _ = crate::db::community::set_community_dissolved(&cid_hex);
5362        }
5363        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: true });
5364    }
5365    let signer = crate::signer::active_signer()?;
5366    let my_pk = me_pk()?;
5367    let my_xonly = my_pk.to_bytes();
5368    let owner = community.owner()?;
5369    let owner_hex = owner.to_hex();
5370    let mut cur = community.clone();
5371    let mut changed = false;
5372
5373    // The rotator/admissibility gates read the PERSISTED roster (folded by a prior
5374    // follow_control; the worker folds control right after this rekey pass). This
5375    // is "one pass late" for the rotator-AUTHORIZATION direction (a newly-granted
5376    // admin's rotation adopts a pass late, never early — safe). It is fail-OPEN for
5377    // the base-admissibility protected-set: a superior whose grant this receiver
5378    // has not yet folded is not in `roster.grants`, so a non-owner Refounding
5379    // excluding them can be adopted within that propagation window. Bounded — the
5380    // owner is ALWAYS hard-protected below (independent of the roster) and can
5381    // counter-refound; and it is inherent to eventual consistency (one cannot gate
5382    // on a grant never seen). Tightening this (fold control before the first rekey,
5383    // or gate non-owner adoption on roster freshness) is a follow-on.
5384    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
5385    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
5386    let me_hex = my_pk.to_hex();
5387    // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
5388    // authority action (CORD-04's `vac`), so a just-demoted admin's rotation is
5389    // never honored by a lagging client." Persisted heads ARE the right floor
5390    // here (unlike the roster fold, which must resolve in-pass): a rotation is
5391    // judged against a roster we already folded, and `follow_control` — v2's only
5392    // roster writer — persists the heads in the same pass it writes the roster.
5393    // A joiner who sees a rotation before folding control simply parks it and
5394    // heals on the next follow, which runs control first.
5395    let cited_ok = |rot: &rekey::Rotation| -> bool {
5396        citation_is_synced(&cid_hex, &owner_hex, &rot.rotator.to_hex(), rot.citation.as_ref())
5397    };
5398    let channel_rotator_ok = |rotator: &PublicKey| -> bool {
5399        if *rotator == owner {
5400            return true;
5401        }
5402        let rh = rotator.to_hex();
5403        !banned.contains(&rh) && roster.is_authorized(&rh, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS)
5404    };
5405    // Concluding MY removal takes more than the bit: the rotator must strictly
5406    // outrank ME (CORD-06 §Authority — "the Rotator must strictly outrank every
5407    // removed target"), so an equal-rank admin can never silently evict a peer
5408    // (or the owner) by minting a complete rotation that skips their blob.
5409    let channel_rotator_outranks_me = |rotator: &PublicKey| -> bool {
5410        if *rotator == owner {
5411            return true;
5412        }
5413        let rh = rotator.to_hex();
5414        !banned.contains(&rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, crate::community::roles::Permissions::MANAGE_CHANNELS)
5415    };
5416    // CORD-06 §Authority: a Refounding requires the BAN permission in the folded
5417    // Roster (NOT owner-identity) — any admin holding BAN may perform it, checked
5418    // against the Roster exactly like a channel rekey checks MANAGE_CHANNELS. The
5419    // owner is always authorized. (Owner-only here silently wedged every member
5420    // whose community was refounded by a non-owner admin.)
5421    let base_rotator_ok = |rotator: &PublicKey| -> bool {
5422        if *rotator == owner {
5423            return true;
5424        }
5425        let rh = rotator.to_hex();
5426        !banned.contains(&rh) && roster.is_authorized(&rh, Some(&owner_hex), crate::community::roles::Permissions::BAN)
5427    };
5428    // Concluding MY removal via a base rotation takes more than the bit: the
5429    // rotator must strictly outrank ME with BAN (CORD-06 §Authority — "the
5430    // Rotator must strictly outrank every removed target"), so an equal-rank
5431    // admin can never evict a peer (or the owner) by minting a rotation that
5432    // skips their blob. Adoption (I hold a blob) only needs `base_rotator_ok`.
5433    let base_rotator_outranks_me = |rotator: &PublicKey| -> bool {
5434        if *rotator == owner {
5435            return true;
5436        }
5437        let rh = rotator.to_hex();
5438        !banned.contains(&rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, crate::community::roles::Permissions::BAN)
5439    };
5440
5441    // Bound the catch-up: each real step consumes a valid authorized rotation, so a
5442    // finite chain terminates naturally; the cap defends against a relay feeding a
5443    // pathological set.
5444    const MAX_STEPS: usize = 128;
5445    for _ in 0..MAX_STEPS {
5446        let mut advanced = false;
5447
5448        // The roots a channel rekey may be addressed under (re-read each pass —
5449        // a base adopt below changes the head, and its predecessor is already
5450        // archived). Shared with streamauth so the auth registration covers
5451        // exactly this fan.
5452        let addressing_roots = channel_rekey_addressing_roots(cur.community_root, &cid_hex);
5453
5454        // Private channels first: a removal-forced channel rekey rides the PRIOR
5455        // root (CORD-06 D2), so read channels before a base adopt moves it.
5456        let channel_ids: Vec<ChannelId> = cur.channels.iter().filter(|c| c.private).map(|c| c.id).collect();
5457        for cid in channel_ids {
5458            let (held_key, held_epoch) = match cur.channel(&cid) {
5459                Some(ch) => (ch.key, ch.epoch),
5460                None => continue,
5461            };
5462            let next = Epoch(held_epoch.0.saturating_add(1));
5463            let ch_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
5464            let mut batches: Vec<(Vec<rekey::RekeyChunk>, Option<(Epoch, [u8; 32])>)> = Vec::new();
5465            // root #0 = current, #1.. = archived priors (indices only — root
5466            // bytes are key material and must never reach a log).
5467            for (ri, root) in addressing_roots.iter().enumerate() {
5468                let group = channel_rekey_group_key(root, &cid, next);
5469                let chunks = match fetch_rekey_chunks(transport, &cur.relays, &group).await {
5470                    Ok(c) => c,
5471                    Err(e) => {
5472                        crate::log_warn!(
5473                            "[v2:follow {}] ch {} next e{} root#{}/{}: rekey plane fetch failed: {}",
5474                            &cid_hex[..8], &ch_hex[..8], next.0, ri, addressing_roots.len(), e
5475                        );
5476                        return Err(e);
5477                    }
5478                };
5479                if chunks.is_empty() {
5480                    continue;
5481                }
5482                crate::log_debug!(
5483                    "[v2:follow {}] ch {} next e{} root#{}/{}: {} rekey chunk(s)",
5484                    &cid_hex[..8], &ch_hex[..8], next.0, ri, addressing_roots.len(), chunks.len()
5485                );
5486                batches.push((chunks, held_key.map(|k| (held_epoch, k))));
5487            }
5488            // Keyless-adopt residual (documented, deferred hardening): a malicious
5489            // AUTHORIZED admin can fork a keyless member onto an orphan low-key
5490            // rotation nothing extends (keyed members' continuity filters it out).
5491            // Recoverable via a fresh bundle; an insider with MANAGE_CHANNELS can
5492            // exclude the member outright anyway, so the marginal harm is the wedge
5493            // outliving their demotion.
5494            match advance_scope(&batches, RekeyScope::Channel(cid), &channel_rotator_ok, &channel_rotator_outranks_me, &cited_ok, &signer, &my_xonly, next).await {
5495                Advance::Adopt { new_key } => {
5496                    if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
5497                        ch.key = Some(new_key);
5498                        ch.epoch = next;
5499                    }
5500                    crate::log_debug!("[v2:follow {}] ch {} ADOPTED e{}", &cid_hex[..8], &ch_hex[..8], next.0);
5501                    // The adopter's own multi-epoch archive (the minter archived at
5502                    // mint) — this channel's history stays readable across rotations.
5503                    // fetch_channel compensates for the CURRENT epoch, so a failed
5504                    // archive only bites after the NEXT rotation — surface it.
5505                    if let Err(e) = crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&cid.0), next.0, &new_key) {
5506                        crate::log_warn!("v2: channel epoch-key archive failed (history across this rotation may not read back): {e}");
5507                    }
5508                    advanced = true;
5509                    changed = true;
5510                }
5511                Advance::Removed => {
5512                    match held_key {
5513                        // A complete rotation dropped my blob — cut from the channel.
5514                        Some(_) => {
5515                            cur.channels.retain(|c| c.id.0 != cid.0);
5516                        }
5517                        // Keyless scan: this epoch's rotation completed without me.
5518                        // Advance the cursor so the walk converges on the channel's
5519                        // CURRENT epoch — my entry point is its next rotation (whose
5520                        // recipients are the members at that time) or a fresh bundle.
5521                        None => {
5522                            if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
5523                                ch.epoch = next;
5524                            }
5525                        }
5526                    }
5527                    advanced = true;
5528                    changed = true;
5529                }
5530                Advance::Stay => {}
5531            }
5532        }
5533
5534        // Base rotation (Refounding): advances the root + root_epoch, re-addressing
5535        // every public channel, the guestbook, and the control plane by derivation
5536        // (refresh_subscription recomputes the author-set from the new root).
5537        {
5538            let held_epoch = cur.root_epoch;
5539            let held_key = cur.community_root;
5540            let next = Epoch(held_epoch.0.saturating_add(1));
5541            let group = base_rekey_group_key(&cur.community_root, cur.id(), next);
5542            let chunks = fetch_rekey_chunks(transport, &cur.relays, &group).await?;
5543            let batches = vec![(chunks, Some((held_epoch, held_key)))];
5544            // A non-owner Refounding may only remove members the rotator strictly
5545            // OUTRANKS. The protected set is the owner plus every grant-holder the
5546            // rotator can't act on with BAN (a peer or superior) — excluding one is
5547            // an authority-escalation takeover, so its rotation is inadmissible.
5548            // Plain members hold no grant and are always outranked by a BAN-holder,
5549            // so removing them is legitimate and needs no memberlist.
5550            let base_admissible = |r: &rekey::Rotation| -> bool {
5551                if r.rotator == owner {
5552                    return true; // the owner is supreme.
5553                }
5554                // Uncited (or citing a Grant we haven't synced) → skip entirely:
5555                // neither adopt nor conclude a removal, exactly like an
5556                // unauthorized rotation. It parks and heals on the next follow.
5557                if !cited_ok(r) {
5558                    return false;
5559                }
5560                let rotator_hex = r.rotator.to_hex();
5561                let has_blob = |xonly: &[u8; 32]| {
5562                    rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), xonly, r.scope, r.new_epoch).is_some()
5563                };
5564                // The owner is never a valid removed target.
5565                if !has_blob(&owner.to_bytes()) {
5566                    return false;
5567                }
5568                for g in &roster.grants {
5569                    if g.member == rotator_hex || g.member == owner_hex || banned.contains(&g.member) {
5570                        continue; // self, owner (checked), or an already-authorized removal.
5571                    }
5572                    // A grant-holder the rotator can't act on is a peer/superior.
5573                    if !roster.can_act_on_member(&rotator_hex, Some(&owner_hex), &g.member, crate::community::roles::Permissions::BAN) {
5574                        if let Ok(pk) = PublicKey::from_hex(&g.member) {
5575                            if !has_blob(&pk.to_bytes()) {
5576                                return false; // a peer/superior was excluded.
5577                            }
5578                        }
5579                    }
5580                }
5581                true
5582            };
5583            match advance_scope(&batches, RekeyScope::Root, &base_rotator_ok, &base_rotator_outranks_me, &base_admissible, &signer, &my_xonly, next).await {
5584                Advance::Adopt { new_key } => {
5585                    cur.community_root = new_key;
5586                    cur.root_epoch = next;
5587                    // Archive on adopt: without this, a member who lived through TWO
5588                    // Refoundings loses the middle epoch's public history (only the
5589                    // minter archived it).
5590                    if let Err(e) = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, next.0, &new_key) {
5591                        crate::log_warn!("v2: base epoch-key archive failed (this epoch's history may not read back after the next rotation): {e}");
5592                    }
5593                    advanced = true;
5594                    changed = true;
5595                }
5596                Advance::Removed => {
5597                    if !session.is_valid() {
5598                        return Err("account changed during rekey follow".to_string());
5599                    }
5600                    return Ok(RekeyFollow { updated: None, self_removed: true, dissolved: false });
5601                }
5602                Advance::Stay => {}
5603            }
5604        }
5605
5606        if !advanced {
5607            break;
5608        }
5609    }
5610
5611    if !changed {
5612        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: false });
5613    }
5614    if !session.is_valid() {
5615        return Err("account changed during rekey follow".to_string());
5616    }
5617    // A leave/delete raced this follow: saving would resurrect the community row
5618    // (the save is an upsert) with no floor rows behind it.
5619    if crate::db::community::community_protocol(community.id())?.is_none() {
5620        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: false });
5621    }
5622    crate::db::community::save_community_v2(&cur)?;
5623    // Carry my own live links across the rotation someone ELSE performed
5624    // (CORD-05 §2). The refounder refreshes only the bundles they can reach —
5625    // their own — so without this every other creator's links keep vending the
5626    // superseded root and drop new joiners onto a dead epoch, which is exactly
5627    // the stranding the stable-URL refresh exists to prevent. Best-effort and
5628    // idempotent: a creator with no links for this community returns early, and
5629    // a failure only delays the heal until the next adoption or refound.
5630    let _ = refresh_public_links(transport, &cur).await;
5631    Ok(RekeyFollow { updated: Some(cur), self_removed: false, dissolved: false })
5632}
5633
5634/// One scope's catch-up decision from the rekey chunks fetched at its next-epoch
5635/// address.
5636enum Advance {
5637    /// Adopt this fresh key for `next_epoch`.
5638    Adopt { new_key: [u8; 32] },
5639    /// A complete owner rotation at `next_epoch` dropped my blob — I'm removed.
5640    Removed,
5641    /// No owner rotation extends my held epoch (yet) — keep the current key.
5642    Stay,
5643}
5644
5645/// Fetch + parse every seal-verified 3303 chunk at a rekey plane address.
5646async fn fetch_rekey_chunks<T: Transport + ?Sized>(
5647    transport: &T,
5648    relays: &[String],
5649    group: &GroupKey,
5650) -> Result<Vec<rekey::RekeyChunk>, String> {
5651    // A rekey plane address is community_root-derived, so ANY member can seal junk
5652    // 3303s there — a flood (or, organically, a large community's own multi-chunk
5653    // rotation past the newest window) could bury the genuine owner/admin rotation
5654    // in a single fixed page. PAGE backwards (inclusive until + wrap-id dedup, the
5655    // control pager's discipline) so a buried authorized chunk is still recovered;
5656    // the seal + authority filter downstream drops the junk. Bounded — a sustained
5657    // flood past this depth degrades to "adopt one pass late", never a false state.
5658    const REKEY_PAGE: usize = 200;
5659    const REKEY_MAX_PAGES: usize = 6;
5660    let mut out = Vec::new();
5661    let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
5662    let mut until: Option<u64> = None;
5663    let mut oldest: Option<u64> = None;
5664    for _ in 0..REKEY_MAX_PAGES {
5665        let query = Query {
5666            kinds: vec![stream::KIND_WRAP],
5667            authors: vec![group.pk_hex()],
5668            until,
5669            limit: Some(REKEY_PAGE),
5670            ..Default::default()
5671        };
5672        // Authenticate AS the rekey plane key: on AUTH-gating relays (Ditto) the
5673        // shared user-authed client's REQ for a plane's events is CLOSED, so an
5674        // offline rotation catch-up would return nothing and wedge at the old
5675        // epoch. `fetch_plane` rides a connection authed as the plane itself.
5676        let wraps = transport.fetch_plane(group.keys(), &query, relays).await?;
5677        let mut fresh = 0usize;
5678        for w in &wraps {
5679            if !seen.insert(w.id) {
5680                continue;
5681            }
5682            fresh += 1;
5683            let at = w.created_at.as_secs();
5684            if oldest.is_none_or(|o| at < o) {
5685                oldest = Some(at);
5686            }
5687            if let Ok(opened) = stream::open_wrap(w, group) {
5688                if let Ok(chunk) = rekey::parse_rekey_chunk(&opened) {
5689                    out.push(chunk);
5690                }
5691            }
5692        }
5693        // Drained, or a same-second wall the pager can't step past (second-granular
5694        // until) — either way stop; the accumulated set is what advance_scope folds.
5695        if fresh == 0 || wraps.len() < REKEY_PAGE {
5696            break;
5697        }
5698        match oldest {
5699            Some(o) if o > 0 => until = Some(o),
5700            _ => break,
5701        }
5702    }
5703    Ok(out)
5704}
5705
5706/// Decide how a scope advances from per-addressing-root chunk batches (pure). Each
5707/// batch pairs the chunks fetched under one root with the continuity to demand of
5708/// them: a rotation qualifies when it's rotator-authorized (`rotator_ok`),
5709/// complete, targets the immediate `next_epoch`, and — when I hold a chain —
5710/// extends my exact `(epoch, key)`. A KEYLESS batch (`held` = None) has no chain
5711/// to extend, so it qualifies on authority + completeness alone (CORD-06 §2:
5712/// continuity is "a convergence check, not a secrecy mechanism"; the rotator's
5713/// seal authority is the boundary). Among qualifying rotations carrying my blob
5714/// the lexicographically lowest new key wins (convergent). All complete
5715/// candidates without my blob conclude Removed for a KEYED holder only when one
5716/// came from a rotator who may remove ME (`rotator_may_remove_me`, the CORD-06
5717/// strict-outrank rule) — else Stay; for a keyless holder they merely advance the
5718/// scan cursor (any bit-holder's real rotation is scan progress, never a loss).
5719async fn advance_scope<S: crate::signer::VectorSigner + ?Sized>(
5720    batches: &[(Vec<rekey::RekeyChunk>, Option<(Epoch, [u8; 32])>)],
5721    scope: RekeyScope,
5722    rotator_ok: &(dyn Fn(&PublicKey) -> bool + Sync),
5723    rotator_may_remove_me: &(dyn Fn(&PublicKey) -> bool + Sync),
5724    admissible: &(dyn Fn(&rekey::Rotation) -> bool + Sync),
5725    signer: &S,
5726    my_xonly: &[u8; 32],
5727    next_epoch: Epoch,
5728) -> Advance {
5729    let mut winners: Vec<[u8; 32]> = Vec::new();
5730    let mut saw_complete_candidate = false;
5731    let mut saw_outranking_candidate = false;
5732    let keyed = batches.iter().any(|(_, held)| held.is_some());
5733    for (chunks, held) in batches {
5734        let rotations = rekey::collect_rotations(chunks);
5735        for r in &rotations {
5736            if !rotator_ok(&r.rotator) || r.scope.id32() != scope.id32() || r.new_epoch.0 != next_epoch.0 || !r.is_complete() {
5737                continue;
5738            }
5739            if let Some((held_epoch, held_key)) = held {
5740                if r.continuity(*held_epoch, held_key) != Continuity::Extends {
5741                    continue;
5742                }
5743            }
5744            // CORD-06 §Authority: a rotator must strictly OUTRANK every removed
5745            // target. An authorized-but-inadmissible rotation (one that excludes
5746            // the owner or a peer/superior the rotator can't act on) is a takeover
5747            // attempt — skip it entirely, so it neither adopts nor concludes a
5748            // removal (it forks; the honest chain wins).
5749            if !admissible(r) {
5750                continue;
5751            }
5752            saw_complete_candidate = true;
5753            saw_outranking_candidate |= rotator_may_remove_me(&r.rotator);
5754            if let Some(blob) = rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), my_xonly, r.scope, r.new_epoch) {
5755                if let Ok(k) = rekey::open_blob(signer, &r.rotator, r.scope, r.new_epoch, blob).await {
5756                    winners.push(k);
5757                }
5758            }
5759        }
5760    }
5761    if !winners.is_empty() {
5762        // `collect_rotations` correlates on `(rotator, scope, new_epoch, prev_commit)`,
5763        // so a single rotator's blobs merge into ONE rotation (and a retried Refounding
5764        // MINT-OR-REUSES its root, so it never emits two distinct roots to fork on).
5765        // The lowest-key tiebreak engages only for CONCURRENT DISTINCT rotators racing
5766        // the same epoch (separate rotations): every follower converges on the same
5767        // lowest new key. A wrap served under two addressing roots can't double-count:
5768        // each rekey wrap opens under exactly one root's group key.
5769        let idx = rekey::lowest_key_winner(&winners).expect("winners is non-empty");
5770        return Advance::Adopt { new_key: winners[idx] };
5771    }
5772    if saw_complete_candidate && (!keyed || saw_outranking_candidate) {
5773        Advance::Removed
5774    } else {
5775        Advance::Stay
5776    }
5777}
5778
5779#[cfg(test)]
5780mod tests {
5781    use crate::ClientRelayExt;
5782    use nostr_sdk::prelude::FinalizeEvent;
5783    use super::super::super::transport::memory::MemoryRelay;
5784    use super::*;
5785    use crate::community::roles::{MemberGrant, Permissions, Role, RoleScope};
5786
5787    /// A distinct npub-shaped account-dir name (bech32 charset) per counter.
5788    fn account_name(n: u32) -> String {
5789        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
5790        let mut acct = String::from("npub1");
5791        let mut v = n as usize;
5792        for _ in 0..58 {
5793            acct.push(B[v % 32] as char);
5794            v = v / 32 + 7;
5795        }
5796        acct
5797    }
5798
5799    /// One test participant: its identity keys and its isolated account DB dir.
5800    struct Actor {
5801        keys: Keys,
5802        account: String,
5803    }
5804
5805    /// Two participants sharing one relay but isolated per-account DBs — the
5806    /// cross-account harness a real invite/join loop needs. `swap_to` mirrors a
5807    /// live `swap_session`: re-point the DB pool + rebind the identity + clear
5808    /// the per-account id caches, so account A's community is invisible to B
5809    /// until B legitimately joins.
5810    struct TestBed {
5811        _tmp: tempfile::TempDir,
5812        _guard: std::sync::MutexGuard<'static, ()>,
5813        relay: MemoryRelay,
5814        relays: Vec<String>,
5815    }
5816
5817    impl TestBed {
5818        fn new() -> (TestBed, Actor, Actor) {
5819            static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(70_000);
5820            let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
5821            crate::db::close_database();
5822            crate::db::clear_id_caches();
5823            let tmp = tempfile::tempdir().unwrap();
5824            crate::db::set_app_data_dir(tmp.path().to_path_buf());
5825
5826            let mk = || {
5827                let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5828                let account = account_name(n);
5829                std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
5830                crate::db::set_current_account(account.clone()).unwrap();
5831                crate::db::init_database(&account).unwrap();
5832                Actor { keys: Keys::generate(), account }
5833            };
5834            let owner = mk();
5835            let member = mk();
5836            let _ = crate::state::take_nostr_client();
5837            let bed = TestBed {
5838                _tmp: tmp,
5839                _guard: guard,
5840                relay: MemoryRelay::new(),
5841                relays: vec!["wss://r".to_string()],
5842            };
5843            (bed, owner, member)
5844        }
5845
5846        /// Become `actor`: swap the account DB + identity, as a real session swap.
5847        /// Bumps the session generation like production `swap_session` does — so any task a
5848        /// prior actor spawned (e.g. the migration finalize) dies at its SessionGuard check
5849        /// instead of racing this actor's DB (a cross-test flake that can't happen in prod).
5850        fn swap_to(&self, actor: &Actor) {
5851            crate::state::bump_session_generation();
5852            crate::db::set_current_account(actor.account.clone()).unwrap();
5853            crate::db::init_database(&actor.account).unwrap();
5854            crate::db::clear_id_caches();
5855            crate::state::MY_SECRET_KEY.store_from_keys(&actor.keys, &[]);
5856            crate::state::set_my_public_key(actor.keys.public_key());
5857        }
5858    }
5859
5860    /// Legacy single-actor helper (the create/send tests below).
5861    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
5862        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
5863        crate::db::close_database();
5864        crate::db::clear_id_caches();
5865        let tmp = tempfile::tempdir().unwrap();
5866        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(50_000);
5867        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5868        let acct = account_name(n);
5869        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
5870        crate::db::set_app_data_dir(tmp.path().to_path_buf());
5871        crate::db::set_current_account(acct.clone()).unwrap();
5872        crate::db::init_database(&acct).unwrap();
5873        let _ = crate::state::take_nostr_client();
5874        let owner = Keys::generate();
5875        crate::state::MY_SECRET_KEY.store_from_keys(&owner, &[]);
5876        crate::state::set_my_public_key(owner.public_key());
5877        (tmp, guard, owner)
5878    }
5879
5880    /// A transport that simulates a session swap landing DURING a fetch await —
5881    /// so a join straddling the fetch sees an invalid session and aborts.
5882    struct SwapMidFetch {
5883        inner: MemoryRelay,
5884    }
5885    #[async_trait::async_trait]
5886    impl Transport for SwapMidFetch {
5887        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
5888        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
5889            self.inner.publish(e, r).await
5890        }
5891        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
5892            self.inner.publish_durable(e, r).await
5893        }
5894        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
5895            let out = self.inner.fetch(q, r).await;
5896            crate::state::bump_session_generation();
5897            out
5898        }
5899    }
5900
5901    /// Bumps the session generation on the first `publish_durable` — the rekey
5902    /// crate a private-channel create ships before it writes anything locally.
5903    struct SwapMidPublish {
5904        inner: MemoryRelay,
5905    }
5906    #[async_trait::async_trait]
5907    impl Transport for SwapMidPublish {
5908        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
5909        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
5910            self.inner.publish(e, r).await
5911        }
5912        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
5913            let out = self.inner.publish_durable(e, r).await;
5914            crate::state::bump_session_generation();
5915            out
5916        }
5917        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
5918            self.inner.fetch(q, r).await
5919        }
5920    }
5921
5922    /// A transport whose `fetch` returns a FIXED, UNSORTED event list — modelling
5923    /// the production `LiveTransport` union (first-responding relay's batch, no
5924    /// global newest-first sort), which `MemoryRelay` hides by sorting. This is
5925    /// the only harness that can exercise the revocation-race ordering.
5926    struct FixedFetch {
5927        events: Vec<Event>,
5928    }
5929    #[async_trait::async_trait]
5930    impl Transport for FixedFetch {
5931        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
5932        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
5933            Ok(())
5934        }
5935        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
5936            Ok(())
5937        }
5938        async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
5939            Ok(self.events.clone())
5940        }
5941    }
5942
5943    /// Fetch a pending Direct Invite (kind 3313 giftwrap) addressed to `me` — the
5944    /// indexed inbox query CORD-05 §6 defines: `{1059, #p:[me], #k:["3313"]}`.
5945    async fn fetch_direct_invite(relay: &MemoryRelay, relays: &[String], me: &PublicKey) -> Event {
5946        let q = Query {
5947            kinds: vec![stream::KIND_WRAP],
5948            p_tags: vec![me.to_hex()],
5949            k_tags: vec!["3313".to_string()],
5950            ..Default::default()
5951        };
5952        relay.fetch(&q, relays).await.unwrap().into_iter().next().expect("a direct invite is waiting")
5953    }
5954
5955    #[tokio::test]
5956    async fn create_persists_and_reloads_a_v2_community() {
5957        let (_tmp, _guard, owner) = init_test_db();
5958        let relay = MemoryRelay::new();
5959        let relays = vec!["wss://r".to_string()];
5960
5961        let created = create_community(&relay, "Vectorville", relays.clone(), Some("hi".into())).await.unwrap();
5962        assert!(created.identity.verify());
5963        assert_eq!(created.owner().unwrap(), owner.public_key());
5964        assert_eq!(created.channels.len(), 1);
5965
5966        // Protocol dispatch sees it as v2, and it reloads byte-faithfully.
5967        assert_eq!(
5968            crate::db::community::community_protocol(created.id()).unwrap(),
5969            Some(crate::community::ConcordProtocol::V2)
5970        );
5971        let loaded = crate::db::community::load_community_v2(created.id()).unwrap().expect("reloads");
5972        assert_eq!(loaded.name, "Vectorville");
5973        assert_eq!(loaded.community_root, created.community_root);
5974        assert_eq!(loaded.identity, created.identity);
5975        assert_eq!(loaded.channels[0].id.0, created.channels[0].id.0);
5976        assert!(!loaded.channels[0].private);
5977
5978        // The genesis control editions + the owner Join landed on the relay.
5979        assert!(relay.count_on("wss://r") >= 3, "2 genesis editions + 1 guestbook join");
5980    }
5981
5982    #[tokio::test]
5983    async fn owner_sends_and_reads_back_a_message() {
5984        let (_tmp, _guard, _owner) = init_test_db();
5985        let relay = MemoryRelay::new();
5986        let community = create_community(&relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
5987        let general = community.channels[0].id;
5988
5989        let id1 = send_message(&relay, &community, &general, "hello world").await.unwrap();
5990        let id2 = send_message(&relay, &community, &general, "second message").await.unwrap();
5991        assert_ne!(id1, id2);
5992
5993        let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
5994        let texts: Vec<String> = page
5995            .iter()
5996            .filter_map(|f| match &f.event {
5997                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
5998                _ => None,
5999            })
6000            .collect();
6001        assert_eq!(texts, vec!["hello world", "second message"], "messages round-trip in ms order");
6002    }
6003
6004    #[tokio::test]
6005    async fn a_second_member_reads_the_public_channel_from_the_root() {
6006        // A member who holds the community_root (via an invite bundle, modeled
6007        // here by cloning the community) reads the owner's public-channel message
6008        // — public channels need no key delivery, they derive from the root.
6009        let (_tmp, _guard, _owner) = init_test_db();
6010        let relay = MemoryRelay::new();
6011        let community = create_community(&relay, "Public", vec!["wss://r".into()], None).await.unwrap();
6012        let general = community.channels[0].id;
6013        send_message(&relay, &community, &general, "everyone can read this").await.unwrap();
6014
6015        // The "member" reconstructs the same read coordinates from the root.
6016        let member_view = community.clone();
6017        let page = fetch_channel(&relay, &member_view, &general, 100).await.unwrap();
6018        assert_eq!(page.len(), 1);
6019        assert!(matches!(&page[0].event, ChatEvent::Message { .. }));
6020        assert_eq!(page[0].event.opened().rumor.content, "everyone can read this");
6021    }
6022
6023    // ── Two-actor end-to-end (the create → invite → join → message loop) ──────
6024
6025    async fn texts_in<T: crate::community::transport::Transport + ?Sized>(relay: &T, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
6026        fetch_channel(relay, community, channel, 100)
6027            .await
6028            .unwrap()
6029            .iter()
6030            .filter_map(|f| match &f.event {
6031                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
6032                _ => None,
6033            })
6034            .collect()
6035    }
6036
6037    #[tokio::test]
6038    async fn direct_invite_full_loop_owner_and_member_converse() {
6039        let (bed, owner, member) = TestBed::new();
6040
6041        // Owner creates a community, posts, and Direct-Invites the member's npub.
6042        bed.swap_to(&owner);
6043        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
6044        let general = community.channels[0].id;
6045        send_message(&bed.relay, &community, &general, "owner: welcome!").await.unwrap();
6046        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
6047
6048        // Member (a DIFFERENT account, no prior knowledge) finds + accepts the invite.
6049        bed.swap_to(&member);
6050        assert!(
6051            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
6052            "the member does not hold the community before joining"
6053        );
6054        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6055        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
6056        assert_eq!(joined.id().0, community.id().0, "joined the same community");
6057        assert!(joined.identity.verify(), "the joiner independently verifies the owner commitment");
6058        assert_eq!(joined.owner().unwrap(), owner.keys.public_key());
6059
6060        // The member reads the owner's public-channel history and replies.
6061        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome!"]);
6062        send_message(&bed.relay, &joined, &general, "member: thanks for the invite").await.unwrap();
6063
6064        // The owner reads the member's reply.
6065        bed.swap_to(&owner);
6066        assert_eq!(
6067            texts_in(&bed.relay, &community, &general).await,
6068            vec!["owner: welcome!", "member: thanks for the invite"],
6069            "both actors' messages interleave in ms order on the shared channel"
6070        );
6071
6072        // The Guestbook memberlist now folds both participants.
6073        let members = memberlist(&bed.relay, &community).await.unwrap();
6074        assert!(members.contains(&owner.keys.public_key()), "owner is a member (genesis Join)");
6075        assert!(members.contains(&member.keys.public_key()), "member is a member (invite Join)");
6076        assert_eq!(members.len(), 2);
6077    }
6078
6079    /// Join-time ban gate: an honest client whose npub is on the authorized banlist
6080    /// refuses to join — no Guestbook Join publish, no local write — through the shared
6081    /// accept path every door (direct invite, parked, public link, migration) funnels into.
6082    #[tokio::test]
6083    async fn a_banned_member_is_refused_at_join_time() {
6084        let (bed, owner, member) = TestBed::new();
6085
6086        bed.swap_to(&owner);
6087        let community = create_community(&bed.relay, "NoEntry", bed.relays.clone(), None).await.unwrap();
6088        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
6089        set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();
6090
6091        bed.swap_to(&member);
6092        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6093        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
6094        assert!(err.contains("banned"), "refusal names the reason: {err}");
6095        assert!(
6096            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
6097            "a refused join persists nothing"
6098        );
6099
6100        // The gate is the LAST word only for banned members: an unbanned bystander with
6101        // the same invite path still joins (the gate doesn't over-refuse).
6102        bed.swap_to(&owner);
6103        set_banlist(&bed.relay, &community, &[]).await.unwrap();
6104        bed.swap_to(&member);
6105        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
6106        assert_eq!(joined.id().0, community.id().0, "unban restores joinability");
6107    }
6108
6109    /// End-to-end member migration: a member holding a v1 community folds the owner's
6110    /// migration dissolution, opens `m`, joins the v2 twin (ban-gated), and the flip
6111    /// re-parents the stitched channel rows + stamps the fence — all from the single event.
6112    #[tokio::test]
6113    async fn member_migrates_v1_to_v2_from_the_dissolution_payload() {
6114        use crate::community::migration;
6115        let (bed, owner, member) = TestBed::new();
6116
6117        // Owner builds the v2 twin (real, verifiable on the shared relay).
6118        bed.swap_to(&owner);
6119        let v2 = create_community(&bed.relay, "Guild v2", bed.relays.clone(), None).await.unwrap();
6120        let v2_hex = crate::simd::hex::bytes_to_hex_32(&v2.identity.community_id.0);
6121        let jm = join_material(&v2);
6122
6123        // The member holds a v1 community owned by the SAME owner identity (the migration
6124        // premise) — construct + save it, and hold its server root.
6125        bed.swap_to(&member);
6126        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6127        let v1_cid = v1.id.to_hex();
6128        v1.owner_attestation = Some({
6129            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6130                .finalize(&owner.keys).unwrap().as_json()
6131        });
6132        crate::db::community::save_community(&v1).unwrap();
6133        let v1_channel = v1.channels[0].id.to_hex();
6134
6135        // The dissolution payload: v2 JoinMaterial sealed under the v1 server root.
6136        let m = migration::seal_m(v1.server_root_key.as_bytes(), &serde_json::to_vec(&jm).unwrap()).unwrap();
6137        let signpost = migration::MigrationSignpost {
6138            v2_community_id: v2_hex.clone(),
6139            owner_xonly: owner.keys.public_key().to_hex(),
6140            owner_salt: crate::simd::hex::bytes_to_hex_32(&v2.identity.owner_salt),
6141            relays: bed.relays.clone(),
6142            name: "Guild".into(),
6143            primary_channel: v1_channel.clone(),
6144            root_epoch: 0,
6145        };
6146        let content = migration::build_migration_content(&signpost, Some(m)).unwrap();
6147        crate::db::community::set_migration_pointer(&v1_cid, &content).unwrap();
6148
6149        // Drive the migration: opens m, joins v2 (ban-gated), flips.
6150        let flipped = migration::drive_migration(&bed.relay, &v1).await.unwrap();
6151        assert_eq!(flipped.as_deref(), Some(v2_hex.as_str()), "the flip completed to the v2 twin");
6152
6153        // Fence: the v1 community is terminally marked, and the v2 twin is held + joined.
6154        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()));
6155        assert!(crate::db::community::get_community_dissolved(&v1_cid).unwrap(), "flip also seals v1 (fence layer 0)");
6156        assert!(crate::db::community::load_community_v2(&v2.identity.community_id).unwrap().is_some(), "v2 twin held");
6157        let _ = v1_channel;
6158
6159        // Idempotent: a second drive is a no-op (already flipped).
6160        assert_eq!(migration::drive_migration(&bed.relay, &v1).await.unwrap(), None);
6161    }
6162
6163    /// The OWNER wizard end-to-end: build the twin (primary channel reuses the v1 id),
6164    /// seal + publish the carrier, flip the owner. Then a MEMBER holding the v1 community
6165    /// folds the same carrier and stitches — proving the channel-STITCH the earlier test
6166    /// couldn't (that twin had mismatched ids).
6167    #[tokio::test]
6168    async fn owner_wizard_then_member_migrate_and_stitch() {
6169        use crate::community::migration;
6170        let (bed, owner, member) = TestBed::new();
6171        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6172
6173        // Owner holds a v1 community (they created it) with one channel.
6174        bed.swap_to(&owner);
6175        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6176        let v1_cid = v1.id.to_hex();
6177        let v1_channel = v1.channels[0].id.to_hex();
6178        v1.owner_attestation = Some({
6179            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6180                .finalize(&owner.keys).unwrap().as_json()
6181        });
6182        crate::db::community::save_community(&v1).unwrap();
6183
6184        // Run the wizard.
6185        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6186        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()),
6187            "owner's own client flipped to v2");
6188        // The owner's v1 channel row re-parented to the twin (stitch), because the twin's
6189        // primary channel REUSES the v1 channel id.
6190        assert_eq!(crate::db::community::community_id_for_channel(&v1_channel).unwrap().as_deref(), Some(v2_hex.as_str()),
6191            "owner channel stitched to v2");
6192
6193        // A MEMBER holding the same v1 community folds the carrier and migrates.
6194        bed.swap_to(&member);
6195        let mut m_v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6196        // The member's v1 community must be the SAME id + root the owner published under.
6197        m_v1.id = v1.id;
6198        m_v1.server_root_key = v1.server_root_key.clone();
6199        m_v1.channels[0].id = v1.channels[0].id;
6200        m_v1.owner_attestation = v1.owner_attestation.clone();
6201        crate::db::community::save_community(&m_v1).unwrap();
6202
6203        // Fold the carrier off the relay: the dissolution arm seals, persists the pointer,
6204        // AND auto-drives the flip — the live one-event member experience, no manual step.
6205        crate::community::service::fetch_and_apply_control(&bed.relay, &m_v1).await.unwrap();
6206        assert!(crate::db::community::get_community_dissolved(&v1_cid).unwrap(), "member sees v1 sealed");
6207        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()),
6208            "the FOLD ITSELF flipped the member (auto-drive)");
6209        assert!(crate::db::community::load_community_v2(&crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&v2_hex))).unwrap().is_some(),
6210            "member holds the v2 twin");
6211        // A manual re-drive is an idempotent no-op.
6212        assert_eq!(migration::drive_migration(&bed.relay, &m_v1).await.unwrap(), None);
6213    }
6214
6215    /// The wizard records the twin in the cross-device community list, like every other v2
6216    /// join/create path. Sibling devices normally discover the twin by folding the carrier
6217    /// themselves, but one that no longer holds the v1 community has no carrier to fold, so
6218    /// the list is its only route in.
6219    #[tokio::test]
6220    async fn wizard_publishes_the_twin_to_the_cross_device_list() {
6221        use crate::community::migration;
6222        let (bed, owner, _member) = TestBed::new();
6223        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6224
6225        bed.swap_to(&owner);
6226        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6227        let v1_cid = v1.id.to_hex();
6228        v1.owner_attestation = Some({
6229            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6230                .finalize(&owner.keys).unwrap().as_json()
6231        });
6232        crate::db::community::save_community(&v1).unwrap();
6233
6234        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6235
6236        // The twin is live in the published list, so a fresh/carrier-less device finds it.
6237        let list = fetch_community_list(&bed.relay, &bed.relays).await.unwrap()
6238            .expect("the wizard published a community list");
6239        assert!(list.is_live(&v2_hex), "the twin must be live in the cross-device list");
6240        // The v1 community is NOT tombstoned there: a tombstone reads as "you left" and
6241        // `sync_community_list` would tear down a sibling's v1 row before it can fold the
6242        // carrier, stranding it. The local `migrated_to` fence is what stops v1 ghosts.
6243        assert!(
6244            !list.tombstones.iter().any(|t| t.community_id == v1_cid),
6245            "migration must not tombstone the v1 community"
6246        );
6247    }
6248
6249    /// The wizard takes the same per-cid claim the member drive does, so a double-fired
6250    /// command (or the owner's own carrier self-fold racing the wizard's phase 2→3 gap)
6251    /// cannot run two wizards: the second would re-mint a twin before the ledger lands
6252    /// (the double-mint orphan) and race its flip against the first.
6253    #[tokio::test]
6254    async fn wizard_refuses_while_a_drive_holds_the_claim() {
6255        use crate::community::migration;
6256        let (bed, owner, _member) = TestBed::new();
6257        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6258
6259        bed.swap_to(&owner);
6260        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6261        let v1_cid = v1.id.to_hex();
6262        v1.owner_attestation = Some({
6263            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6264                .finalize(&owner.keys).unwrap().as_json()
6265        });
6266        crate::db::community::save_community(&v1).unwrap();
6267
6268        // Simulate the concurrent drive holding the cid (what the live carrier fold does).
6269        migration::test_hold_drive_claim(&v1_cid);
6270        let err = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap_err();
6271        assert!(err.contains("already in progress"), "second wizard refused, got: {err}");
6272        // Refused BEFORE minting: no twin, no ledger, nothing to orphan.
6273        assert!(crate::db::community::get_migration_ledger(&v1_cid).unwrap().is_none(), "no ledger row was written");
6274        assert!(crate::db::community::get_migrated_to(&v1_cid).unwrap().is_none(), "no flip happened");
6275
6276        // Once the drive releases, the wizard runs normally.
6277        migration::test_release_drive_claim(&v1_cid);
6278        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6279        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()));
6280    }
6281
6282    /// The flip runs UNDER the twin's follow lock, so it can never straddle a follow
6283    /// worker's whole-row save (which deletes channel rows absent from its pre-flip,
6284    /// channel-less struct — pruning exactly the rows the flip just re-parented).
6285    /// Proves the lock actually serializes rather than being a no-op: with the lock held
6286    /// the wizard cannot reach its flip, and it completes once released.
6287    #[tokio::test]
6288    async fn wizard_flip_waits_for_an_in_flight_follow_pass() {
6289        use crate::community::migration;
6290        let (bed, owner, _member) = TestBed::new();
6291        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6292        // Shared across the spawned wizard, so both halves see the same relay state.
6293        let relay = std::sync::Arc::new(MemoryRelay::new());
6294
6295        bed.swap_to(&owner);
6296        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6297        let v1_cid = v1.id.to_hex();
6298        let v1_channel = v1.channels[0].id.to_hex();
6299        v1.owner_attestation = Some({
6300            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6301                .finalize(&owner.keys).unwrap().as_json()
6302        });
6303        crate::db::community::save_community(&v1).unwrap();
6304
6305        // Phase 1 alone, so the twin's id (and therefore its follow lock) is known before
6306        // the flip runs — exactly what a follow worker would have loaded.
6307        let twin = create_migration_twin(
6308            &*relay, "Guild", bed.relays.clone(), None,
6309            (v1.channels[0].id, "general".to_string()),
6310        ).await.unwrap();
6311        let v2_id = twin.identity.community_id;
6312        let v2_hex = crate::simd::hex::bytes_to_hex_32(&v2_id.0);
6313        crate::db::community::set_migration_ledger(&v1_cid, &v2_hex, migration::PHASE_TWIN_MINTED, "").unwrap();
6314
6315        // A follow pass is in flight: it holds the lock across its network stage.
6316        let held = crate::community::v2::realtime::follow_lock(&v2_id).lock_owned().await;
6317
6318        let wizard = tokio::spawn({
6319            let relay = relay.clone();
6320            let v1 = v1.clone();
6321            async move { migration::migrate_community_to_v2(&*relay, &v1, unlocked).await }
6322        });
6323
6324        // The wizard runs its network phases but must BLOCK at the flip.
6325        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
6326        assert!(!wizard.is_finished(), "the flip must wait for the in-flight follow pass");
6327        assert!(
6328            crate::db::community::get_migrated_to(&v1_cid).unwrap().is_none(),
6329            "the fence must not be stamped while the follow lock is held"
6330        );
6331
6332        // The follow pass finishes; the flip proceeds.
6333        drop(held);
6334        let flipped = wizard.await.unwrap().unwrap();
6335        assert_eq!(flipped, v2_hex, "the wizard completed onto the SAME twin (resumed, never re-minted)");
6336        assert_eq!(
6337            crate::db::community::community_id_for_channel(&v1_channel).unwrap().as_deref(),
6338            Some(v2_hex.as_str()),
6339            "the channel row is stitched to the twin, not pruned"
6340        );
6341    }
6342
6343    /// THE LYNCHPIN: a banned-but-never-cut v1 member CAN open `m` (they hold the v1
6344    /// root — no read-cut ever rotated it), but the wizard cloned the v1 banlist onto the
6345    /// twin, so the ban-gated accept refuses them: no Guestbook Join, no flip, room stays
6346    /// sealed. This is the exact residual JSKitty accepted, proven enforced.
6347    #[tokio::test]
6348    async fn banned_never_cut_member_opens_m_but_cannot_migrate() {
6349        use crate::community::migration;
6350        let (bed, owner, banned) = TestBed::new();
6351        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6352
6353        // Owner's v1 community with the member on the BANLIST (never read-cut: epoch 0).
6354        bed.swap_to(&owner);
6355        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6356        let v1_cid = v1.id.to_hex();
6357        v1.owner_attestation = Some({
6358            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6359                .finalize(&owner.keys).unwrap().as_json()
6360        });
6361        crate::db::community::save_community(&v1).unwrap();
6362        crate::db::community::set_community_banlist(&v1_cid, &[banned.keys.public_key().to_hex()], 1_000).unwrap();
6363
6364        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6365
6366        // The banned member holds the same v1 (same root — never cut) and folds the carrier.
6367        bed.swap_to(&banned);
6368        let mut m_v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6369        m_v1.id = v1.id;
6370        m_v1.server_root_key = v1.server_root_key.clone();
6371        m_v1.channels[0].id = v1.channels[0].id;
6372        m_v1.owner_attestation = v1.owner_attestation.clone();
6373        crate::db::community::save_community(&m_v1).unwrap();
6374        crate::community::service::fetch_and_apply_control(&bed.relay, &m_v1).await.unwrap();
6375
6376        // They hold the pointer AND can open `m` — but the drive is REFUSED at the ban gate.
6377        let raw = crate::db::community::get_migration_pointer(&v1_cid).unwrap().expect("pointer lands");
6378        let payload = migration::parse_migration_payload(&raw).unwrap();
6379        assert!(payload.m.is_some());
6380        let err = migration::drive_migration(&bed.relay, &m_v1).await.unwrap_err();
6381        assert!(err.contains("banned"), "refused at the join-time ban gate: {err}");
6382        assert!(crate::db::community::get_migrated_to(&v1_cid).unwrap().is_none(), "no flip");
6383        assert!(
6384            crate::db::community::load_community_v2(&crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&v2_hex))).unwrap().is_none(),
6385            "banned member never acquires the v2 twin"
6386        );
6387    }
6388
6389    /// Wizard resume never double-mints: a re-run after the TWIN_MINTED ledger row exists
6390    /// completes on the SAME v2 identity — with a NON-vacuous phase-1b re-run (a sibling
6391    /// channel + a banlist entry crash-recovered end-to-end, sibling stitched). Plus the
6392    /// crash-heal: flip landed but the FLIPPED ledger write didn't → re-run reports success.
6393    #[tokio::test]
6394    async fn wizard_resume_continues_on_the_same_twin() {
6395        use crate::community::migration;
6396        let (bed, owner, banned) = TestBed::new();
6397        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6398
6399        bed.swap_to(&owner);
6400        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6401        // A second channel + a banned member make the resumed phase-1b tail REAL work.
6402        let mut sibling = v1.channels[0].clone();
6403        sibling.id = crate::community::ChannelId(crate::community::random_32());
6404        sibling.name = "offtopic".into();
6405        v1.channels.push(sibling.clone());
6406        let v1_cid = v1.id.to_hex();
6407        v1.owner_attestation = Some({
6408            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6409                .finalize(&owner.keys).unwrap().as_json()
6410        });
6411        crate::db::community::save_community(&v1).unwrap();
6412        crate::db::community::set_community_banlist(&v1_cid, &[banned.keys.public_key().to_hex()], 1_000).unwrap();
6413
6414        // Simulate a crash right after the mint: build the twin + ledger TWIN_MINTED, stop
6415        // BEFORE the sibling channel + banlist clone ever ran.
6416        let twin = create_migration_twin(&bed.relay, &v1.name, bed.relays.clone(), None, (v1.channels[0].id, "general".into())).await.unwrap();
6417        let minted_hex = crate::simd::hex::bytes_to_hex_32(&twin.identity.community_id.0);
6418        crate::db::community::set_migration_ledger(&v1_cid, &minted_hex, migration::PHASE_TWIN_MINTED, "").unwrap();
6419
6420        // The re-run resumes onto the SAME identity, re-runs 1b, and completes.
6421        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6422        assert_eq!(v2_hex, minted_hex, "no second twin was minted");
6423        let (ledger_v2, phase, _) = crate::db::community::get_migration_ledger(&v1_cid).unwrap().unwrap();
6424        assert_eq!(ledger_v2, minted_hex);
6425        assert_eq!(phase, migration::PHASE_FLIPPED);
6426        // The crash-recovered sibling stitched too, and the banlist clone landed on the wire
6427        // (folding the twin's control plane yields the banned npub).
6428        assert_eq!(
6429            crate::db::community::community_id_for_channel(&sibling.id.to_hex()).unwrap().as_deref(),
6430            Some(minted_hex.as_str()),
6431            "sibling channel re-parented by the resumed run"
6432        );
6433        let twin_reloaded = crate::db::community::load_community_v2(&twin.identity.community_id).unwrap().unwrap();
6434        let (_, _, wire_banlist) = verify_owner_root_and_reconcile(&bed.relay, twin_reloaded.clone())
6435            .await
6436            .map(|(c, h, b)| (c, h, b))
6437            .unwrap();
6438        assert!(wire_banlist.contains(&banned.keys.public_key().to_hex()),
6439            "the resumed banlist clone is folded from the twin's wire control plane");
6440
6441        // Crash-heal: roll the ledger back to CARRIER_PUBLISHED (flip landed, ledger behind)
6442        // → the re-run reports SUCCESS and heals, never "already been migrated".
6443        crate::db::community::set_migration_ledger(&v1_cid, &minted_hex, migration::PHASE_CARRIER_PUBLISHED, "").unwrap();
6444        let healed = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6445        assert_eq!(healed, minted_hex);
6446        let (_, phase, _) = crate::db::community::get_migration_ledger(&v1_cid).unwrap().unwrap();
6447        assert_eq!(phase, migration::PHASE_FLIPPED, "ledger healed to FLIPPED");
6448
6449        // Resume past a SELF-SEAL: a fold sealed the community after the carrier but
6450        // before the flip write (dissolved=1, migrated_to still NULL, ledger at
6451        // CARRIER_PUBLISHED). A wizard resume must NOT read this as a foreign dissolution.
6452        // Reuse THIS bed (a second TestBed would re-lock DB_TEST_GUARD and deadlock) with a
6453        // fresh v1 owned by the same owner.
6454        let mut v1b = crate::community::Community::create("Guild2", "general", bed.relays.clone());
6455        let v1b_cid = v1b.id.to_hex();
6456        v1b.owner_attestation = Some({
6457            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1b_cid)
6458                .finalize(&owner.keys).unwrap().as_json()
6459        });
6460        crate::db::community::save_community(&v1b).unwrap();
6461        let twin2 = create_migration_twin(&bed.relay, &v1b.name, bed.relays.clone(), None, (v1b.channels[0].id, "general".into())).await.unwrap();
6462        let twin2_hex = crate::simd::hex::bytes_to_hex_32(&twin2.identity.community_id.0);
6463        crate::db::community::set_migration_ledger(&v1b_cid, &twin2_hex, migration::PHASE_CARRIER_PUBLISHED, "").unwrap();
6464        crate::db::community::set_community_dissolved(&v1b_cid).unwrap(); // the self-seal
6465        let resumed = migration::migrate_community_to_v2(&bed.relay, &v1b, unlocked).await.unwrap();
6466        assert_eq!(resumed, twin2_hex, "resume past a self-seal completes, not false-terminal");
6467        assert_eq!(crate::db::community::get_migrated_to(&v1b_cid).unwrap().as_deref(), Some(twin2_hex.as_str()));
6468    }
6469
6470    /// The birth refound SEEDS the roster: rolling a genesis (epoch 0) twin to epoch 1 with an
6471    /// explicit member list makes those members fold into the memberlist WITHOUT any of them
6472    /// publishing a Join — the anti-ghost-town seed for not-yet-migrated v1 members (who hold
6473    /// no v2 keys). Genesis had no snapshot power; epoch 1 (owner = minting refounder) does.
6474    #[tokio::test]
6475    async fn birth_refound_seeds_an_explicit_roster() {
6476        let (bed, owner, _m) = TestBed::new();
6477        bed.swap_to(&owner);
6478        let twin = create_migration_twin(&bed.relay, "Guild", bed.relays.clone(), None,
6479            (ChannelId(crate::community::random_32()), "general".into())).await.unwrap();
6480        assert_eq!(twin.root_epoch, Epoch(0), "twin starts at genesis");
6481        // Two strangers who never join — pure seeded members.
6482        let ghost_a = Keys::generate().public_key();
6483        let ghost_b = Keys::generate().public_key();
6484
6485        let rolled = refound_at_birth(&bed.relay, &twin, &[owner.keys.public_key(), ghost_a, ghost_b]).await.unwrap();
6486        assert_eq!(rolled.root_epoch, Epoch(1), "birth refound advanced the twin to epoch 1");
6487
6488        // The memberlist folds all three from the epoch-1 snapshot, though only the owner
6489        // ever published a Join.
6490        let members = memberlist(&bed.relay, &rolled).await.unwrap();
6491        assert!(members.contains(&owner.keys.public_key()), "owner in the roster");
6492        assert!(members.contains(&ghost_a) && members.contains(&ghost_b), "never-joined members are seeded (no ghost town)");
6493
6494        // The compacted control plane still verifies (owner genesis carried to epoch 1) — a
6495        // fresh joiner at epoch 1 folds it. And a genesis-epoch snapshot has NO power: rolling
6496        // a fresh twin's snapshot only counts because the owner minted epoch 1.
6497        let (_, _, _banlist) = verify_owner_root_and_reconcile(&bed.relay, rolled.clone()).await
6498            .expect("the epoch-1 twin verifies from its compacted control plane");
6499
6500        // RESUME IDEMPOTENCE: a re-call on the already-refounded twin is a no-op (returns
6501        // epoch 1), never a double-advance to epoch 2 — the crash-between-wire-and-ledger case.
6502        let again = refound_at_birth(&bed.relay, &rolled, &[owner.keys.public_key(), ghost_a, ghost_b]).await.unwrap();
6503        assert_eq!(again.root_epoch, Epoch(1), "re-running the birth refound does not advance past epoch 1");
6504        assert_eq!(crate::db::community::load_community_v2(&twin.identity.community_id).unwrap().unwrap().root_epoch, Epoch(1));
6505    }
6506
6507    /// A banned entry in the seed list must NOT wedge the verify-back: fold_members
6508    /// subtracts the banlist, so a banned seed is never "readable" — the defensive filter drops
6509    /// it before the snapshot, so the refound still completes instead of aborting forever.
6510    #[tokio::test]
6511    async fn birth_refound_ignores_a_banned_seed_entry() {
6512        let (bed, owner, _m) = TestBed::new();
6513        bed.swap_to(&owner);
6514        let twin = create_migration_twin(&bed.relay, "Guild", bed.relays.clone(), None,
6515            (ChannelId(crate::community::random_32()), "general".into())).await.unwrap();
6516        let good = Keys::generate().public_key();
6517        let banned = Keys::generate();
6518        // Ban `banned` on the twin, then hand refound a seed list that (wrongly) includes them.
6519        set_banlist(&bed.relay, &twin, &[banned.public_key().to_hex()]).await.unwrap();
6520        let twin = crate::db::community::load_community_v2(&twin.identity.community_id).unwrap().unwrap();
6521
6522        let rolled = refound_at_birth(&bed.relay, &twin, &[owner.keys.public_key(), good, banned.public_key()]).await
6523            .expect("a banned seed entry is filtered, not a permanent verify-back wedge");
6524        assert_eq!(rolled.root_epoch, Epoch(1));
6525        let members = memberlist(&bed.relay, &rolled).await.unwrap();
6526        assert!(members.contains(&good), "the non-banned seed lands");
6527        assert!(!members.contains(&banned.public_key()), "the banned seed is not a member");
6528    }
6529
6530    /// The "late migrator never misses an epoch" property: a SEEDED-but-never-landed
6531    /// member (in the roster only via the birth snapshot, holding no keys, never posted) is a
6532    /// RECIPIENT of a subsequent OWNER refound — so a rotation that happens before they migrate
6533    /// still mints them a rekey blob to walk forward on. Verified by checking the ghost lands
6534    /// in the refound's memberlist-derived recipient set (they get a base-rekey blob).
6535    #[tokio::test]
6536    async fn a_seeded_member_receives_a_later_refound_rekey() {
6537        let (bed, owner, _m) = TestBed::new();
6538        bed.swap_to(&owner);
6539        let twin = create_migration_twin(&bed.relay, "Guild", bed.relays.clone(), None,
6540            (ChannelId(crate::community::random_32()), "general".into())).await.unwrap();
6541        let ghost = Keys::generate();
6542        // Birth refound seeds the ghost (never joins, holds no keys).
6543        let rolled = refound_at_birth(&bed.relay, &twin, &[owner.keys.public_key(), ghost.public_key()]).await.unwrap();
6544        assert!(memberlist(&bed.relay, &rolled).await.unwrap().contains(&ghost.public_key()), "ghost is seeded");
6545
6546        // A later OWNER refound (epoch 1→2) derives its rekey recipients from memberlist(),
6547        // which folds the snapshot — so the ghost IS a recipient (a base-rekey blob is minted
6548        // for them by construction) AND is re-snapshotted at epoch 2. Surviving in the epoch-2
6549        // memberlist proves both: the refound saw them as a member and carried them forward, so
6550        // a late migrator who opens `m` (epoch 1) can then walk their epoch-2 blob forward.
6551        let refounded = refound_community(&bed.relay, &rolled, &[]).await.unwrap();
6552        assert_eq!(refounded.root_epoch, Epoch(2), "the later refound advanced the epoch");
6553        assert!(
6554            memberlist(&bed.relay, &refounded).await.unwrap().contains(&ghost.public_key()),
6555            "a seeded member is a recipient of + re-seeded by a later refound (never misses an epoch)"
6556        );
6557    }
6558
6559    /// Governance survives migration: a v1 ADMIN is re-granted @admin on the twin (holds
6560    /// MANAGE_ROLES there), while a plain member is not.
6561    #[tokio::test]
6562    async fn v1_admin_stays_admin_across_migration() {
6563        use crate::community::migration;
6564        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
6565        let (bed, owner, admin) = TestBed::new();
6566        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6567
6568        bed.swap_to(&owner);
6569        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6570        let v1_cid = v1.id.to_hex();
6571        v1.owner_attestation = Some({
6572            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6573                .finalize(&owner.keys).unwrap().as_json()
6574        });
6575        crate::db::community::save_community(&v1).unwrap();
6576        // v1 governance: one Admin role, granted to `admin`.
6577        let admin_role = Role::admin("a1".repeat(32));
6578        let roles = CommunityRoles {
6579            roles: vec![admin_role.clone()],
6580            grants: vec![MemberGrant { member: admin.keys.public_key().to_hex(), role_ids: vec![admin_role.role_id.clone()] }],
6581        };
6582        crate::db::community::set_community_roles(&v1_cid, &roles, 1_000).unwrap();
6583
6584        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6585        let twin = crate::db::community::load_community_v2(&crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&v2_hex))).unwrap().unwrap();
6586
6587        // Fold the twin's authority from the wire: the admin holds MANAGE_ROLES, a stranger doesn't.
6588        let authority = fetch_authority(&bed.relay, &twin).await;
6589        assert!(
6590            authority.roles.is_authorized(&admin.keys.public_key().to_hex(), Some(&owner.keys.public_key().to_hex()), Permissions::MANAGE_ROLES),
6591            "the v1 admin is an admin on the v2 twin"
6592        );
6593        assert!(
6594            !authority.roles.is_authorized(&Keys::generate().public_key().to_hex(), Some(&owner.keys.public_key().to_hex()), Permissions::MANAGE_ROLES),
6595            "a non-admin gains no authority"
6596        );
6597    }
6598
6599    /// The sweep converges on a PLAIN dissolution (owner-signed, no payload) but a
6600    /// non-owner tombstone (member-mintable) must NOT mark it checked — else a partial-relay
6601    /// probe returning only a stranger's record would permanently stop the sweep before the
6602    /// owner's real carrier is ever fetched.
6603    #[tokio::test]
6604    async fn sweep_marks_checked_only_on_an_owner_tombstone() {
6605        use crate::community::migration;
6606        let (bed, owner, stranger) = TestBed::new();
6607
6608        bed.swap_to(&owner);
6609        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6610        let v1_cid = v1.id.to_hex();
6611        v1.owner_attestation = Some({
6612            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6613                .finalize(&owner.keys).unwrap().as_json()
6614        });
6615        crate::db::community::save_community(&v1).unwrap();
6616
6617        // A STRANGER publishes a (payload-less) tombstone at the dissolved coordinate, and
6618        // the community is locally sealed (as if folded on an old build) but not yet checked.
6619        let inner = crate::community::roster::build_group_dissolved_edition(&stranger.keys, &v1.id, 500).unwrap();
6620        let outer = crate::community::roster::seal_dissolved_edition(&Keys::generate(), &inner, &v1.id).unwrap();
6621        bed.relay.publish_durable(&outer, &bed.relays).await.unwrap();
6622        crate::db::community::set_community_dissolved(&v1_cid).unwrap();
6623
6624        // Sweep: the only record is a stranger's → NOT marked checked (still a candidate).
6625        migration::sweep_dissolved_for_migration(&bed.relay).await;
6626        assert!(
6627            crate::db::community::migration_sweep_candidates().unwrap().contains(&v1_cid),
6628            "a stranger-only probe must not converge the sweep"
6629        );
6630
6631        // Now the OWNER publishes a plain dissolution → sweep marks it checked.
6632        let owner_inner = crate::community::roster::build_group_dissolved_edition(&owner.keys, &v1.id, 600).unwrap();
6633        let owner_outer = crate::community::roster::seal_dissolved_edition(&Keys::generate(), &owner_inner, &v1.id).unwrap();
6634        bed.relay.publish_durable(&owner_outer, &bed.relays).await.unwrap();
6635        migration::sweep_dissolved_for_migration(&bed.relay).await;
6636        assert!(
6637            !crate::db::community::migration_sweep_candidates().unwrap().contains(&v1_cid),
6638            "an owner plain-dissolution converges the sweep"
6639        );
6640    }
6641
6642    /// Wizard preflight refuses before the timelock and for non-owners.
6643    #[tokio::test]
6644    async fn wizard_preflight_gates_timelock_and_ownership() {
6645        use crate::community::migration;
6646        let (bed, owner, _member) = TestBed::new();
6647        bed.swap_to(&owner);
6648        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6649        v1.owner_attestation = Some({
6650            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1.id.to_hex())
6651                .finalize(&owner.keys).unwrap().as_json()
6652        });
6653        crate::db::community::save_community(&v1).unwrap();
6654
6655        // Before the unlock → refused, nothing published.
6656        let err = migration::migrate_community_to_v2(&bed.relay, &v1, migration::MIGRATION_UNLOCK_AT - 1).await.unwrap_err();
6657        assert!(err.contains("not unlocked"), "{err}");
6658        assert!(crate::db::community::get_migration_ledger(&v1.id.to_hex()).unwrap().is_none(), "no ledger row before unlock");
6659    }
6660
6661    #[tokio::test]
6662    async fn public_link_full_loop() {
6663        let (bed, owner, member) = TestBed::new();
6664
6665        bed.swap_to(&owner);
6666        let community = create_community(&bed.relay, "Public Guild", bed.relays.clone(), None).await.unwrap();
6667        let general = community.channels[0].id;
6668        send_message(&bed.relay, &community, &general, "come on in").await.unwrap();
6669        // Mint a shareable link (a non-stock relay so the fragment carries it).
6670        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6671        assert!(link.url.starts_with("https://vectorapp.io/invite/"));
6672        assert!(link.url.contains('#'), "the fragment carries the token");
6673
6674        // Member joins purely from the URL string.
6675        bed.swap_to(&member);
6676        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
6677        assert_eq!(joined.id().0, community.id().0);
6678        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["come on in"]);
6679    }
6680
6681    #[test]
6682    fn bundle_of_snapshots_the_held_icon() {
6683        let owner = Keys::generate();
6684        let g = control::genesis(&owner, control::CommunityMetadata { name: "Logo".into(), ..Default::default() }, 1_000).unwrap();
6685        let mut c = CommunityV2::from_genesis(&g, "Logo", None, vec!["wss://r".into()], 0);
6686        let icon = control::ImageRef { url: "https://blossom.example/i".into(), key: "k".into(), nonce: "n".into(), hash: "h".into(), extra: Default::default() };
6687        c.icon = Some(icon.clone());
6688        let bundle = bundle_of(&c, BundleAudience::Link, None, None, None);
6689        assert_eq!(bundle.icon, Some(icon), "a parked invite renders the real logo from the mint-time snapshot");
6690    }
6691
6692    #[test]
6693    fn addressing_roots_fan_current_plus_archived_bounded_and_deduped() {
6694        // follow_rekeys' fetch fan AND streamauth's plane registration share
6695        // this. A channel rekey rides the PRIOR root (CORD-06 D2), so the set
6696        // MUST include archived roots or an AUTH-gated relay never serves the
6697        // rotation crate → the channel stalls at its old epoch.
6698        let (_tmp, _guard, _owner) = init_test_db();
6699        let cur_root = [9u8; 32];
6700        let cid = crate::community::CommunityId([1u8; 32]);
6701        let cid_hex = cid.to_hex();
6702
6703        // No archives yet → just the current root.
6704        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6705        assert_eq!(roots, vec![cur_root], "with no archived roots the fan is the current root alone");
6706
6707        // Archive two prior roots (freshest-first ordering is asserted below).
6708        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &[1u8; 32]).unwrap();
6709        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1, &[2u8; 32]).unwrap();
6710        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6711        assert_eq!(roots[0], cur_root, "current root leads");
6712        assert!(roots.contains(&[1u8; 32]) && roots.contains(&[2u8; 32]), "both archived roots are in the fan");
6713        assert_eq!(roots.len(), 3, "current + 2 archived, no dupes");
6714        // Freshest-archived-first (epoch 1 before epoch 0).
6715        assert_eq!(roots[1], [2u8; 32], "higher archived epoch is addressed before the lower");
6716
6717        // A stored root equal to the CURRENT one must not duplicate.
6718        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 2, &cur_root).unwrap();
6719        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6720        assert_eq!(roots.iter().filter(|r| **r == cur_root).count(), 1, "the current root is never duplicated");
6721
6722        // Cap: many archives truncate to MAX_ADDRESSING_ROOTS.
6723        for e in 3..20u64 {
6724            crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, e, &[e as u8; 32]).unwrap();
6725        }
6726        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6727        assert_eq!(roots.len(), MAX_ADDRESSING_ROOTS, "the fan is bounded so a relay can't feed an unbounded walk");
6728    }
6729
6730    #[tokio::test]
6731    async fn public_link_preview_shows_live_name_and_icon_without_joining() {
6732        let (bed, owner, member) = TestBed::new();
6733
6734        bed.swap_to(&owner);
6735        let community = create_community(&bed.relay, "Soapbox", bed.relays.clone(), None).await.unwrap();
6736        // The icon lives on the Control Plane, never in the bundle — publish it
6737        // as a metadata edition so the preview must FOLD to see it.
6738        let icon = control::ImageRef {
6739            url: "https://blossom.example/soap".into(),
6740            key: "k".into(),
6741            nonce: "n".into(),
6742            hash: "h".into(),
6743            extra: Default::default(),
6744        };
6745        let mut meta = community.metadata();
6746        meta.icon = Some(icon.clone());
6747        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
6748        // An any-host base — the naddr#fragment payload is domain-agnostic.
6749        let link = mint_public_link(&bed.relay, &community, "https://armada.buzz", None, None).await.unwrap();
6750
6751        // A NON-member previews: the real name + the live icon, nothing persisted.
6752        bed.swap_to(&member);
6753        let preview = preview_public_link(&bed.relay, &link.url).await.unwrap();
6754        assert_eq!(preview.name, "Soapbox");
6755        assert_eq!(preview.icon, Some(icon), "the icon folds from the live Control Plane, not the bundle");
6756        assert!(
6757            crate::db::community::load_community_v2(preview.id()).unwrap().is_none(),
6758            "previewing must not persist a membership"
6759        );
6760    }
6761
6762    #[tokio::test]
6763    async fn a_previewed_join_reuses_the_verified_fold() {
6764        let (bed, owner, member) = TestBed::new();
6765        bed.swap_to(&owner);
6766        let community = create_community(&bed.relay, "FastJoin", bed.relays.clone(), None).await.unwrap();
6767        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6768
6769        bed.swap_to(&member);
6770        let _ = preview_public_link(&bed.relay, &link.url).await.unwrap();
6771        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
6772        assert_eq!(joined.id().0, community.id().0);
6773        assert!(joined.created_at_ms > 0, "the handoff stamps the JOIN's acquisition time, not the preview's");
6774        // The slot was CONSUMED by the join — proving the handoff path ran (a
6775        // verify re-walk would have left the preview's entry in place).
6776        assert!(VERIFIED_PREVIEW.lock().unwrap().is_none(), "the handoff slot must be consumed by the join");
6777    }
6778
6779    #[tokio::test]
6780    async fn guestbook_store_seeds_syncs_incrementally_and_matches_the_live_fold() {
6781        let (bed, owner, member) = TestBed::new();
6782        bed.swap_to(&owner);
6783        let community = create_community(&bed.relay, "GB", bed.relays.clone(), None).await.unwrap();
6784        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6785
6786        bed.swap_to(&member);
6787        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
6788
6789        // Seed from zero: the stored fold equals the authoritative live fold.
6790        let session = SessionGuard::capture();
6791        assert!(!sync_guestbook(&bed.relay, &joined, &session).await.unwrap().is_empty(), "the seed folds fresh events");
6792        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
6793        let (_, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
6794        assert!(cursor > 0, "the cursor advanced past zero");
6795        let stored: std::collections::BTreeSet<_> = stored_memberlist(&joined).unwrap().into_iter().collect();
6796        let live: std::collections::BTreeSet<_> = memberlist(&bed.relay, &joined).await.unwrap().into_iter().collect();
6797        assert_eq!(stored, live, "stored fold == live fold after the seed");
6798        assert!(stored.contains(&member.keys.public_key()));
6799
6800        // Nothing new on the plane → an idle re-sync folds nothing.
6801        assert!(sync_guestbook(&bed.relay, &joined, &session).await.unwrap().is_empty());
6802
6803        // The owner kicks the member; a CURSOR catch-up folds the kick in — no full walk.
6804        bed.swap_to(&owner);
6805        kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
6806        bed.swap_to(&member);
6807        let session = SessionGuard::capture();
6808        assert!(!sync_guestbook(&bed.relay, &joined, &session).await.unwrap().is_empty(), "the kick lands incrementally");
6809        assert!(
6810            !stored_memberlist(&joined).unwrap().contains(&member.keys.public_key()),
6811            "an owner kick removes the member from the stored fold"
6812        );
6813    }
6814
6815    #[tokio::test]
6816    async fn a_preview_then_revoke_still_refuses_the_join() {
6817        let (bed, owner, member) = TestBed::new();
6818        bed.swap_to(&owner);
6819        let community = create_community(&bed.relay, "RevokeRace", bed.relays.clone(), None).await.unwrap();
6820        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6821
6822        // Member previews (warming the verified handoff), THEN the owner revokes.
6823        bed.swap_to(&member);
6824        let p = preview_public_link(&bed.relay, &link.url).await.unwrap();
6825        assert_eq!(p.name, "RevokeRace");
6826        bed.swap_to(&owner);
6827        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
6828        bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();
6829
6830        // The join MUST refuse: the handoff skips only the root re-verify, never
6831        // the bundle re-fetch that carries the revocation gate.
6832        bed.swap_to(&member);
6833        let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
6834        assert!(err.contains("revoked"), "got: {err}");
6835    }
6836
6837    #[tokio::test]
6838    async fn a_revoked_link_refuses_to_join() {
6839        let (bed, owner, member) = TestBed::new();
6840        bed.swap_to(&owner);
6841        let community = create_community(&bed.relay, "Revoked", bed.relays.clone(), None).await.unwrap();
6842        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6843        // Owner retires the link (re-posts the coordinate as a tombstone).
6844        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
6845        bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();
6846
6847        bed.swap_to(&member);
6848        let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
6849        assert!(err.contains("revoked"), "a retired link finds the grave, not keys: {err}");
6850    }
6851
6852    #[tokio::test]
6853    async fn an_expired_direct_invite_refuses_to_join() {
6854        let (bed, owner, member) = TestBed::new();
6855        bed.swap_to(&owner);
6856        let community = create_community(&bed.relay, "Expired", bed.relays.clone(), None).await.unwrap();
6857        // Hand-mint an invite that expired in the past.
6858        let inviter = owner.keys.clone();
6859        let mut bundle = bundle_of(&community, BundleAudience::Link, Some(inviter.public_key()), Some(1_000), None);
6860        bundle.expires_at = Some(1_000); // unix ms, long past
6861        let wrap = invite::build_direct_invite(&inviter, &member.keys.public_key(), &bundle).unwrap();
6862        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
6863
6864        bed.swap_to(&member);
6865        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6866        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
6867        assert!(err.contains("expired"), "a past-expiry invite refuses to join: {err}");
6868    }
6869
6870    #[tokio::test]
6871    async fn a_tombstone_beats_a_live_bundle_regardless_of_fetch_order() {
6872        // The revocation-durability fix: if ANY signer-valid tombstone is among the
6873        // fetched events, refuse — even when a Live bundle is returned FIRST (the
6874        // production union has no newest-first sort, so a stale relay's Live can lead).
6875        let (bed, owner, member) = TestBed::new();
6876        bed.swap_to(&owner);
6877        let community = create_community(&bed.relay, "Rev", bed.relays.clone(), None).await.unwrap();
6878        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6879        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
6880
6881        // A relay union that hands back [Live, tombstone] — Live FIRST. Old
6882        // `events.first()` would join the Live; the scan-all fix must refuse.
6883        let union = FixedFetch { events: vec![link.bundle_event.clone(), tombstone] };
6884
6885        bed.swap_to(&member);
6886        let err = accept_public_link(&union, &link.url).await.unwrap_err();
6887        assert!(err.contains("revoked"), "a tombstone must beat a Live returned first: {err}");
6888    }
6889
6890    #[test]
6891    fn from_bundle_refuses_an_over_cap_bundle_before_allocating() {
6892        // The accept-side DoS bound: from_bundle (which accept_bundle calls)
6893        // rejects a >256-channel bundle via validate() BEFORE the Vec allocation.
6894        // (The Direct-Invite wire path is additionally bounded by NIP-44's 64KB
6895        // cap, which trips even earlier — but the count guard is the real defense
6896        // for the single-layer public-link bundle.)
6897        let owner = Keys::generate();
6898        let identity = super::super::control::CommunityIdentity::mint(&owner.public_key());
6899        let hex = crate::simd::hex::bytes_to_hex_32;
6900        let root = [0x11u8; 32];
6901        let mut bundle = CommunityInvite {
6902            community_id: hex(&identity.community_id.0),
6903            owner: hex(&identity.owner_xonly),
6904            owner_salt: hex(&identity.owner_salt),
6905            community_root: hex(&root),
6906            root_epoch: 0,
6907            channels: vec![],
6908            relays: vec!["wss://r".into()],
6909            name: "X".into(),
6910            icon: None,
6911            expires_at: None,
6912            creator_npub: None,
6913            label: None,
6914            extra: Default::default(),
6915        };
6916        bundle.channels = (0..=invite::MAX_BUNDLE_CHANNELS)
6917            .map(|i| {
6918                let mut id = [0u8; 32];
6919                id[..8].copy_from_slice(&(i as u64).to_be_bytes());
6920                invite::ChannelGrant { id: hex(&id), key: hex(&root), epoch: 0, name: "x".into() }
6921            })
6922            .collect();
6923        assert!(CommunityV2::from_bundle(&bundle, 0).is_err(), "an over-cap bundle is refused before allocating");
6924    }
6925
6926    #[tokio::test]
6927    async fn a_join_swap_between_fetch_and_save_aborts_and_leaves_the_other_account_clean() {
6928        // The SessionGuard straddle: a public-link accept fetches then saves. If the
6929        // account swaps in that window, the join must abort — never write A's
6930        // community into B's DB. SwapMidFetch bumps the session generation during
6931        // the fetch await, exactly as a real swap_session would.
6932        let (bed, owner, member) = TestBed::new();
6933        bed.swap_to(&owner);
6934        let community = create_community(&bed.relay, "Straddle", bed.relays.clone(), None).await.unwrap();
6935        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6936        // A fresh swap-injecting transport holding the same bundle event.
6937        let swap_relay = SwapMidFetch { inner: MemoryRelay::new() };
6938        swap_relay.inner.publish_durable(&link.bundle_event, &bed.relays).await.unwrap();
6939
6940        bed.swap_to(&member);
6941        let err = accept_public_link(&swap_relay, &link.url).await.unwrap_err();
6942        assert!(err.contains("account changed"), "a swap mid-join must abort: {err}");
6943        assert!(
6944            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
6945            "the aborted join wrote nothing to the (member) account DB"
6946        );
6947    }
6948
6949    #[tokio::test]
6950    async fn the_owner_is_a_member_even_without_a_fetched_genesis_join() {
6951        // The owner is derived from the self-certifying community_id, so the
6952        // memberlist includes them independent of any Guestbook fetch.
6953        let (_tmp, _guard, owner) = init_test_db();
6954        let relay = MemoryRelay::new();
6955        let community = create_community(&relay, "Owned", vec!["wss://r".into()], None).await.unwrap();
6956        // A memberlist over an EMPTY guestbook (fetch a community-relay-less view)
6957        // still contains the owner.
6958        let empty = MemoryRelay::new();
6959        let members = memberlist(&empty, &community).await.unwrap();
6960        assert_eq!(members, vec![owner.public_key()], "owner present with no fetched Join");
6961    }
6962
6963    #[tokio::test]
6964    async fn an_expiring_minted_invite_refuses_after_the_deadline() {
6965        // The mint path can now produce an expiring invite, and the accept gate
6966        // trips on it (end-to-end through the real service, not a hand-built bundle).
6967        let (bed, owner, member) = TestBed::new();
6968        bed.swap_to(&owner);
6969        let community = create_community(&bed.relay, "Timed", bed.relays.clone(), None).await.unwrap();
6970        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), Some(1_000), Some("beta".into()))
6971            .await
6972            .unwrap();
6973
6974        bed.swap_to(&member);
6975        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6976        assert!(
6977            accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err().contains("expired"),
6978            "a minted expiring invite refuses past its deadline"
6979        );
6980    }
6981
6982    #[tokio::test]
6983    async fn a_member_who_leaves_drops_from_the_memberlist() {
6984        let (bed, owner, member) = TestBed::new();
6985        bed.swap_to(&owner);
6986        let community = create_community(&bed.relay, "Leaving", bed.relays.clone(), None).await.unwrap();
6987        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
6988
6989        bed.swap_to(&member);
6990        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6991        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
6992        // Let the leave land strictly after the join.
6993        tokio::time::sleep(std::time::Duration::from_millis(2)).await;
6994        leave_community(&bed.relay, &joined).await.unwrap();
6995
6996        bed.swap_to(&owner);
6997        let members = memberlist(&bed.relay, &community).await.unwrap();
6998        assert!(members.contains(&owner.keys.public_key()));
6999        assert!(!members.contains(&member.keys.public_key()), "a member who left drops from the list");
7000    }
7001
7002    #[tokio::test]
7003    async fn a_swapped_member_cannot_see_the_owners_community_until_joining() {
7004        // Multi-account isolation: after the swap, the member's DB holds nothing
7005        // of the owner's community — the dual-stack storage is per-account.
7006        let (bed, owner, member) = TestBed::new();
7007        bed.swap_to(&owner);
7008        let community = create_community(&bed.relay, "Private-so-far", bed.relays.clone(), None).await.unwrap();
7009        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some());
7010
7011        bed.swap_to(&member);
7012        assert!(
7013            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
7014            "the owner's community must be invisible in the member's account DB"
7015        );
7016        assert_eq!(crate::db::community::list_community_ids().unwrap().len(), 0);
7017    }
7018
7019    // ── Live control-follow ──────────────────────────────────────────────────
7020
7021    /// Publish an owner-grammar channel edition straight to the control plane,
7022    /// signed by `signer` (the owner for a legit edit, a stranger for the
7023    /// authority test). `version`/`deleted` drive add-vs-rename-vs-delete.
7024    /// The entity's current head `self_hash` on the relay (highest version wins),
7025    /// so a helper can chain a new edition the way a real owner client does.
7026    async fn head_hash_on_relay(relay: &MemoryRelay, community: &CommunityV2, entity_id: &[u8; 32]) -> Option<[u8; 32]> {
7027        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7028        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
7029        let wraps = relay.fetch(&query, &community.relays).await.ok()?;
7030        let mut head: Option<(u64, [u8; 32])> = None;
7031        for w in &wraps {
7032            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
7033                if ed.entity_id == *entity_id && head.is_none_or(|(v, _)| ed.version > v) {
7034                    head = Some((ed.version, ed.self_hash));
7035                }
7036            }
7037        }
7038        head.map(|(_, h)| h)
7039    }
7040
7041    /// The `vac` a non-owner signer must attach, read off the Grant they were
7042    /// given on the relay (CORD-04 §5). The owner cites nothing. Mirrors what a
7043    /// real client does via `my_authority_citation`, so the fixtures publish the
7044    /// shape Vector actually emits.
7045    async fn cite_on_relay(
7046        relay: &MemoryRelay,
7047        community: &CommunityV2,
7048        signer: &Keys,
7049    ) -> Option<crate::community::edition::AuthorityCitation> {
7050        if community.owner().ok() == Some(signer.public_key()) {
7051            return None;
7052        }
7053        let entity_id = crate::community::v2::derive::grant_locator(community.id(), &signer.public_key().to_bytes());
7054        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7055        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
7056        let wraps = relay.fetch(&query, &community.relays).await.ok()?;
7057        let mut head: Option<(u64, [u8; 32])> = None;
7058        for w in &wraps {
7059            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
7060                if ed.entity_id == entity_id && head.is_none_or(|(v, _)| ed.version > v) {
7061                    head = Some((ed.version, ed.self_hash));
7062                }
7063            }
7064        }
7065        head.map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
7066    }
7067
7068    async fn publish_channel_edition(
7069        relay: &MemoryRelay,
7070        community: &CommunityV2,
7071        signer: &Keys,
7072        channel_id: &ChannelId,
7073        name: &str,
7074        private: bool,
7075        version: u64,
7076        deleted: bool,
7077    ) {
7078        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7079        let prev = head_hash_on_relay(relay, community, &channel_id.0).await;
7080        let meta = control::ChannelMetadata { name: name.into(), private, deleted: deleted.then_some(true), ..Default::default() };
7081        let content = serde_json::to_string(&meta).unwrap();
7082        let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel_id.0, version, prev.as_ref(), &content, 1_000, None);
7083        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
7084        relay.publish(&wrap, &community.relays).await.unwrap();
7085    }
7086
7087    /// Publish an owner-grammar community-metadata edition (rename etc.), chained
7088    /// to the current relay head like a real owner client.
7089    async fn publish_community_meta(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64) {
7090        publish_community_meta_at(relay, community, signer, name, version, 1_000).await;
7091    }
7092
7093    /// As [`publish_community_meta`] with an explicit timestamp, for tests that need
7094    /// relay-side newest-first ordering (paging/eviction scenarios).
7095    async fn publish_community_meta_at(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64, at_secs: u64) {
7096        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7097        let prev = head_hash_on_relay(relay, community, &community.id().0).await;
7098        let meta = control::CommunityMetadata { name: name.into(), ..Default::default() };
7099        let content = serde_json::to_string(&meta).unwrap();
7100        let cite = cite_on_relay(relay, community, signer).await;
7101        let rumor = control::build_edition_rumor(signer.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, version, prev.as_ref(), &content, at_secs, cite.as_ref());
7102        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(at_secs)).unwrap();
7103        relay.publish(&wrap, &community.relays).await.unwrap();
7104    }
7105
7106    #[test]
7107    fn metadata_apply_captures_undriven_fields_for_republish() {
7108        let owner = Keys::generate();
7109        let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
7110        let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
7111        let general = held.channels[0].id;
7112
7113        // A foreign vsk-0 head carrying custom + unknown fields folds them in…
7114        let mut custom = serde_json::Map::new();
7115        custom.insert("accent".into(), serde_json::Value::from("#89f0b6"));
7116        let mut extra = serde_json::Map::new();
7117        extra.insert("vnd_flag".into(), serde_json::Value::Bool(true));
7118        let meta = control::CommunityMetadata { name: "A".into(), custom: Some(custom.clone()), extra: extra.clone(), ..Default::default() };
7119        assert!(apply_community_metadata(&mut held, meta), "gaining custom/extra is a change");
7120        assert_eq!(held.meta_custom, Some(custom.clone()));
7121        assert_eq!(held.meta_extra, extra);
7122        // …and the next local edit's base document republishes them verbatim.
7123        assert_eq!(held.metadata().custom, Some(custom));
7124        assert_eq!(held.metadata().extra, held.meta_extra);
7125
7126        // Same contract for a vsk-2 channel head (voice included).
7127        let mut ch_custom = serde_json::Map::new();
7128        ch_custom.insert("slowmode".into(), serde_json::Value::from(30));
7129        let ch_meta = control::ChannelMetadata {
7130            name: "general".into(),
7131            private: false,
7132            voice: Some(true),
7133            deleted: None,
7134            custom: Some(ch_custom.clone()),
7135            extra: Default::default(),
7136        };
7137        assert!(apply_channel_metadata(&mut held, general, ch_meta), "gaining voice/custom is a change");
7138        let ch = held.channel(&general).unwrap();
7139        assert_eq!(ch.voice, Some(true));
7140        assert_eq!(ch.meta_custom, Some(ch_custom.clone()));
7141        let rename = { let mut d = ch.metadata(); d.name = "lounge".into(); d };
7142        assert_eq!(rename.voice, Some(true), "our rename edition carries the foreign voice flag");
7143        assert_eq!(rename.custom, Some(ch_custom));
7144    }
7145
7146    #[test]
7147    fn community_metadata_apply_sets_and_clears_images() {
7148        let owner = Keys::generate();
7149        let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
7150        let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
7151
7152        let icon = control::ImageRef {
7153            url: "https://blossom.example/i".into(),
7154            key: "k".into(),
7155            nonce: "n".into(),
7156            hash: "h".into(),
7157            extra: Default::default(),
7158        };
7159        let with_icon = control::CommunityMetadata { name: "A".into(), icon: Some(icon.clone()), ..Default::default() };
7160        assert!(apply_community_metadata(&mut held, with_icon), "gaining an icon is a change");
7161        assert_eq!(held.icon.as_ref(), Some(&icon));
7162
7163        // An edition is the FULL document: a head without the icon removes it.
7164        let without = control::CommunityMetadata { name: "A".into(), ..Default::default() };
7165        assert!(apply_community_metadata(&mut held, without), "losing the icon is a change");
7166        assert_eq!(held.icon, None);
7167    }
7168
7169    /// Publish a Role edition (vsk 1) signed by `signer`, chained to the current head.
7170    async fn publish_role(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64) {
7171        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7172        let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).unwrap();
7173        let prev = head_hash_on_relay(relay, community, &role_id).await;
7174        let content = crate::community::v2::roles::role_content_json(role).unwrap();
7175        let cite = cite_on_relay(relay, community, signer).await;
7176        let rumor = control::build_edition_rumor(signer.public_key(), vsk::ROLE, &role_id, version, prev.as_ref(), &content, 1_000, cite.as_ref());
7177        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
7178        relay.publish(&wrap, &community.relays).await.unwrap();
7179    }
7180
7181    /// Publish a Grant edition (vsk 3) signed by `signer`, at grant_locator(cid, member).
7182    async fn publish_grant(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, member: &PublicKey, role_ids: Vec<String>, version: u64) {
7183        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7184        let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
7185        let prev = head_hash_on_relay(relay, community, &eid).await;
7186        let grant = MemberGrant { member: member.to_hex(), role_ids };
7187        let content = crate::community::v2::roles::grant_content_json(&grant).unwrap();
7188        let cite = cite_on_relay(relay, community, signer).await;
7189        let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
7190        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
7191        relay.publish(&wrap, &community.relays).await.unwrap();
7192    }
7193
7194    /// Publish a Banlist edition (vsk 4) signed by `signer`, at banlist_locator(cid).
7195    async fn publish_banlist(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, banned: &[String], version: u64) {
7196        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7197        let eid = crate::community::v2::derive::banlist_locator(community.id());
7198        let prev = head_hash_on_relay(relay, community, &eid).await;
7199        let content = crate::community::v2::roles::banlist_content_json(banned).unwrap();
7200        let cite = cite_on_relay(relay, community, signer).await;
7201        let rumor = control::build_edition_rumor(signer.public_key(), vsk::BANLIST, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
7202        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
7203        relay.publish(&wrap, &community.relays).await.unwrap();
7204    }
7205
7206    fn admin_role(role_id: &str, perms: u64) -> Role {
7207        Role { role_id: role_id.into(), name: "Admin".into(), position: 1, permissions: Permissions(perms), scope: RoleScope::Server, color: 0 }
7208    }
7209
7210    // ── CORD-04 §1 author-aware fold: a seat-holder (holds community_root, so can seal
7211    // any control edition) must not be able to SUPPRESS a role or grant by forging a
7212    // higher version at its coordinate. Owner-only signers mask this entirely, so every
7213    // attacker below signs as a NON-owner member.
7214
7215    #[tokio::test]
7216    async fn a_non_owner_cannot_suppress_the_admin_role_by_forging_a_higher_version() {
7217        let (bed, owner, attacker) = TestBed::new();
7218        bed.swap_to(&owner);
7219        let community = create_community(&bed.relay, "AttackA", bed.relays.clone(), None).await.unwrap();
7220        let victim = Keys::generate().public_key();
7221        grant_admin(&bed.relay, &community, &victim).await.unwrap();
7222
7223        // The admin role sits at a deterministic, publicly-computable coordinate.
7224        let admin_rid = fetch_authority(&bed.relay, &community)
7225            .await
7226            .roles
7227            .roles
7228            .iter()
7229            .find(|r| r.permissions.contains(Permissions::ADMIN_ALL))
7230            .unwrap()
7231            .role_id
7232            .clone();
7233        // Attacker forges v2 of that exact role, stripping its powers.
7234        publish_role(
7235            &bed.relay,
7236            &community,
7237            &attacker.keys,
7238            &Role { role_id: admin_rid.clone(), name: "pwned".into(), position: 1, permissions: Permissions(0), scope: RoleScope::Server, color: 0 },
7239            2,
7240        )
7241        .await;
7242
7243        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
7244        assert!(authority.roles.is_admin(&victim.to_hex()), "the forged strip is DROPPED; the owner's admin role survives beneath it");
7245        assert!(
7246            authority.heads.iter().any(|h| h.entity_hex == admin_rid && h.version == 1),
7247            "the floor advances only to the AUTHORIZED head (owner v1)"
7248        );
7249        assert!(!authority.heads.iter().any(|h| h.version == 2), "the forged v2 never poisons the floor");
7250    }
7251
7252    #[tokio::test]
7253    async fn a_non_owner_cannot_strip_a_members_grant_by_forging_a_higher_version() {
7254        let (bed, owner, attacker) = TestBed::new();
7255        bed.swap_to(&owner);
7256        let community = create_community(&bed.relay, "AttackC", bed.relays.clone(), None).await.unwrap();
7257        let victim = Keys::generate();
7258        grant_admin(&bed.relay, &community, &victim.public_key()).await.unwrap();
7259
7260        // Attacker forges a higher-version EMPTY grant at the victim's grant coordinate.
7261        publish_grant(&bed.relay, &community, &attacker.keys, &victim.public_key(), vec![], 9).await;
7262
7263        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
7264        assert!(
7265            authority.roles.is_admin(&victim.public_key().to_hex()),
7266            "the forged strip is dropped; the owner's grant survives and the victim keeps admin"
7267        );
7268    }
7269
7270    #[tokio::test]
7271    async fn forged_low_id_roles_by_a_non_owner_never_enter_the_authorized_roster() {
7272        let (bed, owner, attacker) = TestBed::new();
7273        bed.swap_to(&owner);
7274        let community = create_community(&bed.relay, "AttackB", bed.relays.clone(), None).await.unwrap();
7275        let victim = Keys::generate().public_key();
7276        grant_admin(&bed.relay, &community, &victim).await.unwrap();
7277
7278        // Low-id roles that WOULD evict the admin from a pre-authorize cap — but they're
7279        // unauthorized, so the post-authorize cap never sees them.
7280        for i in 0u8..6 {
7281            let rid = crate::simd::hex::bytes_to_hex_32(&[i; 32]);
7282            publish_role(&bed.relay, &community, &attacker.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
7283        }
7284
7285        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
7286        assert!(authority.roles.is_admin(&victim.to_hex()), "the legit admin survives the forged flood");
7287        assert_eq!(authority.roles.roles.len(), 1, "only the owner's admin role is authorized; every forgery is dropped");
7288    }
7289
7290    /// A canonical (order-independent) fingerprint of an AuthoritySet's authorized
7291    /// roster + banlist — two clients converge iff these match.
7292    fn authority_fingerprint(a: &AuthoritySet) -> String {
7293        let mut roles = a.roles.roles.clone();
7294        roles.sort_by(|x, y| x.role_id.cmp(&y.role_id));
7295        let mut grants = a.roles.grants.clone();
7296        for g in &mut grants {
7297            g.role_ids.sort();
7298        }
7299        grants.sort_by(|x, y| x.member.cmp(&y.member));
7300        let banned: Vec<&String> = a.banned.iter().collect();
7301        serde_json::json!({ "roles": roles, "grants": grants, "banned": banned }).to_string()
7302    }
7303
7304    #[tokio::test]
7305    async fn the_v2_authority_fold_is_order_independent() {
7306        // THE core consensus property: two honest clients that receive the SAME
7307        // control editions in DIFFERENT arrival orders must resolve the IDENTICAL
7308        // authorized roster + banlist (author-aware select_authorized + banlist
7309        // fold + cap, all deterministic). A divergence here would fork the
7310        // community's moderation state between honest members.
7311        let (bed, owner, _a) = TestBed::new();
7312        bed.swap_to(&owner);
7313        let community = create_community(&bed.relay, "Determinism", bed.relays.clone(), None).await.unwrap();
7314
7315        // A rich control plane: two admins, an extra role, two grants (one of them a
7316        // grant to a member the owner then bans), a banlist, a rename, a channel.
7317        let admin1 = Keys::generate().public_key();
7318        let admin2 = Keys::generate().public_key();
7319        grant_admin(&bed.relay, &community, &admin1).await.unwrap();
7320        grant_admin(&bed.relay, &community, &admin2).await.unwrap();
7321        let mod_rid = "5c".repeat(32);
7322        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&mod_rid, Permissions::KICK | Permissions::MANAGE_MESSAGES), 1).await;
7323        let member = Keys::generate().public_key();
7324        publish_grant(&bed.relay, &community, &owner.keys, &member, vec![mod_rid.clone()], 1).await;
7325        let banned_member = Keys::generate().public_key();
7326        publish_grant(&bed.relay, &community, &owner.keys, &banned_member, vec![mod_rid], 1).await;
7327        set_banlist(&bed.relay, &community, &[banned_member.to_hex()]).await.unwrap();
7328        let meta = control::CommunityMetadata { name: "Renamed".into(), relays: community.relays.clone(), ..Default::default() };
7329        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
7330        create_public_channel(&bed.relay, &community, "extra").await.unwrap();
7331
7332        let editions = fetch_control(&bed.relay, &community).await;
7333        let floors = load_floors(&community);
7334        assert!(editions.len() >= 6, "a rich plane was built ({} editions)", editions.len());
7335
7336        let baseline = authority_fingerprint(&fold_authority(&community, &editions, &floors));
7337
7338        // Fold under many arrival permutations: reversed, and several deterministic
7339        // rotations/interleavings. Every one must match the baseline.
7340        let mut orders: Vec<Vec<ParsedEdition>> = Vec::new();
7341        let mut rev = editions.clone();
7342        rev.reverse();
7343        orders.push(rev);
7344        for shift in [1usize, 3, 5, 7] {
7345            let n = editions.len();
7346            orders.push((0..n).map(|i| editions[(i + shift) % n].clone()).collect());
7347        }
7348        // A deterministic "shuffle": interleave from both ends.
7349        let mut zip = Vec::with_capacity(editions.len());
7350        let (mut lo, mut hi) = (0isize, editions.len() as isize - 1);
7351        while lo <= hi {
7352            zip.push(editions[lo as usize].clone());
7353            if lo != hi {
7354                zip.push(editions[hi as usize].clone());
7355            }
7356            lo += 1;
7357            hi -= 1;
7358        }
7359        orders.push(zip);
7360
7361        for (i, order) in orders.iter().enumerate() {
7362            let got = authority_fingerprint(&fold_authority(&community, order, &floors));
7363            assert_eq!(got, baseline, "arrival order #{i} must resolve the identical authority (consensus)");
7364        }
7365        // Sanity: the fingerprint reflects real state (the banned member is out, the
7366        // honest admins are in).
7367        assert!(baseline.contains(&admin1.to_hex()) || baseline.contains(&member.to_hex()), "grants are present in the fingerprint");
7368        assert!(baseline.contains(&banned_member.to_hex()), "the banlist entry is in the fingerprint");
7369    }
7370
7371    /// A transport that ACKs publishes but ERRORS every fetch — a relay outage / withhold.
7372    struct FetchErrors(MemoryRelay);
7373    #[async_trait::async_trait]
7374    impl crate::community::transport::Transport for FetchErrors {
7375        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
7376        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
7377            self.0.publish(e, r).await
7378        }
7379        async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
7380            Err("relay down".to_string())
7381        }
7382        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
7383            self.0.publish_durable(e, r).await
7384        }
7385    }
7386
7387    #[tokio::test]
7388    async fn fetch_authority_retains_the_persisted_banlist_on_a_transport_error() {
7389        let (bed, owner, victim) = TestBed::new();
7390        bed.swap_to(&owner);
7391        let community = create_community(&bed.relay, "BanRetain", bed.relays.clone(), None).await.unwrap();
7392        let victim_hex = victim.keys.public_key().to_hex();
7393        // A ban is persisted locally (as a completed set_banlist + follow leaves it).
7394        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
7395        crate::db::community::set_community_banlist(&cid_hex, &[victim_hex.clone()], 1).unwrap();
7396
7397        // A relay that ERRORS on fetch must degrade FAIL-SAFE: retain the ban, never
7398        // return an empty banlist (which would silently un-ban on withheld data).
7399        let down = FetchErrors(MemoryRelay::new());
7400        let view = fetch_authority(&down, &community).await;
7401        assert!(view.banned.contains(&victim_hex), "a transport error retains the persisted banlist");
7402    }
7403
7404    #[tokio::test]
7405    async fn follow_control_retains_the_roster_when_a_floored_role_ages_out() {
7406        let (bed, owner, _m) = TestBed::new();
7407        bed.swap_to(&owner);
7408        let community = create_community(&bed.relay, "Complete", bed.relays.clone(), None).await.unwrap();
7409        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
7410        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
7411        let rid = crate::simd::hex::bytes_to_hex_32(&[0x7c; 32]);
7412
7413        // Full state on relay1: an Admin role + two grants → both fold + persist as admins.
7414        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
7415        publish_grant(&bed.relay, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
7416        publish_grant(&bed.relay, &community, &owner.keys, &b, vec![rid.clone()], 1).await;
7417        let session = crate::state::SessionGuard::capture();
7418        follow_control(&bed.relay, &community, &session).await.unwrap();
7419        assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&a.to_hex()), "seeded");
7420
7421        // relay2 serves A's grant but NOT the role (aged out of the window): the fold
7422        // drops both admins yet raises no gap. The completeness gate must RETAIN the
7423        // stored roster rather than persist the lossy one.
7424        let relay2 = MemoryRelay::new();
7425        publish_grant(&relay2, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
7426        follow_control(&relay2, &community, &session).await.unwrap();
7427        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
7428        assert!(roster.is_admin(&a.to_hex()) && roster.is_admin(&b.to_hex()), "a floored-but-unfetched role retains the stored roster");
7429    }
7430
7431    #[tokio::test]
7432    async fn an_uncited_metadata_or_banlist_edition_is_dropped() {
7433        // CORD-04 §5 covers EVERY control entity, not just the delegation chain.
7434        // Vector already gated roles and grants in-fold; metadata, channels and
7435        // the banlist resolved on permission alone, so a client one sweep behind
7436        // honored an edit from an admin whose demotion it had not read yet.
7437        let (_tmp, _guard, owner) = init_test_db();
7438        let relay = MemoryRelay::new();
7439        let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
7440        let admin = Keys::generate();
7441        let rid = "a7".repeat(32);
7442        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA | Permissions::BAN), 1).await;
7443        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid], 1).await;
7444
7445        // The admin acts WITHOUT citing (what every pre-citation client emitted).
7446        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7447        let meta = control::CommunityMetadata { name: "Uncited Rename".into(), ..Default::default() };
7448        let rumor = control::build_edition_rumor(
7449            admin.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2,
7450            head_hash_on_relay(&relay, &community, &community.id().0).await.as_ref(),
7451            &serde_json::to_string(&meta).unwrap(), 1_000, None,
7452        );
7453        let (wrap, _) = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
7454        relay.publish(&wrap, &community.relays).await.unwrap();
7455
7456        let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
7457        let victim = Keys::generate().public_key().to_hex();
7458        let ban_rumor = control::build_edition_rumor(
7459            admin.public_key(), vsk::BANLIST, &ban_eid, 1, None,
7460            &serde_json::to_string(&vec![victim.clone()]).unwrap(), 1_000, None,
7461        );
7462        let (ban_wrap, _) = control::seal_control_edition(&ban_rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
7463        relay.publish(&ban_wrap, &community.relays).await.unwrap();
7464
7465        let session = SessionGuard::capture();
7466        let updated = follow_control(&relay, &community, &session).await.unwrap();
7467        assert!(
7468            updated.as_ref().is_none_or(|c| c.name != "Uncited Rename"),
7469            "an uncited metadata edit must not be honored",
7470        );
7471        let authority = fetch_authority(&relay, &community).await;
7472        assert!(!authority.banned.contains(&victim), "an uncited banlist edition must not be honored");
7473        // The positive case (this same admin, citing, lands) is
7474        // `an_authorized_admin_edits_metadata_but_a_demoted_one_cannot` — its
7475        // helper cites, so it proves the gate is the CITATION and not the
7476        // permission. Re-proving it here would need a fresh chain anyway: a
7477        // cited edition chaining onto the rejected one above is gapped, not
7478        // refused.
7479    }
7480
7481    #[tokio::test]
7482    async fn an_authorized_admin_edits_metadata_but_a_demoted_one_cannot() {
7483        // CORD-04 §5: an admin holding MANAGE_METADATA renames the community; once the
7484        // owner revokes the grant, the (now unauthorized) admin's further edit drops
7485        // and the name holds at the last authorized state.
7486        let (_tmp, _guard, owner) = init_test_db();
7487        let relay = MemoryRelay::new();
7488        let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
7489        let admin = Keys::generate();
7490        let rid = "a1".repeat(32);
7491        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
7492        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
7493        publish_community_meta(&relay, &community, &admin, "Admin Rename", 2).await;
7494
7495        let session = SessionGuard::capture();
7496        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("admin edit authorized");
7497        assert_eq!(updated.name, "Admin Rename", "an admin with MANAGE_METADATA renames");
7498
7499        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke
7500        publish_community_meta(&relay, &community, &admin, "Demoted Rename", 3).await;
7501        let _ = follow_control(&relay, &community, &session).await.unwrap();
7502        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7503        assert_eq!(held.name, "Admin Rename", "a demoted admin's edit is dropped; the name holds");
7504    }
7505
7506    #[tokio::test]
7507    async fn a_roleless_member_cannot_edit_metadata() {
7508        let (_tmp, _guard, _owner) = init_test_db();
7509        let relay = MemoryRelay::new();
7510        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
7511        let stranger = Keys::generate();
7512        publish_community_meta(&relay, &community, &stranger, "Hijacked", 2).await;
7513        let session = SessionGuard::capture();
7514        assert!(
7515            follow_control(&relay, &community, &session).await.unwrap().is_none(),
7516            "a roleless member's metadata edit never folds"
7517        );
7518    }
7519
7520    #[tokio::test]
7521    async fn a_self_signed_grant_is_not_authority() {
7522        // The self-promotion defense: a member self-signs both a role and a grant of
7523        // it to themselves. authorize_delegation drops both (their signer never traces
7524        // to the owner), so their metadata edit stays unauthorized.
7525        let (_tmp, _guard, _owner) = init_test_db();
7526        let relay = MemoryRelay::new();
7527        let community = create_community(&relay, "NoSelfPromo", vec!["wss://r".into()], None).await.unwrap();
7528        let rogue = Keys::generate();
7529        let rid = "b2".repeat(32);
7530        publish_role(&relay, &community, &rogue, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
7531        publish_grant(&relay, &community, &rogue, &rogue.public_key(), vec![rid.clone()], 1).await;
7532        publish_community_meta(&relay, &community, &rogue, "Seized", 2).await;
7533        let session = SessionGuard::capture();
7534        assert!(
7535            follow_control(&relay, &community, &session).await.unwrap().is_none(),
7536            "a self-signed grant confers no authority"
7537        );
7538    }
7539
7540    #[tokio::test]
7541    async fn the_banlist_is_enforced_only_from_a_ban_holder() {
7542        let (_tmp, _guard, owner) = init_test_db();
7543        let relay = MemoryRelay::new();
7544        let community = create_community(&relay, "Bans", vec!["wss://r".into()], None).await.unwrap();
7545        let target = "cc".repeat(32);
7546
7547        // A non-BAN-holder's banlist edition is folded but NOT enforced.
7548        let rogue = Keys::generate();
7549        publish_banlist(&relay, &community, &rogue, &[target.clone()], 1).await;
7550        let floors = load_floors(&community);
7551        let editions = fetch_control(&relay, &community).await;
7552        let authority = fold_authority(&community, &editions, &floors);
7553        assert!(authority.banned.is_empty(), "a non-owner (no BAN) banlist is not enforced");
7554
7555        // The owner (supreme, holds BAN) bans the target: now enforced.
7556        publish_banlist(&relay, &community, &owner, &[target.clone()], 2).await;
7557        let editions = fetch_control(&relay, &community).await;
7558        let authority = fold_authority(&community, &editions, &floors);
7559        assert!(authority.banned.contains(&target), "the owner's banlist is enforced");
7560    }
7561
7562    #[tokio::test]
7563    async fn a_banned_admin_loses_all_authority() {
7564        // CORD-04 §4: a banned npub vanishes — even holding an un-stripped grant, a
7565        // banned admin's authority is dropped and their edits refused.
7566        let (_tmp, _guard, owner) = init_test_db();
7567        let relay = MemoryRelay::new();
7568        let community = create_community(&relay, "BanAuth", vec!["wss://r".into()], None).await.unwrap();
7569        let admin = Keys::generate();
7570        let rid = "e5".repeat(32);
7571        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
7572        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
7573        publish_banlist(&relay, &community, &owner, &[admin.public_key().to_hex()], 1).await; // ban, grant left intact
7574        publish_community_meta(&relay, &community, &admin, "Banned Rename", 2).await;
7575
7576        let session = SessionGuard::capture();
7577        assert!(
7578            follow_control(&relay, &community, &session).await.unwrap().is_none(),
7579            "a banned admin's edit is dropped even with an unstripped grant"
7580        );
7581        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
7582        assert!(authority.banned.contains(&admin.public_key().to_hex()));
7583        assert!(
7584            !authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
7585            "a banned admin holds no bit"
7586        );
7587    }
7588
7589    #[tokio::test]
7590    async fn a_ban_holder_cannot_ban_a_superior_or_the_owner() {
7591        // CORD-04 §3/§5: BAN needs the bit AND a strict outrank of the target. A mod
7592        // (pos 2, holds BAN) can ban a lower member but NOT a superior admin (pos 1)
7593        // and NOT the owner (supreme, unbannable).
7594        let (_tmp, _guard, owner) = init_test_db();
7595        let relay = MemoryRelay::new();
7596        let community = create_community(&relay, "Ranks", vec!["wss://r".into()], None).await.unwrap();
7597        let admin = Keys::generate();
7598        let moder = Keys::generate();
7599        let stranger = Keys::generate();
7600        let (admin_rid, mod_rid) = ("a1".repeat(32), "b2".repeat(32));
7601        publish_role(&relay, &community, &owner, &Role { role_id: admin_rid.clone(), name: "Admin".into(), position: 1, permissions: Permissions(Permissions::ADMIN_ALL), scope: RoleScope::Server, color: 0 }, 1).await;
7602        publish_role(&relay, &community, &owner, &Role { role_id: mod_rid.clone(), name: "Mod".into(), position: 2, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0 }, 1).await;
7603        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![admin_rid], 1).await;
7604        publish_grant(&relay, &community, &owner, &moder.public_key(), vec![mod_rid], 1).await;
7605        publish_banlist(&relay, &community, &moder, &[admin.public_key().to_hex(), owner.public_key().to_hex(), stranger.public_key().to_hex()], 1).await;
7606
7607        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
7608        assert!(!authority.banned.contains(&admin.public_key().to_hex()), "a mod cannot ban a superior admin");
7609        assert!(!authority.banned.contains(&owner.public_key().to_hex()), "nobody can ban the owner");
7610        assert!(authority.banned.contains(&stranger.public_key().to_hex()), "the mod CAN ban a lower-ranked member");
7611    }
7612
7613    #[tokio::test]
7614    async fn an_unauthorized_higher_banlist_cannot_unban() {
7615        // CORD-04 §4 anti-roster fail-CLOSED: a rogue's higher-version empty banlist
7616        // must not erase the owner's ban (author-aware head selection + persisted
7617        // banlist retention).
7618        let (_tmp, _guard, owner) = init_test_db();
7619        let relay = MemoryRelay::new();
7620        let community = create_community(&relay, "NoUnban", vec!["wss://r".into()], None).await.unwrap();
7621        let target = "cc".repeat(32);
7622        publish_banlist(&relay, &community, &owner, &[target.clone()], 1).await;
7623        let session = SessionGuard::capture();
7624        follow_control(&relay, &community, &session).await.unwrap(); // persists the ban
7625
7626        let rogue = Keys::generate();
7627        publish_banlist(&relay, &community, &rogue, &[], 2).await; // unauthorized higher, empty
7628        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
7629        assert!(authority.banned.contains(&target), "an unauthorized higher banlist cannot un-ban");
7630    }
7631
7632    #[tokio::test]
7633    async fn the_community_list_syncs_a_membership_to_a_fresh_device() {
7634        // CORD-02 §8: create publishes the 13302; a fresh device (community dropped
7635        // locally, the 13302 + genesis still on the relay) rehydrates it on sync.
7636        let (_tmp, _guard, _owner) = init_test_db();
7637        let relay = MemoryRelay::new();
7638        let relays = vec!["wss://r".to_string()];
7639        let community = create_community(&relay, "Synced", relays.clone(), None).await.unwrap();
7640        crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
7641        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none());
7642
7643        let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
7644        assert_eq!(rehydrated.len(), 1, "the left-behind membership rehydrates");
7645        assert_eq!(rehydrated[0].id().0, community.id().0);
7646        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some(), "and is now held locally");
7647    }
7648
7649    #[tokio::test]
7650    async fn a_leave_tombstones_the_membership_so_sync_does_not_rejoin() {
7651        let (_tmp, _guard, _owner) = init_test_db();
7652        let relay = MemoryRelay::new();
7653        let relays = vec!["wss://r".to_string()];
7654        let community = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
7655        leave_community(&relay, &community).await.unwrap(); // tombstones the 13302 + deletes
7656
7657        let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
7658        assert!(rehydrated.is_empty(), "a tombstoned membership is not rejoined on sync");
7659    }
7660
7661    #[tokio::test]
7662    async fn accepting_the_same_bundle_twice_is_idempotent() {
7663        // A bot restart or a duplicate invite delivery: accepting the SAME bundle
7664        // again must upsert cleanly — same community_id, no duplicate channels, no
7665        // corruption, the keys unchanged.
7666        let (bed, owner, member) = TestBed::new();
7667        bed.swap_to(&owner);
7668        let community = create_community(&bed.relay, "Idem", bed.relays.clone(), None).await.unwrap();
7669        create_public_channel(&bed.relay, &community, "extra").await.unwrap();
7670        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7671        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
7672
7673        bed.swap_to(&member);
7674        let first = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
7675        let channels_after_first = first.channels.len();
7676        let root_after_first = first.community_root;
7677
7678        // Accept the identical bundle again (restart / redelivery).
7679        let second = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
7680        assert_eq!(second.id().0, first.id().0, "same community_id");
7681        assert_eq!(second.channels.len(), channels_after_first, "no duplicate channels on re-accept");
7682        assert_eq!(second.community_root, root_after_first, "root unchanged");
7683
7684        // The persisted state is a single clean community with the expected channels.
7685        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7686        assert_eq!(reloaded.channels.len(), channels_after_first, "the DB holds one clean channel set");
7687        assert_eq!(crate::db::community::list_community_ids().unwrap().iter().filter(|id| id.0 == community.id().0).count(), 1, "exactly one community row");
7688    }
7689
7690    #[tokio::test]
7691    async fn a_severed_member_can_be_unbanned_and_re_admitted() {
7692        // The full moderation HEAL lifecycle: ban (banlist + grant strip + refound)
7693        // severs a member; the owner then unbans + sends a FRESH invite carrying the
7694        // NEW root; the member rejoins at the new epoch and converses again. Proves
7695        // a ban is reversible end-to-end, not a one-way door.
7696        let (bed, owner, member) = TestBed::new();
7697        bed.swap_to(&owner);
7698        let mut community = create_community(&bed.relay, "Redeemable", bed.relays.clone(), None).await.unwrap();
7699        let general = community.channels[0].id;
7700        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
7701        send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();
7702
7703        bed.swap_to(&member);
7704        let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
7705        let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
7706        assert!(texts_in(&bed.relay, &joined, &general).await.contains(&"owner: welcome".to_string()));
7707
7708        // Owner bans the member (CORD-04 §6 three-removal) → refound severs them.
7709        bed.swap_to(&owner);
7710        set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();
7711        grant_roles(&bed.relay, &community, &member.keys.public_key(), vec![]).await.unwrap();
7712        community = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
7713        assert_eq!(community.root_epoch, Epoch(1));
7714        send_message(&bed.relay, &community, &general, "owner: after the ban").await.unwrap();
7715
7716        // The member's follow concludes severance (no blob at the new epoch).
7717        bed.swap_to(&member);
7718        let session = SessionGuard::capture();
7719        assert!(follow_rekeys(&bed.relay, &joined, &session).await.unwrap().self_removed, "the member is cryptographically severed");
7720
7721        // Owner unbans + re-invites: build the fresh epoch-1 bundle (accept it
7722        // directly, so the test picks the NEW invite unambiguously rather than an
7723        // arbitrary one of the two pending 3313s).
7724        bed.swap_to(&owner);
7725        set_banlist(&bed.relay, &community, &[]).await.unwrap();
7726        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7727        assert_eq!(community.root_epoch, Epoch(1), "the owner's bundle carries epoch 1");
7728        let fresh_bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
7729
7730        // Member accepts the fresh invite → rejoins at epoch 1, reads current + posts.
7731        bed.swap_to(&member);
7732        let rejoined = accept_parked_invite(&bed.relay, &fresh_bundle, None).await.unwrap();
7733        assert_eq!(rejoined.root_epoch, Epoch(1), "rejoined at the current epoch");
7734        assert_eq!(rejoined.community_root, community.community_root, "holds the NEW root");
7735        let seen = texts_in(&bed.relay, &rejoined, &general).await;
7736        assert!(seen.contains(&"owner: after the ban".to_string()), "reads post-ban history with the new root");
7737        send_message(&bed.relay, &rejoined, &general, "member: i am back").await.unwrap();
7738
7739        bed.swap_to(&owner);
7740        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7741        assert!(
7742            texts_in(&bed.relay, &community, &general).await.contains(&"member: i am back".to_string()),
7743            "the re-admitted member converses again at the new epoch"
7744        );
7745        // And they're back in the memberlist.
7746        let members = memberlist(&bed.relay, &community).await.unwrap();
7747        assert!(members.contains(&member.keys.public_key()), "the re-admitted member is in the list");
7748    }
7749
7750    #[tokio::test]
7751    async fn dissolution_blocks_a_join() {
7752        // CORD-02 §9: the owner dissolves; a would-be joiner resolves the grave and
7753        // refuses to join.
7754        let (bed, owner, member) = TestBed::new();
7755        bed.swap_to(&owner);
7756        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
7757        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7758        let bundle_json = serde_json::to_string(&bundle).unwrap();
7759        dissolve_community(&bed.relay, &community).await.unwrap();
7760        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the owner's local hold is sealed");
7761
7762        bed.swap_to(&member);
7763        let err = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap_err();
7764        assert!(err.contains("dissolved"), "a join refuses a dissolved community: {err}");
7765    }
7766
7767    #[tokio::test]
7768    async fn dissolution_seals_writes_but_not_reads() {
7769        // CORD-02 §9: sealed means NO further activity, ever. Reads must survive —
7770        // the history stays browsable, and only explicit user intent deletes it.
7771        let (bed, owner, _member) = TestBed::new();
7772        bed.swap_to(&owner);
7773        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
7774        let general = community.channels[0].id;
7775        send_message(&bed.relay, &community, &general, "before the end").await.unwrap();
7776
7777        dissolve_community(&bed.relay, &community).await.unwrap();
7778        let sealed = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7779
7780        for err in [
7781            send_message(&bed.relay, &sealed, &general, "after the end").await.unwrap_err(),
7782            send_reaction(&bed.relay, &sealed, &general, &"a".repeat(64), &"b".repeat(64), crate::community::v2::kind::MESSAGE, "+", None)
7783                .await
7784                .unwrap_err(),
7785            send_edit(&bed.relay, &sealed, &general, &"a".repeat(64), "revised").await.unwrap_err(),
7786        ] {
7787            assert!(err.contains("dissolved"), "every write is refused, got: {err}");
7788        }
7789        assert!(
7790            texts_in(&bed.relay, &sealed, &general).await.contains(&"before the end".to_string()),
7791            "but the history still reads"
7792        );
7793    }
7794
7795    #[tokio::test]
7796    async fn only_the_owner_can_dissolve() {
7797        let (bed, owner, member) = TestBed::new();
7798        bed.swap_to(&owner);
7799        let community = create_community(&bed.relay, "Mine", bed.relays.clone(), None).await.unwrap();
7800        bed.swap_to(&member);
7801        assert!(dissolve_community(&bed.relay, &community).await.is_err(), "only the owner can dissolve");
7802        assert!(!is_dissolved(&bed.relay, &community).await, "and no tombstone was published");
7803    }
7804
7805    #[tokio::test]
7806    async fn a_foreign_tombstone_is_not_death() {
7807        // A non-owner sealing the dissolved plane is noise (verify_dissolved is
7808        // owner-gated), so the community is not treated as dead.
7809        let (_tmp, _guard, _owner) = init_test_db();
7810        let relay = MemoryRelay::new();
7811        let community = create_community(&relay, "Safe", vec!["wss://r".into()], None).await.unwrap();
7812        let rogue = Keys::generate();
7813        let rumor = crate::community::v2::dissolution::dissolved_tombstone_rumor(rogue.public_key(), community.id(), 1_000);
7814        let wrap = crate::community::v2::dissolution::seal_dissolved(&rumor, community.id(), &rogue, Timestamp::from_secs(1_000)).unwrap();
7815        relay.publish(&wrap, &community.relays).await.unwrap();
7816        assert!(!is_dissolved(&relay, &community).await, "a foreign-signed tombstone is not death");
7817    }
7818
7819    #[tokio::test]
7820    async fn a_public_channel_reads_history_across_a_refounding() {
7821        // CORD-03 §3: after a Refounding rolls the base root, a Public channel's
7822        // pre-rotation messages stay readable (the prior epoch's root is archived and
7823        // the read fans out across held epochs).
7824        let (_tmp, _guard, _owner) = init_test_db();
7825        let relay = MemoryRelay::new();
7826        let community = create_community(&relay, "History", vec!["wss://r".into()], None).await.unwrap();
7827        let general = community.channels[0].id;
7828        send_message(&relay, &community, &general, "before the refounding").await.unwrap();
7829
7830        let refounded = refound_community(&relay, &community, &[]).await.unwrap();
7831        assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
7832        send_message(&relay, &refounded, &general, "after the refounding").await.unwrap();
7833
7834        let texts = texts_in(&relay, &refounded, &general).await;
7835        assert!(texts.contains(&"before the refounding".to_string()), "the epoch-0 message is still readable");
7836        assert!(texts.contains(&"after the refounding".to_string()), "the epoch-1 message reads too");
7837    }
7838
7839    #[tokio::test]
7840    async fn refounding_aborts_when_control_state_is_withheld() {
7841        // B1 coverage gate (CORD-06 §3): a relay serving none of the committed control
7842        // heads must ABORT the Refounding — never silently drop state (e.g. unban a
7843        // member at the new epoch a fresh joiner bootstraps).
7844        let (_tmp, _guard, owner) = init_test_db();
7845        let relay = MemoryRelay::new();
7846        let community = create_community(&relay, "Withheld", vec!["wss://good".into()], None).await.unwrap();
7847        publish_banlist(&relay, &community, &owner, &["cc".repeat(32)], 1).await;
7848        let session = SessionGuard::capture();
7849        follow_control(&relay, &community, &session).await.unwrap(); // seed the banlist floor
7850
7851        // Re-point the held community to an EMPTY relay + save, so the Refounding (which
7852        // reloads fresh state) fetches none of the committed heads.
7853        let mut moved = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7854        moved.relays = vec!["wss://empty".into()];
7855        crate::db::community::save_community_v2(&moved).unwrap();
7856
7857        let err = refound_community(&relay, &moved, &[]).await.unwrap_err();
7858        assert!(err.contains("was not served"), "a withheld control head aborts the refounding: {err}");
7859        assert_eq!(
7860            crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
7861            Epoch(0),
7862            "the epoch did NOT advance (zero published state)"
7863        );
7864    }
7865
7866    #[tokio::test]
7867    async fn refounding_rolls_the_root_and_severs_a_removed_member() {
7868        // CORD-06 §3: the owner re-founds, removing a member. The base root rolls, the
7869        // epoch advances, and the removed member's rekey-follow concludes they're cut.
7870        let (bed, owner, member) = TestBed::new();
7871        bed.swap_to(&owner);
7872        let community = create_community(&bed.relay, "Refound", bed.relays.clone(), None).await.unwrap();
7873        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7874        let bundle_json = serde_json::to_string(&bundle).unwrap();
7875        bed.swap_to(&member);
7876        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7877
7878        bed.swap_to(&owner);
7879        let refounded = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
7880        assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
7881        assert_ne!(refounded.community_root, community.community_root, "the base root rolled");
7882        // The owner still reads the compacted control plane at the new epoch.
7883        assert_eq!(
7884            crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
7885            Epoch(1),
7886            "the owner committed the new epoch"
7887        );
7888
7889        // The removed member, following rekeys, is severed (no blob in the rotation).
7890        // Guard captured AFTER the swap: it must belong to the ACTING account (the harness
7891        // swap now bumps the generation exactly like a production swap_session).
7892        bed.swap_to(&member);
7893        let session = SessionGuard::capture();
7894        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
7895        assert!(follow.self_removed, "the removed member is cut by the re-founding");
7896    }
7897
7898    #[tokio::test]
7899    async fn a_ban_holding_admin_can_re_found_but_not_evict_a_superior() {
7900        // CORD-06 §Authority: a Refounding requires BAN, not owner-identity. A
7901        // non-owner admin granted BAN CAN re-found (and every member follows it —
7902        // see the receive-side test), but the "strictly outrank every removed
7903        // target" rule still holds: they can't use it to evict the owner.
7904        let (bed, owner, member) = TestBed::new();
7905        bed.swap_to(&owner);
7906        let community = create_community(&bed.relay, "Guarded", bed.relays.clone(), None).await.unwrap();
7907        let rid = "b0".repeat(32);
7908        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7909        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
7910        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7911        let bundle_json = serde_json::to_string(&bundle).unwrap();
7912        bed.swap_to(&member);
7913        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7914        // Fold the roster so this member's own DB reflects their BAN grant (the
7915        // authority check reads the folded Roster, not the bundle).
7916        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7917        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7918        // Can't evict the owner (no one outranks the owner).
7919        assert!(refound_community(&bed.relay, &joined, &[owner.keys.public_key()]).await.is_err(), "a BAN-holder can't re-found to evict the owner");
7920        // But CAN re-found removing a plain member they outrank (here, nobody).
7921        assert!(refound_community(&bed.relay, &joined, &[]).await.is_ok(), "a BAN-holding admin can re-found");
7922    }
7923
7924    #[tokio::test]
7925    async fn follow_rekeys_adopts_an_authorized_non_owner_base_rotation() {
7926        // A BAN-holding ADMIN (not the owner) re-founds, and every member must
7927        // follow it — owner-only receive silently strands members whose community
7928        // was refounded by an admin (CORD-06 §Authority: "a Refounding requires
7929        // BAN", checked against the folded Roster).
7930        let (bed, owner, me) = TestBed::new();
7931        let admin = Keys::generate();
7932        bed.swap_to(&owner);
7933        let community = create_community(&bed.relay, "AdminRefound", bed.relays.clone(), None).await.unwrap();
7934        let rid = "b0".repeat(32);
7935        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7936        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
7937
7938        // I (a plain member) join, then fold the roster so I know the admin holds BAN.
7939        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7940        let bundle_json = serde_json::to_string(&bundle).unwrap();
7941        bed.swap_to(&me);
7942        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7943        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7944        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7945
7946        // The admin re-founds keeping the owner + me — the owner must always be a
7947        // recipient of a non-owner Refounding.
7948        let new_root = [0xC7; 32];
7949        publish_base_rotation(&bed.relay, &joined, &admin, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
7950
7951        let updated = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap().updated
7952            .expect("an authorized admin's Refounding is adopted");
7953        assert_eq!(updated.root_epoch, Epoch(1), "advanced past the admin's rotation");
7954        assert_eq!(updated.community_root, new_root, "adopted the admin's fresh root");
7955    }
7956
7957    #[tokio::test]
7958    async fn adopting_someone_elses_rotation_refreshes_my_own_live_links() {
7959        // CORD-05 §2: a link shared once keeps working across rotations, because
7960        // its bundle is re-posted behind the same URL. The Refounder can only
7961        // refresh the bundles they hold signer secrets for — their OWN — so
7962        // every other creator has to heal their links when they ADOPT the
7963        // rotation. Without that, an admin's links keep vending the superseded
7964        // root and drop new joiners onto a dead epoch, which is precisely the
7965        // stranding the stable-URL refresh exists to prevent.
7966        let (bed, owner, me) = TestBed::new();
7967        bed.swap_to(&owner);
7968        let community = create_community(&bed.relay, "LinkHeal", bed.relays.clone(), None).await.unwrap();
7969        let rid = "b1".repeat(32);
7970        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7971        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
7972
7973        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7974        let bundle_json = serde_json::to_string(&bundle).unwrap();
7975        bed.swap_to(&me);
7976        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7977        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7978        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7979
7980        // I mint a link of my own at the CURRENT epoch.
7981        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
7982        let vended_before = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
7983        assert_eq!(vended_before.root_epoch, 0, "my link vends the epoch I minted it at");
7984
7985        // The OWNER re-founds. Their refresh can't touch my bundle: only I hold
7986        // its signer secret.
7987        let new_root = [0xD4; 32];
7988        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
7989
7990        let updated = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap().updated
7991            .expect("the owner's Refounding is adopted");
7992        assert_eq!(updated.root_epoch, Epoch(1), "I advanced to the new epoch");
7993
7994        let vended_after = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
7995        assert_eq!(vended_after.root_epoch, 1, "my link must now vend the NEW epoch, not strand its joiners");
7996        assert_eq!(
7997            crate::simd::hex::hex_to_bytes_32(&vended_after.community_root),
7998            new_root,
7999            "and the new root behind the same URL",
8000        );
8001    }
8002
8003    #[tokio::test]
8004    async fn follow_rekeys_refuses_a_refounding_that_excludes_the_owner() {
8005        // Authority escalation: a BAN-admin can't use a Refounding to evict the
8006        // OWNER (no one outranks the owner). Excluding them makes the rotation
8007        // inadmissible — members fork-reject it rather than migrate to the coup.
8008        let (bed, owner, me) = TestBed::new();
8009        let admin = Keys::generate();
8010        bed.swap_to(&owner);
8011        let community = create_community(&bed.relay, "NoCoup", bed.relays.clone(), None).await.unwrap();
8012        let rid = "b0".repeat(32);
8013        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
8014        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
8015
8016        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
8017        let bundle_json = serde_json::to_string(&bundle).unwrap();
8018        bed.swap_to(&me);
8019        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8020        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
8021        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
8022
8023        // The admin re-founds delivering to me but NOT the owner — a takeover.
8024        publish_base_rotation(&bed.relay, &joined, &admin, &[me.keys.public_key()], &[0xEE; 32], &joined.community_root).await;
8025        let follow = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap();
8026        assert!(follow.updated.is_none() && !follow.self_removed, "an owner-excluding Refounding is not adopted");
8027    }
8028
8029    #[tokio::test]
8030    async fn follow_rekeys_refuses_a_refounding_that_excludes_a_peer_admin() {
8031        // Authority escalation: two equal-rank BAN-admins — neither strictly
8032        // outranks the other, so one can't Refound the other out. Excluding a
8033        // peer makes the rotation inadmissible.
8034        let (bed, owner, me) = TestBed::new();
8035        let admin_a = Keys::generate();
8036        let admin_b = Keys::generate(); // the peer admin the rotation excludes.
8037        bed.swap_to(&owner);
8038        let community = create_community(&bed.relay, "Peers", bed.relays.clone(), None).await.unwrap();
8039        let rid = "b0".repeat(32);
8040        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
8041        // Both A and B hold the SAME role (same position 1) → peers.
8042        publish_grant(&bed.relay, &community, &owner.keys, &admin_a.public_key(), vec![rid.clone()], 1).await;
8043        publish_grant(&bed.relay, &community, &owner.keys, &admin_b.public_key(), vec![rid], 1).await;
8044
8045        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
8046        let bundle_json = serde_json::to_string(&bundle).unwrap();
8047        bed.swap_to(&me);
8048        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8049        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
8050        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
8051
8052        // Admin A re-founds keeping the owner + me but EXCLUDING peer admin B.
8053        publish_base_rotation(&bed.relay, &joined, &admin_a, &[owner.keys.public_key(), me.keys.public_key()], &[0xDD; 32], &joined.community_root).await;
8054
8055        let follow = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap();
8056        assert!(follow.updated.is_none() && !follow.self_removed, "excluding an equal-rank peer admin is inadmissible");
8057    }
8058
8059    #[tokio::test]
8060    async fn a_retried_refounding_reuses_the_same_root() {
8061        // B1 idempotency: minting for the same (scope, epoch) twice yields the SAME
8062        // root, so a retried Refounding re-delivers one root — never a double-mint fork.
8063        let (_tmp, _guard, _owner) = init_test_db();
8064        let relay = MemoryRelay::new();
8065        let community = create_community(&relay, "Retry", vec!["wss://r".into()], None).await.unwrap();
8066        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
8067        let first = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
8068        let second = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
8069        assert_eq!(first, second, "a retry reuses the archived root, never double-mints");
8070    }
8071
8072    #[tokio::test]
8073    async fn a_mid_rank_admin_cannot_demote_a_role_that_outranks_them() {
8074        // CORD-04 §2 rank inversion. Minting at a position you outrank is
8075        // necessary but NOT sufficient: an edition replaces the entity, so a
8076        // gate that only reads the NEW position lets an admin at position 5
8077        // rewrite the position-1 role to position 9. Every check passes (9 is
8078        // beneath them), and the role that outranked them — plus everyone
8079        // holding it — is now beneath them.
8080        let (bed, owner, attacker) = TestBed::new();
8081        bed.swap_to(&owner);
8082        let community = create_community(&bed.relay, "Ranks", bed.relays.clone(), None).await.unwrap();
8083
8084        // A senior role at position 1, and a mid role at position 5 the attacker holds.
8085        let senior = "a1".repeat(32);
8086        let mid = "a5".repeat(32);
8087        publish_role(&bed.relay, &community, &owner.keys,
8088            &Role { role_id: senior.clone(), name: "Senior".into(), position: 1, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0 }, 1).await;
8089        publish_role(&bed.relay, &community, &owner.keys,
8090            &Role { role_id: mid.clone(), name: "Mid".into(), position: 5, permissions: Permissions(Permissions::MANAGE_ROLES), scope: RoleScope::Server, color: 0 }, 1).await;
8091        publish_grant(&bed.relay, &community, &owner.keys, &attacker.keys.public_key(), vec![mid.clone()], 1).await;
8092
8093        // The attacker republishes the SENIOR role, dropping it beneath themselves.
8094        publish_role(&bed.relay, &community, &attacker.keys,
8095            &Role { role_id: senior.clone(), name: "Senior".into(), position: 9, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0 }, 2).await;
8096
8097        let authority = fetch_authority(&bed.relay, &community).await;
8098        let folded_senior = authority.roles.role(&senior).expect("the senior role survives the fold");
8099        assert_eq!(
8100            folded_senior.position, 1,
8101            "a role may only be repositioned by someone who outranks where it STOOD, not just where it lands",
8102        );
8103    }
8104
8105    #[tokio::test]
8106    async fn a_non_owner_admins_edition_cites_its_grant_and_the_owners_does_not() {
8107        // CORD-04 §5. Armada's reader REQUIRES this on every non-owner control
8108        // edition (`citationOk`: "a non-owner action MUST cite its grant"), so
8109        // an uncited Vector admin's ban/role/channel edit was silently dropped
8110        // by every Armada client — only the owner's actions crossed. The
8111        // citation must name the actor's OWN grant coordinate, at the version
8112        // and edition hash the verifier can match against a grant it holds.
8113        let (bed, owner, admin) = TestBed::new();
8114        bed.swap_to(&owner);
8115        let community = create_community(&bed.relay, "Cited", bed.relays.clone(), None).await.unwrap();
8116        let rid = "c1".repeat(32);
8117        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::MANAGE_METADATA), 1).await;
8118        publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;
8119
8120        // The owner's own edition carries NO citation: their rank is the id.
8121        let owner_meta = control::CommunityMetadata { name: "By Owner".into(), relays: community.relays.clone(), ..Default::default() };
8122        edit_community_metadata(&bed.relay, &community, &owner_meta).await.unwrap();
8123        let owner_ed = fetch_control(&bed.relay, &community).await.into_iter()
8124            .filter(|e| e.author == owner.keys.public_key() && e.vsk == vsk::COMMUNITY_METADATA)
8125            .max_by_key(|e| e.version).expect("the owner's metadata edition");
8126        assert!(owner_ed.authority.is_none(), "the owner cites nothing — rank comes from the community id");
8127
8128        // The admin JOINS and folds — the citation names the grant head their own
8129        // client has actually synced, so the fold must have persisted it.
8130        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
8131        let bundle_json = serde_json::to_string(&bundle).unwrap();
8132        bed.swap_to(&admin);
8133        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8134        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
8135        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
8136        set_banlist(&bed.relay, &joined, &["ee".repeat(32)]).await.unwrap();
8137
8138        let ban_ed = fetch_control(&bed.relay, &joined).await.into_iter()
8139            .find(|e| e.author == admin.keys.public_key() && e.vsk == vsk::BANLIST)
8140            .expect("the admin's banlist edition");
8141        let cite = ban_ed.authority.as_ref().expect("a non-owner MUST cite its grant");
8142        assert_eq!(
8143            cite.entity_id,
8144            crate::community::v2::derive::grant_locator(community.id(), &admin.keys.public_key().to_bytes()),
8145            "the citation must name the ACTOR'S OWN grant coordinate",
8146        );
8147        assert!(cite.version >= 1, "pinned to a real grant version");
8148    }
8149
8150    #[tokio::test]
8151    async fn a_folded_metadata_edition_cannot_push_the_relay_set_past_the_cap() {
8152        // `cap_relays` is the truncate-on-read invariant everywhere else, and the
8153        // fold is a boundary like any other: MANAGE_METADATA makes an editor
8154        // authorized, not trusted. An oversize list costs every member a fan-out
8155        // per publish and the slowest of N per fetch — and Armada caps at 5, so
8156        // an uncapped fold also splits the two clients' operative sets.
8157        let (_tmp, _guard, _owner) = init_test_db();
8158        let relay = MemoryRelay::new();
8159        let community = create_community(&relay, "Fanout", vec!["wss://a".into()], None).await.unwrap();
8160
8161        let many: Vec<String> = (0..30).map(|i| format!("wss://r{i}")).collect();
8162        let meta = control::CommunityMetadata { name: "Fanout".into(), relays: many, ..Default::default() };
8163        edit_community_metadata(&relay, &community, &meta).await.unwrap();
8164
8165        let updated = follow_control(&relay, &community, &SessionGuard::capture()).await.unwrap()
8166            .expect("the metadata edition is folded");
8167        assert_eq!(
8168            updated.relays.len(),
8169            crate::community::MAX_COMMUNITY_RELAYS,
8170            "a folded relay list must be truncated, never adopted whole",
8171        );
8172
8173        // …and the fold must SETTLE: comparing an oversize edition against the
8174        // capped working set would never be equal, so every later fold would
8175        // report a change and re-save forever.
8176        let again = follow_control(&relay, &updated, &SessionGuard::capture()).await.unwrap();
8177        assert!(again.is_none(), "re-folding the same oversize edition must be a no-op");
8178    }
8179
8180    #[tokio::test]
8181    async fn adopting_a_rotation_writes_no_registry_where_i_never_minted() {
8182        // One Invite List spans every community, so "I hold links" must never be
8183        // read as "I hold links HERE". A member with links elsewhere adopting a
8184        // rotation would otherwise publish an empty Registry edition into this
8185        // community — a control-plane write and a version bump on a coordinate
8186        // they never owned, every rotation, forever.
8187        let (bed, owner, me) = TestBed::new();
8188        bed.swap_to(&owner);
8189        let host = create_community(&bed.relay, "Host", bed.relays.clone(), None).await.unwrap();
8190        let elsewhere = create_community(&bed.relay, "Elsewhere", bed.relays.clone(), None).await.unwrap();
8191        let rid = "b2".repeat(32);
8192        publish_role(&bed.relay, &host, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
8193        publish_grant(&bed.relay, &host, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
8194
8195        let bundle = bundle_of(&host, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
8196        let bundle_json = serde_json::to_string(&bundle).unwrap();
8197        bed.swap_to(&me);
8198        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8199        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
8200        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
8201
8202        // My only link lives in a DIFFERENT community.
8203        mint_public_link(&bed.relay, &elsewhere, "https://other", None, None).await.unwrap();
8204
8205        let before = bed.relay.stored_count();
8206        let new_root = [0xE1; 32];
8207        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
8208        let rotation_events = bed.relay.stored_count() - before;
8209
8210        let after_adopt = bed.relay.stored_count();
8211        follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap();
8212        assert_eq!(
8213            bed.relay.stored_count(),
8214            after_adopt,
8215            "adopting a rotation must publish NOTHING when I minted no links here",
8216        );
8217        assert!(rotation_events > 0, "the rotation itself did publish (guards the counter)");
8218    }
8219
8220    #[tokio::test]
8221    async fn an_expired_link_stops_keeping_the_community_public() {
8222        // CORD-05 §1/§5: expiry is the one way a link dies with no user action.
8223        // A joiner is refused by `InviteBundle::expired`, so leaving the link in
8224        // the Registry states a door that isn't there — the aggregate never
8225        // empties and the community reads Public forever, silently inverting
8226        // every gate that hangs off that reading.
8227        let (_tmp, _guard, _owner) = init_test_db();
8228        let relay = MemoryRelay::new();
8229        let community = create_community(&relay, "Lapsing", vec!["wss://r".into()], None).await.unwrap();
8230
8231        // A link that lapsed a minute ago.
8232        let past = now_ms() - 60_000;
8233        mint_public_link(&relay, &community, "https://x", Some(past), None).await.unwrap();
8234        assert!(
8235            !community_is_public(&relay, &community).await,
8236            "an already-expired link must never read as a live door",
8237        );
8238
8239        // …and one that hasn't, to prove the filter isn't just dropping everything.
8240        mint_public_link(&relay, &community, "https://y", Some(now_ms() + 600_000), None).await.unwrap();
8241        assert!(community_is_public(&relay, &community).await, "an unexpired link is still live");
8242    }
8243
8244    #[tokio::test]
8245    async fn minting_a_link_makes_the_community_public_and_revoke_makes_it_private() {
8246        // CORD-05 §5: the Registry is the Public/Private source of truth. Minting a
8247        // link publishes it (Public); retiring the last link empties it (Private).
8248        let (_tmp, _guard, _owner) = init_test_db();
8249        let relay = MemoryRelay::new();
8250        let community = create_community(&relay, "Invitable", vec!["wss://r".into()], None).await.unwrap();
8251        assert!(!community_is_public(&relay, &community).await, "a fresh community is Private");
8252
8253        let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
8254        assert!(community_is_public(&relay, &community).await, "a live link makes it Public");
8255        let list = fetch_invite_list(&relay, &community.relays).await.unwrap().expect("the 13303 list was published");
8256        assert_eq!(list.entries.len(), 1, "the minted link is recorded across devices");
8257
8258        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
8259        revoke_public_link(&relay, &community, &token_hex).await.unwrap();
8260        assert!(!community_is_public(&relay, &community).await, "retiring the last link makes it Private again");
8261        let after = fetch_invite_list(&relay, &community.relays).await.unwrap().unwrap();
8262        assert!(after.entries.is_empty() && after.tombstones.len() == 1, "the link is tombstoned in the invite list");
8263    }
8264
8265    #[tokio::test]
8266    async fn the_registry_is_cached_locally_so_public_private_is_a_sync_read() {
8267        // Every caller reads the `invite_registry` COLUMN, never the async fold. v2
8268        // published the Registry to the plane but never mirrored it locally, so every
8269        // v2 community read Private no matter how many live links it had.
8270        let (_tmp, _guard, _owner) = init_test_db();
8271        let relay = MemoryRelay::new();
8272        let community = create_community(&relay, "Cached", vec!["wss://r".into()], None).await.unwrap();
8273        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
8274        let cached = || crate::db::community::get_community_invite_registry(&cid_hex).unwrap();
8275        // The per-creator split is a SEPARATE table, and it drives the "first link flips
8276        // the community Public" confirm — an empty one re-asks on every later link.
8277        let per_creator = || crate::db::community::get_invite_link_sets(&cid_hex).unwrap();
8278        assert!(cached().is_empty(), "a fresh community caches an empty registry");
8279        assert!(per_creator().is_empty(), "…and no per-creator sets");
8280
8281        let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
8282        assert!(!cached().is_empty(), "minting caches the registry, so the UI reads Public without folding");
8283        let sets = per_creator();
8284        assert_eq!(sets.len(), 1, "the minting creator gets a set");
8285        assert_eq!(sets[0].locators.len(), 1, "carrying exactly their one live link");
8286
8287        // Both caches must SHRINK too — a union-only mirror would strand it Public.
8288        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
8289        revoke_public_link(&relay, &community, &token_hex).await.unwrap();
8290        assert!(cached().is_empty(), "retiring the last link empties the cache back to Private");
8291        assert!(per_creator().is_empty(), "…and clears the per-creator sets");
8292    }
8293
8294    #[tokio::test]
8295    async fn a_rogue_registry_fork_cannot_retire_the_owners_live_link() {
8296        // Registries are coordinate-bound to their creator, but `fold_head` picks an
8297        // equal-version winner AUTHOR-BLIND, by lowest inner id — and an author grinds
8298        // that freely by varying content. Folding before authorising would let any
8299        // member occupy the owner's registry head, fail the authority check, and drop
8300        // the whole registry: a live invite link silently retired, flipping the
8301        // community to Private and steering a moderator into the wrong ban remedy.
8302        let (_tmp, _guard, owner) = init_test_db();
8303        let relay = MemoryRelay::new();
8304        let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
8305        mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
8306        assert!(community_is_public(&relay, &community).await, "a live link makes it Public");
8307
8308        let cid = community.id();
8309        let control = control_group_key(&community.community_root, cid, community.root_epoch);
8310        let eid = crate::community::v2::derive::invite_links_locator(cid, &owner.public_key().to_bytes());
8311
8312        let query = Query {
8313            kinds: vec![stream::KIND_WRAP],
8314            authors: vec![control.pk_hex()],
8315            limit: Some(FOLLOW_PAGE),
8316            ..Default::default()
8317        };
8318        let wraps = relay.fetch(&query, &community.relays).await.unwrap();
8319        let target = wraps
8320            .iter()
8321            .filter_map(|w| control::open_control_edition(w, &control).ok().map(|(e, _)| e))
8322            .filter(|e| e.entity_id == eid)
8323            .max_by_key(|e| e.version)
8324            .expect("the owner published a registry");
8325
8326        // Grind a same-version fork under the owner's coordinate that OUTRANKS the
8327        // real head on the tiebreak (~2 tries against a uniform id).
8328        let rogue = Keys::generate();
8329        let mut planted = false;
8330        for n in 0..4_000u64 {
8331            let content = format!("[{{\"token\":\"{n:032x}\",\"url\":\"https://evil\",\"expires_at\":0}}]");
8332            let rumor = control::build_edition_rumor(
8333                rogue.public_key(),
8334                vsk::INVITE_LINKS,
8335                &eid,
8336                target.version,
8337                target.prev_hash.as_ref(),
8338                &content,
8339                9_000,
8340                None,
8341            );
8342            let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
8343            let (ed, _) = control::open_control_edition(&w, &control).unwrap();
8344            if ed.inner_id < target.inner_id {
8345                relay.publish(&w, &community.relays).await.unwrap();
8346                planted = true;
8347                break;
8348            }
8349        }
8350        assert!(planted, "the test needs a fork that wins the tiebreak");
8351
8352        assert!(
8353            community_is_public(&relay, &community).await,
8354            "an unauthorised fork must not retire the owner's live link"
8355        );
8356    }
8357
8358    #[tokio::test]
8359    async fn a_registry_from_a_non_create_invite_holder_does_not_make_it_public() {
8360        // The CREATE_INVITE gate: a rogue publishing a registry can't fake Public.
8361        let (_tmp, _guard, owner) = init_test_db();
8362        let relay = MemoryRelay::new();
8363        let community = create_community(&relay, "Gated", vec!["wss://r".into()], None).await.unwrap();
8364        let rogue = Keys::generate();
8365        // Rogue publishes a registry edition at THEIR coordinate with a fake signer.
8366        let eid = crate::community::v2::derive::invite_links_locator(community.id(), &rogue.public_key().to_bytes());
8367        let content = crate::community::v2::invite::build_registry_content(&[Keys::generate().public_key()]);
8368        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
8369        let rumor = control::build_edition_rumor(rogue.public_key(), vsk::INVITE_LINKS, &eid, 1, None, &content, 1_000, None);
8370        let (wrap, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(1_000)).unwrap();
8371        relay.publish(&wrap, &community.relays).await.unwrap();
8372        let _ = owner;
8373        assert!(!community_is_public(&relay, &community).await, "a non-CREATE_INVITE registry is ignored");
8374    }
8375
8376    #[tokio::test]
8377    async fn full_lifecycle_e2e() {
8378        // The whole stack end to end across two accounts: create -> Public link ->
8379        // owner grants an admin -> member joins + reads history -> admin edits metadata
8380        // (authorized fold) -> owner bans the member (CORD-04 §6: banlist + strip +
8381        // Refounding) -> the banned member is severed AND stays banned across the new
8382        // epoch -> pre-ban history still reads -> owner dissolves -> sealed.
8383        let (bed, owner, member) = TestBed::new();
8384
8385        bed.swap_to(&owner);
8386        let community = create_community(&bed.relay, "Lifecycle", bed.relays.clone(), None).await.unwrap();
8387        let general = community.channels[0].id;
8388        send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();
8389
8390        // Public link → the community reads Public.
8391        let _minted = mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
8392        assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");
8393
8394        // Owner defines + grants an Admin role (MANAGE_METADATA among the bits).
8395        let rid = "aa".repeat(32);
8396        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
8397        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
8398
8399        // Member joins from the bundle + reads the owner's message.
8400        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
8401        let bundle_json = serde_json::to_string(&bundle).unwrap();
8402        bed.swap_to(&member);
8403        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8404        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome"]);
8405        // The admin renames the community.
8406        publish_community_meta(&bed.relay, &joined, &member.keys, "Lifecycle Renamed", 2).await;
8407
8408        // Owner follows: the admin's rename folds (authorized).
8409        bed.swap_to(&owner);
8410        let session = SessionGuard::capture();
8411        let updated = follow_control(&bed.relay, &community, &session).await.unwrap().expect("the admin edit folds");
8412        assert_eq!(updated.name, "Lifecycle Renamed", "an authorized admin's metadata edit is honored");
8413
8414        // Ban the member (the three-removal composition, in order).
8415        set_banlist(&bed.relay, &updated, &[member.keys.public_key().to_hex()]).await.unwrap();
8416        grant_roles(&bed.relay, &updated, &member.keys.public_key(), vec![]).await.unwrap();
8417        let refounded = refound_community(&bed.relay, &updated, &[member.keys.public_key()]).await.unwrap();
8418        assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
8419        // The ban survives the Refounding (the banlist head compacted forward).
8420        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8421        assert!(post.banned.contains(&member.keys.public_key().to_hex()), "the ban survives the re-founding");
8422        // Pre-ban history still reads across the new epoch.
8423        assert!(
8424            texts_in(&bed.relay, &refounded, &general).await.contains(&"owner: welcome".to_string()),
8425            "pre-refounding history stays readable"
8426        );
8427
8428        // The banned member's rekey-follow concludes they're severed. Guard captured AFTER
8429        // the swap (the harness swap bumps the generation like production).
8430        bed.swap_to(&member);
8431        let session = SessionGuard::capture();
8432        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
8433        assert!(follow.self_removed, "the banned member is cryptographically cut");
8434
8435        // Owner dissolves → sealed.
8436        bed.swap_to(&owner);
8437        dissolve_community(&bed.relay, &refounded).await.unwrap();
8438        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
8439    }
8440
8441    /// The deep two-account e2e the way a real deployment runs: owner (A) + member (B)
8442    /// over one shared relay, create → channels (public + private) → converse both ways →
8443    /// persist (get_messages-level) → react/edit/delete → moderate (ban/unban) → dissolve.
8444    /// Every account, community, channel, and action is LOGGED (run with --nocapture) so it
8445    /// doubles as a reference transcript and a re-runnable regression.
8446    #[tokio::test]
8447    async fn a_forged_edition_cannot_suppress_a_role_across_a_refounding() {
8448        // A member forges a higher-version role edition at the admin coordinate before a
8449        // refounding. The compaction must carry the AUTHORIZED floor head, not the
8450        // author-blind version tip — else the forgery is re-anchored, honest folders drop
8451        // it, and the admin role vanishes at the new epoch (silent suppression).
8452        let (bed, owner, member) = TestBed::new();
8453        let attacker = Keys::generate();
8454        bed.swap_to(&owner);
8455        let community = create_community(&bed.relay, "NoSuppress", bed.relays.clone(), None).await.unwrap();
8456        let rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
8457        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
8458        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
8459        // Owner folds → the authorized role/grant heads are floored.
8460        let session = SessionGuard::capture();
8461        follow_control(&bed.relay, &community, &session).await.unwrap();
8462        assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member.keys.public_key().to_hex()), "member is admin pre-attack");
8463
8464        // The attacker (a non-owner) forges v2 of the admin role, chaining onto v1.
8465        publish_role(&bed.relay, &community, &attacker, &Role { role_id: rid.clone(), name: "pwn".into(), position: 1, permissions: Permissions(0), scope: RoleScope::Server, color: 0 }, 2).await;
8466
8467        // Owner refounds (keeping everyone).
8468        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
8469        assert_eq!(refounded.root_epoch, Epoch(1), "root rolled");
8470
8471        // Post-refound, the admin role SURVIVES (the authorized floor head was carried).
8472        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8473        assert!(post.roles.is_admin(&member.keys.public_key().to_hex()), "the admin role survives the refounding despite the forgery");
8474    }
8475
8476    #[tokio::test]
8477    async fn memberlist_survives_a_refounding_via_the_snapshot() {
8478        // A silent survivor (didn't re-post at the new epoch) must stay in the memberlist
8479        // after a refounding — the owner's 3312 snapshot re-seeds them (CORD-02 §5).
8480        let (bed, owner, member) = TestBed::new();
8481        bed.swap_to(&owner);
8482        let community = create_community(&bed.relay, "Snapshot", bed.relays.clone(), None).await.unwrap();
8483
8484        // Member joins (a Guestbook Join at epoch 0).
8485        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
8486        bed.swap_to(&member);
8487        accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
8488        bed.swap_to(&owner);
8489        assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "member present pre-refound");
8490
8491        // Owner refounds keeping everyone (removed = []); survivors are snapshotted to epoch 1.
8492        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
8493        assert_eq!(refounded.root_epoch, Epoch(1), "the root rolled");
8494
8495        // The member is STILL a member at epoch 1 purely via the snapshot (never re-posted).
8496        let members = memberlist(&bed.relay, &refounded).await.unwrap();
8497        assert!(members.contains(&member.keys.public_key()), "a silent survivor stays a member after the refounding");
8498        assert!(members.contains(&owner.keys.public_key()), "owner is always a member");
8499    }
8500
8501    #[tokio::test]
8502    async fn e2e_two_accounts_channels_converse_moderate() {
8503        use crate::community::v2::inbound::{apply_chat_to_state, persist_chat};
8504        use nostr_sdk::prelude::ToBech32;
8505        let (bed, a, b) = TestBed::new();
8506        let (a_npub, b_npub) = (a.keys.public_key().to_bech32().unwrap(), b.keys.public_key().to_bech32().unwrap());
8507        let (a_hex, b_hex) = (a.keys.public_key().to_hex(), b.keys.public_key().to_hex());
8508        println!("\n===== Concord v2 deep e2e =====");
8509        println!("[acct] A (owner)  = {a_npub}");
8510        println!("[acct] B (member) = {b_npub}");
8511
8512        // ── A creates the community + a PRIVATE channel + two extra PUBLIC channels ──
8513        bed.swap_to(&a);
8514        let mut community = create_community(&bed.relay, "Deep E2E", bed.relays.clone(), None).await.unwrap();
8515        let general = community.channels[0].id;
8516        println!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
8517
8518        // A PRIVATE channel via the REAL create path: an independent key minted at
8519        // channel-epoch 1, delivered over the rekey plane (A is the only member yet),
8520        // then announced (vsk 2) — later carried to B in the join bundle.
8521        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
8522        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8523        let priv_ch = community.channel(&priv_id).unwrap();
8524        assert!(priv_ch.private && priv_ch.key.is_some() && priv_ch.epoch == Epoch(1), "born-private: keyed at epoch 1");
8525        println!("[channel] +private #mods {} (native create: key over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&priv_id.0));
8526
8527        // Two more PUBLIC channels via the real create path.
8528        let announcements = create_public_channel(&bed.relay, &community, "announcements").await.unwrap();
8529        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8530        let random = create_public_channel(&bed.relay, &community, "random").await.unwrap();
8531        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8532        println!("[channel] +public #announcements {} · #random {}", crate::simd::hex::bytes_to_hex_32(&announcements.0), crate::simd::hex::bytes_to_hex_32(&random.0));
8533        assert_eq!(community.channels.len(), 4, "general + mods + announcements + random");
8534
8535        // A talks in a few channels.
8536        let m1 = send_message(&bed.relay, &community, &general, "A: welcome to the deep e2e").await.unwrap();
8537        send_message(&bed.relay, &community, &announcements, "A: read the rules").await.unwrap();
8538        send_message(&bed.relay, &community, &priv_id, "A: mods-only channel").await.unwrap();
8539        println!("[msg] A posted in #general / #announcements / #mods");
8540
8541        // ── A grants B admin, mints a public link, B joins from the bundle ──
8542        let admin_rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
8543        publish_role(&bed.relay, &community, &a.keys, &admin_role(&admin_rid, Permissions::ADMIN_ALL), 1).await;
8544        publish_grant(&bed.relay, &community, &a.keys, &b.keys.public_key(), vec![admin_rid], 1).await;
8545        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
8546        assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");
8547        println!("[invite] granted B @admin · minted link {}", link.url);
8548
8549        // A private channel is readable only by granted role-holders (CORD-03), so
8550        // B is added to its access list before the bundle is minted.
8551        grant_channel_access(&bed.relay, &community, &priv_id, &b.keys.public_key()).await.unwrap();
8552        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(b.keys.public_key()), Some(a.keys.public_key()), None, None)).unwrap();
8553        bed.swap_to(&b);
8554        let mut b_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8555        println!("[join] B joined; sees {} channels", b_view.channels.len());
8556        assert_eq!(b_view.channels.len(), 4, "B receives all four channels (incl. the private one's key) in the bundle");
8557        assert!(b_view.channels.iter().any(|c| c.id.0 == priv_id.0 && c.private && c.key.is_some()), "B holds the private channel key");
8558        assert!(texts_in(&bed.relay, &b_view, &general).await.contains(&"A: welcome to the deep e2e".to_string()), "B reads A's #general history");
8559        assert!(texts_in(&bed.relay, &b_view, &priv_id).await.contains(&"A: mods-only channel".to_string()), "B reads the PRIVATE channel with the bundle key");
8560        // B folds the control plane (persisting the roster) — the live worker does
8561        // this right after any join; B's admin standing gates B's channel ops below.
8562        let session_b = SessionGuard::capture();
8563        if let Some(fresh) = follow_control(&bed.relay, &b_view, &session_b).await.unwrap() {
8564            b_view = fresh;
8565        }
8566        println!("[follow] B folded control (roster persisted: B is @admin)");
8567
8568        // ── Conversation both ways + persistence (get_messages-level) ──
8569        send_message(&bed.relay, &b_view, &general, "B: thanks, glad to be here").await.unwrap();
8570        send_message(&bed.relay, &b_view, &priv_id, "B: mods checking in").await.unwrap();
8571        println!("[msg] B replied in #general + #mods");
8572        // Persist B's own #general view into the shared store (what sync/live ingest does)
8573        // and confirm it reads back via STATE — get_messages parity.
8574        let my_pk = b.keys.public_key();
8575        let gh = crate::simd::hex::bytes_to_hex_32(&general.0);
8576        for f in fetch_channel(&bed.relay, &b_view, &general, 100).await.unwrap() {
8577            let outcome = { let mut st = crate::state::STATE.lock().await; apply_chat_to_state(&mut st, &f.event, &gh, &my_pk) };
8578            if let Some(o) = outcome { persist_chat(&gh, &o).await; }
8579        }
8580        assert!(crate::db::events::event_exists(&m1).unwrap(), "A's message persisted into B's shared store (get_messages backfill)");
8581        println!("[persist] #general history persisted into the shared events store");
8582
8583        // B (admin) reacts to + the author edits/deletes — the chat-op surface.
8584        send_reaction(&bed.relay, &b_view, &general, &m1, &a_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
8585        bed.swap_to(&a);
8586        let m_edit = send_message(&bed.relay, &community, &general, "A: this will be edited").await.unwrap();
8587        send_edit(&bed.relay, &community, &general, &m_edit, "A: edited!").await.unwrap();
8588        let m_del = send_message(&bed.relay, &community, &general, "A: this will be deleted").await.unwrap();
8589        send_delete(&bed.relay, &community, &general, &m_del, super::super::kind::MESSAGE).await.unwrap();
8590        println!("[ops] reaction + edit + delete round-tripped");
8591
8592        // ── B creates a channel as admin, A folds it in ──
8593        bed.swap_to(&b);
8594        let bugs = create_public_channel(&bed.relay, &b_view, "bug-reports").await.unwrap();
8595        println!("[channel] B(admin) +public #bug-reports {}", crate::simd::hex::bytes_to_hex_32(&bugs.0));
8596        bed.swap_to(&a);
8597        let session = SessionGuard::capture();
8598        if let Some(updated) = follow_control(&bed.relay, &community, &session).await.unwrap() {
8599            community = updated;
8600        }
8601        assert!(community.channels.iter().any(|c| c.id.0 == bugs.0), "A folds in B's authorized new channel");
8602        println!("[follow] A folded in B's #bug-reports (now {} channels)", community.channels.len());
8603
8604        // ── A creates a SECOND private channel while B is already a member. B is
8605        // NOT on its access list, so B learns the channel exists (control-follow,
8606        // keyless) and gets no key: CORD-03's private channel is readable only by
8607        // granted role-holders, never by every member. B keys up if and when A
8608        // grants them the channel's access role and vends the key ──
8609        let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
8610        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8611        send_message(&bed.relay, &community, &vault, "A: vault is open").await.unwrap();
8612        println!("[channel] +private #vault {} (B is unentitled — no delivery)", crate::simd::hex::bytes_to_hex_32(&vault.0));
8613        bed.swap_to(&b);
8614        let session_b2 = SessionGuard::capture();
8615        if let Some(fresh) = follow_control(&bed.relay, &b_view, &session_b2).await.unwrap() {
8616            b_view = fresh;
8617        }
8618        let ch = b_view.channel(&vault).expect("B recorded the announced private channel");
8619        assert!(ch.private && ch.key.is_none() && ch.epoch == Epoch(0), "B's record is keyless at cursor 0");
8620        let rf = follow_rekeys(&bed.relay, &b_view, &session_b2).await.unwrap();
8621        if let Some(fresh) = rf.updated {
8622            b_view = fresh;
8623        }
8624        let ch = b_view.channel(&vault).expect("still recorded");
8625        assert!(ch.key.is_none(), "an unentitled member is never delivered the key");
8626        assert!(
8627            texts_in(&bed.relay, &b_view, &vault).await.is_empty(),
8628            "and reads nothing from it"
8629        );
8630        assert!(
8631            send_message(&bed.relay, &b_view, &vault, "B: in the vault").await.is_err(),
8632            "an unentitled member cannot post into the channel either"
8633        );
8634        bed.swap_to(&a);
8635        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8636        println!("[private] #vault stayed sealed to the unentitled B (no key, no read, no send)");
8637
8638        // ── Members ──
8639        let members = memberlist(&bed.relay, &community).await.unwrap();
8640        let member_hexes: std::collections::BTreeSet<String> = members.iter().map(|m| m.to_hex()).collect();
8641        assert!(member_hexes.contains(&a_hex) && member_hexes.contains(&b_hex), "A + B both in the memberlist");
8642        println!("[members] {} members: A + B present", members.len());
8643
8644        // ── Moderate: ban B (banlist + strip + refound), verify severance + survival ──
8645        set_banlist(&bed.relay, &community, &[b_hex.clone()]).await.unwrap();
8646        grant_roles(&bed.relay, &community, &b.keys.public_key(), vec![]).await.unwrap();
8647        let refounded = refound_community(&bed.relay, &community, &[b.keys.public_key()]).await.unwrap();
8648        assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
8649        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8650        assert!(post.banned.contains(&b_hex), "the ban survives the refounding");
8651        assert!(texts_in(&bed.relay, &refounded, &general).await.iter().any(|t| t == "A: welcome to the deep e2e"), "pre-ban history reads across the new epoch");
8652        assert!(
8653            texts_in(&bed.relay, &refounded, &priv_id).await.iter().any(|t| t == "A: mods-only channel"),
8654            "PRIVATE history reads across the channel's own rotation (per-channel multi-epoch archive)"
8655        );
8656        println!("[ban] B banned; root rolled to epoch 1; ban survives; pre-ban history intact (public + private)");
8657        // B concludes it's severed.
8658        bed.swap_to(&b);
8659        let session_b3 = SessionGuard::capture();
8660        assert!(follow_rekeys(&bed.relay, &b_view, &session_b3).await.unwrap().self_removed, "B is cryptographically cut by the ban-refound");
8661        println!("[ban] B's rekey-follow: self_removed = true (severed)");
8662
8663        // ── Unban: A lifts the ban ──
8664        bed.swap_to(&a);
8665        set_banlist(&bed.relay, &refounded, &[]).await.unwrap();
8666        let after_unban = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8667        assert!(!after_unban.banned.contains(&b_hex), "the unban clears B from the banlist");
8668        println!("[unban] B removed from the banlist (re-invitable)");
8669
8670        // ── Dissolve ──
8671        dissolve_community(&bed.relay, &refounded).await.unwrap();
8672        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
8673        println!("[dissolve] community sealed (read-only)\n===== e2e PASS =====\n");
8674    }
8675
8676    /// The same scenario on a REAL relay with TWO throwaway accounts, off by default. It
8677    /// LOGS both nsecs (+ every id) so you can inspect the run and RE-RUN against the same
8678    /// accounts by exporting `VECTOR_E2E_NSEC_A` / `_B`. Set `VECTOR_E2E_LOG=<path>` to also
8679    /// append the transcript to a file, `VECTOR_E2E_RELAY=<url>` to pick the relay.
8680    ///   cargo test -p vector-core -- --ignored --nocapture live_e2e_two_accounts
8681    #[tokio::test]
8682    #[ignore]
8683    async fn live_e2e_two_accounts() {
8684        use crate::community::transport::LiveTransport;
8685        use nostr_sdk::prelude::ToBech32;
8686
8687        let relay = std::env::var("VECTOR_E2E_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
8688        let relays = vec![relay.clone()];
8689        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
8690        crate::db::close_database();
8691        crate::db::clear_id_caches();
8692        let tmp = tempfile::tempdir().unwrap();
8693        crate::db::set_app_data_dir(tmp.path().to_path_buf());
8694
8695        // Throwaway (or bring-your-own via env for a re-run against the same accounts).
8696        let a = std::env::var("VECTOR_E2E_NSEC_A").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);
8697        let b = std::env::var("VECTOR_E2E_NSEC_B").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);
8698
8699        let log = |line: String| {
8700            println!("{line}");
8701            if let Ok(p) = std::env::var("VECTOR_E2E_LOG") {
8702                use std::io::Write;
8703                if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {
8704                    let _ = writeln!(f, "{line}");
8705                }
8706            }
8707        };
8708        log(format!("===== LIVE Concord v2 e2e on {relay} ====="));
8709        log(format!("VECTOR_E2E_NSEC_A={}  ({})", a.secret_key().to_bech32().unwrap(), a.public_key().to_bech32().unwrap()));
8710        log(format!("VECTOR_E2E_NSEC_B={}  ({})", b.secret_key().to_bech32().unwrap(), b.public_key().to_bech32().unwrap()));
8711
8712        for k in [&a, &b] {
8713            let npub = k.public_key().to_bech32().unwrap();
8714            std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
8715            crate::db::set_current_account(npub.clone()).unwrap();
8716            crate::db::init_database(&npub).unwrap();
8717        }
8718        // One relay connection: a v2 wrap is pre-signed (ephemeral p-key) and its seal is
8719        // signed by MY_SECRET_KEY, so publishing needs no per-account client signer.
8720        let client = crate::nostr_client_builder().build();
8721        client.add_managed_relay(relay.as_str()).await.ok();
8722        client.connect().await;
8723        crate::state::set_nostr_client(client);
8724        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
8725        let become_acct = |k: &Keys| {
8726            let npub = k.public_key().to_bech32().unwrap();
8727            crate::db::set_current_account(npub.clone()).unwrap();
8728            crate::db::init_database(&npub).unwrap();
8729            crate::db::clear_id_caches();
8730            crate::state::MY_SECRET_KEY.store_from_keys(k, &[]);
8731            crate::state::set_my_public_key(k.public_key());
8732        };
8733        let settle = || tokio::time::sleep(std::time::Duration::from_secs(2));
8734
8735        // A: create + a channel + grant B admin + mint link.
8736        become_acct(&a);
8737        let mut community = create_community(&transport, "Live E2E", relays.clone(), None).await.expect("create");
8738        let general = community.channels[0].id;
8739        log(format!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0)));
8740        send_message(&transport, &community, &general, "A: live hello").await.expect("send");
8741        let ann = create_public_channel(&transport, &community, "announcements").await.expect("channel");
8742        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8743        log(format!("[channel] +public #announcements {}", crate::simd::hex::bytes_to_hex_32(&ann.0)));
8744        grant_admin(&transport, &community, &b.public_key()).await.expect("grant admin");
8745        let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint");
8746        log(format!("[invite] B granted @admin · link {}", link.url));
8747        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(a.public_key()), None, None)).unwrap();
8748        settle().await;
8749
8750        // B: join + read A's history + reply.
8751        become_acct(&b);
8752        let b_view = accept_parked_invite(&transport, &bundle_json, None).await.expect("join");
8753        log(format!("[join] B joined; {} channels", b_view.channels.len()));
8754        settle().await;
8755        let page = fetch_channel(&transport, &b_view, &general, 50).await.expect("fetch");
8756        let seen: Vec<String> = page.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
8757        log(format!("[read] B sees #general: {seen:?}"));
8758        assert!(seen.iter().any(|t| t == "A: live hello"), "B reads A's message over the real relay");
8759        send_message(&transport, &b_view, &general, "B: live reply").await.expect("reply");
8760
8761        // B posts a NIP-22 kind-1111 THREADED REPLY to A's message (the shape Armada
8762        // sends) directly onto the chat plane — proving the cross-client thread
8763        // RECEIVE path works live, not just in the offline fixture.
8764        let hello = page.iter().find(|f| f.event.opened().rumor.content == "A: live hello").expect("A's message");
8765        let hello_id = hello.event.opened().rumor_id.to_hex();
8766        let bkeys = crate::state::MY_SECRET_KEY.to_keys().unwrap();
8767        let cgroup = channel_group_key(&b_view.community_root, &general, b_view.root_epoch);
8768        let reply_rumor = chat::build_comment_rumor(bkeys.public_key(), &general, b_view.root_epoch, "B: threaded reply to hello", &hello_id, super::super::kind::MESSAGE, &a.public_key().to_hex(), None, &[], now_ms());
8769        let (reply_wrap, _) = chat::seal_chat_rumor(&reply_rumor, &cgroup, &bkeys, Timestamp::from_secs(now_ms() / 1000), false).expect("seal 1111");
8770        transport.publish(&reply_wrap, &b_view.relays).await.expect("publish 1111");
8771        log("[thread] B published a kind-1111 threaded reply to A's message".to_string());
8772        settle().await;
8773
8774        // A reads the thread reply back, rendered inline with A's message as parent.
8775        become_acct(&a);
8776        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8777        let a_page = fetch_channel(&transport, &community, &general, 50).await.expect("A fetch");
8778        let thread = a_page.iter().find(|f| f.event.opened().rumor.content == "B: threaded reply to hello").expect("A sees the 1111");
8779        if let chat::ChatEvent::Message { reply_to, opened, .. } = &thread.event {
8780            assert_eq!(opened.rumor.kind.as_u16(), super::super::kind::COMMENT, "wire kind preserved as 1111");
8781            assert_eq!(reply_to.as_ref().map(|r| crate::simd::hex::bytes_to_hex_32(&r.id)), Some(hello_id.clone()), "the 1111 renders inline with A's message as parent");
8782        } else {
8783            panic!("the 1111 parsed as a Message");
8784        }
8785        log("[thread] A read B's threaded reply, parent resolved — cross-client 1111 interop OK".to_string());
8786        become_acct(&b);
8787        settle().await;
8788
8789        // A: create a PRIVATE channel while B is already a member — B is a recipient
8790        // of the creation delivery, so B keys up from the rekey plane over the real
8791        // relay (no bundle involved), then the two converse on it.
8792        become_acct(&a);
8793        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8794        let vault = create_private_channel(&transport, &community, "vault").await.expect("private channel");
8795        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8796        send_message(&transport, &community, &vault, "A: vault live").await.expect("vault send");
8797        log(format!("[channel] +private #vault {} (key delivered over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&vault.0)));
8798        settle().await;
8799
8800        become_acct(&b);
8801        let session_b = SessionGuard::capture();
8802        let mut b_view = crate::db::community::load_community_v2(b_view.id()).unwrap().unwrap();
8803        if let Some(fresh) = follow_control(&transport, &b_view, &session_b).await.expect("B control follow") {
8804            b_view = fresh;
8805        }
8806        if let Some(fresh) = follow_rekeys(&transport, &b_view, &session_b).await.expect("B rekey follow").updated {
8807            b_view = fresh;
8808        }
8809        let vch = b_view.channel(&vault).expect("B folded the vault");
8810        assert!(vch.key.is_some() && vch.epoch == Epoch(1), "B adopted the vault key from the live rekey plane");
8811        let vseen = texts_in(&transport, &b_view, &vault).await;
8812        log(format!("[read] B sees #vault: {vseen:?}"));
8813        assert!(vseen.iter().any(|t| t == "A: vault live"), "B reads the private channel with the ADOPTED key");
8814        send_message(&transport, &b_view, &vault, "B: in the live vault").await.expect("vault reply");
8815        settle().await;
8816
8817        become_acct(&a);
8818        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8819        assert!(
8820            texts_in(&transport, &community, &vault).await.iter().any(|t| t == "B: in the live vault"),
8821            "A reads B's private reply"
8822        );
8823        log("[private] two-way #vault conversation over the live relay".to_string());
8824
8825        // A: ban B (three-removal) + dissolve.
8826        set_banlist(&transport, &community, &[b.public_key().to_hex()]).await.expect("banlist");
8827        grant_roles(&transport, &community, &b.public_key(), vec![]).await.expect("strip");
8828        let refounded = refound_community(&transport, &community, &[b.public_key()]).await.expect("refound");
8829        log(format!("[ban] B banned; root → epoch {}", refounded.root_epoch.0));
8830        settle().await;
8831        dissolve_community(&transport, &refounded).await.expect("dissolve");
8832        log("[dissolve] community sealed".to_string());
8833        log("===== LIVE e2e PASS =====".to_string());
8834    }
8835
8836    #[tokio::test]
8837    async fn an_offline_member_learns_of_a_dissolution_on_catch_up() {
8838        // The tombstone rides its own public plane, watched live — an OFFLINE
8839        // member's catch-up must fetch it too, or they follow (and post into) a
8840        // grave forever.
8841        let (bed, owner, member) = TestBed::new();
8842        bed.swap_to(&owner);
8843        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
8844        let general = community.channels[0].id;
8845        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
8846
8847        bed.swap_to(&member);
8848        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
8849        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
8850
8851        // The owner dissolves while the member sleeps.
8852        bed.swap_to(&owner);
8853        dissolve_community(&bed.relay, &community).await.unwrap();
8854
8855        // The member's catch-up learns of the death, seals, and refuses to post.
8856        bed.swap_to(&member);
8857        let session = SessionGuard::capture();
8858        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
8859        assert!(follow.dissolved, "the catch-up surfaces the tombstone");
8860        assert!(!follow.self_removed && follow.updated.is_none());
8861        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
8862        assert!(crate::db::community::get_community_dissolved(&cid_hex).unwrap(), "sealed read-only locally");
8863        let err = send_message(&bed.relay, &joined, &general, "into the void").await.unwrap_err();
8864        assert!(err.contains("dissolved"), "sends refuse a grave: {err}");
8865        // Subsequent follows take the local fast path — still dissolved, no churn.
8866        let again = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
8867        assert!(again.dissolved && again.updated.is_none());
8868    }
8869
8870    #[tokio::test]
8871    async fn a_wide_community_survives_refoundings_and_an_offline_member_converges() {
8872        // Scale stress: MANY private channels, each rotated on every Refounding.
8873        // A member offline across two refoundings must converge on all of them
8874        // (the per-channel rotation fan in refound + the follow's channel×root×step
8875        // loops stay bounded) with every channel's history readable.
8876        const PRIV_CHANNELS: usize = 6;
8877        let (bed, owner, member) = TestBed::new();
8878        bed.swap_to(&owner);
8879        let mut community = create_community(&bed.relay, "Wide", bed.relays.clone(), None).await.unwrap();
8880        let mut priv_ids = Vec::new();
8881        for i in 0..PRIV_CHANNELS {
8882            let id = create_private_channel(&bed.relay, &community, &format!("priv{i}")).await.unwrap();
8883            community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8884            send_message(&bed.relay, &community, &id, &format!("priv{i} epoch0")).await.unwrap();
8885            priv_ids.push(id);
8886        }
8887        // Private channels are readable only by granted role-holders (CORD-03).
8888        for id in &priv_ids {
8889            grant_channel_access(&bed.relay, &community, id, &member.keys.public_key()).await.unwrap();
8890        }
8891        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();
8892
8893        // Member joins at epoch 0 with all channel keys, then goes offline.
8894        bed.swap_to(&member);
8895        let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8896        assert_eq!(member_view.channels.iter().filter(|c| c.private && c.key.is_some()).count(), PRIV_CHANNELS, "joined with all private keys");
8897
8898        // Two refoundings (each rotates the base + every private channel).
8899        bed.swap_to(&owner);
8900        for epoch in 1..=2u64 {
8901            community = refound_community(&bed.relay, &community, &[]).await.unwrap();
8902            assert_eq!(community.root_epoch, Epoch(epoch));
8903            for id in &priv_ids {
8904                send_message(&bed.relay, &community, id, &format!("{} epoch{epoch}", crate::simd::hex::bytes_to_hex_32(&id.0))).await.unwrap();
8905            }
8906        }
8907
8908        // Member returns: bounded follow to quiescence.
8909        bed.swap_to(&member);
8910        let session = SessionGuard::capture();
8911        let mut passes = 0;
8912        loop {
8913            passes += 1;
8914            assert!(passes <= 8, "a wide catch-up must converge, not churn (pass {passes})");
8915            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8916            let rk = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
8917            assert!(!rk.self_removed);
8918            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8919            let ctl = follow_control(&bed.relay, &cur, &session).await.unwrap();
8920            if rk.updated.is_none() && ctl.is_none() {
8921                break;
8922            }
8923        }
8924        let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8925        assert_eq!(caught_up.root_epoch, Epoch(2), "walked both refoundings");
8926        // Every private channel converged to the owner's current key + reads all epochs.
8927        for id in &priv_ids {
8928            let mine = caught_up.channel(id).expect("channel survived");
8929            let theirs = community.channel(id).unwrap();
8930            assert_eq!(mine.key, theirs.key, "channel {} converged on the owner key", crate::simd::hex::bytes_to_hex_32(&id.0));
8931            assert_eq!(mine.epoch, theirs.epoch, "…at the same epoch");
8932            let texts = texts_in(&bed.relay, &caught_up, id).await;
8933            let id_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
8934            assert!(texts.iter().any(|t| t.contains("epoch0")), "channel {id_hex} reads epoch-0 history");
8935            for epoch in 1..=2u64 {
8936                assert!(texts.iter().any(|t| t.contains(&format!("epoch{epoch}"))), "channel {id_hex} reads epoch-{epoch} history");
8937            }
8938        }
8939    }
8940
8941    #[tokio::test]
8942    async fn an_offline_member_catches_up_across_three_refoundings() {
8943        // The deep offline-online scenario: a member sleeps through THREE
8944        // Refoundings, per-refound private-channel rotations, a mid-life private
8945        // channel CREATED while they slept, a public channel, a rename, and a
8946        // ban — then returns and converges by follow alone (no rejoin).
8947        use nostr_sdk::prelude::ToBech32;
8948        let (bed, owner, member) = TestBed::new();
8949        bed.swap_to(&owner);
8950        let mut community = create_community(&bed.relay, "Sleeper", bed.relays.clone(), None).await.unwrap();
8951        let general = community.channels[0].id;
8952        let mods = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
8953        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8954        send_message(&bed.relay, &community, &general, "epoch0: hello").await.unwrap();
8955        send_message(&bed.relay, &community, &mods, "epoch0: mods secret").await.unwrap();
8956        // Private channels are readable only by granted role-holders (CORD-03).
8957        grant_channel_access(&bed.relay, &community, &mods, &member.keys.public_key()).await.unwrap();
8958        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();
8959
8960        // Member joins at epoch 0, then goes OFFLINE.
8961        bed.swap_to(&member);
8962        let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8963        assert_eq!(member_view.root_epoch, Epoch(0));
8964
8965        // While they sleep, the owner reshapes everything across three epochs.
8966        bed.swap_to(&owner);
8967        let stranger = Keys::generate();
8968        for epoch in 1..=3u64 {
8969            community = refound_community(&bed.relay, &community, &[]).await.unwrap();
8970            assert_eq!(community.root_epoch, Epoch(epoch));
8971            send_message(&bed.relay, &community, &general, &format!("epoch{epoch}: general news")).await.unwrap();
8972            send_message(&bed.relay, &community, &mods, &format!("epoch{epoch}: mods word")).await.unwrap();
8973        }
8974        let news = create_public_channel(&bed.relay, &community, "news").await.unwrap();
8975        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8976        let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
8977        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8978        // The sleeper is on this channel's access list, so the refoundings that
8979        // follow deliver its key to them (CORD-03).
8980        grant_channel_access(&bed.relay, &community, &vault, &member.keys.public_key()).await.unwrap();
8981        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8982        send_message(&bed.relay, &community, &vault, "epoch3: vault opened").await.unwrap();
8983        set_banlist(&bed.relay, &community, &[stranger.public_key().to_hex()]).await.unwrap();
8984        let meta = control::CommunityMetadata { name: "Sleeper Reborn".into(), relays: community.relays.clone(), ..Default::default() };
8985        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
8986
8987        // The member RETURNS: rekey+control follow to quiescence (the worker's
8988        // loop, driven explicitly). Bounded — convergence must be fast.
8989        bed.swap_to(&member);
8990        let session = SessionGuard::capture();
8991        let mut passes = 0;
8992        loop {
8993            passes += 1;
8994            assert!(passes <= 6, "catch-up must converge, not churn");
8995            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8996            let rekeyed = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
8997            assert!(!rekeyed.self_removed, "the member was never removed");
8998            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8999            let controlled = follow_control(&bed.relay, &cur, &session).await.unwrap();
9000            if rekeyed.updated.is_none() && controlled.is_none() {
9001                break;
9002            }
9003        }
9004        let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
9005
9006        // Base + name converged.
9007        assert_eq!(caught_up.root_epoch, Epoch(3), "walked all three refoundings");
9008        assert_eq!(caught_up.community_root, community.community_root, "landed on the owner's root");
9009        assert_eq!(caught_up.name, "Sleeper Reborn");
9010        // Channels: renamed set incl. the mid-sleep public + private ones.
9011        assert!(caught_up.channels.iter().any(|c| c.id.0 == news.0), "folded the new public channel");
9012        let m = caught_up.channel(&mods).expect("mods survived");
9013        let owner_mods = community.channel(&mods).unwrap();
9014        assert_eq!(m.epoch, owner_mods.epoch, "mods walked every per-refound rotation");
9015        assert_eq!(m.key, owner_mods.key, "…to the owner's exact key");
9016        let v = caught_up.channel(&vault).expect("vault folded in");
9017        // The sleeper is on vault's access list, but it was created AFTER the last
9018        // refounding — no rotation followed the grant, so no blob was ever
9019        // addressed to them. They hold the channel keyless until the grant's own
9020        // key vend lands (CORD-05 §6), which is what a rekey-only walk cannot do.
9021        assert!(v.private && v.key.is_none(), "vault folds in keyless: entitled, but never delivered");
9022        // Banlist survived the compactions.
9023        let cid_hex = crate::simd::hex::bytes_to_hex_32(&caught_up.id().0);
9024        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap();
9025        assert!(banned.contains(&stranger.public_key().to_hex()), "the ban folded through");
9026        // History reads across EVERY epoch (public via base-root archive, private
9027        // via the per-channel archive built during the walk).
9028        let gen_texts = texts_in(&bed.relay, &caught_up, &general).await;
9029        for epoch in 0..=3u64 {
9030            let needle = if epoch == 0 { "epoch0: hello".to_string() } else { format!("epoch{epoch}: general news") };
9031            assert!(gen_texts.contains(&needle), "general history spans epoch {epoch}: {gen_texts:?}");
9032        }
9033        let mods_texts = texts_in(&bed.relay, &caught_up, &mods).await;
9034        for epoch in 0..=3u64 {
9035            let needle = if epoch == 0 { "epoch0: mods secret".to_string() } else { format!("epoch{epoch}: mods word") };
9036            assert!(mods_texts.contains(&needle), "private history spans epoch {epoch}: {mods_texts:?}");
9037        }
9038        // Keyless (above) means unreadable — a rekey walk cannot substitute for the
9039        // key vend that a grant carries.
9040        assert!(texts_in(&bed.relay, &caught_up, &vault).await.is_empty());
9041        // And the member can still speak.
9042        send_message(&bed.relay, &caught_up, &general, "member: good morning").await.unwrap();
9043        bed.swap_to(&owner);
9044        assert!(
9045            texts_in(&bed.relay, &community, &general).await.contains(&"member: good morning".to_string()),
9046            "the caught-up member converses at the new epoch ({})",
9047            member.keys.public_key().to_bech32().unwrap()
9048        );
9049    }
9050
9051    /// Seal `n` messages onto a community's #general, one per second starting at
9052    /// `base_secs` (distinct wrap seconds so relay-side `until` paging engages).
9053    async fn flood_general(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, n: usize, base_secs: u64) {
9054        let general = community.channels[0].id;
9055        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
9056        for i in 0..n {
9057            let at = base_secs + i as u64;
9058            let rumor = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, &format!("msg {i}"), None, &[], vec![], at * 1000);
9059            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, author, Timestamp::from_secs(at), false).unwrap();
9060            relay.publish(&wrap, &community.relays).await.unwrap();
9061        }
9062    }
9063
9064    #[tokio::test]
9065    async fn the_history_walk_pages_past_a_multi_page_burst() {
9066        // A bot offline through 120 messages must catch ALL of them, not the
9067        // newest page — the v1 sync-gap class, closed by until-paging.
9068        let (_tmp, _guard, owner) = init_test_db();
9069        let relay = MemoryRelay::new();
9070        let community = create_community(&relay, "Burst", vec!["wss://r".into()], None).await.unwrap();
9071        let general = community.channels[0].id;
9072        flood_general(&relay, &community, &owner, 120, 10_000).await;
9073
9074        let all = fetch_channel_history(&relay, &community, &general, 50, 8, None, crate::community::transport::Evidence::Quorum, |_| true).await.unwrap();
9075        assert_eq!(all.len(), 120, "the walk pages the whole burst");
9076        // Oldest→newest, no duplicates.
9077        let contents: Vec<String> = all.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
9078        assert_eq!(contents.first().map(String::as_str), Some("msg 0"));
9079        assert_eq!(contents.last().map(String::as_str), Some("msg 119"));
9080        let unique: std::collections::HashSet<&String> = contents.iter().collect();
9081        assert_eq!(unique.len(), 120, "wrap-id + rumor-id dedup holds across page boundaries");
9082
9083        // The single-page fetch stays a single page.
9084        let one = fetch_channel(&relay, &community, &general, 50).await.unwrap();
9085        assert_eq!(one.len(), 50, "fetch_channel is one newest page");
9086        assert_eq!(one.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
9087    }
9088
9089    #[tokio::test]
9090    async fn the_history_walk_stops_when_the_caller_is_caught_up() {
9091        let (_tmp, _guard, owner) = init_test_db();
9092        let relay = MemoryRelay::new();
9093        let community = create_community(&relay, "Caught", vec!["wss://r".into()], None).await.unwrap();
9094        let general = community.channels[0].id;
9095        flood_general(&relay, &community, &owner, 120, 10_000).await;
9096
9097        // The caller says "I hold everything" after the first page — no deeper fetch.
9098        let mut pages = 0usize;
9099        let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, crate::community::transport::Evidence::Quorum, |_| {
9100            pages += 1;
9101            false
9102        })
9103        .await
9104        .unwrap();
9105        assert_eq!(pages, 1, "the early stop is consulted once");
9106        assert_eq!(got.len(), 50, "only the newest page is fetched");
9107        assert_eq!(got.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
9108    }
9109
9110    #[tokio::test]
9111    async fn a_same_second_history_wall_terminates_instead_of_looping() {
9112        // 60 messages in ONE second with a 25-wrap page: a second-granular
9113        // `until` can never page past the wall — the walk must step over it
9114        // (bounded loss, logged) rather than spin.
9115        let (_tmp, _guard, owner) = init_test_db();
9116        let relay = MemoryRelay::new();
9117        let community = create_community(&relay, "Wall", vec!["wss://r".into()], None).await.unwrap();
9118        let general = community.channels[0].id;
9119        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
9120        for i in 0..60usize {
9121            let rumor = chat::build_message_rumor(owner.public_key(), &general, community.root_epoch, &format!("burst {i}"), None, &[], vec![], 5_000_000 + i as u64);
9122            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &owner, Timestamp::from_secs(5_000), false).unwrap();
9123            relay.publish(&wrap, &community.relays).await.unwrap();
9124        }
9125        let got = fetch_channel_history(&relay, &community, &general, 25, 8, None, crate::community::transport::Evidence::Quorum, |_| true).await.unwrap();
9126        assert!(got.len() >= 25, "at least the relay page is read");
9127        assert!(got.len() <= 60, "sane bound");
9128        // Termination is the assertion: reaching here means the wall didn't loop.
9129    }
9130
9131    #[tokio::test]
9132    async fn a_grant_revoke_survives_a_withholding_relay() {
9133        // Floor persistence on the delegation plane: after the owner revokes an admin,
9134        // a relay serving only the OLD (still owner-signed) grant can't resurrect it.
9135        let (_tmp, _guard, owner) = init_test_db();
9136        let relay = MemoryRelay::new();
9137        let community = create_community(&relay, "Revoke", vec!["wss://good".into()], None).await.unwrap();
9138        let admin = Keys::generate();
9139        let rid = "d4".repeat(32);
9140        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
9141        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
9142        let session = SessionGuard::capture();
9143        follow_control(&relay, &community, &session).await.unwrap(); // seed floors incl. the grant at v1
9144        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke → grant floor v2
9145        follow_control(&relay, &community, &session).await.unwrap();
9146
9147        // A stale relay serves only the grant prefix (v1, the live grant).
9148        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
9149        let mut stale = community.clone();
9150        stale.relays = vec!["wss://stale".into()];
9151        let floors = load_floors(&community);
9152        let editions = fetch_control(&relay, &stale).await;
9153        let authority = fold_authority(&stale, &editions, &floors);
9154        assert!(
9155            !authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
9156            "the persisted grant floor refuses the rolled-back (re-granted) view"
9157        );
9158    }
9159
9160    /// Load the current-epoch floors for a community (test mirror of follow_control).
9161    fn load_floors(community: &CommunityV2) -> Floors {
9162        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9163        crate::db::community::get_all_edition_heads_full(&cid_hex)
9164            .unwrap_or_default()
9165            .into_iter()
9166            .filter(|(_, f)| f.0 == community.root_epoch.0)
9167            .map(|(e, f)| (e, (f.1, f.2, f.3)))
9168            .collect()
9169    }
9170
9171    /// Fetch + open every control edition at a community's control plane (test helper).
9172    async fn fetch_control(relay: &MemoryRelay, community: &CommunityV2) -> Vec<ParsedEdition> {
9173        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9174        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
9175        relay
9176            .fetch(&q, &community.relays)
9177            .await
9178            .unwrap_or_default()
9179            .iter()
9180            .filter_map(|w| control::open_control_edition(w, &group).ok().map(|(ed, _)| ed))
9181            .collect()
9182    }
9183
9184    #[tokio::test]
9185    async fn follow_control_is_a_noop_on_a_freshly_created_community() {
9186        let (_tmp, _guard, _owner) = init_test_db();
9187        let relay = MemoryRelay::new();
9188        let community = create_community(&relay, "Fresh", vec!["wss://r".into()], None).await.unwrap();
9189        let session = SessionGuard::capture();
9190        // Only the genesis editions exist; folding them reproduces the held view.
9191        assert!(follow_control(&relay, &community, &session).await.unwrap().is_none());
9192    }
9193
9194    #[tokio::test]
9195    async fn follow_control_adds_a_new_public_channel_and_re_subscribes_it() {
9196        let (_tmp, _guard, owner) = init_test_db();
9197        let relay = MemoryRelay::new();
9198        let community = create_community(&relay, "Grow", vec!["wss://r".into()], None).await.unwrap();
9199        let new_id = ChannelId([0x5a; 32]);
9200        publish_channel_edition(&relay, &community, &owner, &new_id, "announcements", false, 1, false).await;
9201
9202        let session = SessionGuard::capture();
9203        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("a new channel changed the view");
9204        assert_eq!(updated.channels.len(), 2);
9205        let added = updated.channel(&new_id).expect("the new channel folded in");
9206        assert_eq!(added.name, "announcements");
9207        assert!(!added.private);
9208        assert_eq!(added.key, None, "a public channel derives from the root (no stored key)");
9209
9210        // The new channel is now in the realtime author-set (it would be subscribed).
9211        let authors = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
9212        let addr = channel_group_key(&updated.community_root, &new_id, updated.root_epoch).pk();
9213        assert!(authors.contains(&addr), "the added channel joins the live subscription");
9214
9215        // Persisted: a reload sees it too.
9216        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9217        assert!(reloaded.channel(&new_id).is_some());
9218    }
9219
9220    #[tokio::test]
9221    async fn follow_control_renames_the_community_and_an_existing_channel() {
9222        let (_tmp, _guard, owner) = init_test_db();
9223        let relay = MemoryRelay::new();
9224        let community = create_community(&relay, "Old Name", vec!["wss://r".into()], None).await.unwrap();
9225        let general = community.channels[0].id;
9226        // A v2 metadata edition renames the community; a v2 channel edition renames #general.
9227        publish_community_meta(&relay, &community, &owner, "New Name", 2).await;
9228        publish_channel_edition(&relay, &community, &owner, &general, "lobby", false, 2, false).await;
9229
9230        let session = SessionGuard::capture();
9231        let updated = follow_control(&relay, &community, &session).await.unwrap().unwrap();
9232        assert_eq!(updated.name, "New Name");
9233        assert_eq!(updated.channel(&general).unwrap().name, "lobby");
9234        assert_eq!(updated.channels.len(), 1, "a rename doesn't add a channel");
9235    }
9236
9237    #[tokio::test]
9238    async fn follow_control_deletes_a_channel() {
9239        let (_tmp, _guard, owner) = init_test_db();
9240        let relay = MemoryRelay::new();
9241        let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
9242        let extra = ChannelId([0x77; 32]);
9243        let session = SessionGuard::capture();
9244
9245        // The channel is first added and folded into the held view.
9246        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
9247        let with_extra = follow_control(&relay, &community, &session).await.unwrap().expect("added");
9248        assert!(with_extra.channel(&extra).is_some());
9249
9250        // Then it's tombstoned — the delete (higher version) folds the held one back out.
9251        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
9252        let updated = follow_control(&relay, &with_extra, &session).await.unwrap().expect("removed");
9253        assert!(updated.channel(&extra).is_none(), "a deleted channel folds out");
9254        assert_eq!(updated.channels.len(), 1, "only #general remains");
9255    }
9256
9257    /// Re-inject only the OLD prefix (every edition at/below `max_version`) of a
9258    /// community's control plane onto a second relay URL — the withholding-relay
9259    /// simulation: everything it serves is genuinely owner-signed, just stale.
9260    async fn inject_stale_prefix(relay: &MemoryRelay, community: &CommunityV2, max_version: u64, stale_relay: &str) {
9261        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9262        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
9263        let wraps = relay.fetch(&query, &community.relays).await.unwrap();
9264        for w in &wraps {
9265            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
9266                if ed.version <= max_version {
9267                    relay.inject(w, &[stale_relay.to_string()]);
9268                }
9269            }
9270        }
9271    }
9272
9273    #[tokio::test]
9274    async fn a_withholding_relay_cannot_roll_back_a_rename() {
9275        // W2 persisted floor: after adopting the owner's v2 rename, a relay serving
9276        // only the (owner-signed) v1 genesis must not revert the held name.
9277        let (_tmp, _guard, owner) = init_test_db();
9278        let relay = MemoryRelay::new();
9279        let community = create_community(&relay, "Original", vec!["wss://good".into()], None).await.unwrap();
9280        publish_community_meta(&relay, &community, &owner, "Renamed", 2).await;
9281
9282        let session = SessionGuard::capture();
9283        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("rename adopted");
9284        assert_eq!(updated.name, "Renamed");
9285
9286        // The stale relay holds only the genesis prefix; point the follow at it.
9287        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
9288        let mut stale_view = updated.clone();
9289        stale_view.relays = vec!["wss://stale".into()];
9290        assert!(
9291            follow_control(&relay, &stale_view, &session).await.unwrap().is_none(),
9292            "a stale-only relay must not change the held view"
9293        );
9294        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9295        assert_eq!(held.name, "Renamed", "the persisted floor refuses the rollback");
9296    }
9297
9298    #[tokio::test]
9299    async fn a_withholding_relay_cannot_resurrect_a_deleted_channel() {
9300        let (_tmp, _guard, owner) = init_test_db();
9301        let relay = MemoryRelay::new();
9302        let community = create_community(&relay, "Prune2", vec!["wss://good".into()], None).await.unwrap();
9303        let extra = ChannelId([0x44; 32]);
9304        let session = SessionGuard::capture();
9305
9306        // A same-content metadata edit: no visible change (None), but the floor must
9307        // still advance to v2 (so the genesis metadata can't re-present below).
9308        publish_community_meta(&relay, &community, &owner, "Prune2", 2).await;
9309        assert!(follow_control(&relay, &community, &session).await.unwrap().is_none());
9310
9311        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
9312        let with_extra = follow_control(&relay, &community, &session).await.unwrap().expect("added");
9313        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
9314        let pruned = follow_control(&relay, &with_extra, &session).await.unwrap().expect("removed");
9315        assert!(pruned.channel(&extra).is_none());
9316
9317        // The stale relay serves the add (v1) but withholds the delete (v2).
9318        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
9319        let mut stale_view = pruned.clone();
9320        stale_view.relays = vec!["wss://stale".into()];
9321        assert!(
9322            follow_control(&relay, &stale_view, &session).await.unwrap().is_none(),
9323            "the withheld delete must not resurrect the channel"
9324        );
9325        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9326        assert!(held.channel(&extra).is_none(), "the deleted channel stays deleted");
9327    }
9328
9329    #[tokio::test]
9330    async fn a_new_epoch_bootstraps_past_an_old_epoch_floor() {
9331        // The Armada-convergence carve-out: a Refounding compacts the chain and
9332        // re-wraps a detached head at the NEW epoch's control plane. The old epoch's
9333        // floor must not block it — epoch-filtering makes the entity bootstrap.
9334        let (_tmp, _guard, owner) = init_test_db();
9335        let relay = MemoryRelay::new();
9336        let community = create_community(&relay, "Before", vec!["wss://good".into()], None).await.unwrap();
9337        let session = SessionGuard::capture();
9338        publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
9339        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("edit adopted");
9340        assert_eq!(updated.name, "Edited");
9341
9342        // Refounding lands (epoch bump saved by the rekey path); the compacted head
9343        // arrives DETACHED (high version, no prev) on the new epoch's plane.
9344        let mut refounded = updated.clone();
9345        refounded.root_epoch = crate::community::Epoch(1);
9346        crate::db::community::save_community_v2(&refounded).unwrap();
9347        publish_community_meta(&relay, &refounded, &owner, "Compacted", 5).await;
9348
9349        let adopted = follow_control(&relay, &refounded, &session).await.unwrap().expect("compacted head adopted");
9350        assert_eq!(adopted.name, "Compacted", "a fresh epoch bootstraps despite the dangling prev");
9351        // The persisted floor is stamped with the epoch the FOLD ran under.
9352        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9353        let heads = crate::db::community::get_all_edition_heads_epoched(&cid_hex).unwrap();
9354        assert!(
9355            heads.get(&cid_hex).is_some_and(|(e, v, _)| *e == 1 && *v == 5),
9356            "the adopted head carries the fold's epoch + version"
9357        );
9358    }
9359
9360    #[tokio::test]
9361    async fn a_same_version_owner_fork_at_the_floor_converges_to_the_deterministic_winner() {
9362        // Two owner-signed editions at the SAME version (publish retry / two owner
9363        // devices): every client must land on the lower-inner-id winner. A hash-strict
9364        // floor would wedge here forever while Armada converges — the floor must
9365        // CONVERGE instead (the v1 decide() rule).
9366        let (_tmp, _guard, owner) = init_test_db();
9367        let relay = MemoryRelay::new();
9368        let community = create_community(&relay, "Fork", vec!["wss://r".into()], None).await.unwrap();
9369        let session = SessionGuard::capture();
9370        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9371        let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9372
9373        publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
9374        let ours = follow_control(&relay, &community, &session).await.unwrap().expect("ours adopted");
9375        assert_eq!(ours.name, "Ours");
9376
9377        // Our committed v2 edition's tiebreak id.
9378        let our_inner = {
9379            let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
9380            let wraps = relay.fetch(&q, &community.relays).await.unwrap();
9381            wraps
9382                .iter()
9383                .find_map(|w| {
9384                    control::open_control_edition(w, &group)
9385                        .ok()
9386                        .filter(|(ed, _)| ed.version == 2 && ed.vsk == vsk::COMMUNITY_METADATA)
9387                        .map(|(ed, _)| ed.inner_id)
9388                })
9389                .unwrap()
9390        };
9391
9392        // Craft the concurrent fork so it WINS the deterministic tiebreak (vary the
9393        // authored timestamp until its inner id is lower).
9394        let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
9395        let content = serde_json::to_string(&meta).unwrap();
9396        let mut ts = 2_000u64;
9397        let fork_wrap = loop {
9398            let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
9399            let inner = rumor.id.unwrap().to_bytes();
9400            if inner < our_inner {
9401                break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
9402            }
9403            ts += 1;
9404        };
9405        relay.publish(&fork_wrap, &community.relays).await.unwrap();
9406
9407        let converged = follow_control(&relay, &ours, &session).await.unwrap().expect("fork winner adopted");
9408        assert_eq!(converged.name, "Theirs", "the floor converges to the lower-inner-id winner");
9409        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9410        let held = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap();
9411        assert!(held.is_some_and(|h| h < our_inner), "the persisted floor's tiebreak key moved to the winner");
9412    }
9413
9414    #[tokio::test]
9415    async fn an_anchored_prefix_applies_while_a_gap_above_awaits_the_missing_link() {
9416        // v2 chains to the floor; v4 arrives but its v3 link is withheld. The
9417        // chain-verified prefix (v2) applies NOW — refuse-downgrade holds for it —
9418        // while the detached v4 waits. When v3 lands, the chain heals to v4.
9419        let (_tmp, _guard, owner) = init_test_db();
9420        let relay = MemoryRelay::new();
9421        let community = create_community(&relay, "Prefix", vec!["wss://r".into()], None).await.unwrap();
9422        let session = SessionGuard::capture();
9423        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9424
9425        publish_community_meta(&relay, &community, &owner, "Two", 2).await;
9426        let v2_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9427
9428        // Craft v3 (held back) and v4 (published, chained to the withheld v3).
9429        let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
9430        let r3 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 3, Some(&v2_hash), &c3, 3_000, None);
9431        let (w3, _) = control::seal_control_edition(&r3, &group, &owner, Timestamp::from_secs(3_000)).unwrap();
9432        let (ed3, _) = control::open_control_edition(&w3, &group).unwrap();
9433        let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
9434        let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&ed3.self_hash), &c4, 4_000, None);
9435        let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(4_000)).unwrap();
9436        relay.publish(&w4, &community.relays).await.unwrap();
9437
9438        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("the verified prefix applies");
9439        assert_eq!(updated.name, "Two", "the anchored prefix lands; the detached v4 does not");
9440
9441        relay.publish(&w3, &community.relays).await.unwrap();
9442        let healed = follow_control(&relay, &updated, &session).await.unwrap().expect("the chain heals");
9443        assert_eq!(healed.name, "Four", "once the link arrives, the head advances past the prefix");
9444    }
9445
9446    #[tokio::test]
9447    async fn paging_rescues_a_floor_link_evicted_from_the_newest_window() {
9448        // The held floor is v2; the owner publishes v3, then a flood of foreign junk
9449        // wraps fills the newest window, then v4. Page 1 sees only v4 (detached →
9450        // gapped); paging older must recover v3 (and the floor link) and heal to v4.
9451        let (_tmp, _guard, owner) = init_test_db();
9452        let relay = MemoryRelay::new();
9453        let community = create_community(&relay, "Paged", vec!["wss://r".into()], None).await.unwrap();
9454        let session = SessionGuard::capture();
9455        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9456
9457        publish_community_meta(&relay, &community, &owner, "Two", 2).await;
9458        let base = follow_control(&relay, &community, &session).await.unwrap().expect("floor at v2");
9459        publish_community_meta(&relay, &base, &owner, "Three", 3).await; // ts 1_000 (old)
9460        let v3_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9461
9462        // Rogue flood occupying the newest window (sealed to the control plane, but
9463        // non-owner — the authority gate drops them; they only crowd the page).
9464        let rogue = Keys::generate();
9465        for i in 0..(FOLLOW_PAGE as u64 - 1) {
9466            let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xCC; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 4_000 + i, None);
9467            let (w, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(4_000 + i)).unwrap();
9468            relay.publish(&w, &community.relays).await.unwrap();
9469        }
9470        // v4 chained to the real v3 (crafted directly: the flood also blinds the
9471        // helper's own newest-window head lookup), timestamped newest of all.
9472        let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
9473        let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&v3_hash), &c4, 10_000, None);
9474        let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(10_000)).unwrap();
9475        relay.publish(&w4, &community.relays).await.unwrap();
9476
9477        let healed = follow_control(&relay, &base, &session).await.unwrap().expect("paging recovered the chain");
9478        assert_eq!(healed.name, "Four", "the gap paged past the flood to the floor link");
9479    }
9480
9481    #[tokio::test]
9482    async fn a_follow_after_delete_does_not_resurrect_the_community() {
9483        // A leave/delete racing an in-flight follow: the follow must not re-insert
9484        // the community row or floor rows past delete_community's wipe.
9485        let (_tmp, _guard, owner) = init_test_db();
9486        let relay = MemoryRelay::new();
9487        let community = create_community(&relay, "Gone", vec!["wss://r".into()], None).await.unwrap();
9488        publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
9489        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9490        crate::db::community::delete_community(&cid_hex).unwrap();
9491
9492        let session = SessionGuard::capture();
9493        assert!(
9494            follow_control(&relay, &community, &session).await.unwrap().is_none(),
9495            "a follow racing a delete is a no-op"
9496        );
9497        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
9498        assert!(crate::db::community::edition_head_entity_ids(&cid_hex).unwrap().is_empty(), "no orphan floor rows");
9499    }
9500
9501    #[tokio::test]
9502    async fn a_rekey_follow_after_delete_does_not_resurrect_the_community() {
9503        // The rekey sibling of the follow_control guard: an owner rotation adopted
9504        // mid-race must not upsert the community row back after a leave/delete.
9505        let (_tmp, _guard, owner) = init_test_db();
9506        let relay = MemoryRelay::new();
9507        let community = create_community(&relay, "GoneKeys", vec!["wss://r".into()], None).await.unwrap();
9508        let new_root = [0xB2; 32];
9509        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
9510        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9511        crate::db::community::delete_community(&cid_hex).unwrap();
9512
9513        let session = SessionGuard::capture();
9514        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
9515        assert!(follow.updated.is_none() && !follow.self_removed, "a rekey follow racing a delete adopts nothing");
9516        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
9517    }
9518
9519    #[tokio::test]
9520    async fn a_joiner_bootstraps_the_highest_head_across_a_lost_middle_edition() {
9521        // {v1, v3} on the relays with v2 lost at publish time (a rate-limiting relay
9522        // that still ACKed): the genesis anchors, so an anchored-prefix-first fold
9523        // would take v1 and SEED the joiner's floor there — pinning them below the
9524        // head Armada shows, forever. A joiner (floor 0) must bootstrap v3.
9525        let (bed, owner, member) = TestBed::new();
9526        bed.swap_to(&owner);
9527        let community = create_community(&bed.relay, "Skip", bed.relays.clone(), None).await.unwrap();
9528        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9529        let genesis_hash = head_hash_on_relay(&bed.relay, &community, &community.id().0).await.unwrap();
9530
9531        // v2 is crafted but NEVER published; v3 chains to it and is published.
9532        let c2 = serde_json::to_string(&control::CommunityMetadata { name: "Two".into(), ..Default::default() }).unwrap();
9533        let r2 = control::build_edition_rumor(owner.keys.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &c2, 2_000, None);
9534        let (w2, _) = control::seal_control_edition(&r2, &group, &owner.keys, Timestamp::from_secs(2_000)).unwrap();
9535        let (ed2, _) = control::open_control_edition(&w2, &group).unwrap();
9536        let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
9537        let r3 = control::build_edition_rumor(owner.keys.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 3, Some(&ed2.self_hash), &c3, 3_000, None);
9538        let (w3, _) = control::seal_control_edition(&r3, &group, &owner.keys, Timestamp::from_secs(3_000)).unwrap();
9539        bed.relay.publish(&w3, &community.relays).await.unwrap();
9540
9541        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
9542        let bundle_json = serde_json::to_string(&bundle).unwrap();
9543        bed.swap_to(&member);
9544        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
9545        assert_eq!(joined.name, "Three", "the joiner bootstraps the highest signed head, not the anchored stale prefix");
9546        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
9547        let head = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap();
9548        assert!(head.is_some_and(|(v, _)| v == 3), "the seeded floor is the bootstrap head");
9549    }
9550
9551    #[tokio::test]
9552    async fn a_losing_same_version_fork_cannot_replace_the_held_floor() {
9553        // The refusal half of fork convergence: a relay withholding OUR committed
9554        // floor edition while serving only a same-version fork with a HIGHER inner
9555        // id must be treated as withholding — held state and floor unchanged.
9556        let (_tmp, _guard, owner) = init_test_db();
9557        let relay = MemoryRelay::new();
9558        let community = create_community(&relay, "Fork2", vec!["wss://good".into()], None).await.unwrap();
9559        let session = SessionGuard::capture();
9560        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9561        let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9562
9563        publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
9564        let ours = follow_control(&relay, &community, &session).await.unwrap().expect("ours adopted");
9565        assert_eq!(ours.name, "Ours");
9566        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9567        let held_before = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
9568        let our_inner = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap().unwrap();
9569
9570        // Grind the fork to LOSE the tiebreak (higher inner id), then serve it —
9571        // with the genesis but WITHOUT our v2 — from a withholding relay.
9572        let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
9573        let content = serde_json::to_string(&meta).unwrap();
9574        let mut ts = 5_000u64;
9575        let fork_wrap = loop {
9576            let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
9577            if rumor.id.unwrap().to_bytes() > our_inner {
9578                break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
9579            }
9580            ts += 1;
9581        };
9582        inject_stale_prefix(&relay, &community, 1, "wss://stale").await; // genesis only
9583        relay.inject(&fork_wrap, &["wss://stale".to_string()]);
9584        let mut stale_view = ours.clone();
9585        stale_view.relays = vec!["wss://stale".into()];
9586
9587        assert!(
9588            follow_control(&relay, &stale_view, &session).await.unwrap().is_none(),
9589            "a losing fork served without our floor edition changes nothing"
9590        );
9591        let held_after = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
9592        assert_eq!(held_after, held_before, "the floor row is untouched");
9593        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9594        assert_eq!(held.name, "Ours", "the held state is untouched");
9595    }
9596
9597    #[tokio::test]
9598    async fn follow_control_ignores_a_non_owner_edition() {
9599        // A member holds the community_root, so they CAN seal a control edition —
9600        // but they aren't the owner, so the authority gate drops it (first cut:
9601        // owner-only). The rogue channel must never appear.
9602        let (_tmp, _guard, _owner) = init_test_db();
9603        let relay = MemoryRelay::new();
9604        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
9605        let rogue = Keys::generate();
9606        let rogue_id = ChannelId([0x99; 32]);
9607        publish_channel_edition(&relay, &community, &rogue, &rogue_id, "backdoor", false, 1, false).await;
9608
9609        let session = SessionGuard::capture();
9610        assert!(
9611            follow_control(&relay, &community, &session).await.unwrap().is_none(),
9612            "a non-owner control edition is not folded"
9613        );
9614    }
9615
9616    #[tokio::test]
9617    async fn follow_control_records_a_new_private_channel_keyless_and_unreadable() {
9618        // A Private channel's key rides the rekey plane, not the control edition —
9619        // control-follow records it KEYLESS (epoch 0, the rekey-scan cursor), and
9620        // every read/send path refuses it until the key lands (never the root plane).
9621        let (_tmp, _guard, owner) = init_test_db();
9622        let relay = MemoryRelay::new();
9623        let community = create_community(&relay, "Priv", vec!["wss://r".into()], None).await.unwrap();
9624        let priv_id = ChannelId([0x33; 32]);
9625        publish_channel_edition(&relay, &community, &owner, &priv_id, "mods", true, 1, false).await;
9626
9627        let session = SessionGuard::capture();
9628        let updated = follow_control(&relay, &community, &session)
9629            .await
9630            .unwrap()
9631            .expect("the keyless record is a change");
9632        let ch = updated.channel(&priv_id).expect("the private channel is recorded");
9633        assert!(ch.private && ch.key.is_none(), "recorded keyless");
9634        assert_eq!(ch.epoch, Epoch(0), "epoch 0 = the root generation (scan cursor)");
9635        assert!(updated.channel_read_coords(ch).is_empty(), "unreadable until keyed");
9636        assert!(
9637            fetch_channel(&relay, &updated, &priv_id, 50).await.unwrap().is_empty(),
9638            "a keyless fetch returns empty (and never queries the root plane)"
9639        );
9640        assert!(
9641            send_message(&relay, &updated, &priv_id, "nope").await.is_err(),
9642            "a keyless send refuses"
9643        );
9644        // The keyless record round-trips (the stored placeholder never surfaces
9645        // as a real key).
9646        let reloaded = crate::db::community::load_community_v2(updated.id()).unwrap().unwrap();
9647        let rch = reloaded.channel(&priv_id).unwrap();
9648        assert!(rch.private && rch.key.is_none() && rch.epoch == Epoch(0), "keyless survives reload");
9649        // And a bundle minted while keyless never carries the placeholder — a
9650        // MEMBER audience, so it's the keyless filter proving it (the link
9651        // filter would drop the channel for the weaker reason).
9652        let bundle = bundle_of(&reloaded, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
9653        assert!(
9654            !bundle.channels.iter().any(|c| c.id == crate::simd::hex::bytes_to_hex_32(&priv_id.0)),
9655            "an ungrantable keyless channel stays out of invite bundles"
9656        );
9657    }
9658
9659    #[tokio::test]
9660    async fn a_link_bundle_never_carries_a_private_channel_key() {
9661        // A link's audience holds no Role by construction (CORD-05), so a HELD
9662        // private key must never ride a link bundle — anyone with the URL would
9663        // get the channel. A member bundle carries it; a link bundle only the
9664        // public channels.
9665        let (_tmp, _guard, _owner) = init_test_db();
9666        let relay = MemoryRelay::new();
9667        let community = create_community(&relay, "Leak", vec!["wss://r".into()], None).await.unwrap();
9668        create_private_channel(&relay, &community, "mods").await.unwrap();
9669        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9670        let priv_hex = held
9671            .channels
9672            .iter()
9673            .find(|c| c.private)
9674            .map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0))
9675            .expect("the private channel is held WITH its key");
9676
9677        let link = bundle_of(&held, BundleAudience::Link, None, None, None);
9678        assert!(
9679            !link.channels.iter().any(|c| c.id == priv_hex),
9680            "a held private key must never ride a link bundle"
9681        );
9682        assert!(
9683            link.channels.iter().any(|c| c.id != priv_hex),
9684            "the public channels still ride it"
9685        );
9686
9687        // A member bundle grants it only to the ENTITLED. An unrelated npub holds
9688        // no scoped role, so it gets nothing; the creator (granted the companion
9689        // access role at create) gets the key.
9690        let stranger = bundle_of(&held, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
9691        assert!(
9692            !stranger.channels.iter().any(|c| c.id == priv_hex),
9693            "an unentitled member gets no private key"
9694        );
9695        let mine = bundle_of(&held, BundleAudience::Member(me_pk().unwrap()), None, None, None);
9696        assert!(
9697            mine.channels.iter().any(|c| c.id == priv_hex),
9698            "the creator is entitled via the companion access role"
9699        );
9700    }
9701
9702    #[tokio::test]
9703    async fn a_private_channel_mints_its_access_role_and_entitlement_follows_the_grant() {
9704        // CORD-03/04: the roles scoped to a channel ARE its access list. Proven
9705        // against a NON-owner so the owner-is-always-entitled rule can't carry it.
9706        let (_tmp, _guard, _owner) = init_test_db();
9707        let relay = MemoryRelay::new();
9708        let community = create_community(&relay, "Scoped", vec!["wss://r".into()], None).await.unwrap();
9709        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
9710        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9711        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9712
9713        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
9714        let access = roster.channel_roles(&chan_hex);
9715        assert_eq!(access.len(), 1, "the channel minted exactly one access role");
9716        assert!(
9717            access[0].permissions == crate::community::roles::Permissions::empty(),
9718            "the access role confers READ access (key possession), never authority"
9719        );
9720        assert_eq!(access[0].name, "mods", "named for its channel");
9721
9722        // A stranger holds no scoped role: unentitled, and no key rides their bundle.
9723        let stranger = Keys::generate().public_key();
9724        let owner_hex = community.owner().unwrap().to_hex();
9725        assert!(!roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]));
9726
9727        // Granting the access role entitles them; revoking un-entitles them. Both
9728        // proven through the roster, which is what routes keys.
9729        let role_id = access[0].role_id.clone();
9730        assert!(
9731            roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, std::slice::from_ref(&role_id), &[]),
9732            "the grant overlay entitles before the fold catches up"
9733        );
9734
9735        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9736        grant_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
9737        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
9738        assert!(
9739            after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
9740            "the grant landed in the local roster (the fold runs later)"
9741        );
9742        let vend = bundle_of(&held, BundleAudience::Member(stranger), None, None, None);
9743        assert!(
9744            vend.channels.iter().any(|c| c.id == chan_hex),
9745            "a now-entitled member's bundle carries the channel key"
9746        );
9747
9748        revoke_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
9749        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
9750        assert!(
9751            !after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
9752            "the revoke dropped the access role"
9753        );
9754        let rotated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9755        assert_eq!(
9756            rotated.channel(&priv_id).unwrap().epoch,
9757            Epoch(2),
9758            "the revoke rotated the channel — a removal that doesn't rekey severs nobody"
9759        );
9760
9761        // The access summary a bot reads back: roles, holders, and key state.
9762        let access = crate::VectorCore.channel_access(&cid_hex, &chan_hex).unwrap();
9763        assert_eq!(access["private"], true);
9764        assert_eq!(access["readable"], true, "we minted it, so we hold its key");
9765        assert_eq!(access["roles"].as_array().unwrap().len(), 1, "one access role");
9766        let holders = access["members"].as_array().unwrap();
9767        let me_npub = {
9768            use nostr_sdk::prelude::ToBech32;
9769            me_pk().unwrap().to_bech32().unwrap()
9770        };
9771        assert_eq!(holders.len(), 1, "only the creator holds it — the revoked member is gone");
9772        assert_eq!(holders[0], serde_json::json!(me_npub), "and that holder is the creator");
9773    }
9774
9775    #[tokio::test]
9776    async fn a_vended_key_parks_until_the_fold_proves_the_grant_then_adopts() {
9777        // JSKitty's race: the vend can land BEFORE the control fold that proves
9778        // the grant. It must park quietly (a lagging fold is not an anomaly) and
9779        // be adopted on the re-judge once the roster catches up.
9780        let (bed, owner, member) = TestBed::new();
9781        bed.swap_to(&owner);
9782        let community = create_community(&bed.relay, "Vend", bed.relays.clone(), None).await.unwrap();
9783        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
9784        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9785        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9786        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9787        let real_key = held.channel(&priv_id).unwrap().key.unwrap();
9788        let owner_hex = community.owner().unwrap().to_hex();
9789
9790        // Judge as the MEMBER — the owner is always entitled, so only a non-owner
9791        // can exercise the grant rule at all.
9792        bed.swap_to(&member);
9793        let me = member.keys.public_key().to_hex();
9794        // Their fold has the channel (control-follow records it keyless) but not
9795        // yet the grant that entitles them.
9796        let mut member_view = held.clone();
9797        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9798            c.key = None;
9799            c.epoch = Epoch(0);
9800        }
9801
9802        // Ungranted → PARK, never refuse: this is exactly the "not synced enough
9803        // to judge" case, and it must stay quiet and retryable.
9804        let empty = crate::community::roles::CommunityRoles::default();
9805        assert!(matches!(
9806            judge_channel_key_vend(&member_view, &empty, &priv_id, Epoch(1), &owner_hex),
9807            VendVerdict::Park(_)
9808        ));
9809
9810        // A channel our fold says is PUBLIC never heals — that's a spoof shape.
9811        let mut public_view = member_view.clone();
9812        if let Some(c) = public_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9813            c.private = false;
9814        }
9815        assert!(matches!(
9816            judge_channel_key_vend(&public_view, &empty, &priv_id, Epoch(1), &owner_hex),
9817            VendVerdict::Refuse(_)
9818        ));
9819
9820        // An unknown channel parks (our fold may simply be behind), never refuses.
9821        assert!(matches!(
9822            judge_channel_key_vend(&member_view, &empty, &ChannelId([0x77; 32]), Epoch(1), &owner_hex),
9823            VendVerdict::Park(_)
9824        ));
9825
9826        // Park the vend, then re-judge with a roster that still lacks our grant:
9827        // it must SURVIVE, not be discarded.
9828        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
9829        crate::db::community::set_community_roles(&cid_hex, &empty, 0).unwrap();
9830        crate::db::community::save_community_v2(&member_view).unwrap();
9831        let session = SessionGuard::capture();
9832        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9833        assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "unprovable vend adopts nothing");
9834        assert_eq!(
9835            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
9836            1,
9837            "and stays parked for the next fold"
9838        );
9839
9840        // The fold catches up: our grant lands, so the same vend now adopts.
9841        let access = crate::community::roles::Role {
9842            role_id: "44".repeat(32),
9843            name: "mods".into(),
9844            position: u32::MAX - 1,
9845            permissions: crate::community::roles::Permissions::empty(),
9846            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
9847            color: 0,
9848        };
9849        let folded = crate::community::roles::CommunityRoles {
9850            grants: vec![crate::community::roles::MemberGrant { member: me.clone(), role_ids: vec![access.role_id.clone()] }],
9851            roles: vec![access],
9852        };
9853        crate::db::community::set_community_roles(&cid_hex, &folded, 1).unwrap();
9854        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9855        let adopted = absorb_parked_channel_keys(&reloaded, &session);
9856        assert_eq!(adopted.len(), 1, "the re-judge adopts once the grant folds");
9857
9858        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9859        let ch = after.channel(&priv_id).unwrap();
9860        assert_eq!(ch.key, Some(real_key), "adopted the vended key");
9861        assert_eq!(ch.epoch, Epoch(1));
9862        assert!(
9863            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
9864            "and the park is discharged"
9865        );
9866    }
9867
9868    #[tokio::test]
9869    async fn a_vend_at_epoch_zero_is_adopted_onto_a_keyless_channel() {
9870        // Live cross-client finding: a peer that mints born-private channels at
9871        // epoch 0 vends epoch 0, which collides with our keyless cursor (also 0).
9872        // The monotonic guard (`new > current`) would refuse the only key we are
9873        // ever offered, and refuse it SILENTLY. First delivery is not a rotation.
9874        let (bed, owner, member) = TestBed::new();
9875        bed.swap_to(&owner);
9876        let community = create_community(&bed.relay, "EpochZero", bed.relays.clone(), None).await.unwrap();
9877        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
9878        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9879        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9880        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9881        let vended = [0x5a; 32];
9882        let owner_hex = community.owner().unwrap().to_hex();
9883
9884        bed.swap_to(&member);
9885        // The member's view: channel known, keyless, parked at the epoch-0 cursor.
9886        let mut member_view = held.clone();
9887        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9888            c.key = None;
9889            c.epoch = Epoch(0);
9890        }
9891        crate::db::community::save_community_v2(&member_view).unwrap();
9892
9893        // Entitle them, then park a vend AT EPOCH 0 (what the peer actually sends).
9894        let access = crate::community::roles::Role {
9895            role_id: "77".repeat(32),
9896            name: "mods".into(),
9897            position: u32::MAX - 1,
9898            permissions: crate::community::roles::Permissions::empty(),
9899            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
9900            color: 0,
9901        };
9902        let roster = crate::community::roles::CommunityRoles {
9903            grants: vec![crate::community::roles::MemberGrant {
9904                member: member.keys.public_key().to_hex(),
9905                role_ids: vec![access.role_id.clone()],
9906            }],
9907            roles: vec![access],
9908        };
9909        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
9910        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &vended, &owner_hex).unwrap();
9911
9912        let session = SessionGuard::capture();
9913        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9914        let adopted = absorb_parked_channel_keys(&reloaded, &session);
9915        assert_eq!(adopted.len(), 1, "an epoch-0 vend onto a keyless channel is adopted");
9916
9917        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9918        let ch = after.channel(&priv_id).unwrap();
9919        assert_eq!(ch.key, Some(vended), "the key actually landed on the row");
9920        assert_eq!(ch.epoch, Epoch(0), "at the epoch the vendor named");
9921        assert!(
9922            !after.channel_read_coords(ch).is_empty(),
9923            "and the channel is readable — the whole point"
9924        );
9925        assert!(
9926            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
9927            "the park is discharged"
9928        );
9929    }
9930
9931    #[tokio::test]
9932    async fn a_wildly_ahead_vend_epoch_is_refused_not_seated() {
9933        // The channel head is MONOTONIC, so over-advancing it can never be walked
9934        // back: every genuine rotation afterwards lands at head+1, reads as stale,
9935        // and the channel dies for us with no heal path at all. An entitled
9936        // insider vending a garbage key costs isolation (accepted); one vending a
9937        // garbage EPOCH would cost the channel permanently, which is not.
9938        let (bed, owner, member) = TestBed::new();
9939        bed.swap_to(&owner);
9940        let community = create_community(&bed.relay, "Poison", bed.relays.clone(), None).await.unwrap();
9941        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
9942        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9943        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9944        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9945        let owner_hex = community.owner().unwrap().to_hex();
9946
9947        bed.swap_to(&member);
9948        let mut member_view = held.clone();
9949        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9950            c.key = None;
9951            c.epoch = Epoch(0);
9952        }
9953        crate::db::community::save_community_v2(&member_view).unwrap();
9954        let access = crate::community::roles::Role {
9955            role_id: "99".repeat(32),
9956            name: "mods".into(),
9957            position: u32::MAX - 1,
9958            permissions: crate::community::roles::Permissions::empty(),
9959            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
9960            color: 0,
9961        };
9962        let roster = crate::community::roles::CommunityRoles {
9963            grants: vec![crate::community::roles::MemberGrant {
9964                member: member.keys.public_key().to_hex(),
9965                role_ids: vec![access.role_id.clone()],
9966            }],
9967            roles: vec![access],
9968        };
9969        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
9970        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9971
9972        // Everything else about this vend is valid — only the epoch is absurd.
9973        assert!(matches!(
9974            judge_channel_key_vend(&reloaded, &roster, &priv_id, Epoch(1 << 40), &owner_hex),
9975            VendVerdict::Refuse(_)
9976        ));
9977        // REFUSED, not parked: a row nothing can ever discharge is its own leak.
9978        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1 << 40, &[0xEE; 32], &owner_hex).unwrap();
9979        let session = SessionGuard::capture();
9980        assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "a poison epoch adopts nothing");
9981        assert!(
9982            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
9983            "and the row is discharged rather than parked forever"
9984        );
9985        // The head is untouched, so the genuine vend still lands afterwards.
9986        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9987        assert_eq!(after.channel(&priv_id).unwrap().epoch, Epoch(0), "head never advanced");
9988        assert!(matches!(
9989            judge_channel_key_vend(&after, &roster, &priv_id, Epoch(1), &owner_hex),
9990            VendVerdict::Accept
9991        ));
9992    }
9993
9994    #[tokio::test]
9995    async fn a_channel_rename_lands_locally_without_waiting_for_the_fold() {
9996        // The fold is the authority but runs later, so publishing alone leaves the
9997        // edit reading back stale — it looks like the rename silently failed.
9998        let (_tmp, _guard, _owner) = init_test_db();
9999        let relay = MemoryRelay::new();
10000        let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
10001        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
10002        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10003        let key_before = held.channel(&priv_id).unwrap().key;
10004
10005        let mut meta = held.channel(&priv_id).unwrap().metadata();
10006        meta.name = "staff".into();
10007        edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();
10008
10009        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10010        let ch = after.channel(&priv_id).unwrap();
10011        assert_eq!(ch.name, "staff", "the rename is visible immediately");
10012        assert!(ch.private, "and privacy survives the edit");
10013        assert_eq!(ch.key, key_before, "as does the key — a rename is not a rotation");
10014    }
10015
10016    #[tokio::test]
10017    async fn a_channel_rename_carries_its_companion_access_role() {
10018        let (_tmp, _guard, _owner) = init_test_db();
10019        let relay = MemoryRelay::new();
10020        let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
10021        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
10022        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10023        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
10024
10025        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
10026        let before = roster.channel_roles(&chan_hex);
10027        assert_eq!(before.len(), 1, "one companion role, minted at create");
10028        assert_eq!(before[0].name, "mods", "named after the channel it gates");
10029        let role_id = before[0].role_id.clone();
10030
10031        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10032        let mut meta = held.channel(&priv_id).unwrap().metadata();
10033        meta.name = "staff".into();
10034        edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();
10035
10036        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
10037        let after = roster.channel_roles(&chan_hex);
10038        assert_eq!(after.len(), 1, "renamed in place, never duplicated");
10039        assert_eq!(after[0].role_id, role_id, "a rename is a versioned edit of the same id");
10040        assert_eq!(after[0].name, "staff", "the access role followed the channel");
10041        assert_eq!(
10042            after[0].permissions,
10043            crate::community::roles::Permissions::empty(),
10044            "and still confers read access, never authority"
10045        );
10046    }
10047
10048    #[tokio::test]
10049    async fn a_customised_access_role_name_survives_a_channel_rename() {
10050        // The label is cosmetic — entitlement rides the scope. Overwriting a name
10051        // someone chose deliberately is the surprising half of "keep them in step".
10052        let (_tmp, _guard, _owner) = init_test_db();
10053        let relay = MemoryRelay::new();
10054        let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
10055        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
10056        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10057        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
10058
10059        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
10060        let mut role = roster.channel_roles(&chan_hex)[0].clone();
10061        role.name = "Lab Insiders".into();
10062        set_role(&relay, &community, &role).await.unwrap();
10063        merge_local_roster(&cid_hex, Some(&role), None);
10064
10065        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10066        let mut meta = held.channel(&priv_id).unwrap().metadata();
10067        meta.name = "staff".into();
10068        edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();
10069
10070        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
10071        assert_eq!(
10072            roster.channel_roles(&chan_hex)[0].name,
10073            "Lab Insiders",
10074            "a deliberate name is left alone"
10075        );
10076    }
10077
10078    #[tokio::test]
10079    async fn a_squatted_park_row_cannot_suppress_the_genuine_vend() {
10080        // Parking is reachable by ANY npub that can gift-wrap us — the bundle
10081        // self-certifies and its inputs are public for a public community. With a
10082        // single slot per channel, a stranger could pre-park and the admin's real
10083        // vend would be a silent no-op, leaving the member keyless with no retry.
10084        // Candidates + judge-them-all is what closes that.
10085        let (bed, owner, member) = TestBed::new();
10086        bed.swap_to(&owner);
10087        let community = create_community(&bed.relay, "Squat", bed.relays.clone(), None).await.unwrap();
10088        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
10089        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10090        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
10091        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10092        let real_key = held.channel(&priv_id).unwrap().key.unwrap();
10093        let owner_hex = community.owner().unwrap().to_hex();
10094
10095        bed.swap_to(&member);
10096        let mut member_view = held.clone();
10097        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
10098            c.key = None;
10099            c.epoch = Epoch(0);
10100        }
10101        crate::db::community::save_community_v2(&member_view).unwrap();
10102        let access = crate::community::roles::Role {
10103            role_id: "aa".repeat(32),
10104            name: "mods".into(),
10105            position: u32::MAX - 1,
10106            permissions: crate::community::roles::Permissions::empty(),
10107            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
10108            color: 0,
10109        };
10110        let roster = crate::community::roles::CommunityRoles {
10111            grants: vec![crate::community::roles::MemberGrant {
10112                member: member.keys.public_key().to_hex(),
10113                role_ids: vec![access.role_id.clone()],
10114            }],
10115            roles: vec![access],
10116        };
10117        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
10118
10119        // A stranger squats FIRST, at a higher epoch than the genuine vend.
10120        let stranger = Keys::generate().public_key().to_hex();
10121        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 9, &[0xBA; 32], &stranger).unwrap();
10122        // The admin's real vend arrives after, at the true epoch.
10123        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
10124        assert_eq!(
10125            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
10126            2,
10127            "the squatter never displaces the genuine vend — both are candidates"
10128        );
10129
10130        let session = SessionGuard::capture();
10131        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10132        let adopted = absorb_parked_channel_keys(&reloaded, &session);
10133        assert_eq!(adopted.len(), 1, "exactly one adoption");
10134
10135        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10136        let ch = after.channel(&priv_id).unwrap();
10137        assert_eq!(ch.key, Some(real_key), "the OWNER's key won, not the squatter's");
10138        assert_eq!(ch.epoch, Epoch(1), "at the genuine epoch");
10139        assert!(
10140            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
10141            "and every candidate for the channel is discharged"
10142        );
10143    }
10144
10145    #[tokio::test]
10146    async fn revoking_without_a_folded_access_role_refuses_instead_of_evicting_everyone() {
10147        // With no access role folded, the retained-set filter matches NOBODY, so
10148        // the rotation would cut off every legitimately entitled member while the
10149        // Grant it published revoked nothing. Reachable with no attacker: the
10150        // channel was made on another admin's client and its role hasn't folded.
10151        let (_tmp, _guard, _owner) = init_test_db();
10152        let relay = MemoryRelay::new();
10153        let community = create_community(&relay, "NoRole", vec!["wss://r".into()], None).await.unwrap();
10154        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
10155        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10156        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10157        let before = held.channel(&priv_id).unwrap().epoch;
10158
10159        // Neither the cache nor the plane serves the access role — a withholding
10160        // relay, or a channel minted on another admin's client. (Wiping only the
10161        // cache is no longer enough: the revoke re-fetches authority first.)
10162        crate::db::community::set_community_roles(&cid_hex, &crate::community::roles::CommunityRoles::default(), 0).unwrap();
10163        let mut blind = held.clone();
10164        blind.relays = vec!["wss://empty".into()];
10165        let err = revoke_channel_access(&relay, &blind, &priv_id, &Keys::generate().public_key())
10166            .await
10167            .unwrap_err();
10168        assert!(err.contains("has not folded"), "refuses with a retryable reason: {err}");
10169
10170        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10171        assert_eq!(after.channel(&priv_id).unwrap().epoch, before, "and rotates nothing");
10172    }
10173
10174    // ── Live rekey-follow ────────────────────────────────────────────────────
10175
10176    /// Publish an owner-grammar base rotation (Refounding) delivering `new_root`
10177    /// to each recipient. `rotator` is the seal signer (owner for a legit rotation,
10178    /// a stranger for the authority test); `prev_key` is the root it claims to
10179    /// extend (mismatch → a fork).
10180    async fn publish_base_rotation(
10181        relay: &MemoryRelay,
10182        community: &CommunityV2,
10183        rotator: &Keys,
10184        recipients: &[PublicKey],
10185        new_root: &[u8; 32],
10186        prev_key: &[u8; 32],
10187    ) {
10188        let new_epoch = Epoch(community.root_epoch.0 + 1);
10189        let prev_epoch = community.root_epoch;
10190        let prev_commit = super::super::derive::epoch_key_commitment(prev_epoch, prev_key);
10191        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
10192        let blobs: Vec<_> = recipients
10193            .iter()
10194            .map(|r| rekey::build_blob_local(rotator.secret_key(), &rotator.public_key().to_bytes(), r, RekeyScope::Root, new_epoch, new_root).unwrap())
10195            .collect();
10196        let events = rekey::build_rekey_chunks_local(rotator, &group, RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &blobs, 2_000, my_authority_citation(community, &rotator.public_key()).as_ref()).unwrap();
10197        for e in &events {
10198            relay.publish(e, &community.relays).await.unwrap();
10199        }
10200    }
10201
10202    /// Attach a Private channel (key + epoch) to a held community and persist it.
10203    fn add_private_channel(community: &mut CommunityV2, id: ChannelId, key: [u8; 32], epoch: Epoch) {
10204        community.channels.push(ChannelV2 { id, name: "mods".into(), private: true, key: Some(key), epoch, voice: None, meta_custom: None, meta_extra: Default::default() });
10205        crate::db::community::save_community_v2(community).unwrap();
10206    }
10207
10208    #[tokio::test]
10209    async fn follow_rekeys_is_a_noop_without_rotations() {
10210        let (_tmp, _guard, _owner) = init_test_db();
10211        let relay = MemoryRelay::new();
10212        let community = create_community(&relay, "Still", vec!["wss://r".into()], None).await.unwrap();
10213        let session = SessionGuard::capture();
10214        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
10215        assert!(follow.updated.is_none() && !follow.self_removed, "no rotation → nothing to adopt");
10216    }
10217
10218    #[tokio::test]
10219    async fn follow_rekeys_adopts_an_owner_base_rotation() {
10220        let (_tmp, _guard, owner) = init_test_db();
10221        let relay = MemoryRelay::new();
10222        let community = create_community(&relay, "Refound", vec!["wss://r".into()], None).await.unwrap();
10223        let new_root = [0xB1; 32];
10224        // Owner rotates the base to epoch 1, delivering the new root to me.
10225        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
10226
10227        let session = SessionGuard::capture();
10228        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
10229        assert_eq!(updated.root_epoch, Epoch(1), "advanced one epoch");
10230        assert_eq!(updated.community_root, new_root, "adopted the fresh root");
10231        // The public channel now reads under the NEW root/epoch (its address moved).
10232        let addr = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
10233        let general = updated.channels[0].id;
10234        let new_chat = channel_group_key(&new_root, &general, Epoch(1)).pk();
10235        assert!(addr.contains(&new_chat), "the public channel re-addresses under the new root");
10236    }
10237
10238    #[tokio::test]
10239    async fn follow_rekeys_adopts_an_owner_private_channel_rotation() {
10240        let (_tmp, _guard, owner) = init_test_db();
10241        let relay = MemoryRelay::new();
10242        let mut community = create_community(&relay, "PrivRot", vec!["wss://r".into()], None).await.unwrap();
10243        let priv_id = ChannelId([0x33; 32]);
10244        add_private_channel(&mut community, priv_id, [0x44; 32], Epoch(0));
10245
10246        // Owner rotates the private channel to epoch 1 with a fresh key, delivered to me.
10247        let new_key = [0x55; 32];
10248        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &[0x44; 32]);
10249        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
10250        let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(1), &new_key).unwrap();
10251        let events = rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &prev_commit, &[blob], 2_000, None).unwrap();
10252        for e in &events {
10253            relay.publish(e, &community.relays).await.unwrap();
10254        }
10255
10256        let session = SessionGuard::capture();
10257        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
10258        let ch = updated.channel(&priv_id).unwrap();
10259        assert_eq!(ch.epoch, Epoch(1), "the private channel advanced an epoch");
10260        assert_eq!(ch.key, Some(new_key), "adopted the fresh channel key");
10261        assert_eq!(updated.root_epoch, Epoch(0), "the base is untouched by a channel rotation");
10262    }
10263
10264    #[tokio::test]
10265    async fn follow_rekeys_ignores_a_non_owner_rotation() {
10266        // A member holds the community_root, so they can derive the rekey group key
10267        // and mint a rotation — but they aren't the owner, so it's not adopted.
10268        let (_tmp, _guard, _owner) = init_test_db();
10269        let relay = MemoryRelay::new();
10270        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
10271        let rogue = Keys::generate();
10272        publish_base_rotation(&relay, &community, &rogue, &[rogue.public_key()], &[0xEE; 32], &community.community_root).await;
10273
10274        let session = SessionGuard::capture();
10275        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
10276        assert!(follow.updated.is_none() && !follow.self_removed, "a non-owner rotation is not adopted");
10277    }
10278
10279    #[tokio::test]
10280    async fn follow_rekeys_ignores_a_rotation_off_the_wrong_prev() {
10281        // A rotation whose prevcommit doesn't match the key I hold is a fork, not an
10282        // extension — never adopted (would splice me onto an unrelated chain).
10283        let (_tmp, _guard, owner) = init_test_db();
10284        let relay = MemoryRelay::new();
10285        let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
10286        // prev_key ≠ the real community_root → the continuity check reads Fork.
10287        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &[0xB2; 32], &[0x00; 32]).await;
10288
10289        let session = SessionGuard::capture();
10290        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
10291        assert!(follow.updated.is_none(), "a fork off the wrong prev is not adopted");
10292    }
10293
10294    #[tokio::test]
10295    async fn follow_rekeys_holds_on_an_incomplete_rotation() {
10296        // A 2-chunk rotation with only chunk 1 present can never conclude — not an
10297        // adoption, and crucially NOT a removal (a missing chunk might carry my blob).
10298        let (_tmp, _guard, owner) = init_test_db();
10299        let relay = MemoryRelay::new();
10300        let community = create_community(&relay, "Partial", vec!["wss://r".into()], None).await.unwrap();
10301        let new_epoch = Epoch(1);
10302        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
10303        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
10304        // Chunk 1 of a declared 2, carrying someone else's blob (not mine).
10305        let other = Keys::generate();
10306        let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &other.public_key(), RekeyScope::Root, new_epoch, &[0xB3; 32]).unwrap();
10307        let rumor = rekey::build_rekey_rumor(owner.public_key(), RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[blob], 1, 2, 2_000, None).unwrap();
10308        let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &owner, Timestamp::from_secs(2_000)).unwrap();
10309        relay.publish(&wrap, &community.relays).await.unwrap();
10310
10311        let session = SessionGuard::capture();
10312        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
10313        assert!(follow.updated.is_none() && !follow.self_removed, "an incomplete rotation neither adopts nor removes");
10314    }
10315
10316    #[tokio::test]
10317    async fn follow_rekeys_removes_a_member_dropped_by_a_base_rotation() {
10318        // Realistic two-actor removal: the owner Refounds the base and delivers the
10319        // new root to a THIRD party, not the member — a complete rotation with no
10320        // blob for the member is a removal.
10321        let (bed, owner, member) = TestBed::new();
10322        bed.swap_to(&owner);
10323        let community = create_community(&bed.relay, "Evict", bed.relays.clone(), None).await.unwrap();
10324        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
10325
10326        bed.swap_to(&member);
10327        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
10328        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
10329
10330        // Owner rotates, delivering only to a stranger (the member is dropped).
10331        bed.swap_to(&owner);
10332        let stranger = Keys::generate();
10333        publish_base_rotation(&bed.relay, &community, &owner.keys, &[stranger.public_key()], &[0xC4; 32], &community.community_root).await;
10334
10335        // The member's follow concludes removal (a complete rotation without their blob).
10336        bed.swap_to(&member);
10337        let session = SessionGuard::capture();
10338        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
10339        assert!(follow.self_removed, "a complete base rotation dropping the member removes them");
10340        assert!(follow.updated.is_none(), "a removed member adopts nothing");
10341    }
10342
10343    #[tokio::test]
10344    async fn follow_rekeys_finds_a_channel_rekey_under_an_archived_prior_root() {
10345        // PROTO-B2 regression: a Refounding's channel rekeys ride the PRIOR root
10346        // (CORD-06 §3). A follower who adopted the BASE first (the live window:
10347        // the base crate landed and was walked before the channel crates) must
10348        // still find them — the lookup fans across the archived roots, not just
10349        // the current one.
10350        let (_tmp, _guard, owner) = init_test_db();
10351        let relay = MemoryRelay::new();
10352        let mut community = create_community(&relay, "Strand", vec!["wss://r".into()], None).await.unwrap();
10353        let root0 = community.community_root;
10354        let priv_id = ChannelId([0x33; 32]);
10355        let key1 = [0x44; 32];
10356        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10357
10358        // The refounder's channel rekey (1 → 2), sealed + addressed under the PRIOR
10359        // root (root0), delivering the fresh key to me.
10360        let key2 = [0x55; 32];
10361        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10362        let group = channel_rekey_group_key(&root0, &priv_id, Epoch(2));
10363        let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10364        for e in rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &prev_commit, &[blob], 2_000, None).unwrap() {
10365            relay.publish(&e, &community.relays).await.unwrap();
10366        }
10367
10368        // Simulate the base having ALREADY advanced (the stranding order): the head
10369        // moved to a fresh root while root0 sits in the epoch-key archive (where
10370        // genesis put it).
10371        community.community_root = [0xB7; 32];
10372        community.root_epoch = Epoch(1);
10373        crate::db::community::save_community_v2(&community).unwrap();
10374
10375        let session = SessionGuard::capture();
10376        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the prior-root crate is found");
10377        let ch = updated.channel(&priv_id).unwrap();
10378        assert_eq!(ch.epoch, Epoch(2), "the channel advanced despite the moved base");
10379        assert_eq!(ch.key, Some(key2), "adopted the key delivered under the prior root");
10380    }
10381
10382    #[tokio::test]
10383    async fn follow_rekeys_keyless_cursor_walks_past_an_excluding_rotation_then_adopts() {
10384        // A keyless private channel (announced by vsk-2, key not yet held) has no
10385        // chain, so its epoch is a scan cursor: a complete rotation that excludes
10386        // us advances the cursor (never a removal — we were never in); a later
10387        // rotation that includes us is the entry point.
10388        let (_tmp, _guard, owner) = init_test_db();
10389        let relay = MemoryRelay::new();
10390        let mut community = create_community(&relay, "Cursor", vec!["wss://r".into()], None).await.unwrap();
10391        let priv_id = ChannelId([0x66; 32]);
10392        community.channels.push(ChannelV2 { id: priv_id, name: "vault".into(), private: true, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default() });
10393        crate::db::community::save_community_v2(&community).unwrap();
10394        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10395        assert!(community.channel(&priv_id).unwrap().key.is_none(), "keyless survives the round-trip");
10396
10397        // Epoch 1: the creation delivery went to a stranger only (pre-dates us).
10398        let stranger = Keys::generate();
10399        let key1 = [0x71; 32];
10400        let pc1 = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
10401        let g1 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
10402        let b1 = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &stranger.public_key(), RekeyScope::Channel(priv_id), Epoch(1), &key1).unwrap();
10403        for e in rekey::build_rekey_chunks_local(&owner, &g1, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &pc1, &[b1], 2_000, None).unwrap() {
10404            relay.publish(&e, &community.relays).await.unwrap();
10405        }
10406        // Epoch 2: a later rotation includes ME (e.g. a removal-forced re-mint whose
10407        // recipient set is the CURRENT members).
10408        let key2 = [0x72; 32];
10409        let pc2 = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10410        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10411        let b2 = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10412        for e in rekey::build_rekey_chunks_local(&owner, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc2, &[b2], 2_100, None).unwrap() {
10413            relay.publish(&e, &community.relays).await.unwrap();
10414        }
10415
10416        // ONE follow: the cursor walks 0→1 (excluded, still keyless) and 1→2 (my
10417        // blob — adopt), because each real step re-loops.
10418        let session = SessionGuard::capture();
10419        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the walk lands on the included epoch");
10420        let ch = updated.channel(&priv_id).unwrap();
10421        assert_eq!(ch.epoch, Epoch(2), "cursor walked through the excluding epoch to the included one");
10422        assert_eq!(ch.key, Some(key2), "adopted the delivery that includes us");
10423    }
10424
10425    #[tokio::test]
10426    async fn follow_rekeys_honors_an_admin_channel_rotation_but_never_a_strangers() {
10427        // CORD-06 §Authority: a CHANNEL rekey is honored from the owner or a
10428        // MANAGE_CHANNELS holder under the persisted roster — so an admin-run
10429        // rotation keys members up; a mere keyholder's forgery never does.
10430        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10431        let (_tmp, _guard, _owner) = init_test_db();
10432        let relay = MemoryRelay::new();
10433        let mut community = create_community(&relay, "AdminRot", vec!["wss://r".into()], None).await.unwrap();
10434        let priv_id = ChannelId([0x88; 32]);
10435        let key1 = [0x91; 32];
10436        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10437
10438        // Persist a roster granting `admin` the Admin role (MANAGE_CHANNELS ⊂ ADMIN_ALL).
10439        let admin = Keys::generate();
10440        let role = Role::admin("aa".repeat(32));
10441        let roster = CommunityRoles {
10442            roles: vec![role.clone()],
10443            grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
10444        };
10445        seed_roster_with_heads(&community, &roster, 1_000);
10446
10447        // The ADMIN rotates the channel 1 → 2, delivering to me: adopted.
10448        let key2 = [0x92; 32];
10449        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10450        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10451        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
10452        let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10453        for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, my_authority_citation(&community, &admin.public_key()).as_ref()).unwrap() {
10454            relay.publish(&e, &community.relays).await.unwrap();
10455        }
10456        let session = SessionGuard::capture();
10457        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("an admin rotation is honored");
10458        assert_eq!(updated.channel(&priv_id).unwrap().key, Some(key2), "adopted the admin's key");
10459
10460        // A STRANGER (keyholder, no roster standing) rotates 2 → 3: refused.
10461        let rogue = Keys::generate();
10462        let key3 = [0x93; 32];
10463        let pc3 = super::super::derive::epoch_key_commitment(Epoch(2), &key2);
10464        let g3 = channel_rekey_group_key(&updated.community_root, &priv_id, Epoch(3));
10465        let rb = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(3), &key3).unwrap();
10466        for e in rekey::build_rekey_chunks_local(&rogue, &g3, RekeyScope::Channel(priv_id), Epoch(3), Epoch(2), &pc3, &[rb], 2_100, None).unwrap() {
10467            relay.publish(&e, &updated.relays).await.unwrap();
10468        }
10469        let follow = follow_rekeys(&relay, &updated, &session).await.unwrap();
10470        assert!(follow.updated.is_none(), "a stranger's channel rotation is never adopted");
10471    }
10472
10473    #[tokio::test]
10474    async fn a_non_outranking_admins_rotation_never_concludes_my_removal() {
10475        // CORD-06 §Authority: the Rotator must strictly OUTRANK every removed
10476        // target. An equal-rank bit-holder's complete rotation that skips my blob
10477        // must read Stay (my record survives); the OWNER's reads Removed. Needs a
10478        // two-account bed: the follower must be a NON-owner admin.
10479        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10480        let (bed, owner, member) = TestBed::new();
10481        bed.swap_to(&owner);
10482        let community = create_community(&bed.relay, "Outrank", bed.relays.clone(), None).await.unwrap();
10483
10484        // The MEMBER's device: holds the community + the private channel, with a
10485        // persisted roster granting the member AND a peer the same Admin role.
10486        bed.swap_to(&member);
10487        let mut held = community.clone();
10488        let priv_id = ChannelId([0xAB; 32]);
10489        let key1 = [0xA1; 32];
10490        add_private_channel(&mut held, priv_id, key1, Epoch(1));
10491        let peer = Keys::generate();
10492        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10493        let role = Role::admin("bb".repeat(32));
10494        let roster = CommunityRoles {
10495            roles: vec![role.clone()],
10496            grants: vec![
10497                MemberGrant { member: peer.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
10498                MemberGrant { member: member.keys.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
10499            ],
10500        };
10501        crate::db::community::set_community_roles(&cid_hex, &roster, 1_000).unwrap();
10502
10503        // The equal-rank PEER rotates 1 → 2 delivering only to themselves.
10504        let key2 = [0xA2; 32];
10505        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10506        let g2 = channel_rekey_group_key(&held.community_root, &priv_id, Epoch(2));
10507        let pb = rekey::build_blob_local(peer.secret_key(), &peer.public_key().to_bytes(), &peer.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10508        for e in rekey::build_rekey_chunks_local(&peer, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[pb], 2_000, my_authority_citation(&held, &peer.public_key()).as_ref()).unwrap() {
10509            bed.relay.publish(&e, &held.relays).await.unwrap();
10510        }
10511        let session = SessionGuard::capture();
10512        let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
10513        assert!(follow.updated.is_none(), "an equal-rank rotation excluding me is Stay, never my removal");
10514        let reloaded = crate::db::community::load_community_v2(held.id()).unwrap().unwrap();
10515        assert!(reloaded.channel(&priv_id).is_some(), "my channel record survives the peer's rotation");
10516
10517        // The OWNER's rotation excluding me IS a removal (owner outranks everyone).
10518        let key3 = [0xA3; 32];
10519        let stranger = Keys::generate();
10520        let ob = rekey::build_blob_local(owner.keys.secret_key(), &owner.keys.public_key().to_bytes(), &stranger.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key3).unwrap();
10521        for e in rekey::build_rekey_chunks_local(&owner.keys, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[ob], 2_100, None).unwrap() {
10522            bed.relay.publish(&e, &held.relays).await.unwrap();
10523        }
10524        let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
10525        let updated = follow.updated.expect("the owner's removal folds");
10526        assert!(updated.channel(&priv_id).is_none(), "the owner's exclusion cuts my channel record");
10527    }
10528
10529    #[tokio::test]
10530    async fn converting_a_public_channel_to_private_is_refused() {
10531        // The conversion (CORD-03 §2) is a key rotation this build doesn't mint yet:
10532        // the producer refuses the flag flip, so no reader is left unkeyable.
10533        let (_tmp, _guard, _owner) = init_test_db();
10534        let relay = MemoryRelay::new();
10535        let community = create_community(&relay, "NoConvert", vec!["wss://r".into()], None).await.unwrap();
10536        let general = community.channels[0].id;
10537        let meta = control::ChannelMetadata { name: "general".into(), private: true, voice: None, deleted: None, custom: None, extra: Default::default() };
10538        let err = edit_channel_metadata(&relay, &community, &general, &meta).await.unwrap_err();
10539        assert!(err.contains("not supported"), "conversion is refused at the producer: {err}");
10540        // A rename of the same public channel still works.
10541        let meta = control::ChannelMetadata { name: "lobby".into(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() };
10542        edit_channel_metadata(&relay, &community, &general, &meta).await.unwrap();
10543    }
10544
10545    /// Publish a 13302 (signed by `me`) carrying a leave tombstone for `cid_hex` at
10546    /// `removed_at` — simulating a sibling device having left that community.
10547    async fn publish_remote_tombstone(relay: &MemoryRelay, me: &Keys, relays: &[String], cid_hex: &str, removed_at: u64) {
10548        let doc = super::super::list::CommunityList {
10549            entries: vec![],
10550            tombstones: vec![super::super::list::Tombstone { community_id: cid_hex.to_string(), removed_at, extra: Default::default() }],
10551            extra: Default::default(),
10552        };
10553        let event = super::super::list::build_list_event(me, &doc).unwrap();
10554        relay.publish(&event, relays).await.unwrap();
10555    }
10556
10557    #[tokio::test]
10558    async fn joining_one_community_does_not_resurrect_a_sibling_left_community() {
10559        // W1 (send side): a sibling device left X (a remote tombstone). Joining a
10560        // DIFFERENT community must not re-add X to the 13302 with added_at=now,
10561        // which would silently undo the leave everywhere.
10562        let (_tmp, _guard, me) = init_test_db();
10563        let relay = MemoryRelay::new();
10564        let x = create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
10565        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
10566
10567        // A sibling leaves X: a remote tombstone strictly newer than X's add.
10568        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;
10569
10570        // Now join a different community Y → republish(just_joined = Y).
10571        let y = create_community(&relay, "Y", vec!["wss://r".into()], None).await.unwrap();
10572        republish_community_list(&relay, Some(y.id())).await.unwrap();
10573
10574        // X must still read as LEFT in the published list; Y must be live.
10575        let list = fetch_community_list(&relay, &x.relays).await.unwrap().unwrap();
10576        assert!(!list.is_live(&x_hex), "joining Y did not resurrect the sibling-left X");
10577        assert!(list.is_live(&crate::simd::hex::bytes_to_hex_32(&y.id().0)), "Y is live");
10578    }
10579
10580    #[tokio::test]
10581    async fn sync_tears_down_a_community_a_sibling_left() {
10582        // W1 (receive side): a community still held locally that the synced 13302
10583        // shows tombstoned-and-not-live is torn down, so a leave propagates.
10584        let (_tmp, _guard, me) = init_test_db();
10585        let relay = MemoryRelay::new();
10586        let x = create_community(&relay, "Leaveme", vec!["wss://r".into()], None).await.unwrap();
10587        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
10588        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "held before sync");
10589
10590        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;
10591        sync_community_list(&relay, &x.relays).await.unwrap();
10592        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the sibling's leave tore X down locally");
10593    }
10594
10595    #[tokio::test]
10596    async fn a_rejoined_community_survives_a_stale_tombstone_on_sync() {
10597        // The re-join case must NOT be torn down: a fresh join re-adds live (beating
10598        // the tombstone), so a later sync keeps it.
10599        let (_tmp, _guard, me) = init_test_db();
10600        let relay = MemoryRelay::new();
10601        let x = create_community(&relay, "Rejoin", vec!["wss://r".into()], None).await.unwrap();
10602        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
10603        // A stale tombstone from a prior leave (OLDER than the current hold's re-add).
10604        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, 1).await;
10605        // Re-record the membership (a re-join) → live entry at now >> 1.
10606        republish_community_list(&relay, Some(x.id())).await.unwrap();
10607        sync_community_list(&relay, &x.relays).await.unwrap();
10608        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "a re-joined community is not torn down by a stale tombstone");
10609    }
10610
10611    #[tokio::test]
10612    async fn a_failed_remote_fetch_never_clobbers_the_published_list() {
10613        // W2: a transient fetch failure during republish must not drive the
10614        // replaceable-event write (which would drop other entries / regress seeds).
10615        let (_tmp, _guard, _me) = init_test_db();
10616        let good = MemoryRelay::new();
10617        let community = create_community(&good, "Seeded", vec!["wss://r".into()], None).await.unwrap();
10618        assert!(fetch_community_list(&good, &community.relays).await.unwrap().is_some());
10619
10620        // A transport whose fetch always errors: republish must bail, publishing nothing.
10621        struct FetchErrors;
10622        #[async_trait::async_trait]
10623        impl Transport for FetchErrors {
10624            async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
10625            async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
10626                panic!("republish must NOT publish when the remote fetch failed");
10627            }
10628            async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
10629                Ok(())
10630            }
10631            async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
10632                Err("relay unreachable".to_string())
10633            }
10634        }
10635        // Returns Ok (best-effort) but must not have published (the panic guards it).
10636        republish_community_list(&FetchErrors, Some(community.id())).await.unwrap();
10637    }
10638
10639    #[tokio::test]
10640    async fn a_granted_member_survives_a_refounding_even_with_no_guestbook_join() {
10641        // B1 regression: refound_community's recipient set = memberlist. A member
10642        // the owner GRANTED a role to but who never left a (surviving) Guestbook
10643        // Join — a lurking admin, or one whose Join aged out of the window — must
10644        // still be a rekey recipient, or the Refounding SEVERS them. The folded
10645        // roster's granted members are the consensus-complete backstop.
10646        let (_tmp, _guard, owner) = init_test_db();
10647        let relay = MemoryRelay::new();
10648        let community = create_community(&relay, "Backstop", vec!["wss://r".into()], None).await.unwrap();
10649
10650        // A lurker gets an admin grant but publishes NO Guestbook Join and no chat.
10651        let lurker = Keys::generate();
10652        let rid = "b1".repeat(32);
10653        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
10654        publish_grant(&relay, &community, &owner, &lurker.public_key(), vec![rid.clone()], 1).await;
10655
10656        // memberlist includes the lurker purely via the roster backstop.
10657        let members = memberlist(&relay, &community).await.unwrap();
10658        assert!(members.contains(&lurker.public_key()), "a granted member with no Join is still a member");
10659
10660        // A banned grantee whose grant wasn't stripped is NOT re-admitted.
10661        let banned_grantee = Keys::generate();
10662        publish_grant(&relay, &community, &owner, &banned_grantee.public_key(), vec![rid], 1).await;
10663        set_banlist(&relay, &community, &[banned_grantee.public_key().to_hex()]).await.unwrap();
10664        let members = memberlist(&relay, &community).await.unwrap();
10665        assert!(members.contains(&lurker.public_key()), "the honest grantee still counts");
10666        assert!(!members.contains(&banned_grantee.public_key()), "a banned grantee is not re-admitted by the union");
10667
10668        // And the Refounding actually delivers the new root to the lurker.
10669        let refounded = refound_community(&relay, &community, &[]).await.unwrap();
10670        assert_eq!(refounded.root_epoch, Epoch(1));
10671        let base_group = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
10672        let chunks = fetch_rekey_chunks(&relay, &community.relays, &base_group).await.unwrap();
10673        let rotations = rekey::collect_rotations(&chunks);
10674        let lurker_x = lurker.public_key().to_bytes();
10675        let delivered = rotations.iter().any(|r| {
10676            rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &lurker_x, r.scope, r.new_epoch).is_some()
10677        });
10678        assert!(delivered, "the Refounding delivered the new root to the granted lurker");
10679    }
10680
10681    #[tokio::test]
10682    async fn the_memberlist_pages_past_a_guestbook_flood() {
10683        // The roleless-member half of B1: >500 Guestbook events must not evict an
10684        // honest member's Join from the counted set (an insider can flood throwaway
10685        // Joins to force exactly this). The pager sees them all.
10686        let (_tmp, _guard, _owner) = init_test_db();
10687        let relay = MemoryRelay::new();
10688        let community = create_community(&relay, "GBFlood", vec!["wss://r".into()], None).await.unwrap();
10689        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
10690
10691        // An honest member's Join (oldest), then 600 throwaway Joins on top.
10692        let honest = Keys::generate();
10693        let join = guestbook::build_join_rumor(honest.public_key(), None, 1_000);
10694        let (w, _) = guestbook::seal_guestbook_rumor(&join, &gb, &honest, Timestamp::from_secs(1)).unwrap();
10695        relay.publish(&w, &community.relays).await.unwrap();
10696        for i in 0..600u64 {
10697            let throwaway = Keys::generate();
10698            let j = guestbook::build_join_rumor(throwaway.public_key(), None, 2_000 + i);
10699            let (w, _) = guestbook::seal_guestbook_rumor(&j, &gb, &throwaway, Timestamp::from_secs(2 + i)).unwrap();
10700            relay.publish(&w, &community.relays).await.unwrap();
10701        }
10702
10703        let members = memberlist(&relay, &community).await.unwrap();
10704        assert!(members.contains(&honest.public_key()), "the honest member's aged-out Join is still counted past the flood");
10705    }
10706
10707    #[tokio::test]
10708    async fn a_rekey_plane_flood_cannot_bury_a_genuine_rotation() {
10709        // An insider floods the next-epoch rekey address (community_root-derived,
10710        // so any member can seal there) with >200 junk 3303s to push the owner's
10711        // genuine rotation out of a single fetch window. The paginated fetch must
10712        // still recover it and adopt.
10713        let (_tmp, _guard, owner) = init_test_db();
10714        let relay = MemoryRelay::new();
10715        let community = create_community(&relay, "Flooded", vec!["wss://r".into()], None).await.unwrap();
10716        let new_root = [0xD9; 32];
10717        let new_epoch = Epoch(1);
10718        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
10719
10720        // The GENUINE owner rotation lands first (oldest).
10721        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
10722
10723        // Then a member floods 260 well-formed-but-unauthorized junk chunks ON TOP
10724        // (newer), burying the genuine one past the 200 newest.
10725        let rogue = Keys::generate();
10726        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
10727        for i in 0..260u64 {
10728            let blob = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &rogue.public_key(), RekeyScope::Root, new_epoch, &[0xEE; 32]).unwrap();
10729            let rumor = rekey::build_rekey_rumor(rogue.public_key(), RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[blob], 1, 1, 3_000 + i, None).unwrap();
10730            let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &rogue, Timestamp::from_secs(3_000 + i)).unwrap();
10731            relay.publish(&wrap, &community.relays).await.unwrap();
10732        }
10733
10734        let session = SessionGuard::capture();
10735        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the genuine rotation is recovered past the flood");
10736        assert_eq!(updated.root_epoch, Epoch(1));
10737        assert_eq!(updated.community_root, new_root, "adopted the owner's root, not a junk one");
10738    }
10739
10740    #[tokio::test]
10741    async fn a_swap_during_create_private_channel_aborts_without_a_write() {
10742        // create_private_channel publishes the key crate, then the channel
10743        // edition, then whole-row-saves. A swap anywhere in that window must
10744        // abort — never mint a channel into the swapped-in account, and never
10745        // leave a half-published key crate adopted locally.
10746        let (bed, owner, _member) = TestBed::new();
10747        bed.swap_to(&owner);
10748        let community = create_community(&bed.relay, "SwapCreate", bed.relays.clone(), None).await.unwrap();
10749        let before = crate::db::community::load_community_v2(community.id()).unwrap().unwrap().channels.len();
10750
10751        // The key-crate publish inside create bumps the generation mid-flight.
10752        let swap_relay = SwapMidPublish { inner: MemoryRelay::new() };
10753        let err = create_private_channel(&swap_relay, &community, "ghost").await.unwrap_err();
10754        assert!(err.contains("account changed"), "a swap mid-create aborts: {err}");
10755        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10756        assert_eq!(after.channels.len(), before, "no channel row was written");
10757        assert!(!after.channels.iter().any(|c| c.name == "ghost"), "the ghost channel never persisted");
10758    }
10759
10760    #[tokio::test]
10761    async fn an_uncited_admin_rotation_is_not_adopted() {
10762        // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
10763        // authority action, so a just-demoted admin's rotation is never honored by
10764        // a lagging client." An uncited rotation is skipped entirely — neither
10765        // adopted nor allowed to conclude a removal.
10766        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10767        let (_tmp, _guard, _owner) = init_test_db();
10768        let relay = MemoryRelay::new();
10769        let mut community = create_community(&relay, "Uncited", vec!["wss://r".into()], None).await.unwrap();
10770        let priv_id = ChannelId([0x8A; 32]);
10771        let key1 = [0x93; 32];
10772        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10773
10774        let admin = Keys::generate();
10775        let role = Role::admin("cf".repeat(32));
10776        let roster = CommunityRoles {
10777            roles: vec![role.clone()],
10778            grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
10779        };
10780        seed_roster_with_heads(&community, &roster, 1_000);
10781
10782        let key2 = [0x94; 32];
10783        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10784        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10785        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
10786        let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10787        // Authorized admin, correct continuity, my blob present — but NO citation.
10788        for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, None).unwrap() {
10789            relay.publish(&e, &community.relays).await.unwrap();
10790        }
10791
10792        let out = follow_rekeys(&relay, &community, &SessionGuard::capture()).await.unwrap();
10793        assert!(out.updated.is_none(), "an uncited rotation is not adopted");
10794
10795        // The SAME rotation, cited, is adopted — proving the refusal was the
10796        // citation and not the rank or the continuity.
10797        let cited = my_authority_citation(&community, &admin.public_key());
10798        assert!(cited.is_some(), "the seeded head yields a citation");
10799        let blob2 = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10800        for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob2], 2_100, cited.as_ref()).unwrap() {
10801            relay.publish(&e, &community.relays).await.unwrap();
10802        }
10803        let out = follow_rekeys(&relay, &community, &SessionGuard::capture()).await.unwrap();
10804        assert!(out.updated.is_some(), "the cited rotation IS adopted");
10805    }
10806
10807    #[tokio::test]
10808    async fn two_admins_racing_a_channel_rotation_converge_on_one_key() {
10809        // CORD-06 §Failure-and-races: two DISTINCT authorized rotators mint the
10810        // same channel epoch concurrently (reachable — both hold MANAGE_CHANNELS).
10811        // Every follower must converge on the SAME key (the lexicographically
10812        // lowest), so the community never permanently forks. (Retaining the losing
10813        // fork's key for its race-window messages needs a multi-key-per-epoch
10814        // archive — a deferred refinement shared with v1; convergence, the
10815        // security-critical property, is what this pins.)
10816        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10817        let (_tmp, _guard, _owner) = init_test_db();
10818        let relay = MemoryRelay::new();
10819        let mut community = create_community(&relay, "Race", vec!["wss://r".into()], None).await.unwrap();
10820        let priv_id = ChannelId([0xC0; 32]);
10821        let key1 = [0xC1; 32];
10822        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10823
10824        // Two admins (a, b) both hold the Admin role; I hold the channel key.
10825        let (a, b) = (Keys::generate(), Keys::generate());
10826        let role = Role::admin("ce".repeat(32));
10827        let roster = CommunityRoles {
10828            roles: vec![role.clone()],
10829            grants: [&a, &b].iter().map(|k| MemberGrant { member: k.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }).collect(),
10830        };
10831        seed_roster_with_heads(&community, &roster, 1_000);
10832
10833        // Both rotate 1 → 2, each delivering their OWN fresh key to me, off the
10834        // same prevcommit — a genuine same-epoch fork.
10835        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
10836        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10837        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10838        let key_a = [0x0A; 32];
10839        let key_b = [0xFB; 32]; // higher — a's must win regardless of publish order
10840        for (signer, k) in [(&a, &key_a), (&b, &key_b)] {
10841            let blob = rekey::build_blob_local(signer.secret_key(), &signer.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), k).unwrap();
10842            for e in rekey::build_rekey_chunks_local(signer, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, my_authority_citation(&community, &signer.public_key()).as_ref()).unwrap() {
10843                relay.publish(&e, &community.relays).await.unwrap();
10844            }
10845        }
10846
10847        let session = SessionGuard::capture();
10848        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopts a winner");
10849        let adopted = updated.channel(&priv_id).unwrap().key.unwrap();
10850        assert_eq!(adopted, key_a, "converges on the lexicographically lowest key (deterministic across clients)");
10851
10852        // A SECOND follower (fresh, holding the same epoch-1 key) converges identically.
10853        let mut peer = community.clone();
10854        if let Some(c) = peer.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
10855            c.key = Some(key1);
10856            c.epoch = Epoch(1);
10857        }
10858        // Re-run the same fold from the peer's identical starting point → same winner.
10859        let updated2 = follow_rekeys(&relay, &peer, &session).await.unwrap().updated.expect("peer adopts");
10860        assert_eq!(updated2.channel(&priv_id).unwrap().key.unwrap(), key_a, "every follower lands on the identical key");
10861    }
10862
10863    #[tokio::test]
10864    async fn create_private_channel_refuses_a_member_without_manage_channels() {
10865        // The local mirror of the reader's gate: an unauthorized member is refused
10866        // BEFORE any publish (no floor pollution, no orphan key crate).
10867        let (bed, owner, member) = TestBed::new();
10868        bed.swap_to(&owner);
10869        let community = create_community(&bed.relay, "Gate", bed.relays.clone(), None).await.unwrap();
10870        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
10871
10872        bed.swap_to(&member);
10873        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
10874        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
10875        let err = create_private_channel(&bed.relay, &joined, "sneaky").await.unwrap_err();
10876        assert!(err.contains("MANAGE_CHANNELS"), "refused with the permission it lacks: {err}");
10877        let err = create_public_channel(&bed.relay, &joined, "sneaky-too").await.unwrap_err();
10878        assert!(err.contains("MANAGE_CHANNELS"), "public creation gates identically: {err}");
10879    }
10880
10881    // ── Audit regressions ────────────────────────────────────────────────────
10882
10883    #[tokio::test]
10884    async fn accept_rejects_a_bundle_with_a_forged_community_root() {
10885        // The eclipse: community_id commits only to (owner, salt) — both semi-public
10886        // — so a forged invite pairs the REAL triple with an attacker root, and every
10887        // plane derives from it. The join-time owner-genesis check must refuse.
10888        let (bed, owner, member) = TestBed::new();
10889        bed.swap_to(&owner);
10890        let community = create_community(&bed.relay, "Real", bed.relays.clone(), None).await.unwrap();
10891
10892        let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
10893        let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
10894        forged.community_root = fake.clone();
10895        for ch in &mut forged.channels {
10896            ch.key = fake.clone();
10897        }
10898        let attacker = Keys::generate();
10899        let wrap = invite::build_direct_invite(&attacker, &member.keys.public_key(), &forged).unwrap();
10900        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
10901
10902        bed.swap_to(&member);
10903        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
10904        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
10905        assert!(err.contains("could not verify"), "a forged root fails the owner-genesis check: {err}");
10906        assert!(
10907            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
10908            "a rejected join persists nothing"
10909        );
10910    }
10911
10912    #[tokio::test]
10913    async fn accept_verifies_a_rotated_plane_whose_metadata_head_is_admin_signed() {
10914        // CORD-06 compaction re-wraps CURRENT heads with their original signatures,
10915        // so a rotated plane whose metadata an admin last edited carries no
10916        // owner-signed vsk-0. The join anchor there is the community-bound metadata
10917        // head plus any owner-signed edition under the same root.
10918        let (bed, owner, member) = TestBed::new();
10919        bed.swap_to(&owner);
10920        let community = create_community(&bed.relay, "Rotated", bed.relays.clone(), None).await.unwrap();
10921        let general = community.channels[0].id;
10922
10923        let mut rotated = community.clone();
10924        rotated.community_root = [0x5A; 32];
10925        rotated.root_epoch = Epoch(1);
10926        let admin = Keys::generate();
10927        publish_community_meta(&bed.relay, &rotated, &admin, "Rotated", 3).await;
10928        publish_channel_edition(&bed.relay, &rotated, &owner.keys, &general, "general", false, 2, false).await;
10929
10930        bed.swap_to(&member);
10931        let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
10932        let session = SessionGuard::capture();
10933        let joined = accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap();
10934        assert_eq!(joined.root_epoch, Epoch(1), "the rotated root is adopted");
10935    }
10936
10937    #[tokio::test]
10938    async fn only_an_actual_join_publishes_a_guestbook_join() {
10939        // A Guestbook Join is a member's own word that they JOINED. A re-accept of
10940        // a held community and a cross-device key sync (announce_join=false) must
10941        // both stay silent — each re-publish renders as "<user> has joined" spam.
10942        let (bed, owner, member) = TestBed::new();
10943        bed.swap_to(&owner);
10944        let community = create_community(&bed.relay, "Quiet", bed.relays.clone(), None).await.unwrap();
10945
10946        let gb_pk = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk_hex();
10947        async fn gb_count(relay: &MemoryRelay, gb_pk: &str, relays: &[String]) -> usize {
10948            let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb_pk.to_string()], ..Default::default() };
10949            relay.fetch(&q, relays).await.map(|v| v.len()).unwrap_or(0)
10950        }
10951        let baseline = gb_count(&bed.relay, &gb_pk, &bed.relays).await; // the owner's creation Join
10952
10953        bed.swap_to(&member);
10954        let bundle = bundle_of(&community, BundleAudience::Link, None, None, None);
10955        let session = SessionGuard::capture();
10956        accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap();
10957        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a first join announces exactly once");
10958
10959        accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap();
10960        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a re-accept of a held community stays silent");
10961
10962        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10963        crate::db::community::delete_community(&cid_hex).unwrap();
10964        accept_bundle(&bed.relay, &session, &bundle, None, false).await.unwrap();
10965        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a cross-device key sync is not a membership event");
10966    }
10967
10968    #[tokio::test]
10969    async fn accept_refuses_a_rotated_plane_with_no_owner_signed_edition() {
10970        // The fallback's second half is load-bearing: a community-bound metadata
10971        // head alone is self-signable by anyone who knows the (public) community_id.
10972        let (bed, owner, member) = TestBed::new();
10973        bed.swap_to(&owner);
10974        let community = create_community(&bed.relay, "NoOwner", bed.relays.clone(), None).await.unwrap();
10975
10976        let mut rotated = community.clone();
10977        rotated.community_root = [0x5B; 32];
10978        rotated.root_epoch = Epoch(1);
10979        let attacker = Keys::generate();
10980        publish_community_meta(&bed.relay, &rotated, &attacker, "NoOwner", 3).await;
10981
10982        bed.swap_to(&member);
10983        let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
10984        let session = SessionGuard::capture();
10985        let err = accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap_err();
10986        assert!(err.contains("could not verify"), "no owner-signed edition → refuse: {err}");
10987    }
10988
10989    #[tokio::test]
10990    async fn accept_requires_the_strict_owner_genesis_on_an_epoch_zero_plane() {
10991        // The fallback applies to rotated planes only: at epoch 0 the spec guarantees
10992        // an owner-signed genesis, so owner material without it stays insufficient.
10993        let (bed, owner, member) = TestBed::new();
10994        bed.swap_to(&owner);
10995        let community = create_community(&bed.relay, "Strict", bed.relays.clone(), None).await.unwrap();
10996        let general = community.channels[0].id;
10997
10998        let mut fake = community.clone();
10999        fake.community_root = [0x5C; 32]; // epoch stays 0
11000        let admin = Keys::generate();
11001        publish_community_meta(&bed.relay, &fake, &admin, "Strict", 2).await;
11002        publish_channel_edition(&bed.relay, &fake, &owner.keys, &general, "general", false, 2, false).await;
11003
11004        bed.swap_to(&member);
11005        let bundle = bundle_of(&fake, BundleAudience::Link, None, None, None);
11006        let session = SessionGuard::capture();
11007        let err = accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap_err();
11008        assert!(err.contains("could not verify"), "epoch 0 demands the owner genesis: {err}");
11009    }
11010
11011    #[tokio::test]
11012    async fn follow_control_heals_a_bundle_misclassified_public_channel() {
11013        // A bundle can set a PUBLIC channel's grant key to the attacker's, so the
11014        // joiner addresses it at a plane only the attacker reads. The owner's genuine
11015        // public:false edition must override it on follow.
11016        let (_tmp, _guard, _owner) = init_test_db();
11017        let relay = MemoryRelay::new();
11018        let community = create_community(&relay, "Heal", vec!["wss://r".into()], None).await.unwrap();
11019        let general = community.channels[0].id;
11020        let mut poisoned = community.clone();
11021        poisoned.channels[0].private = true;
11022        poisoned.channels[0].key = Some([0x66; 32]);
11023        crate::db::community::save_community_v2(&poisoned).unwrap();
11024
11025        let session = SessionGuard::capture();
11026        let healed = follow_control(&relay, &poisoned, &session).await.unwrap().expect("healed");
11027        let ch = healed.channel(&general).unwrap();
11028        assert!(!ch.private, "the owner's public declaration overrides the bundle");
11029        assert_eq!(ch.key, None, "a healed public channel derives from the root");
11030    }
11031
11032    #[tokio::test]
11033    async fn a_deleted_channel_does_not_resurrect_on_reload() {
11034        // save_community_v2 must prune orphan channel rows, or a control-follow delete
11035        // reappears (with a stale key) on the next reload.
11036        let (_tmp, _guard, owner) = init_test_db();
11037        let relay = MemoryRelay::new();
11038        let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
11039        let extra = ChannelId([0x77; 32]);
11040        let session = SessionGuard::capture();
11041        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
11042        let with_extra = follow_control(&relay, &community, &session).await.unwrap().unwrap();
11043        assert!(with_extra.channel(&extra).is_some());
11044        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
11045        let after = follow_control(&relay, &with_extra, &session).await.unwrap().unwrap();
11046        assert!(after.channel(&extra).is_none());
11047
11048        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
11049        assert!(reloaded.channel(&extra).is_none(), "a deleted channel must not resurrect on reload");
11050        assert_eq!(reloaded.channels.len(), 1);
11051    }
11052
11053    #[tokio::test]
11054    async fn a_channel_owned_by_another_community_is_skipped_not_clobbered() {
11055        // channel_id is the sole DB primary key, so a bundle/replay reusing another
11056        // community's channel_id must NOT overwrite that row. It's skipped (not an
11057        // error — erroring would wedge all of this community's control persistence).
11058        let (_tmp, _guard, _owner) = init_test_db();
11059        let relay = MemoryRelay::new();
11060        let a = create_community(&relay, "A", vec!["wss://r".into()], None).await.unwrap();
11061        let a_channel = a.channels[0].id;
11062        let mut b = create_community(&relay, "B", vec!["wss://r".into()], None).await.unwrap();
11063        let b_channel = b.channels[0].id;
11064        // B's set includes a phantom whose id collides with A's channel.
11065        b.channels.push(ChannelV2 { id: a_channel, name: "phantom".into(), private: false, key: None, epoch: b.root_epoch, voice: None, meta_custom: None, meta_extra: Default::default() });
11066
11067        crate::db::community::save_community_v2(&b).expect("save succeeds, the phantom is skipped");
11068        // A's channel row is untouched.
11069        let a_reloaded = crate::db::community::load_community_v2(a.id()).unwrap().unwrap();
11070        assert!(!a_reloaded.channels.iter().any(|c| c.private), "A's channel is untouched");
11071        assert_eq!(a_reloaded.channels[0].id.0, a_channel.0);
11072        // B keeps its own channel but never acquired a row for the foreign id.
11073        let b_reloaded = crate::db::community::load_community_v2(b.id()).unwrap().unwrap();
11074        assert!(b_reloaded.channel(&b_channel).is_some(), "B's own channel persists");
11075        assert!(b_reloaded.channel(&a_channel).is_none(), "the foreign-owned channel is skipped, not stolen");
11076    }
11077
11078    /// A single relay that CAPS every query below the page size (modelling a real
11079    /// relay's maxFilterLimit) and honors `until` — so the join-verify walk MUST
11080    /// paginate to reach an old genesis. MemoryRelay can't model this (it unions then
11081    /// truncates the whole set), which is why a MemoryRelay flood test gives false
11082    /// confidence about the production `LiveTransport` behaviour.
11083    struct CappedRelay {
11084        events: Vec<Event>,
11085        cap: usize,
11086    }
11087    #[async_trait::async_trait]
11088    impl Transport for CappedRelay {
11089        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
11090        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
11091            Ok(())
11092        }
11093        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
11094            Ok(())
11095        }
11096        async fn fetch(&self, q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
11097            let mut m: Vec<Event> = self
11098                .events
11099                .iter()
11100                .filter(|e| q.authors.is_empty() || q.authors.contains(&e.pubkey.to_hex()))
11101                .filter(|e| q.until.is_none_or(|u| e.created_at.as_secs() <= u))
11102                .cloned()
11103                .collect();
11104            m.sort_by(|a, b| b.created_at.cmp(&a.created_at)); // newest first
11105            m.truncate(self.cap.min(q.limit.unwrap_or(usize::MAX)));
11106            Ok(m)
11107        }
11108    }
11109
11110    #[tokio::test]
11111    async fn refound_aborts_when_the_control_plane_cannot_be_read_in_full() {
11112        // CORD-06 §3: a Refounder that cannot fold every Control Event must abort.
11113        // `until` is inclusive, so a page-wide block of same-second wraps is a wall
11114        // no cursor steps past — everything older (the genesis editions, a Banlist)
11115        // is unreachable. Compacting THAT view carries only what was read into the
11116        // new epoch, dropping the rest for every member, permanently. Any member can
11117        // build the wall: the plane key comes from the community root they hold.
11118        let (_tmp, _guard, _owner) = init_test_db();
11119        let memory = MemoryRelay::new();
11120        let community = create_community(&memory, "Walled", vec!["wss://r".into()], None).await.unwrap();
11121        let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
11122
11123        let rogue = Keys::generate();
11124        let mut events: Vec<Event> = Vec::new();
11125        for i in 0..FOLLOW_PAGE {
11126            let content = format!("{{\"name\":\"junk{i}\",\"private\":false}}");
11127            let rumor = control::build_edition_rumor(
11128                rogue.public_key(),
11129                vsk::CHANNEL_METADATA,
11130                &[0xAB; 32],
11131                1,
11132                None,
11133                &content,
11134                9_000,
11135                None,
11136            );
11137            let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
11138            events.push(w);
11139        }
11140        let relay = CappedRelay { events, cap: FOLLOW_PAGE };
11141
11142        let err = refound_community(&relay, &community, &[])
11143            .await
11144            .expect_err("a plane that can't be read whole must never be compacted");
11145        assert!(err.contains("too deep to read in full"), "unexpected error: {err}");
11146    }
11147
11148    #[tokio::test]
11149    async fn verify_pages_a_capped_relay_past_a_flood_to_the_genesis() {
11150        // The join-verify DoS mitigation, tested against a relay that caps below PAGE
11151        // (production behaviour MemoryRelay hides): a rogue root-holder buries the
11152        // genesis under junk, and the `until`-walk must page past it. Uses fixed OLD
11153        // timestamps so `until = now` includes everything and the walk is deterministic.
11154        let (_tmp, _guard, owner) = init_test_db();
11155        let meta = control::CommunityMetadata { name: "Capped".into(), relays: vec!["wss://r".into()], ..Default::default() };
11156        let g = control::genesis(&owner, meta, 1_000).unwrap();
11157        let community = CommunityV2::from_genesis(&g, "Capped", None, vec!["wss://r".into()], 1_000);
11158
11159        let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
11160        let rogue = Keys::generate();
11161        let mut events: Vec<Event> = g.wraps.to_vec();
11162        for i in 0..250u64 {
11163            let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xAB; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 1_001 + i, None);
11164            let (wrap, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(1_001 + i)).unwrap();
11165            events.push(wrap);
11166        }
11167        // Cap 100/query forces the walk across ~3 pages down to the genesis at ts 1000.
11168        let relay = CappedRelay { events, cap: 100 };
11169        let verified = verify_owner_root_and_reconcile(&relay, community.clone()).await;
11170        assert!(verified.is_ok(), "the until-walk pages a capped relay past the flood to the genesis: {:?}", verified.err());
11171    }
11172
11173    #[tokio::test]
11174    async fn accept_parked_invite_joins_from_the_stored_bundle() {
11175        // The 3313 receive path: an invite is parked as its bundle JSON, then accepted
11176        // from the stored bundle (re-verifying the owner root over the network).
11177        let (bed, owner, member) = TestBed::new();
11178        bed.swap_to(&owner);
11179        let community = create_community(&bed.relay, "Parked", bed.relays.clone(), None).await.unwrap();
11180        let general = community.channels[0].id;
11181        send_message(&bed.relay, &community, &general, "owner: hi").await.unwrap();
11182        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
11183        let bundle_json = serde_json::to_string(&bundle).unwrap();
11184        let inviter_hex = owner.keys.public_key().to_hex();
11185
11186        bed.swap_to(&member);
11187        let joined = accept_parked_invite(&bed.relay, &bundle_json, Some(&inviter_hex)).await.unwrap();
11188        assert_eq!(joined.id().0, community.id().0, "joined the community from the parked bundle");
11189        assert!(joined.identity.verify());
11190        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: hi"]);
11191        // The join seeded the verified fold as the member's initial floor, so their
11192        // first follow can't roll below the state the join just showed.
11193        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
11194        assert!(
11195            crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().is_some(),
11196            "the joiner's control floor is seeded from the join-time fold"
11197        );
11198
11199        // The Guestbook memberlist now folds both participants.
11200        bed.swap_to(&owner);
11201        let members = memberlist(&bed.relay, &community).await.unwrap();
11202        assert!(members.contains(&member.keys.public_key()), "the parked-invite joiner is a member");
11203    }
11204
11205    #[tokio::test]
11206    async fn accept_parked_invite_rejects_a_forged_root() {
11207        // A forged-root parked bundle (real identity triple, attacker-chosen root) fails
11208        // accept — the shared accept path re-verifies the owner root, so a parked invite
11209        // gets the same eclipse protection as a live one.
11210        let (_tmp, _guard, _owner) = init_test_db();
11211        let relay = MemoryRelay::new();
11212        let community = create_community(&relay, "Real", vec!["wss://r".into()], None).await.unwrap();
11213        let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
11214        let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
11215        forged.community_root = fake.clone();
11216        for ch in &mut forged.channels {
11217            ch.key = fake.clone();
11218        }
11219        let bundle_json = serde_json::to_string(&forged).unwrap();
11220
11221        let err = accept_parked_invite(&relay, &bundle_json, None).await.unwrap_err();
11222        assert!(err.contains("could not verify"), "a forged-root parked bundle fails definitively: {err}");
11223    }
11224
11225    #[test]
11226    fn v2_and_v1_bundles_are_distinguishable_by_parse() {
11227        // The protocol discriminator the facade list/accept relies on: a v2 bundle
11228        // (self-certifying: owner + owner_salt + community_root) parses; a v1-shaped
11229        // one does not, so a parked invite routes to the right accept path.
11230        let owner = Keys::generate();
11231        let identity = super::super::control::CommunityIdentity::mint(&owner.public_key());
11232        let hex = crate::simd::hex::bytes_to_hex_32;
11233        let v2 = invite::CommunityInvite {
11234            community_id: hex(&identity.community_id.0),
11235            owner: hex(&identity.owner_xonly),
11236            owner_salt: hex(&identity.owner_salt),
11237            community_root: hex(&[0x11; 32]),
11238            root_epoch: 0,
11239            channels: vec![],
11240            relays: vec!["wss://r".into()],
11241            name: "V2".into(),
11242            icon: None,
11243            expires_at: None,
11244            creator_npub: None,
11245            label: None,
11246            extra: Default::default(),
11247        };
11248        let v2_json = serde_json::to_string(&v2).unwrap();
11249        assert!(invite::CommunityInvite::from_bundle_json(&v2_json).is_ok(), "a real v2 bundle parses");
11250        let v1_like = r#"{"community_id":"aa","name":"X","relays":[]}"#;
11251        assert!(invite::CommunityInvite::from_bundle_json(v1_like).is_err(), "a v1 bundle is not a v2 bundle");
11252    }
11253
11254    #[tokio::test]
11255    async fn verify_rejects_a_cross_community_owner_edition_replay() {
11256        // The eclipse-via-replay: an owner-signed edition from community X (eid == X.id)
11257        // rewrapped onto a FORGED community T's fake control plane must NOT authenticate
11258        // T. T's genesis has eid == T.id, so X's edition — a genuine owner signature but
11259        // a different eid — is not a valid proof of T's root. This is why "any owner
11260        // edition" is unsound and the eid==community_id genesis pin is required.
11261        let (_tmp, _guard, owner) = init_test_db();
11262
11263        // Community X (real), owned by `owner`.
11264        let gx = control::genesis(&owner, control::CommunityMetadata { name: "X".into(), ..Default::default() }, 1_000).unwrap();
11265        let x_control = control_group_key(&gx.community_root, &gx.identity.community_id, Epoch(0));
11266        let (_ed, opened) = control::open_control_edition(&gx.wraps[0], &x_control).unwrap();
11267
11268        // Forged community T: the real owner triple but an ATTACKER-chosen root.
11269        let t_identity = control::CommunityIdentity::mint(&owner.public_key());
11270        let fake_root = [0xEE; 32];
11271        let t = CommunityV2 {
11272            identity: t_identity,
11273            community_root: fake_root,
11274            root_epoch: Epoch(0),
11275            name: "T".into(),
11276            description: None,
11277            icon: None,
11278            banner: None,
11279            meta_custom: None,
11280            meta_extra: Default::default(),
11281            relays: vec!["wss://r".into()],
11282            channels: vec![],
11283            dissolved: false,
11284            created_at_ms: 0,
11285        };
11286        // Rewrap X's owner-signed genesis onto T's fake control plane (the attacker
11287        // controls the fake root, so they can derive its control group key).
11288        let t_control = control_group_key(&fake_root, t.id(), t.root_epoch);
11289        let (replayed, _) = stream::rewrap_seal(&opened.seal, &t_control, Timestamp::from_secs(1_000)).unwrap();
11290        let relay = MemoryRelay::new();
11291        relay.publish(&replayed, &t.relays).await.unwrap();
11292
11293        let verified = verify_owner_root_and_reconcile(&relay, t.clone()).await;
11294        assert!(verified.is_err(), "a cross-community owner-edition replay must not authenticate a forged root");
11295    }
11296
11297    /// LIVE smoke test (network) — ignored by default. Creates a v2 community on a
11298    /// REAL relay via `LiveTransport`, sends a message, fetches it back, and mints
11299    /// a public link. A fresh throwaway identity in an isolated temp data dir, so
11300    /// it never touches real accounts. Run explicitly:
11301    /// ```sh
11302    /// cargo test -p vector-core -- --ignored --nocapture live_smoke
11303    /// ```
11304    #[tokio::test]
11305    #[ignore = "hits a real relay over the network"]
11306    async fn live_smoke_create_send_fetch_on_a_real_relay() {
11307        use crate::community::transport::LiveTransport;
11308        use nostr_sdk::prelude::ToBech32;
11309
11310        let relay = std::env::var("VECTOR_SMOKE_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
11311        let relays = vec![relay.clone()];
11312
11313        // Isolated account + data dir (a fresh throwaway key — never a real account).
11314        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
11315        crate::db::close_database();
11316        crate::db::clear_id_caches();
11317        let tmp = tempfile::tempdir().unwrap();
11318        // Bring your own key (VECTOR_SMOKE_NSEC) to create a community you can log
11319        // into elsewhere; otherwise a fresh throwaway.
11320        let keys = match std::env::var("VECTOR_SMOKE_NSEC") {
11321            Ok(n) => Keys::parse(&n).expect("VECTOR_SMOKE_NSEC is not a valid nsec"),
11322            Err(_) => Keys::generate(),
11323        };
11324        let npub = keys.public_key().to_bech32().unwrap();
11325        // Off by default (never leak secrets from a committed test); set
11326        // VECTOR_SMOKE_PRINT_NSEC=1 to print the owner nsec for cross-client login.
11327        if std::env::var("VECTOR_SMOKE_PRINT_NSEC").is_ok() {
11328            println!("[smoke] OWNER nsec (throwaway — do NOT reuse): {}", keys.secret_key().to_bech32().unwrap());
11329        }
11330        std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
11331        crate::db::set_app_data_dir(tmp.path().to_path_buf());
11332        crate::db::set_current_account(npub.clone()).unwrap();
11333        crate::db::init_database(&npub).unwrap();
11334        crate::state::MY_SECRET_KEY.store_from_keys(&keys, &[]);
11335        crate::state::set_my_public_key(keys.public_key());
11336        println!("[smoke] throwaway identity {npub}");
11337
11338        // A live client (LiveTransport rides the global NOSTR_CLIENT + warms relays).
11339        let client = crate::nostr_client_builder().build();
11340        client.add_managed_relay(relay.as_str()).await.ok();
11341        client.connect().await;
11342        crate::state::set_nostr_client(client);
11343        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
11344
11345        // Create → send → fetch-back → verify.
11346        let community = create_community(&transport, "V2 Live Smoke", relays.clone(), None).await.expect("create");
11347        let general = community.channels[0].id;
11348        println!("[smoke] created community {} on {relay}", crate::simd::hex::bytes_to_hex_32(&community.id().0));
11349
11350        let text = "hello from a Vector Concord v2 live smoke test";
11351        let sent_id = send_message(&transport, &community, &general, text).await.expect("send");
11352        println!("[smoke] sent message {sent_id}");
11353
11354        // Give the relay a moment to store + be ready to serve it.
11355        tokio::time::sleep(std::time::Duration::from_secs(3)).await;
11356
11357        let page = fetch_channel(&transport, &community, &general, 50).await.expect("fetch");
11358        let texts: Vec<String> = page
11359            .iter()
11360            .filter_map(|f| match &f.event {
11361                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
11362                _ => None,
11363            })
11364            .collect();
11365        println!("[smoke] fetched {} message(s) back: {texts:?}", texts.len());
11366        assert!(texts.contains(&text.to_string()), "the message did not round-trip through the real relay");
11367
11368        // Mint a shareable v2 link (the thing a bot hands out).
11369        let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint link");
11370        println!("[smoke] invite link: {}", link.url);
11371        println!("[smoke] PASS — v2 create+send+fetch+invite round-tripped on {relay}");
11372    }
11373
11374    #[tokio::test]
11375    async fn chat_ops_react_edit_delete_round_trip() {
11376        let (bed, owner, _member) = TestBed::new();
11377        bed.swap_to(&owner);
11378        let community = create_community(&bed.relay, "Ops", bed.relays.clone(), None).await.unwrap();
11379        let general = community.channels[0].id;
11380        let me_hex = owner.keys.public_key().to_hex();
11381
11382        let msg_id = send_message(&bed.relay, &community, &general, "original").await.unwrap();
11383        send_reaction(&bed.relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, ":fire:", Some(("fire", "https://e/f.png")))
11384            .await
11385            .unwrap();
11386        send_edit(&bed.relay, &community, &general, &msg_id, "edited").await.unwrap();
11387        send_delete(&bed.relay, &community, &general, &msg_id, super::super::kind::MESSAGE).await.unwrap();
11388
11389        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11390        let target = crate::simd::hex::hex_to_bytes_32(&msg_id);
11391        let mut saw = (false, false, false);
11392        for f in &page {
11393            match &f.event {
11394                ChatEvent::Reaction { target: t, emoji, emoji_url, .. } if *t == target => {
11395                    assert_eq!(emoji, ":fire:");
11396                    assert_eq!(emoji_url.as_deref(), Some("https://e/f.png"));
11397                    saw.0 = true;
11398                }
11399                ChatEvent::Edit { target: t, new_content, .. } if *t == target => {
11400                    assert_eq!(new_content, "edited");
11401                    saw.1 = true;
11402                }
11403                ChatEvent::Delete { target: t, .. } if *t == target => saw.2 = true,
11404                _ => {}
11405            }
11406        }
11407        assert!(saw.0 && saw.1 && saw.2, "reaction/edit/delete all round-trip: {saw:?}");
11408    }
11409
11410    #[tokio::test]
11411    async fn a_typing_signal_rides_the_ephemeral_wrap_and_is_never_stored() {
11412        let (bed, owner, _member) = TestBed::new();
11413        bed.swap_to(&owner);
11414        let community = create_community(&bed.relay, "Typ", bed.relays.clone(), None).await.unwrap();
11415        let general = community.channels[0].id;
11416        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
11417
11418        // A live subscriber sees the 21059 wrap and it opens as Typing…
11419        let mut sub = bed.relay.subscribe(Query {
11420            kinds: vec![stream::KIND_WRAP_EPHEMERAL],
11421            authors: vec![group.pk_hex()],
11422            ..Default::default()
11423        });
11424        send_typing(&bed.relay, &community, &general).await.unwrap();
11425        let wrap = sub.try_recv().expect("the typing wrap streams to a live subscriber");
11426        let opened = match chat::open_chat_event(&wrap, &group, &general, community.root_epoch) {
11427            Ok(ChatEvent::Typing { opened }) => opened,
11428            other => panic!("the ephemeral wrap must open as a Typing event, got {other:?}"),
11429        };
11430
11431        // …while nothing durable is stored (relays never keep the ephemeral tier),
11432        // so channel history stays free of typing noise…
11433        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11434        assert!(page.iter().all(|f| !matches!(f.event, ChatEvent::Typing { .. })));
11435
11436        // …and no scrub key is retained (there is no durable wrap to ever delete).
11437        assert!(
11438            crate::db::community::get_message_key(&opened.rumor_id.to_hex()).unwrap().is_none(),
11439            "ephemeral sends must not retain scrub keys"
11440        );
11441    }
11442
11443    #[tokio::test]
11444    async fn a_durable_send_retains_the_wrap_scrub_key_and_full_delete_nukes_the_relay_copy() {
11445        let (bed, owner, _member) = TestBed::new();
11446        bed.swap_to(&owner);
11447        let community = create_community(&bed.relay, "Nuke", bed.relays.clone(), None).await.unwrap();
11448        let general = community.channels[0].id;
11449        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
11450
11451        let id = send_message(&bed.relay, &community, &general, "scrub me").await.unwrap();
11452
11453        // Retained: the row maps the rumor id to the exact published wrap, holds the
11454        // key that SIGNED that wrap (same-author NIP-09), and the relay set.
11455        let (keys, outer_hex, relays) =
11456            crate::db::community::get_message_key(&id).unwrap().expect("a durable send retains its scrub key");
11457        assert_eq!(relays, community.relays);
11458        let wrap_query = Query {
11459            kinds: vec![stream::KIND_WRAP],
11460            authors: vec![group.pk_hex()],
11461            ..Default::default()
11462        };
11463        let wraps = bed.relay.fetch(&wrap_query, &community.relays).await.unwrap();
11464        let wrap = wraps.iter().find(|w| w.id.to_hex() == outer_hex).expect("retained outer id is the published wrap");
11465        assert_eq!(keys.public_key(), wrap.pubkey, "retained key is the wrap's author");
11466
11467        // Reactions ride the same retention (revoke_reaction's relay-nuke layer).
11468        let me_hex = owner.keys.public_key().to_hex();
11469        let rid = send_reaction(&bed.relay, &community, &general, &id, &me_hex, super::super::kind::MESSAGE, "🔥", None)
11470            .await
11471            .unwrap();
11472        assert!(crate::db::community::get_message_key(&rid).unwrap().is_some(), "reaction sends retain too");
11473
11474        // The shared v1 delete path (Layer 1 of delete_community_message / revoke_reaction)
11475        // scrubs the wrap off the relay via the retained key, then consumes the row.
11476        crate::community::service::delete_message(&bed.relay, &id).await.unwrap();
11477        assert!(crate::db::community::get_message_key(&id).unwrap().is_none(), "key consumed after the scrub");
11478        let after = bed.relay.fetch(&wrap_query, &community.relays).await.unwrap();
11479        assert!(!after.iter().any(|w| w.id.to_hex() == outer_hex), "wrap scrubbed from the relay");
11480    }
11481
11482    #[tokio::test]
11483    async fn backfill_heals_scrub_keys_for_own_pre_retention_messages_only() {
11484        let (bed, owner, _member) = TestBed::new();
11485        bed.swap_to(&owner);
11486        let community = create_community(&bed.relay, "Heal", bed.relays.clone(), None).await.unwrap();
11487        let general = community.channels[0].id;
11488        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
11489
11490        // Simulate a pre-retention / other-device send: our message on the relay,
11491        // but no local mapping row.
11492        let id = send_message(&bed.relay, &community, &general, "old send").await.unwrap();
11493        crate::db::community::delete_message_key(&id).unwrap();
11494        assert!(crate::db::community::get_message_key(&id).unwrap().is_none());
11495
11496        // A stranger member's message rides the same channel.
11497        let mkeys = Keys::generate();
11498        let rumor = chat::build_message_rumor(mkeys.public_key(), &general, community.root_epoch, "foreign", None, &[], vec![], 6_000);
11499        let foreign_id = rumor.id.unwrap().to_hex();
11500        let (fw, _) = chat::seal_chat_rumor(&rumor, &group, &mkeys, Timestamp::from_secs(6), false).unwrap();
11501        bed.relay.publish(&fw, &community.relays).await.unwrap();
11502
11503        // One history open re-derives the mapping for the OWN message…
11504        fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11505        let (keys, _outer, relays) =
11506            crate::db::community::get_message_key(&id).unwrap().expect("backfill heals own unretained rows");
11507        assert_eq!(keys.public_key(), group.pk(), "healed key is the wrap's signing key");
11508        assert_eq!(relays, community.relays);
11509
11510        // …and never manufactures one for a foreign author.
11511        assert!(crate::db::community::get_message_key(&foreign_id).unwrap().is_none());
11512
11513        // The healed row is a working full delete: the shared path scrubs the wrap.
11514        crate::community::service::delete_message(&bed.relay, &id).await.unwrap();
11515        let left = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11516        assert!(
11517            !left.iter().any(|f| f.event.opened().rumor_id.to_hex() == id),
11518            "healed message scrubbed from the relay"
11519        );
11520    }
11521
11522    #[tokio::test]
11523    async fn send_chat_message_threads_the_reply_and_extra_tags() {
11524        let (bed, owner, _member) = TestBed::new();
11525        bed.swap_to(&owner);
11526        let community = create_community(&bed.relay, "Re", bed.relays.clone(), None).await.unwrap();
11527        let general = community.channels[0].id;
11528        let me_hex = owner.keys.public_key().to_hex();
11529
11530        let parent_id = send_message(&bed.relay, &community, &general, "parent").await.unwrap();
11531        let imeta = nostr_sdk::prelude::Tag::custom(
11532            "imeta",
11533            ["url https://e/blob".to_string(), "m image/png".to_string()],
11534        );
11535        let child_id = send_chat_message(
11536            &bed.relay, &community, &general, "child",
11537            Some((parent_id.as_str(), me_hex.as_str())), &[], vec![imeta],
11538        )
11539        .await
11540        .unwrap();
11541
11542        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11543        let child = page
11544            .iter()
11545            .find_map(|f| match &f.event {
11546                ChatEvent::Message { opened, reply_to, .. } if opened.rumor_id.to_hex() == child_id => Some((opened, reply_to)),
11547                _ => None,
11548            })
11549            .expect("the reply message round-trips");
11550        let reply = child.1.as_ref().expect("the reply reference is carried");
11551        assert_eq!(crate::simd::hex::bytes_to_hex_32(&reply.id), parent_id);
11552        assert_eq!(reply.author, Some(owner.keys.public_key()));
11553        assert!(
11554            child.0.rumor.tags.iter().any(|t| t.kind() == "imeta"),
11555            "the imeta attachment tag rides the rumor verbatim"
11556        );
11557    }
11558
11559    #[tokio::test]
11560    async fn a_kick_needs_kick_authority_and_removes_the_target() {
11561        let (bed, owner, member) = TestBed::new();
11562        bed.swap_to(&owner);
11563        let community = create_community(&bed.relay, "Kick", bed.relays.clone(), None).await.unwrap();
11564
11565        // The target announces a Join (as an accepted invite would).
11566        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
11567        let join = guestbook::build_join_rumor(member.keys.public_key(), None, 2_000);
11568        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(2)).unwrap();
11569        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
11570        let before = memberlist(&bed.relay, &community).await.unwrap();
11571        assert!(before.contains(&member.keys.public_key()), "the join lands first");
11572
11573        // An unprivileged member's kick of the owner is refused locally…
11574        bed.swap_to(&member);
11575        let err = kick_member(&bed.relay, &community, &owner.keys.public_key()).await.unwrap_err();
11576        assert!(err.contains("not authorized"), "unprivileged kick refused: {err}");
11577
11578        // …and the owner (supreme, no grant needed) kicks the member out.
11579        bed.swap_to(&owner);
11580        kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11581        let after = memberlist(&bed.relay, &community).await.unwrap();
11582        assert!(!after.contains(&member.keys.public_key()), "the kicked member leaves the fold");
11583        assert!(after.contains(&owner.keys.public_key()), "the owner remains");
11584    }
11585
11586    #[tokio::test]
11587    async fn a_rejoin_survives_a_stale_kick_and_an_uncaught_up_store() {
11588        // The self-eviction race: on a REJOIN the guestbook store starts empty while the
11589        // control fold has already re-derived the member's old ban mark, so the MEMBERLIST
11590        // legitimately excludes them for that window. A stale Kick landing there used to
11591        // read as an authorized eviction and the client nuked its own community.
11592        let (bed, owner, member) = TestBed::new();
11593        bed.swap_to(&owner);
11594        let community = create_community(&bed.relay, "Rejoin", bed.relays.clone(), None).await.unwrap();
11595        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11596        let (o, m) = (owner.keys.public_key(), member.keys.public_key());
11597        let join = |at: u64, id: u8| guestbook::GuestbookEvent {
11598            rumor_id: [id; 32],
11599            entry: guestbook::GuestbookEntry::Join { member: m, invited_by: None, at_ms: at },
11600        };
11601        let kick = |at: u64, id: u8| guestbook::GuestbookEvent {
11602            rumor_id: [id; 32],
11603            entry: guestbook::GuestbookEntry::Kick { actor: o, target: m, citation: None, at_ms: at },
11604        };
11605
11606        // An authorized kick after their join stands.
11607        crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2)], 2).unwrap();
11608        assert!(stored_kick_verdict(&community, &m), "an authorized kick after the join is honored");
11609
11610        // A rejoin supersedes it — latest entry wins (CORD-02 §5).
11611        crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2), join(3_000, 3)], 3).unwrap();
11612        assert!(!stored_kick_verdict(&community, &m), "a Join newer than the kick clears the verdict");
11613
11614        // The catch-up window itself: nothing folded yet decides nothing.
11615        crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
11616        assert!(!stored_kick_verdict(&community, &m), "an empty store is not an eviction");
11617
11618        // And the memberlist is NOT a substitute: with the store empty it excludes them,
11619        // which is exactly the false positive this verdict replaced.
11620        assert!(
11621            !stored_memberlist(&community).unwrap().contains(&m),
11622            "the memberlist excludes an un-caught-up member — why it can't gate a kick"
11623        );
11624    }
11625
11626    /// Seed a roster the way production does: `follow_control` writes the roster
11627    /// AND the folded edition heads in one pass, so a citation against a grant is
11628    /// resolvable. Seeding the roster alone yields a client that can never satisfy
11629    /// any `vac` — a shape no v2 production path produces.
11630    fn seed_roster_with_heads(community: &CommunityV2, roster: &crate::community::roles::CommunityRoles, at: i64) {
11631        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11632        crate::db::community::set_community_roles(&cid_hex, roster, at).unwrap();
11633        for g in &roster.grants {
11634            let Some(m) = crate::simd::hex::hex_to_bytes_32_checked(&g.member) else { continue };
11635            let eid = super::super::derive::grant_locator(community.id(), &m);
11636            let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
11637            crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, 1, &[0xA1; 32], &[0xA2; 32], community.root_epoch.0).unwrap();
11638        }
11639    }
11640
11641    /// Publish an edition CITING a specific grant version (CORD-04 §5's `vac`).
11642    async fn publish_grant_citing(
11643        relay: &MemoryRelay,
11644        community: &CommunityV2,
11645        signer: &Keys,
11646        member: &PublicKey,
11647        role_ids: Vec<String>,
11648        version: u64,
11649        citation: Option<&crate::community::edition::AuthorityCitation>,
11650    ) {
11651        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
11652        let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
11653        let prev = head_hash_on_relay(relay, community, &eid).await;
11654        let grant = MemberGrant { member: member.to_hex(), role_ids };
11655        let content = crate::community::v2::roles::grant_content_json(&grant).unwrap();
11656        let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, citation);
11657        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
11658        relay.publish(&wrap, &community.relays).await.unwrap();
11659    }
11660
11661    #[tokio::test]
11662    async fn an_uncited_admin_edition_is_not_folded_but_a_cited_one_is() {
11663        // CORD-04 §5 on the CONTROL PLANE: "a verifier won't act on the edition
11664        // until it has synced at least that Grant". The citation resolves against
11665        // the heads THIS fold accepted — an external floor would refuse every
11666        // non-owner edition on a bootstrap and the roster could never fold.
11667        let (bed, owner, admin) = TestBed::new();
11668        bed.swap_to(&owner);
11669        let community = create_community(&bed.relay, "Cited", bed.relays.clone(), None).await.unwrap();
11670        let admin_pk = admin.keys.public_key();
11671        let rid = "c3".repeat(32);
11672        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::admin().0), 1).await;
11673        publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![rid.clone()], 1).await;
11674
11675        // The admin grants a bystander, citing NOTHING.
11676        // A LOWER role (position 5) — an admin at position 1 may grant beneath
11677        // themselves but never at their own rank (equal cannot act on equal).
11678        let low_rid = "c4".repeat(32);
11679        let mut low = admin_role(&low_rid, Permissions::admin().0);
11680        low.position = 5;
11681        publish_role(&bed.relay, &community, &owner.keys, &low, 1).await;
11682
11683        let bystander = Keys::generate().public_key();
11684        publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![low_rid.clone()], 1, None).await;
11685        let view = fetch_authority(&bed.relay, &community).await;
11686        assert!(
11687            !view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
11688            "an uncited non-owner edition is not folded"
11689        );
11690        // The owner's own editions still fold — supreme cites nothing.
11691        assert!(view.roles.is_admin(&admin_pk.to_hex()), "the owner-authored grant folds");
11692
11693        // Same edition, now citing the admin's real grant: honored. (follow_control
11694        // is what PERSISTS the folded heads a citation is built from.)
11695        let _ = follow_control(&bed.relay, &community, &SessionGuard::capture()).await;
11696        let entity_id = crate::community::v2::derive::grant_locator(community.id(), &admin_pk.to_bytes());
11697        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11698        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
11699        let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex).unwrap().unwrap();
11700        let cite = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
11701        publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![low_rid], 2, Some(&cite)).await;
11702
11703        let view = fetch_authority(&bed.relay, &community).await;
11704        assert!(
11705            view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
11706            "the same edition WITH its synced citation folds"
11707        );
11708    }
11709
11710    #[tokio::test]
11711    async fn a_join_landing_inside_the_ban_window_survives_the_unban() {
11712        // The invite is deliberately ungated, so a fresh Join can arrive seconds
11713        // BEFORE the unban edition. It must reach the store (banned = a fold
11714        // verdict, not a storage verdict) so the unban resurrects the member —
11715        // dropped at ingest, they stayed invisible forever.
11716        let (bed, owner, member) = TestBed::new();
11717        bed.swap_to(&owner);
11718        let community = create_community(&bed.relay, "Window", bed.relays.clone(), None).await.unwrap();
11719        let member_pk = member.keys.public_key();
11720        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11721
11722        // Locally banned (edition folded at t=1000s), with the outliving mark.
11723        crate::db::community::set_community_banlist(&cid_hex, &[member_pk.to_hex()], 1_000).unwrap();
11724        crate::db::community::merge_community_ban_marks(&cid_hex, &[(member_pk.to_hex(), 1_000u64)].into_iter().collect()).unwrap();
11725
11726        // Their Join lands 60s after the ban mark, while the banlist still says banned.
11727        let join = guestbook::GuestbookEvent {
11728            rumor_id: [9u8; 32],
11729            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_060_000 },
11730        };
11731        assert!(ingest_guestbook_event(&community, join, 1_060).unwrap(), "stored while banned");
11732        assert!(
11733            !stored_memberlist(&community).unwrap().contains(&member_pk),
11734            "while banned, the fold keeps them out"
11735        );
11736
11737        // The unban folds: same store, no refetch needed — the Join resurrects them.
11738        crate::db::community::set_community_banlist(&cid_hex, &[], 2_000).unwrap();
11739        assert!(
11740            stored_memberlist(&community).unwrap().contains(&member_pk),
11741            "after the unban the raced Join makes them a member again"
11742        );
11743    }
11744
11745    #[tokio::test]
11746    async fn a_stale_root_admin_write_is_refused_not_misdirected() {
11747        // The ban→unban race: a Ban's refound buries the old root over several
11748        // publishes while a concurrently-issued command still holds the
11749        // pre-commit struct. That unban used to land on the buried control
11750        // plane — "succeeding" while no reader would ever fold it — and a
11751        // concurrently-minted invite stranded its joiner on the dead epoch.
11752        let (bed, owner, member) = TestBed::new();
11753        bed.swap_to(&owner);
11754        let community = create_community(&bed.relay, "Race", bed.relays.clone(), None).await.unwrap();
11755        let member_pk = member.keys.public_key();
11756
11757        set_banlist(&bed.relay, &community, &[member_pk.to_hex()]).await.unwrap();
11758        let _rotated = refound_community(&bed.relay, &community, &[member_pk]).await.unwrap();
11759
11760        // The stale-struct unban is REFUSED (retryable), never misdirected.
11761        let err = set_banlist(&bed.relay, &community, &[]).await.unwrap_err();
11762        assert!(err.contains("re-founded"), "unban: {err}");
11763        // A stale invite must not mint dead-epoch key material.
11764        let err = send_direct_invite(&bed.relay, &community, &member_pk, None, None).await.unwrap_err();
11765        assert!(err.contains("re-founded"), "invite: {err}");
11766        // Neither is a kick allowed to ride the buried guestbook.
11767        let err = kick_member(&bed.relay, &community, &member_pk).await.unwrap_err();
11768        assert!(err.contains("re-founded"), "kick: {err}");
11769
11770        // The retry path: a fresh load lands the unban on the LIVING plane.
11771        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
11772        set_banlist(&bed.relay, &fresh, &[]).await.unwrap();
11773        let view = fetch_authority(&bed.relay, &fresh).await;
11774        assert!(view.banned.is_empty(), "the retried unban actually unbans");
11775    }
11776
11777    #[tokio::test]
11778    async fn an_uncited_kick_from_an_admin_is_not_honored() {
11779        // CORD-04 §5: a non-owner authority action must name the Grant it acts
11780        // under, and the reader refuses until it holds that Grant. Emitting the
11781        // `vac` without checking it buys nothing — a demoted admin's kick would
11782        // still land on any client that hadn't synced the demotion.
11783        let (bed, owner, member) = TestBed::new();
11784        bed.swap_to(&owner);
11785        let community = create_community(&bed.relay, "Uncited", bed.relays.clone(), None).await.unwrap();
11786        let admin = Keys::generate();
11787        let member_pk = member.keys.public_key();
11788        grant_admin(&bed.relay, &community, &admin.public_key()).await.unwrap();
11789
11790        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11791        let view = fetch_authority(&bed.relay, &community).await;
11792        crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();
11793
11794        let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
11795        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
11796        let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex).unwrap().unwrap();
11797        let cite = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
11798
11799        let joined = guestbook::GuestbookEvent {
11800            rumor_id: [1u8; 32],
11801            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_000 },
11802        };
11803        let kick = |citation, id: u8, at| guestbook::GuestbookEvent {
11804            rumor_id: [id; 32],
11805            entry: guestbook::GuestbookEntry::Kick { actor: admin.public_key(), target: member_pk, citation, at_ms: at },
11806        };
11807        let roles = crate::db::community::get_community_roles(&cid_hex).unwrap();
11808        let empty_bans = std::collections::BTreeSet::new();
11809        let empty_marks = std::collections::BTreeMap::new();
11810        let fold = |evs: &[guestbook::GuestbookEvent]| {
11811            fold_members(&community, evs, Default::default(), &roles, &empty_bans, &empty_marks).unwrap()
11812        };
11813
11814        assert!(
11815            fold(&[joined.clone(), kick(None, 2, 2_000)]).contains(&member_pk),
11816            "an uncited kick from an admin is not honored"
11817        );
11818        assert!(
11819            !fold(&[joined, kick(Some(cite), 3, 3_000)]).contains(&member_pk),
11820            "the same kick WITH its synced citation removes them"
11821        );
11822    }
11823
11824    #[tokio::test]
11825    async fn kicking_an_admin_strips_their_roles_first() {
11826        // CORD-04 §6 composition: Role Removal THEN the directive. Kicking without the
11827        // strip leaves the target out of the memberlist but still holding every
11828        // management bit, so every client keeps honoring their control editions.
11829        let (bed, owner, member) = TestBed::new();
11830        bed.swap_to(&owner);
11831        let community = create_community(&bed.relay, "Compose", bed.relays.clone(), None).await.unwrap();
11832        let member_pk = member.keys.public_key();
11833        let member_hex = member_pk.to_hex();
11834        let owner_hex = owner.keys.public_key().to_hex();
11835
11836        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11837        assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member_hex));
11838
11839        kick_member(&bed.relay, &community, &member_pk).await.unwrap();
11840
11841        let view = fetch_authority(&bed.relay, &community).await;
11842        assert!(!view.roles.is_admin(&member_hex), "the kick stripped their rank");
11843        assert!(
11844            !view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES),
11845            "a kicked admin holds no bit"
11846        );
11847        assert!(
11848            !memberlist(&bed.relay, &community).await.unwrap().contains(&member_pk),
11849            "and the directive still removed them"
11850        );
11851    }
11852
11853    #[tokio::test]
11854    async fn grant_admin_mints_one_deterministic_role_and_revoke_strips_it() {
11855        let (bed, owner, member) = TestBed::new();
11856        bed.swap_to(&owner);
11857        let community = create_community(&bed.relay, "Adm", bed.relays.clone(), None).await.unwrap();
11858        let member_pk = member.keys.public_key();
11859        let member_hex = member_pk.to_hex();
11860        let owner_hex = owner.keys.public_key().to_hex();
11861
11862        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11863        let view = fetch_authority(&bed.relay, &community).await;
11864        assert!(view.roles.is_admin(&member_hex), "the grant folds as admin");
11865        assert!(view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES));
11866
11867        // A second grant (any device) converges on the SAME role entity — and a
11868        // repeat is a no-op, not a version bump.
11869        let second = Keys::generate().public_key();
11870        grant_admin(&bed.relay, &community, &second).await.unwrap();
11871        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11872        let view = fetch_authority(&bed.relay, &community).await;
11873        assert_eq!(view.roles.roles.len(), 1, "one Admin role, never a fork");
11874        assert!(view.roles.is_admin(&member_hex) && view.roles.is_admin(&second.to_hex()));
11875        let grant = view.roles.grants.iter().find(|g| g.member == member_hex).unwrap();
11876        assert_eq!(grant.role_ids.len(), 1, "no duplicate role id in the grant");
11877
11878        // Revoke strips ONLY the admin role and de-authorizes.
11879        revoke_admin(&bed.relay, &community, &member_pk).await.unwrap();
11880        let view = fetch_authority(&bed.relay, &community).await;
11881        assert!(!view.roles.is_admin(&member_hex), "revoked");
11882        assert!(view.roles.is_admin(&second.to_hex()), "the other admin is untouched");
11883        assert!(!view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::KICK));
11884    }
11885
11886    #[tokio::test]
11887    async fn follow_control_persists_the_roster_for_sync_local_reads() {
11888        let (bed, owner, member) = TestBed::new();
11889        bed.swap_to(&owner);
11890        let community = create_community(&bed.relay, "Persist", bed.relays.clone(), None).await.unwrap();
11891        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11892        let member_hex = member.keys.public_key().to_hex();
11893        grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11894
11895        // The passive follow folds + persists; the read is then LOCAL (v1 parity).
11896        let session = crate::state::SessionGuard::capture();
11897        follow_control(&bed.relay, &community, &session).await.unwrap();
11898        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
11899        assert!(roster.is_admin(&member_hex), "the persisted roster reads back without a fetch");
11900
11901        // A withholding relay serves nothing — an empty fold raises no gap flag, and
11902        // the stored roster must be RETAINED, never wiped.
11903        let withholding = MemoryRelay::new();
11904        let _ = follow_control(&withholding, &community, &session).await;
11905        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
11906        assert!(roster.is_admin(&member_hex), "withholding never shrinks standing");
11907
11908        // A real revocation (a NEWER grant edition) does replace it.
11909        revoke_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11910        follow_control(&bed.relay, &community, &session).await.unwrap();
11911        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
11912        assert!(!roster.is_admin(&member_hex), "the revoke folds + persists");
11913    }
11914
11915    #[tokio::test]
11916    async fn grant_admin_is_refused_for_a_non_owner_and_publishes_nothing() {
11917        let (bed, owner, member) = TestBed::new();
11918        bed.swap_to(&owner);
11919        let community = create_community(&bed.relay, "NoSquat", bed.relays.clone(), None).await.unwrap();
11920
11921        bed.swap_to(&member);
11922        let err = grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap_err();
11923        assert!(err.contains("owner"), "refused before any publish: {err}");
11924
11925        // The deterministic admin-role entity stays unsquatted — the owner's later
11926        // legitimate mint is version 1 and folds cleanly.
11927        bed.swap_to(&owner);
11928        let view = fetch_authority(&bed.relay, &community).await;
11929        assert!(view.roles.roles.is_empty(), "no role edition landed");
11930        grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11931        let view = fetch_authority(&bed.relay, &community).await;
11932        assert!(view.roles.is_admin(&member.keys.public_key().to_hex()));
11933    }
11934
11935    #[tokio::test]
11936    async fn grant_admin_merges_other_roles_and_refuses_a_withheld_grant() {
11937        let (bed, owner, member) = TestBed::new();
11938        bed.swap_to(&owner);
11939        let community = create_community(&bed.relay, "Merge", bed.relays.clone(), None).await.unwrap();
11940        let member_pk = member.keys.public_key();
11941
11942        // The member already holds a Mod role, granted through the real send path
11943        // (so this device's floors track both entities).
11944        let mod_rid = crate::simd::hex::bytes_to_hex_32(&[0x66; 32]);
11945        set_role(&bed.relay, &community, &admin_role(&mod_rid, Permissions::BAN)).await.unwrap();
11946        grant_roles(&bed.relay, &community, &member_pk, vec![mod_rid.clone()]).await.unwrap();
11947
11948        // A relay that withholds the control plane must refuse the merge — a blind
11949        // push would erase the Mod role at a higher version.
11950        let withholding = MemoryRelay::new();
11951        let err = grant_admin(&withholding, &community, &member_pk).await.unwrap_err();
11952        assert!(err.contains("could not be fetched"), "withheld grant refused: {err}");
11953
11954        // Against the full relay the merge preserves the Mod role.
11955        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11956        let view = fetch_authority(&bed.relay, &community).await;
11957        let grant = view.roles.grants.iter().find(|g| g.member == member_pk.to_hex()).unwrap();
11958        assert_eq!(grant.role_ids.len(), 2, "admin ADDED to the existing grant, not replacing it");
11959        assert!(grant.role_ids.contains(&mod_rid));
11960    }
11961
11962    #[tokio::test]
11963    async fn fetch_authority_reflects_a_granted_admin() {
11964        let (bed, owner, member) = TestBed::new();
11965        bed.swap_to(&owner);
11966        let community = create_community(&bed.relay, "Auth", bed.relays.clone(), None).await.unwrap();
11967        let rid = crate::simd::hex::bytes_to_hex_32(&[0x5a; 32]);
11968        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
11969        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
11970
11971        let view = fetch_authority(&bed.relay, &community).await;
11972        let member_hex = member.keys.public_key().to_hex();
11973        assert!(view.roles.is_admin(&member_hex), "the granted member folds as admin");
11974        assert!(
11975            view.roles.is_authorized(&member_hex, Some(&owner.keys.public_key().to_hex()), Permissions::KICK),
11976            "an ADMIN_ALL grant carries KICK"
11977        );
11978        assert!(view.banned.is_empty());
11979    }
11980}