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        .filter_map(|c| {
2767            c.key.map(|k| super::list::ChannelKeyRef { id: hex(&c.id.0), key: hex(&k), epoch: c.epoch.0, name: c.name.clone() })
2768        })
2769        .collect();
2770    super::list::JoinMaterial {
2771        community_id: hex(&community.identity.community_id.0),
2772        owner: hex(&community.identity.owner_xonly),
2773        owner_salt: hex(&community.identity.owner_salt),
2774        community_root: hex(&community.community_root),
2775        root_epoch: community.root_epoch.0,
2776        channels,
2777        relays: community.relays.clone(),
2778        name: community.name.clone(),
2779        extra: Default::default(),
2780    }
2781}
2782
2783/// Rebuild an invite bundle from list join material, for a cross-device rehydrate
2784/// (the material IS the membership subset of a bundle). The owner root is still
2785/// verified over the network before the community is trusted (accept_bundle).
2786fn material_to_invite(jm: &super::list::JoinMaterial) -> CommunityInvite {
2787    let channels = jm
2788        .channels
2789        .iter()
2790        .map(|c| invite::ChannelGrant { id: c.id.clone(), key: c.key.clone(), epoch: c.epoch, name: c.name.clone() })
2791        .collect();
2792    CommunityInvite {
2793        community_id: jm.community_id.clone(),
2794        owner: jm.owner.clone(),
2795        owner_salt: jm.owner_salt.clone(),
2796        community_root: jm.community_root.clone(),
2797        root_epoch: jm.root_epoch,
2798        channels,
2799        relays: jm.relays.clone(),
2800        name: jm.name.clone(),
2801        icon: None,
2802        expires_at: None,
2803        creator_npub: None,
2804        label: None,
2805        extra: Default::default(),
2806    }
2807}
2808
2809/// The union of every held v2 community's relays — where this account's 13302 list
2810/// lives (a fresh device that opens any held community reaches the same set).
2811fn held_v2_relays() -> Vec<String> {
2812    let mut set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
2813    if let Ok(ids) = crate::db::community::list_community_ids() {
2814        for id in ids {
2815            if matches!(crate::db::community::community_protocol(&id), Ok(Some(crate::community::ConcordProtocol::V2))) {
2816                if let Ok(Some(c)) = crate::db::community::load_community_v2(&id) {
2817                    set.extend(c.relays);
2818                }
2819            }
2820        }
2821    }
2822    set.into_iter().collect()
2823}
2824
2825/// Fetch this account's own 13302 Community List from `relays` (the newest wins;
2826/// a decrypt/parse failure is "no news", never a clobber of the local mirror).
2827/// Fetch this account's newest 13302 list. `Err` = the transport FAILED (a caller
2828/// must NOT drive a replaceable-event write from a failed read — it would clobber
2829/// the live list); `Ok(None)` = genuinely no list yet; `Ok(Some)` = the list.
2830async fn fetch_community_list<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<Option<super::list::CommunityList>, String> {
2831    let signer = crate::signer::active_signer()?;
2832    let my_pk = me_pk()?;
2833    let query = Query {
2834        kinds: vec![super::kind::COMMUNITY_LIST],
2835        authors: vec![my_pk.to_hex()],
2836        limit: Some(4),
2837        ..Default::default()
2838    };
2839    let events = transport.fetch(&query, relays).await?;
2840    let mut best: Option<(u64, super::list::CommunityList)> = None;
2841    for e in events {
2842        if let Ok(l) = super::list::parse_list_event_signed(&signer, my_pk, &e).await {
2843            let at = e.created_at.as_secs();
2844            if best.as_ref().map(|(b, _)| at > *b).unwrap_or(true) {
2845                best = Some((at, l));
2846            }
2847        }
2848    }
2849    Ok(best.map(|(_, l)| l))
2850}
2851
2852/// Rebuild this account's 13302 from its held v2 communities, MERGE with the remote
2853/// copy (preserving tombstones, other-device entries, unknown fields), and publish.
2854/// `just_joined` is the community THIS call is recording a create/join for — the
2855/// ONLY community whose entry is (re)stamped `now`, so it beats any prior tombstone
2856/// (a deliberate re-join resurrects). Every OTHER held community that the remote
2857/// has tombstoned is left tombstoned (a sibling device's leave is NOT undone just
2858/// because we joined something else — the W1 resurrection hole). Idempotent;
2859/// best-effort — a list-publish failure never fails the membership change itself.
2860/// Returns `Ok(true)` when the list was PUBLISHED, `Ok(false)` when the attempt was
2861/// skipped without failing the caller (a failed remote fetch — see below). Callers that
2862/// need the membership to actually land use [`republish_community_list_durable`].
2863pub async fn republish_community_list<T: Transport + ?Sized>(transport: &T, just_joined: Option<&crate::community::CommunityId>) -> Result<bool, String> {
2864    let session = SessionGuard::capture();
2865    let signer = crate::signer::active_signer()?;
2866    let my_pk = me_pk()?;
2867    let relays = held_v2_relays();
2868    if relays.is_empty() {
2869        return Ok(false); // nothing held → nothing to sync
2870    }
2871    // A FAILED remote fetch must not drive this replaceable-event write: publishing
2872    // a list built without the remote seeds would drop older-epoch backfill anchors
2873    // and re-stamp add-times (the W2 seed-regression + a resurrection window).
2874    let remote = match fetch_community_list(transport, &relays).await {
2875        Ok(r) => r.unwrap_or_default(),
2876        Err(e) => {
2877            // SILENT-SKIP HAZARD: bailing is correct (publishing a list built without the
2878            // remote seeds drops backfill anchors), but the membership this call was meant
2879            // to record is now simply unrecorded. A join that lands here leaves a community
2880            // held locally with no list entry — and if it also carries an older tombstone,
2881            // nothing ever out-ranks it again. Say so loudly; `Ok(())` keeps it non-fatal.
2882            crate::log_warn!(
2883                "[CommunityList] republish SKIPPED (remote fetch failed: {}){}",
2884                e,
2885                just_joined
2886                    .map(|c| format!(" — the join of {} is NOT recorded across devices", &crate::simd::hex::bytes_to_hex_32(&c.0)[..8]))
2887                    .unwrap_or_default()
2888            );
2889            return Ok(false);
2890        }
2891    };
2892    let just_joined_hex = just_joined.map(|c| crate::simd::hex::bytes_to_hex_32(&c.0));
2893    let now = now_ms();
2894    let mut local = super::list::CommunityList::default();
2895    for id in crate::db::community::list_community_ids()? {
2896        if !matches!(crate::db::community::community_protocol(&id), Ok(Some(crate::community::ConcordProtocol::V2))) {
2897            continue;
2898        }
2899        let Some(c) = crate::db::community::load_community_v2(&id)? else { continue };
2900        let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
2901        let is_join = just_joined_hex.as_deref() == Some(cid_hex.as_str());
2902        // A held community the remote has tombstoned (a sibling device left it) that
2903        // we are NOT currently (re)joining stays LEFT — don't re-add it, or joining a
2904        // different community would silently undo the leave everywhere.
2905        //
2906        // UNLESS our hold POST-DATES the removal. A rejoin whose membership never
2907        // reached the list (this publish is best-effort — a failed remote fetch
2908        // silently skips it) leaves a tombstone with no entry, and nothing can ever
2909        // out-rank it again: every boot the list sync reads "removed", tears the
2910        // community down, the rejoin re-adds it, and it loops forever. Our own hold
2911        // is first-hand evidence of membership, so let it settle the tie by the same
2912        // add-vs-remove rule the list already uses everywhere else.
2913        let tombstoned_at = remote
2914            .tombstones
2915            .iter()
2916            .find(|t| t.community_id == cid_hex)
2917            .map(|t| t.removed_at)
2918            .unwrap_or(0);
2919        let held_since = c.created_at_ms;
2920        if !is_join && !remote.is_live(&cid_hex) && tombstoned_at > 0 && held_since <= tombstoned_at {
2921            crate::log_warn!(
2922                "[CommunityList] holding {} but NOT recording it: a tombstone at {} post-dates our hold ({}) — treated as a leave from another device",
2923                &cid_hex[..8], tombstoned_at, held_since
2924            );
2925            continue;
2926        }
2927        // Keep an already-live entry's add time (no churn); the joined community (or a
2928        // genuinely-new one) stamps `now` so a re-join beats a stale tombstone. A hold
2929        // that outlived a tombstone re-asserts itself at its own join time, which is
2930        // already newer than the removal.
2931        let added_at = if remote.is_live(&cid_hex) && !is_join {
2932            remote.entries.iter().find(|e| e.community_id == cid_hex).map(|e| e.added_at).unwrap_or(now)
2933        } else if !is_join && tombstoned_at > 0 {
2934            held_since
2935        } else {
2936            now
2937        };
2938        let jm = join_material(&c);
2939        local.entries.push(super::list::CommunityListEntry { community_id: cid_hex, seed: jm.clone(), current: jm, added_at, extra: Default::default() });
2940    }
2941    let merged = remote.merge(&local);
2942    merged.assert_fits().map_err(|e| e.to_string())?;
2943    let event = super::list::build_list_event_signed(&signer, my_pk, &merged).await.map_err(|e| e.to_string())?;
2944    if !session.is_valid() {
2945        return Err("account changed during community-list publish".to_string());
2946    }
2947    if let Err(e) = transport.publish(&event, &relays).await {
2948        crate::log_warn!("[CommunityList] publish FAILED ({}) — memberships stay local-only until the next edit", e);
2949        return Err(e);
2950    }
2951    Ok(true)
2952}
2953
2954/// Retry budget for [`republish_community_list_durable`]. An unrecorded membership is
2955/// invisible to the user and self-heals only on their NEXT join, so ride out a relay
2956/// blip rather than a single shot. Bounded: a permanently dead relay set gives up
2957/// instead of spinning.
2958const LIST_REPUBLISH_BACKOFF_SECS: [u64; 6] = [2, 5, 15, 45, 120, 300];
2959
2960/// Record a membership across devices DURABLY: retry in the background until the list
2961/// actually lands.
2962///
2963/// [`republish_community_list`] must never fail a join, and it deliberately publishes
2964/// NOTHING when the remote fetch fails (a list built without the remote seeds would drop
2965/// other devices' entries). One shot at that means a relay blip during a join leaves the
2966/// membership unrecorded until the user happens to join something else — and if a stale
2967/// tombstone out-ranks it, the community is stranded until a manual leave+rejoin.
2968///
2969/// Non-blocking. Skipped entirely without a live client (headless/unit tests drive the
2970/// generic fn directly). The `SessionGuard` is captured BEFORE the spawn and re-checked
2971/// before every attempt, so an account swap mid-backoff can't publish A's list from B.
2972pub fn republish_community_list_durable(just_joined: Option<crate::community::CommunityId>) {
2973    if crate::state::nostr_client().is_none() {
2974        return;
2975    }
2976    let session = SessionGuard::capture();
2977    tokio::spawn(async move {
2978        for (attempt, wait) in LIST_REPUBLISH_BACKOFF_SECS.iter().enumerate() {
2979            if !session.is_valid() {
2980                return;
2981            }
2982            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
2983            match republish_community_list(&transport, just_joined.as_ref()).await {
2984                Ok(true) => {
2985                    if attempt > 0 {
2986                        crate::log_info!("[CommunityList] membership recorded on retry #{}", attempt);
2987                    }
2988                    return;
2989                }
2990                Ok(false) => {} // skipped (remote fetch failed) — already logged; retry
2991                Err(e) => crate::log_warn!("[CommunityList] republish attempt #{} failed: {}", attempt, e),
2992            }
2993            tokio::time::sleep(std::time::Duration::from_secs(*wait)).await;
2994        }
2995        crate::log_warn!(
2996            "[CommunityList] gave up recording membership after {} attempts — it will re-record on the next join/leave",
2997            LIST_REPUBLISH_BACKOFF_SECS.len()
2998        );
2999    });
3000}
3001
3002/// Record a permanent leave tombstone for `community_id` in the 13302, published to
3003/// `relays` (the leaving community's own, since it's about to be deleted locally).
3004async fn tombstone_community_list<T: Transport + ?Sized>(transport: &T, community_id: &crate::community::CommunityId, relays: &[String]) -> Result<(), String> {
3005    let signer = crate::signer::active_signer()?;
3006    let my_pk = me_pk()?;
3007    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);
3008    // A failed fetch here would drop other communities' entries (only the
3009    // tombstone would survive); preserve them by bailing — the leave re-records
3010    // on the next attempt, and the local teardown already happened.
3011    let mut doc = match fetch_community_list(transport, relays).await {
3012        Ok(d) => d.unwrap_or_default(),
3013        Err(e) => return Err(e),
3014    };
3015    let now = now_ms();
3016    doc.tombstones.retain(|t| t.community_id != cid_hex);
3017    doc.tombstones.push(super::list::Tombstone { community_id: cid_hex, removed_at: now, extra: Default::default() });
3018    doc.assert_fits().map_err(|e| e.to_string())?;
3019    let event = super::list::build_list_event_signed(&signer, my_pk, &doc).await.map_err(|e| e.to_string())?;
3020    transport.publish(&event, relays).await
3021}
3022
3023/// Sync memberships from the 13302 across devices: fetch this account's list from
3024/// `bootstrap_relays` (its held communities' relays plus any caller-supplied set for
3025/// a fresh device), and JOIN every live entry not already held — reconstructing the
3026/// community from its join material and re-verifying the owner root. Returns the
3027/// newly-rehydrated communities (so the caller can subscribe + notify).
3028/// What one Community-List sync changed locally.
3029pub struct ListSyncOutcome {
3030    /// Communities newly adopted from the list (already persisted + chat-registered).
3031    pub joined: Vec<CommunityV2>,
3032    /// Communities a sibling device LEFT, as `(community_id_hex, channel_id_hexes)`.
3033    ///
3034    /// The rows are already gone here, so the ids are captured BEFORE deletion: the caller
3035    /// still has to finish the local teardown (chat rows, STATE, the live subscription),
3036    /// and it can't look them up afterwards. Deleting the community while leaving its chat
3037    /// row behind is what produces a ghost "0 Members" room pointing at nothing.
3038    pub removed: Vec<(String, Vec<String>)>,
3039}
3040
3041pub async fn sync_community_list<T: Transport + ?Sized>(transport: &T, bootstrap_relays: &[String]) -> Result<ListSyncOutcome, String> {
3042    let session = SessionGuard::capture();
3043    let mut relays = held_v2_relays();
3044    relays.extend(bootstrap_relays.iter().cloned());
3045    relays.sort();
3046    relays.dedup();
3047    if relays.is_empty() {
3048        return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
3049    }
3050    let list = match fetch_community_list(transport, &relays).await {
3051        Ok(Some(l)) => l,
3052        Ok(None) | Err(_) => return Ok(ListSyncOutcome { joined: vec![], removed: vec![] }),
3053    };
3054    // Receive-side teardown (the counterpart to the republish tombstone guard):
3055    // a community this device still holds but the synced list shows TOMBSTONED (a
3056    // sibling device left it) and NOT live gets torn down here, so a leave on one
3057    // device propagates to the others. A re-join would have re-added it live
3058    // (beating the tombstone), so is_live short-circuits the honest case.
3059    let mut removed: Vec<(String, Vec<String>)> = Vec::new();
3060    for t in &list.tombstones {
3061        if list.is_live(&t.community_id) {
3062            continue;
3063        }
3064        let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&t.community_id) else { continue };
3065        let id = crate::community::CommunityId(cid);
3066        let Some(held) = crate::db::community::load_community_v2(&id).ok().flatten() else {
3067            continue; // not held — nothing to tear down
3068        };
3069        // `is_live` above assumes a rejoin re-added an entry, but recording that entry is
3070        // best-effort: a relay blip at join time leaves the tombstone unopposed forever, and
3071        // this would then delete the community on every sync. So let the LOCAL hold break the
3072        // tie too — a hold created after the removal IS the rejoin, whether or not its entry
3073        // ever reached the list. Same rule the v1 sweep uses.
3074        if held.created_at_ms > t.removed_at {
3075            crate::log_warn!(
3076                "[CommunityList] {} is tombstoned at {} but our hold ({}) post-dates it — treating as a rejoin, not tearing down",
3077                &t.community_id[..8], t.removed_at, held.created_at_ms
3078            );
3079            continue;
3080        }
3081        if !session.is_valid() {
3082            return Err("account changed during community-list sync".to_string());
3083        }
3084        let channel_ids: Vec<String> = held.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
3085        let _ = crate::db::community::delete_community(&t.community_id);
3086        removed.push((t.community_id.clone(), channel_ids));
3087    }
3088    let mut joined = Vec::new();
3089    for entry in list.live_entries() {
3090        let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&entry.community_id) else { continue };
3091        if crate::db::community::load_community_v2(&crate::community::CommunityId(cid)).ok().flatten().is_some() {
3092            continue; // already held
3093        }
3094        if !session.is_valid() {
3095            return Err("account changed during community-list sync".to_string());
3096        }
3097        // The material IS a bundle; accept_bundle re-verifies the owner root, saves,
3098        // and seeds floors. NO Guestbook Join: this device is receiving keys the
3099        // account already holds elsewhere — the membership was announced when it
3100        // actually joined, and a key sync is not a membership event.
3101        let bundle = material_to_invite(&entry.current);
3102        if let Ok(community) = accept_bundle(transport, &session, &bundle, None, false).await {
3103            joined.push(community);
3104        }
3105    }
3106    Ok(ListSyncOutcome { joined, removed })
3107}
3108
3109// ── Control edition authoring (CORD-04 roles / CORD-02 §6 / CORD-03 §2) ──────
3110
3111/// Publish one control edition (a role, grant, banlist, community-metadata, or
3112/// channel-metadata edit) at the next version for its entity, chaining `prev` from
3113/// our held head, and advance our local floor. Authority is enforced by every
3114/// reader's roster fold (CORD-04 §5: authority is rejection, not prevention), so this
3115/// requires only a valid local signer; a well-behaved client checks its own rank
3116/// first, but a reader drops an unauthorized edition regardless.
3117/// This actor's authority citation for a control edition (CORD-04 §5): the head
3118/// of their OWN Grant entity, pinned by coordinate + version + edition hash.
3119///
3120/// A SYNC FLOOR, not a verdict — a verifier refuses to act until it has synced
3121/// at least this Grant, then resolves rank against its CURRENT roster, so a
3122/// demoted admin is never grandfathered by an old-but-once-valid citation.
3123///
3124/// `None` for the owner (supreme, rank comes from the community id) and `None`
3125/// when no Grant head is held — an actor who cannot cite has no rank to claim,
3126/// and the edition is dropped by a conforming reader either way.
3127/// The verify half of [`my_authority_citation`] (CORD-04 §5): does the actor's
3128/// cited Grant prove authority we have actually SYNCED? The owner is supreme and
3129/// cites nothing. A non-owner MUST cite, and we must hold that Grant at ≥ the
3130/// cited version with the cited hash at the tip — else fail closed, because
3131/// honoring an action whose authority we can't confirm is exactly how a demoted
3132/// moderator keeps moderating.
3133///
3134/// Completeness only: the permission + outrank is the separate roster check, so a
3135/// since-demoted actor is refused there (refuse-superseded). An action citing a
3136/// version we haven't synced parks and is re-judged on the next roster sync — the
3137/// sync path can't escalate to a blocking fetch.
3138pub(super) fn citation_is_synced(
3139    cid_hex: &str,
3140    owner_hex: &str,
3141    actor_hex: &str,
3142    citation: Option<&crate::community::edition::AuthorityCitation>,
3143) -> bool {
3144    if owner_hex == actor_hex {
3145        return true;
3146    }
3147    if citation.is_none() {
3148        return false;
3149    }
3150    let cid_bytes = crate::simd::hex::hex_to_bytes_32(cid_hex);
3151    let actor_bytes = crate::simd::hex::hex_to_bytes_32(actor_hex);
3152    let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(
3153        &crate::community::CommunityId(cid_bytes),
3154        &actor_bytes,
3155    ));
3156    let head: Vec<crate::community::roster::EntityHead> =
3157        crate::db::community::get_edition_head(cid_hex, &grant_hex)
3158            .ok()
3159            .flatten()
3160            .map(|(version, self_hash)| crate::community::roster::EntityHead {
3161                entity_hex: grant_hex.clone(),
3162                version,
3163                self_hash,
3164                inner_id: [0u8; 32],
3165                citation: None,
3166            })
3167            .into_iter()
3168            .collect();
3169    crate::community::roster::authority_citation_satisfied(&head, Some(owner_hex), actor_hex, &grant_hex, citation)
3170}
3171
3172/// [`my_authority_citation`], but refusing to emit an action every reader will
3173/// drop (CORD-04 §5: an uncited non-owner action is not honored).
3174///
3175/// The citation is built from PERSISTED heads, which only `follow_control` writes
3176/// — so an admin who hasn't folded yet (just promoted, or freshly restored) would
3177/// otherwise publish uncited and have the action silently vanish on every client,
3178/// with nothing shown locally. Failing here turns that into one retryable error.
3179fn required_authority_citation(
3180    community: &CommunityV2,
3181    actor: &PublicKey,
3182) -> Result<Option<crate::community::edition::AuthorityCitation>, String> {
3183    if community.owner().ok().as_ref() == Some(actor) {
3184        return Ok(None); // supreme, cites nothing
3185    }
3186    my_authority_citation(community, actor).map(Some).ok_or_else(|| {
3187        "your admin rights aren't synced on this device yet — reopen the community and retry".to_string()
3188    })
3189}
3190
3191fn my_authority_citation(
3192    community: &CommunityV2,
3193    actor: &PublicKey,
3194) -> Option<crate::community::edition::AuthorityCitation> {
3195    if community.owner().ok().as_ref() == Some(actor) {
3196        return None;
3197    }
3198    let entity_id = super::derive::grant_locator(community.id(), &actor.to_bytes());
3199    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3200    let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
3201    crate::db::community::get_edition_head(&cid_hex, &entity_hex)
3202        .ok()
3203        .flatten()
3204        .map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
3205}
3206
3207/// Refuse a root-derived write whose in-hand struct predates a rotation.
3208///
3209/// A Ban's refound buries the old root while the caller's `CommunityV2` still
3210/// points at it; publishing there lands on a plane nobody folds — the action
3211/// "succeeds" and silently never happened (an unban that doesn't unban, an
3212/// invite that strands its joiner on a dead epoch). Failing loudly instead lets
3213/// the caller reload and retry against the living root.
3214fn assert_current_root(community: &CommunityV2) -> Result<(), String> {
3215    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3216    match crate::db::community::get_server_root_epoch(&cid_hex)? {
3217        Some(held) if held != community.root_epoch.0 => Err(format!(
3218            "the community re-founded mid-action (epoch {} -> {held}); retry",
3219            community.root_epoch.0
3220        )),
3221        _ => Ok(()), // no row = a not-yet-persisted create; nothing newer to defer to
3222    }
3223}
3224
3225async fn publish_control_edition<T: Transport + ?Sized>(
3226    transport: &T,
3227    community: &CommunityV2,
3228    session: &SessionGuard,
3229    vsk: &str,
3230    entity_id: &[u8; 32],
3231    content: &str,
3232) -> Result<(), String> {
3233    assert_current_root(community)?;
3234    let signer = crate::signer::active_signer()?;
3235    let my_pk = me_pk()?;
3236    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
3237    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3238    let entity_hex = crate::simd::hex::bytes_to_hex_32(entity_id);
3239    let (version, prev) = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
3240        Some((v, h)) => (v + 1, Some(h)),
3241        None => (1, None),
3242    };
3243    // CORD-04 §5: a non-owner names the exact Grant edition it claims its rank
3244    // under. Computed here rather than passed in — the citation is a property of
3245    // WHO IS ACTING, identical for every entity kind, so deciding it per call
3246    // site is nine chances to forget (and nine were, silently: every site passed
3247    // None). The owner cites nothing; their rank is the community id itself.
3248    let citation = required_authority_citation(community, &my_pk)?;
3249    let at = now_ms() / 1000;
3250    let rumor = control::build_edition_rumor(my_pk, vsk, entity_id, version, prev.as_ref(), content, at, citation.as_ref());
3251    let (wrap, _) = control::seal_control_edition_signed(&signer, my_pk, &rumor, &control, Timestamp::from_secs(at)).await.map_err(|e| e.to_string())?;
3252    if !session.is_valid() {
3253        return Err("account changed before control publish".to_string());
3254    }
3255    transport.publish(&wrap, &community.relays).await?;
3256    // Advance our own floor so a follow-up edit chains from this head and refuse-
3257    // downgrade holds; open our own wrap to recover the self_hash + inner_id.
3258    // Re-check the session AFTER the publish await: a swap mid-publish means the
3259    // pool now points at another account's DB — skipping is safe (the next own
3260    // edit rebuilds the same head from the relay's copy).
3261    if !session.is_valid() {
3262        return Ok(());
3263    }
3264    if let Ok((ed, _)) = control::open_control_edition(&wrap, &control) {
3265        crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, community.root_epoch.0)?;
3266    }
3267    Ok(())
3268}
3269
3270/// Merge our OWN just-published Role/Grant into the locally stored roster.
3271///
3272/// v2 persists the roster only inside `follow_control`, so a role or grant we
3273/// just published is invisible to every sync local read (entitlement, capability
3274/// gates, the next grant) until the next fold. This writes what we are already
3275/// authorized to have written; the next fold recomputes from the plane and
3276/// converges. Mirrors the fold's own write, so the stored `roles_at` is left
3277/// alone — a real edition always outranks this optimistic merge.
3278fn merge_local_roster(cid_hex: &str, role: Option<&crate::community::roles::Role>, grant: Option<&crate::community::roles::MemberGrant>) {
3279    let mut roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
3280    if let Some(r) = role {
3281        match roster.roles.iter_mut().find(|x| x.role_id == r.role_id) {
3282            Some(slot) => *slot = r.clone(),
3283            None => roster.roles.push(r.clone()),
3284        }
3285    }
3286    if let Some(g) = grant {
3287        match roster.grants.iter_mut().find(|x| x.member == g.member) {
3288            Some(slot) => *slot = g.clone(),
3289            None => roster.grants.push(g.clone()),
3290        }
3291    }
3292    let at = crate::db::community::get_community_roles_at(cid_hex).unwrap_or(0);
3293    if let Err(e) = crate::db::community::set_community_roles(cid_hex, &roster, at) {
3294        crate::log_warn!("v2: local roster merge failed (heals on the next control fold): {e}");
3295    }
3296}
3297
3298/// Create or edit a Role (vsk 1, CORD-04 §2). `role.role_id` is the coordinate; a
3299/// rename or permission change is a versioned edit of the same id. Gated on the
3300/// reader side by `MANAGE_ROLES` + outrank.
3301pub async fn set_role<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role: &crate::community::roles::Role) -> Result<(), String> {
3302    let session = SessionGuard::capture();
3303    super::roles::validate_role(role)?;
3304    let content = super::roles::role_content_json(role)?;
3305    let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).ok_or("role_id must be 32-byte hex")?;
3306    publish_control_edition(transport, community, &session, vsk::ROLE, &role_id, &content).await
3307}
3308
3309/// Grant or revoke a member's Roles (vsk 3, CORD-04 §2). Empty `role_ids` is a
3310/// revoke. Gated on the reader side by `MANAGE_ROLES` + outrank of every role + the
3311/// member.
3312pub async fn grant_roles<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey, role_ids: Vec<String>) -> Result<(), String> {
3313    let session = SessionGuard::capture();
3314    let grant = crate::community::roles::MemberGrant { member: member.to_hex(), role_ids };
3315    let content = super::roles::grant_content_json(&grant)?;
3316    let eid = super::derive::grant_locator(community.id(), &member.to_bytes());
3317    publish_control_edition(transport, community, &session, vsk::GRANT, &eid, &content).await
3318}
3319
3320/// The community's @admin role id: the folded Server-scope ADMIN_ALL role when one
3321/// exists, else (with `create_if_missing`) a DETERMINISTIC mint — the same id on
3322/// every device, so concurrent grants converge as editions of ONE entity instead
3323/// of forking two Admin roles.
3324pub async fn ensure_admin_role<T: Transport + ?Sized>(
3325    transport: &T,
3326    community: &CommunityV2,
3327    view: &AuthorityView,
3328    create_if_missing: bool,
3329) -> Result<Option<String>, String> {
3330    use crate::community::roles::{Permissions, Role, RoleScope};
3331    if let Some(r) = view
3332        .roles
3333        .roles
3334        .iter()
3335        .find(|r| matches!(r.scope, RoleScope::Server) && r.permissions.contains(Permissions::ADMIN_ALL))
3336    {
3337        return Ok(Some(r.role_id.clone()));
3338    }
3339    if !create_if_missing {
3340        return Ok(None);
3341    }
3342    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3343    let role_id = crate::crypto::sha256_hex(format!("vector/v2/role/admin/{cid_hex}").as_bytes());
3344    set_role(transport, community, &Role::admin(role_id.clone())).await?;
3345    Ok(Some(role_id))
3346}
3347
3348/// Grant the @admin role (minting it deterministically when absent), MERGED into
3349/// the member's existing grant — a grant entity replaces whole (CORD-04 §2), so a
3350/// blind push would erase their other roles. Owner-only: the position-1 Admin is
3351/// manageable only by position 0 (an equal never outranks it), and refusing
3352/// before any publish keeps an unauthorized edition of the DETERMINISTIC admin
3353/// entity from advancing this device's own floor onto a head readers reject.
3354pub async fn grant_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
3355    // Guard spans the multi-page fetch below: a swap mid-fetch must not let the
3356    // downstream publish's own (post-swap) guard write account A's floor into B.
3357    let session = SessionGuard::capture();
3358    let my_pk = me_pk()?;
3359    if my_pk != community.owner()? {
3360        return Err("only the community owner can grant @admin".to_string());
3361    }
3362    let view = fetch_authority(transport, community).await;
3363    if !session.is_valid() {
3364        return Err("account changed during grant".to_string());
3365    }
3366    let member_hex = member.to_hex();
3367    require_grant_head(community, &view, &member_hex)?;
3368    let role_id = ensure_admin_role(transport, community, &view, true)
3369        .await?
3370        .expect("create_if_missing yields an id");
3371    let mut role_ids = view
3372        .roles
3373        .grants
3374        .iter()
3375        .find(|g| g.member == member_hex)
3376        .map(|g| g.role_ids.clone())
3377        .unwrap_or_default();
3378    if role_ids.contains(&role_id) {
3379        return Ok(()); // already admin — don't bump the grant edition for nothing.
3380    }
3381    role_ids.push(role_id);
3382    grant_roles(transport, community, member, role_ids).await
3383}
3384
3385/// Strip the @admin role from the member's grant, preserving their other roles.
3386/// A no-op when they don't hold it. Owner-only, like [`grant_admin`].
3387pub async fn revoke_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
3388    let session = SessionGuard::capture();
3389    let my_pk = me_pk()?;
3390    if my_pk != community.owner()? {
3391        return Err("only the community owner can revoke @admin".to_string());
3392    }
3393    let view = fetch_authority(transport, community).await;
3394    if !session.is_valid() {
3395        return Err("account changed during revoke".to_string());
3396    }
3397    let member_hex = member.to_hex();
3398    require_grant_head(community, &view, &member_hex)?;
3399    let Some(role_id) = ensure_admin_role(transport, community, &view, false).await? else {
3400        return Ok(()); // no admin role exists — nothing to revoke.
3401    };
3402    let mut role_ids = view
3403        .roles
3404        .grants
3405        .iter()
3406        .find(|g| g.member == member_hex)
3407        .map(|g| g.role_ids.clone())
3408        .unwrap_or_default();
3409    let before = role_ids.len();
3410    role_ids.retain(|r| r != &role_id);
3411    if role_ids.len() == before {
3412        return Ok(());
3413    }
3414    grant_roles(transport, community, member, role_ids).await
3415}
3416
3417/// A grant replaces whole — refuse the merge when this member's grant is FLOORED
3418/// locally but no head folded (withheld / evicted): a blind push at that point
3419/// would erase their other roles at a higher version.
3420fn require_grant_head(community: &CommunityV2, view: &AuthorityView, member_hex: &str) -> Result<(), String> {
3421    let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(member_hex) else {
3422        return Err("malformed member key".to_string());
3423    };
3424    let eid_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &member));
3425    if view.floored.contains(&eid_hex) && !view.head_entities.contains(&eid_hex) {
3426        return Err("this member's current grant could not be fetched; try again once relays serve the control plane".to_string());
3427    }
3428    Ok(())
3429}
3430
3431/// Replace the Banlist (vsk 4, CORD-04 §4) with `banned` (lowercase-hex npubs), the
3432/// whole list on every edit. Gated on the reader side by `BAN`.
3433pub async fn set_banlist<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, banned: &[String]) -> Result<(), String> {
3434    let session = SessionGuard::capture();
3435    super::roles::validate_banlist(banned)?;
3436    let content = super::roles::banlist_content_json(banned)?;
3437    let eid = super::derive::banlist_locator(community.id());
3438    publish_control_edition(transport, community, &session, vsk::BANLIST, &eid, &content).await
3439}
3440
3441/// Edit the community metadata (vsk 0, CORD-02 §6). Gated on the reader side by
3442/// `MANAGE_METADATA`.
3443pub async fn edit_community_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, meta: &control::CommunityMetadata) -> Result<(), String> {
3444    let session = SessionGuard::capture();
3445    control::validate_community_metadata(meta).map_err(|e| e.to_string())?;
3446    let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
3447    publish_control_edition(transport, community, &session, vsk::COMMUNITY_METADATA, &community.id().0, &content).await
3448}
3449
3450/// Persist a freshly-published icon/banner onto the held row and return the fresh
3451/// row. Reloads under the community's follow lock: `save_community_v2` is a
3452/// whole-row save that prunes channels absent from the passed struct, so writing
3453/// a stale pre-upload copy would drop rows a concurrent fold just landed.
3454pub async fn persist_community_image(
3455    id: &crate::community::CommunityId,
3456    img: control::ImageRef,
3457    is_banner: bool,
3458    session: &SessionGuard,
3459) -> Option<CommunityV2> {
3460    let lock = super::realtime::follow_lock(id);
3461    let _guard = lock.lock().await;
3462    if !session.is_valid() {
3463        return None;
3464    }
3465    let mut fresh = crate::db::community::load_community_v2(id).ok()??;
3466    if is_banner {
3467        fresh.banner = Some(img);
3468    } else {
3469        fresh.icon = Some(img);
3470    }
3471    crate::db::community::save_community_v2(&fresh).ok()?;
3472    Some(fresh)
3473}
3474
3475/// Add or edit a channel's metadata (vsk 2, CORD-03 §2). `channel_id` is the
3476/// coordinate. Gated on the reader side by `MANAGE_CHANNELS`.
3477pub async fn edit_channel_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata) -> Result<(), String> {
3478    let session = SessionGuard::capture();
3479    let my_pk = me_pk()?;
3480    ensure_channel_manager(community, &my_pk)?;
3481    // Public → private CONVERSION is a key rotation (CORD-03 §2) this build doesn't
3482    // mint yet — refuse the flag flip rather than publish an edition no reader can
3483    // key (members would keep posting on the root-derived plane, splitting the
3484    // channel). Private → public works (readers heal to the root derivation).
3485    if meta.private {
3486        if let Some(held) = community.channel(channel_id) {
3487            if !held.private {
3488                return Err("converting a public channel to private is not supported yet".to_string());
3489            }
3490        }
3491    }
3492    control::validate_channel_metadata(meta).map_err(|e| e.to_string())?;
3493    let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
3494    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
3495    // Apply locally too. The fold is the authority but runs later, so without this
3496    // an edit we just made reads back stale until some future control pass — the
3497    // rename appears to have silently failed.
3498    if !session.is_valid() {
3499        return Ok(());
3500    }
3501    if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
3502        if let Some(ch) = held.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
3503            ch.name = meta.name.clone();
3504            ch.private = meta.private;
3505            ch.voice = meta.voice;
3506            ch.meta_custom = meta.custom.clone();
3507            ch.meta_extra = meta.extra.clone();
3508            crate::db::community::save_community_v2(&held)?;
3509        }
3510    }
3511    Ok(())
3512}
3513
3514/// The local mirror of the reader's `MANAGE_CHANNELS` fold gate (CORD-03 §2): the
3515/// owner, or a roster-authorized manager who isn't banned. Refusing BEFORE any
3516/// publish keeps an unauthorized device from advancing its own edition floor onto
3517/// a head every reader rejects (wedging its later, legitimately-authorized edits
3518/// behind a rejected chain).
3519fn ensure_channel_manager(community: &CommunityV2, me: &PublicKey) -> Result<(), String> {
3520    let owner = community.owner()?;
3521    if *me == owner {
3522        return Ok(());
3523    }
3524    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3525    let me_hex = me.to_hex();
3526    if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&me_hex) {
3527        return Err("you are banned from this community".to_string());
3528    }
3529    let roster = crate::db::community::get_community_roles(&cid_hex)?;
3530    if roster.is_authorized(&me_hex, Some(&owner.to_hex()), crate::community::roles::Permissions::MANAGE_CHANNELS) {
3531        Ok(())
3532    } else {
3533        Err("managing channels here needs the MANAGE_CHANNELS permission".to_string())
3534    }
3535}
3536
3537/// Create a new PUBLIC channel (CORD-03 §2): mint a fresh id, publish its metadata
3538/// edition (vsk 2), and add it to the held community. A Public channel derives its Chat
3539/// Plane from the `community_root` (no per-channel key), so other members fold it in on
3540/// their next control follow with nothing to distribute. Returns the new channel id.
3541/// Reader-gated by `MANAGE_CHANNELS`.
3542pub async fn create_public_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
3543    let channel_id = ChannelId(super::super::random_32());
3544    create_public_channel_with_id(transport, community, name, channel_id).await?;
3545    Ok(channel_id)
3546}
3547
3548/// [`create_public_channel`] with a CALLER-CHOSEN id — the migration-only entry point
3549/// (§migration) that reuses a v1 channel's id so chat history stitches through the flip.
3550/// Asserts the id isn't already live in a DIFFERENT held v2 community before minting.
3551pub async fn create_public_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
3552    let session = SessionGuard::capture();
3553    // Serialize with the follow worker: the save below writes the WHOLE community
3554    // row from this caller's struct, so an unserialized concurrent follow adopting
3555    // a rotation would be rolled back to a stale root (a deaf community).
3556    let lock = super::realtime::follow_lock(community.id());
3557    let _guard = lock.lock().await;
3558    let my_pk = me_pk()?;
3559    ensure_channel_manager(community, &my_pk)?;
3560    assert_channel_id_free(&channel_id, community.id())?;
3561    let meta = control::ChannelMetadata { name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() };
3562    control::validate_channel_metadata(&meta).map_err(|e| e.to_string())?;
3563    let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
3564    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
3565    if !session.is_valid() {
3566        return Err("account changed during channel create".to_string());
3567    }
3568    // Add locally + persist so the creator can post immediately (peers fold it in).
3569    let mut updated = community.clone();
3570    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() });
3571    crate::db::community::save_community_v2(&updated)?;
3572    Ok(())
3573}
3574
3575/// Refuse a channel id already live in a DIFFERENT held v2 community — the same
3576/// cross-community hijack the `save_community_v2` guard forecloses, checked up front so a
3577/// migration twin never adopts an id it doesn't own. A collision with a v1-owned row is
3578/// fine (that's the whole point — the flip re-parents it); only a foreign v2 owner blocks.
3579fn assert_channel_id_free(channel_id: &ChannelId, community_id: &crate::community::CommunityId) -> Result<(), String> {
3580    let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
3581    if let Ok(Some(existing)) = crate::db::community::community_id_for_channel(&ch_hex) {
3582        let mine = crate::simd::hex::bytes_to_hex_32(&community_id.0);
3583        let existing_id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&existing));
3584        if existing != mine
3585            && matches!(crate::db::community::community_protocol(&existing_id), Ok(Some(crate::community::ConcordProtocol::V2)))
3586        {
3587            return Err("channel id is already live in another v2 community".to_string());
3588        }
3589    }
3590    Ok(())
3591}
3592
3593/// Create a new PRIVATE channel (CORD-03 §2): mint a fresh id + an independent
3594/// random key at channel-epoch 1, mint a companion channel-scoped Role that is
3595/// the channel's access list (CORD-04 §2), deliver the key to the entitled over
3596/// the rekey plane (CORD-06 §1), then announce the channel (vsk 2, `private`).
3597/// Epoch 0 is the root generation ("the first privatisation is epoch 1"), so the
3598/// delivery commits its continuity to `(0, community_root)` — verifiable by every
3599/// member and bound to THIS community's root. The key ships BEFORE the
3600/// announcement: an aborted attempt leaves only an unannounced crate (invisible),
3601/// and a retry mints a fresh id, so there is no same-coordinate double-mint to
3602/// fork on. Live public links are refreshed; they carry no private key, so this
3603/// only re-states the public set.
3604pub async fn create_private_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
3605    let channel_id = ChannelId(super::super::random_32());
3606    create_private_channel_with_id(transport, community, name, channel_id).await?;
3607    Ok(channel_id)
3608}
3609
3610/// The companion Role minted alongside a Private channel — the channel's access
3611/// list (CORD-04 §2 `scope: {"kind":"channel"}`). Same name as the channel, and
3612/// **no permission bits**: it confers read access, which is key possession, never
3613/// authority. Position sits below every management role for the same reason.
3614pub fn channel_access_role(channel_id: &ChannelId, name: &str) -> crate::community::roles::Role {
3615    use crate::community::roles::{Permissions, Role, RoleScope};
3616    Role {
3617        role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
3618        name: name.to_string(),
3619        position: u32::MAX - 1,
3620        permissions: Permissions::empty(),
3621        scope: RoleScope::Channel(crate::simd::hex::bytes_to_hex_32(&channel_id.0)),
3622        color: 0,
3623    }
3624}
3625
3626/// [`create_private_channel`] with a CALLER-CHOSEN id — the migration-only entry point
3627/// (§migration) reusing a v1 private channel's id so history stitches through the flip.
3628pub async fn create_private_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
3629    let session = SessionGuard::capture();
3630    // Serialize with the follow worker across the whole fetch→publish→save span
3631    // (the memberlist fetch is seconds long; an unserialized follow adopting a
3632    // rotation meanwhile would be rolled back by the whole-row save below).
3633    let lock = super::realtime::follow_lock(community.id());
3634    let _guard = lock.lock().await;
3635    let signer = crate::signer::active_signer()?;
3636    let my_pk = me_pk()?;
3637    ensure_channel_manager(community, &my_pk)?;
3638    assert_channel_id_free(&channel_id, community.id())?;
3639    let meta = control::ChannelMetadata { name: name.to_string(), private: true, voice: None, deleted: None, custom: None, extra: Default::default() };
3640    control::validate_channel_metadata(&meta).map_err(|e| e.to_string())?;
3641    let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
3642
3643    let channel_key = super::super::random_32();
3644    let epoch = Epoch(1);
3645
3646    // The channel's access list: a companion channel-scoped Role (CORD-04 §2),
3647    // granted to me so the creator is entitled from the first edition.
3648    let access_role = channel_access_role(&channel_id, name);
3649    let access_role_ids = vec![access_role.role_id.clone()];
3650
3651    // Recipients are the ENTITLED, not the memberlist: CORD-03's private channel
3652    // is "readable only by granted role-holders". At create that is me (plus the
3653    // owner, who is always entitled) — everyone else keys up when granted.
3654    let owner = community.owner()?;
3655    let mut recipients = vec![my_pk];
3656    if owner != my_pk {
3657        recipients.push(owner);
3658    }
3659    let prev_commit = super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
3660    let mut blobs = Vec::with_capacity(recipients.len());
3661    for r in &recipients {
3662        blobs.push(
3663            rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(channel_id), epoch, &channel_key)
3664                .await
3665                .map_err(|e| e.to_string())?,
3666        );
3667    }
3668    let group = channel_rekey_group_key(&community.community_root, &channel_id, epoch);
3669    let at_secs = now_ms() / 1000;
3670    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())
3671        .await
3672        .map_err(|e| e.to_string())?;
3673    if !session.is_valid() {
3674        return Err("account changed during channel create".to_string());
3675    }
3676    for c in &chunks {
3677        transport.publish_durable(c, &community.relays).await?;
3678    }
3679    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
3680    if !session.is_valid() {
3681        return Err("account changed during channel create".to_string());
3682    }
3683    // Publish the access list AFTER the channel exists, so a peer folding the
3684    // Role always resolves the channel it scopes to. A failure here leaves a
3685    // channel only its creator can read — recoverable by re-granting, never a
3686    // leak.
3687    set_role(transport, community, &access_role).await?;
3688    grant_roles(transport, community, &my_pk, access_role_ids.clone()).await?;
3689    if !session.is_valid() {
3690        return Err("account changed during channel create".to_string());
3691    }
3692    // The fold is the authority but runs later; without this the creator is not
3693    // yet entitled to their own channel and the next grant finds no access role.
3694    merge_local_roster(
3695        &crate::simd::hex::bytes_to_hex_32(&community.id().0),
3696        Some(&access_role),
3697        Some(&crate::community::roles::MemberGrant { member: my_pk.to_hex(), role_ids: access_role_ids }),
3698    );
3699    // A leave/delete raced the create: saving would resurrect the community row.
3700    if crate::db::community::community_protocol(community.id())?.is_none() {
3701        return Err("community removed during channel create".to_string());
3702    }
3703    let mut updated = community.clone();
3704    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() });
3705    crate::db::community::save_community_v2(&updated)?;
3706    // Archive the epoch-1 key so this channel's history stays readable across its
3707    // future rotations (CORD-03 §3).
3708    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3709    crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&channel_id.0), epoch.0, &channel_key)?;
3710    // Re-state live links. They carry no private key (CORD-05 §2 — a link's
3711    // audience holds no Role), so this only refreshes the public set.
3712    let _ = refresh_public_links(transport, &updated).await;
3713    Ok(())
3714}
3715
3716/// Tombstone a channel (CORD-03 §2, `deleted: true`) + drop it locally. Reader-gated by
3717// ── Receiving a key vend (CORD-03 "delivered on grant") ──────────────────────
3718
3719/// What a client should do with a vended Private-Channel key right now.
3720#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3721pub enum VendVerdict {
3722    /// Every rule passed — adopt the key.
3723    Accept,
3724    /// Cannot judge YET: our fold lags the grant it delivers. Park quietly and
3725    /// re-judge after the next control follow. NOT an anomaly — a lagging fold
3726    /// is the normal case for a vend that races its own Grant.
3727    Park(&'static str),
3728    /// Judged invalid against evidence that cannot become true later. Alarm-worthy.
3729    Refuse(&'static str),
3730}
3731
3732/// Judge a vended Private-Channel key against our OWN folded state.
3733///
3734/// The Grant is the authority half and rides the owner-rooted control plane, so
3735/// it cannot be forged; the vend is only delivery. Acceptance therefore rests
3736/// entirely on what our own fold proves — a bundle can never introduce a channel
3737/// our control plane doesn't define, which is what closes the hidden-channel
3738/// injection class.
3739///
3740/// `community` must already be the held (self-certified) community: the caller
3741/// resolves it by `community_id`, so a bundle naming a community we're not in is
3742/// never judged here at all.
3743pub fn judge_channel_key_vend(
3744    community: &CommunityV2,
3745    roster: &crate::community::roles::CommunityRoles,
3746    channel_id: &ChannelId,
3747    epoch: Epoch,
3748    sender_hex: &str,
3749) -> VendVerdict {
3750    let me = match me_pk() {
3751        Ok(pk) => pk.to_hex(),
3752        Err(_) => return VendVerdict::Park("no active identity"),
3753    };
3754    let owner_hex = match community.owner() {
3755        Ok(o) => o.to_hex(),
3756        Err(_) => return VendVerdict::Refuse("community has no resolvable owner"),
3757    };
3758    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
3759
3760    // (2) The channel must exist in OUR fold, and be private there. The bundle's
3761    // own claims are ignored: a vend may deliver a key, never define a channel.
3762    let Some(ch) = community.channel(channel_id) else {
3763        return VendVerdict::Park("channel not in our fold yet");
3764    };
3765    if !ch.private {
3766        // Never heals: our owner-rooted fold says this channel is public, so a
3767        // "private key" for it is a spoof, not a lagging view.
3768        return VendVerdict::Refuse("vend names a channel our fold says is public");
3769    }
3770
3771    // (5) Epoch sanity, BOTH directions. Below is superseded by the rotation that
3772    // produced our copy. Above matters more: the channel head is monotonic, so a
3773    // wildly-ahead epoch is not merely wrong, it is PERMANENT — every genuine
3774    // rotation afterwards lands at `head + 1`, is refused as stale, and the
3775    // channel dies for us with no heal path at all (not a rekey, not a re-grant,
3776    // not a refound). Rotations advance one epoch at a time, so a lead this large
3777    // is never a delivery we could place.
3778    if ch.key.is_some() && epoch.0 <= ch.epoch.0 {
3779        return VendVerdict::Refuse("superseded: we already hold this epoch or newer");
3780    }
3781    if epoch.0 > ch.epoch.0.saturating_add(MAX_VEND_EPOCH_LEAD) {
3782        return VendVerdict::Refuse("vend epoch is implausibly far ahead of the channel head");
3783    }
3784
3785    // (3) OUR fold must show US granted a role scoped to this channel. This is
3786    // the rule that kills the spoof class: an attacker cannot forge the Grant,
3787    // so they cannot make us accept a key for a channel we were never granted.
3788    if !roster.is_entitled(Some(&owner_hex), &me, &chan_hex, &[], &[]) {
3789        return VendVerdict::Park("our grant for this channel has not folded yet");
3790    }
3791
3792    // (4) The vendor must be entitled too — they hold the real key, so a wrong
3793    // key from them costs isolation, never confidentiality.
3794    if sender_hex != owner_hex && !roster.is_entitled(Some(&owner_hex), sender_hex, &chan_hex, &[], &[]) {
3795        return VendVerdict::Park("vendor's entitlement has not folded yet");
3796    }
3797
3798    VendVerdict::Accept
3799}
3800
3801/// How long an unprovable parked vend is kept. Deliberately long: the fallback
3802/// heal is the channel's next rotation, which may never come.
3803const PARKED_VEND_TTL_SECS: u64 = 30 * 24 * 3600;
3804
3805/// How far above our channel head a vend may claim to be. Generous — a keyless
3806/// cursor can lag a busy channel by many rotations — but bounded, because the
3807/// head is monotonic and an over-advance can never be walked back.
3808const MAX_VEND_EPOCH_LEAD: u64 = 1024;
3809
3810/// Re-judge every parked key vend for this community and adopt the ones that now
3811/// pass. Runs after a control follow (the fold moved, so verdicts can change) and
3812/// on the boot sweep.
3813///
3814/// Returns the channels newly keyed up.
3815pub fn absorb_parked_channel_keys(community: &CommunityV2, session: &SessionGuard) -> Vec<ChannelId> {
3816    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3817    let parked = match crate::db::community::get_pending_channel_keys(&cid_hex) {
3818        Ok(p) if !p.is_empty() => p,
3819        _ => return Vec::new(),
3820    };
3821    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3822    let mut adopted = Vec::new();
3823    let now = now_ms() / 1000;
3824    for p in parked {
3825        // Several candidates may name one channel (parking is open to any sender,
3826        // so a stranger can never suppress the entitled vendor's key by holding a
3827        // slot). Once one is seated the rest are moot.
3828        if adopted.iter().any(|c: &ChannelId| crate::simd::hex::bytes_to_hex_32(&c.0) == p.channel_id) {
3829            let _ = crate::db::community::drop_pending_channel_key(p.id);
3830            continue;
3831        }
3832        // A vend we were never able to prove is not kept forever: an admin who
3833        // adds then immediately removes someone leaves a row nothing will ever
3834        // discharge. Generous by design — the alternative heal (the channel's
3835        // next rotation) can be arbitrarily far away, so this is hygiene, not a
3836        // deadline.
3837        if now.saturating_sub(p.received_at.max(0) as u64) > PARKED_VEND_TTL_SECS {
3838            let _ = crate::db::community::drop_pending_channel_key(p.id);
3839            continue;
3840        }
3841        let Some(id_bytes) = crate::simd::hex::hex_to_bytes_32_checked(&p.channel_id) else {
3842            let _ = crate::db::community::drop_pending_channel_key(p.id);
3843            continue;
3844        };
3845        let channel_id = ChannelId(id_bytes);
3846        match judge_channel_key_vend(community, &roster, &channel_id, Epoch(p.epoch), &p.sender) {
3847            VendVerdict::Accept => {
3848                if !session.is_valid() {
3849                    return adopted;
3850                }
3851                // First delivery vs rotation. A keyless channel must bypass the
3852                // monotonic guard: it sits at the epoch-0 cursor, and a peer that
3853                // mints born-private channels at epoch 0 vends that same epoch, so
3854                // `new > current` would refuse the only key on offer.
3855                let keyless = community.channel(&channel_id).is_some_and(|c| c.key.is_none());
3856                let seated = if keyless {
3857                    crate::db::community::seat_channel_key(&cid_hex, &p.channel_id, p.epoch, &p.key)
3858                } else {
3859                    crate::db::community::advance_channel_epoch(&cid_hex, &p.channel_id, p.epoch, &p.key).map(|_| ())
3860                };
3861                if let Err(e) = seated {
3862                    crate::log_warn!("v2: adopting a vended channel key failed: {e}");
3863                    continue;
3864                }
3865                // The key landed — every other candidate for this channel is moot.
3866                let _ = crate::db::community::drop_pending_channel_keys_for(&cid_hex, &p.channel_id);
3867                adopted.push(channel_id);
3868            }
3869            VendVerdict::Refuse(why) => {
3870                crate::log_warn!("v2: refused a vended channel key for {}: {why}", p.channel_id);
3871                // Only THIS candidate — a sibling may still be the genuine vend.
3872                let _ = crate::db::community::drop_pending_channel_key(p.id);
3873            }
3874            // Quiet by design: the fold simply hasn't caught up.
3875            VendVerdict::Park(_) => {}
3876        }
3877    }
3878    adopted
3879}
3880
3881/// Grant `member` read access to a Private channel (CORD-03 "delivered on
3882/// grant"): publish a Grant adding the channel's access role, then vend the key
3883/// as a CORD-05 §6 Direct Invite whose bundle carries exactly the channels they
3884/// are now entitled to.
3885///
3886/// The Grant is the authority half and rides the owner-rooted control plane, so
3887/// it cannot be forged; the vend is only delivery. A recipient accepts the key
3888/// solely on the strength of their OWN fold showing this grant — the bundle can
3889/// never introduce a channel their control plane doesn't define.
3890pub async fn grant_channel_access<T: Transport + ?Sized>(
3891    transport: &T,
3892    community: &CommunityV2,
3893    channel_id: &ChannelId,
3894    member: &PublicKey,
3895) -> Result<(), String> {
3896    let session = SessionGuard::capture();
3897    let my_pk = me_pk()?;
3898    let ch = community.channel(channel_id).ok_or("unknown channel")?;
3899    if !ch.private {
3900        return Err("channel is public — every member already reads it".to_string());
3901    }
3902    if ch.key.is_none() {
3903        return Err("we hold no key for this channel, so we cannot vend it".to_string());
3904    }
3905    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3906    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
3907    let owner_hex = community.owner()?.to_hex();
3908    // A Grant REPLACES the member's role set, so the union it is built from must
3909    // be CURRENT: a stale local roster would silently strip every role this
3910    // client hasn't folded yet. Fetch the authority fresh rather than trusting
3911    // the cache, and merge the local view on top so a role we just published
3912    // ourselves (which the plane has but no fold has read back) survives too.
3913    let mut roster = fetch_authority(transport, community).await.roles;
3914    let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3915    for r in cached.roles {
3916        if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
3917            roster.roles.push(r);
3918        }
3919    }
3920    for g in cached.grants {
3921        if !roster.grants.iter().any(|x| x.member == g.member) {
3922            roster.grants.push(g);
3923        }
3924    }
3925    if !session.is_valid() {
3926        return Err("account changed during grant".to_string());
3927    }
3928    // Reader-gated by MANAGE_ROLES, like any Grant; narrowed to this channel so
3929    // a channel-scoped manager can run its own access list.
3930    if !roster.is_authorized_in(&my_pk.to_hex(), Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
3931        return Err("not authorized to manage this channel's access".to_string());
3932    }
3933    // The channel's roles are ordered by AUTHORITY, so `.first()` is the most
3934    // privileged — granting read access must never hand out a per-channel
3935    // moderator role that happens to share the scope. Pick the permission-less
3936    // one: conferring read access is exactly what carries no authority.
3937    let role_id = roster
3938        .channel_roles(&chan_hex)
3939        .into_iter()
3940        .find(|r| r.permissions == crate::community::roles::Permissions::empty())
3941        .map(|r| r.role_id.clone())
3942        .ok_or("channel has no permission-less access role to grant")?;
3943
3944    let mut role_ids: Vec<String> = roster.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
3945    if !role_ids.contains(&role_id) {
3946        role_ids.push(role_id.clone());
3947    }
3948    grant_roles(transport, community, member, role_ids.clone()).await?;
3949    if !session.is_valid() {
3950        return Err("account changed during grant".to_string());
3951    }
3952    merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids }));
3953    // Settle the vend against the Grant we JUST published — the fold lags it.
3954    let bundle = bundle_of_with_overlay(
3955        community,
3956        BundleAudience::Member(*member),
3957        Some(my_pk),
3958        None,
3959        None,
3960        std::slice::from_ref(&role_id),
3961        &[],
3962    );
3963    let signer = crate::signer::active_signer()?;
3964    let wrap = invite::build_direct_invite_signed(&signer, my_pk, member, &bundle).await.map_err(|e| e.to_string())?;
3965    if !session.is_valid() {
3966        return Err("account changed before vending the key".to_string());
3967    }
3968    transport.publish(&wrap, &community.relays).await?;
3969    Ok(())
3970}
3971
3972/// Revoke `member`'s read access to a Private channel (CORD-03 "rekeyed on
3973/// removal"): drop the channel's access role from their Grant, then rotate the
3974/// channel to its next epoch delivering the fresh key to everyone still
3975/// entitled (CORD-06). The revoked member keeps whatever history they already
3976/// read — a rekey protects the future, never the past.
3977pub async fn revoke_channel_access<T: Transport + ?Sized>(
3978    transport: &T,
3979    community: &CommunityV2,
3980    channel_id: &ChannelId,
3981    member: &PublicKey,
3982) -> Result<(), String> {
3983    let session = SessionGuard::capture();
3984    let my_pk = me_pk()?;
3985    let ch = community.channel(channel_id).ok_or("unknown channel")?;
3986    if !ch.private {
3987        return Err("channel is public — there is no access to revoke".to_string());
3988    }
3989    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
3990    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
3991    let owner_hex = community.owner()?.to_hex();
3992    // Same replace-not-merge hazard as the grant: the retained set must be built
3993    // from a CURRENT roster or this revoke strips roles we simply hadn't folded.
3994    let mut roster = fetch_authority(transport, community).await.roles;
3995    let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
3996    for r in cached.roles {
3997        if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
3998            roster.roles.push(r);
3999        }
4000    }
4001    for g in cached.grants {
4002        if !roster.grants.iter().any(|x| x.member == g.member) {
4003            roster.grants.push(g);
4004        }
4005    }
4006    if !session.is_valid() {
4007        return Err("account changed during revoke".to_string());
4008    }
4009    if !roster.is_authorized_in(&my_pk.to_hex(), Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
4010        return Err("not authorized to manage this channel's access".to_string());
4011    }
4012    if *member == community.owner()? {
4013        return Err("the owner is supreme and cannot be removed".to_string());
4014    }
4015    let access_ids = roster.channel_role_ids(&chan_hex);
4016    // Without the access list this revoke is a no-op that still ROTATES, and the
4017    // rotation's recipient filter would match nobody — cutting off every
4018    // legitimately entitled member. Refuse rather than mass-evict.
4019    if access_ids.is_empty() {
4020        return Err("this channel's access role has not folded yet — retry once the control plane serves it".to_string());
4021    }
4022    let remaining: Vec<String> = roster
4023        .roles_of(&member.to_hex())
4024        .map(|r| r.role_id.clone())
4025        .filter(|id| !access_ids.contains(id))
4026        .collect();
4027    grant_roles(transport, community, member, remaining.clone()).await?;
4028    if !session.is_valid() {
4029        return Err("account changed during revoke".to_string());
4030    }
4031    merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids: remaining }));
4032    // Rotate so the removal actually severs them (CORD-06 §1). The revoked
4033    // member is excluded from the recipient set by the overlay, since the fold
4034    // has not yet caught the Grant we just published.
4035    rekey_channel_excluding(transport, community, channel_id, &roster, &access_ids, member).await
4036}
4037
4038/// Rotate one Private channel to its next epoch, delivering the fresh key to
4039/// everyone entitled EXCEPT `removed` (CORD-06 §1 single-channel rekey).
4040///
4041/// `roster` must be the caller's CURRENT view (fetched, not the local cache):
4042/// the recipient set is built from it, so a cached roster silently drops every
4043/// member granted since this client last folded — they keep a dead key with no
4044/// heal path. `access_ids` is that roster's access-role set for this channel;
4045/// `removed` is excluded explicitly, since the revoking Grant was published
4046/// moments ago and no fold has caught it.
4047async fn rekey_channel_excluding<T: Transport + ?Sized>(
4048    transport: &T,
4049    community: &CommunityV2,
4050    channel_id: &ChannelId,
4051    roster: &crate::community::roles::CommunityRoles,
4052    access_ids: &[String],
4053    removed: &PublicKey,
4054) -> Result<(), String> {
4055    let session = SessionGuard::capture();
4056    // Whole-row save below — serialize with the follow worker (see create_*_channel).
4057    let lock = super::realtime::follow_lock(community.id());
4058    let _guard = lock.lock().await;
4059    let signer = crate::signer::active_signer()?;
4060    let my_pk = me_pk()?;
4061    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
4062    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
4063    let ch = community.channel(channel_id).ok_or("unknown channel")?.clone();
4064    let old_key = ch.key.ok_or("we hold no key for this channel, so we cannot rotate it")?;
4065    let new_epoch = Epoch(ch.epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
4066    let owner = community.owner()?;
4067    let owner_hex = owner.to_hex();
4068
4069    // Everyone still entitled: the owner (always), me (the rotator must be able
4070    // to read what it rekeys), and every member the roster shows holding an
4071    // access role — minus the removal.
4072    let removed_hex = removed.to_hex();
4073    let mut recipients: Vec<PublicKey> = vec![my_pk];
4074    if owner != my_pk {
4075        recipients.push(owner);
4076    }
4077    for g in &roster.grants {
4078        if g.member == removed_hex || g.member == owner_hex {
4079            continue;
4080        }
4081        if !g.role_ids.iter().any(|id| access_ids.contains(id)) {
4082            continue;
4083        }
4084        if let Ok(pk) = PublicKey::parse(&g.member) {
4085            if !recipients.contains(&pk) {
4086                recipients.push(pk);
4087            }
4088        }
4089    }
4090    // Mint-or-reuse keyed by (channel, next epoch) so a retry after a partial
4091    // publish re-uses the same key instead of forking the epoch.
4092    let new_key = mint_or_reuse_rotation_key(&cid_hex, &chan_hex, new_epoch.0)?;
4093    let prev_commit = super::derive::epoch_key_commitment(ch.epoch, &old_key);
4094    let mut blobs = Vec::with_capacity(recipients.len());
4095    for r in &recipients {
4096        blobs.push(
4097            rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(*channel_id), new_epoch, &new_key)
4098                .await
4099                .map_err(|e| e.to_string())?,
4100        );
4101    }
4102    let group = channel_rekey_group_key(&community.community_root, channel_id, new_epoch);
4103    let at_secs = now_ms() / 1000;
4104    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())
4105        .await
4106        .map_err(|e| e.to_string())?;
4107    if !session.is_valid() {
4108        return Err("account changed during channel rekey".to_string());
4109    }
4110    for c in &chunks {
4111        transport.publish_durable(c, &community.relays).await?;
4112    }
4113    if !session.is_valid() {
4114        return Err("account changed during channel rekey".to_string());
4115    }
4116    if crate::db::community::community_protocol(community.id())?.is_none() {
4117        return Err("community removed during channel rekey".to_string());
4118    }
4119    // Adopt locally + archive, so our own history reads across the rotation.
4120    crate::db::community::advance_channel_epoch(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;
4121    crate::db::community::store_epoch_key(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;
4122    Ok(())
4123}
4124
4125/// Tombstone a channel (CORD-03 §2, `deleted: true`) + drop it locally. Reader-gated by
4126/// `MANAGE_CHANNELS`; the coordinate stays folded as a grave so peers hide it.
4127pub async fn delete_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, name: &str) -> Result<(), String> {
4128    let session = SessionGuard::capture();
4129    // Whole-row save below — serialize with the follow worker (see create_*_channel).
4130    let lock = super::realtime::follow_lock(community.id());
4131    let _guard = lock.lock().await;
4132    let my_pk = me_pk()?;
4133    ensure_channel_manager(community, &my_pk)?;
4134    // The tombstone carries the FULL held document (deleted flag set): a strict
4135    // reader treats an edition as the entity, so even a deletion must not strip
4136    // fields it didn't touch (CORD-02 §6).
4137    let mut meta = community.channel(channel_id).map(|c| c.metadata()).unwrap_or_else(|| control::ChannelMetadata {
4138        name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default(),
4139    });
4140    meta.deleted = Some(true);
4141    let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
4142    publish_control_edition(transport, community, &session, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
4143    if !session.is_valid() {
4144        return Err("account changed during channel delete".to_string());
4145    }
4146    let mut updated = community.clone();
4147    updated.channels.retain(|c| c.id.0 != channel_id.0);
4148    crate::db::community::save_community_v2(&updated)?;
4149    Ok(())
4150}
4151
4152// ── Live control-follow (CORD-02 §6 / CORD-03 §2) ────────────────────────────
4153
4154/// Re-fold this community's Control Plane and apply the current metadata +
4155/// **public** channel set to the held community, persisting any change. Called
4156/// when a control-plane wrap arrives in realtime (a rename, a new channel, an
4157/// edited description) so a long-running bot tracks the community mid-session
4158/// instead of freezing at its join-time view.
4159///
4160/// **Authority (CORD-04 §5):** the roster (roles/grants/banlist) folds first into
4161/// the owner-seeded authorized set ([`fold_authority`]), then each metadata/channel
4162/// edition is eligible only if its signer CURRENTLY holds the entity's management
4163/// bit (`MANAGE_METADATA`/`MANAGE_CHANNELS`) — so an authorized admin's edits fold,
4164/// a demoted one's drop. The owner is supreme, proven by the self-certifying
4165/// community_id (no network trust).
4166///
4167/// **Private channels are skipped here:** a Private channel's Chat-Plane key is
4168/// delivered over the rekey plane (or an invite bundle), never derivable from a
4169/// control edition alone. A new Private channel therefore surfaces only once
4170/// [`follow_rekeys`] delivers its key. Public channels derive from the
4171/// community_root, so they fold in directly.
4172///
4173/// Returns the updated community iff something changed (so the caller can skip a
4174/// redundant re-subscribe + refresh notification).
4175pub async fn follow_control<T: Transport + ?Sized>(
4176    transport: &T,
4177    community: &CommunityV2,
4178    session: &SessionGuard,
4179) -> Result<Option<CommunityV2>, String> {
4180    community.owner()?; // fail fast if the community is somehow unproven.
4181    let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
4182    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
4183
4184    // Per-entity refuse-downgrade floors for the CURRENT epoch only. A head recorded
4185    // under a prior epoch is excluded, so that entity auto-bootstraps after a
4186    // Refounding (Armada accepts a compacted head across a dangling prev — matched).
4187    // A read error FAILS CLOSED: an empty map would silently re-open the rollback
4188    // window the floor exists to shut.
4189    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
4190        .into_iter()
4191        .filter(|(_, f)| f.0 == community.root_epoch.0)
4192        .map(|(entity, f)| (entity, (f.1, f.2, f.3)))
4193        .collect();
4194
4195    // Newest window first; page OLDER only while a tracking entity is gapped (its
4196    // floor link evicted from the window — H1/M8 refetch), bounded like the join
4197    // verifier. A withholding relay still converges to fail-closed after the cap.
4198    let mut editions: Vec<ParsedEdition> = Vec::new();
4199    let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
4200    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
4201    let mut oldest: Option<u64> = None;
4202    let mut until: Option<u64> = None;
4203    let mut fold = ControlFold { updated: None, heads: Vec::new(), gapped: false };
4204    let mut authority = AuthoritySet::owner_only();
4205    // Whether this round gave up with editions still unread. The follow is
4206    // procedural by design — process what arrives, converge with everyone else —
4207    // so a short read never blocks reading, writing or epoch adoption. It only
4208    // withholds the ROSTER cache below: caching a partial authority as this
4209    // device's baseline is the one step that outlives the round.
4210    let mut truncated = true;
4211    for _ in 0..FOLLOW_MAX_PAGES {
4212        // Quorum, DECLARED (the until→Full transport floor is gone): these
4213        // control reads tolerate a partial union — their fold semantics are
4214        // fail-safe on gaps (seeded banlists, withheld roster cache).
4215        let query = Query {
4216            kinds: vec![stream::KIND_WRAP],
4217            authors: vec![control.pk_hex()],
4218            until,
4219            limit: Some(FOLLOW_PAGE),
4220            evidence: crate::community::transport::Evidence::Quorum,
4221            ..Default::default()
4222        };
4223        let wraps = transport.fetch(&query, &community.relays).await?;
4224        // The `until` cursor is INCLUSIVE (a `-1` step can skip same-second siblings
4225        // at a page boundary); the wrap-id dedup makes re-served boundary events
4226        // free, and a page with nothing new means the relay is exhausted.
4227        let mut fresh = 0usize;
4228        for w in &wraps {
4229            if !seen_wraps.insert(w.id) {
4230                continue;
4231            }
4232            fresh += 1;
4233            let at = w.created_at.as_secs();
4234            if oldest.is_none_or(|o| at < o) {
4235                oldest = Some(at);
4236            }
4237            // Open + seal-verify every edition; authority is resolved by the roster
4238            // fold (CORD-04 §5), not by a signer filter here — an admin's edits fold.
4239            if let Ok((ed, _)) = control::open_control_edition(w, &control) {
4240                if seen.insert(ed.inner_id) {
4241                    editions.push(ed);
4242                }
4243            }
4244        }
4245        // Roster first (roles/grants/banlist → authorized set), then the authority-
4246        // gated metadata/channel fold over the same edition set.
4247        authority = fold_authority(community, &editions, &floors);
4248        fold = apply_control_fold(community, &editions, &floors, &authority);
4249        if !(fold.gapped || authority.gapped) {
4250            truncated = false; // nothing is gapped: this view is coherent
4251            break;
4252        }
4253        if fresh == 0 {
4254            // A FULL page with nothing new is a same-second wall no `until` steps
4255            // past, so older editions stay unreachable; a short page is the end
4256            // of the plane, and a gap in THAT is the relay withholding, not us
4257            // giving up early.
4258            truncated = wraps.len() >= FOLLOW_PAGE;
4259            break;
4260        }
4261        until = oldest;
4262    }
4263
4264    // The fetches straddled awaits; a swap since the guard was captured must not
4265    // write account A's control state into B.
4266    if !session.is_valid() {
4267        return Err("account changed during control follow".to_string());
4268    }
4269    // A leave/delete raced this follow: writing now would resurrect the community
4270    // row and orphan floor rows past delete_community's wipe.
4271    if crate::db::community::community_protocol(community.id())?.is_none() {
4272        return Ok(None);
4273    }
4274    // Persist advanced floors BEFORE the state save (a failed floor write must not
4275    // let saved state outrun its floor), stamping the epoch this fold ran under —
4276    // not the row's write-time value, which a concurrent re-founding can bump. Both
4277    // the metadata/channel heads and the roster/banlist heads advance their floors;
4278    // run the advance (v+1) and same-version convergence (fork tiebreak) paths.
4279    for h in fold.heads.iter().chain(authority.heads.iter()) {
4280        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)?;
4281        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)?;
4282    }
4283    // Persist the authorized banlist content (retained/withholding folds carry None,
4284    // so the stored banlist is left intact — an anti-roster never silently un-bans).
4285    let mut authority_changed = false;
4286    // Ban marks MERGE (never replace): they must outlive both the ban and this window,
4287    // so a later un-ban can't resurrect a pre-ban Join. Persisted even when the banlist
4288    // itself was retained — the history is what the suppression reads.
4289    let _ = crate::db::community::merge_community_ban_marks(&cid_hex, &authority.banned_at);
4290    if let Some((banned, version)) = &authority.banlist_persist {
4291        let mut before = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
4292        crate::db::community::set_community_banlist(&cid_hex, banned, *version as i64)?;
4293        let mut after = banned.clone();
4294        before.sort();
4295        after.sort();
4296        authority_changed |= before != after;
4297    }
4298    // Persist the authorized roster so capabilities/roles stay sync LOCAL reads
4299    // (v1 parity: the passive follow folds, reads never fetch). Guarded like v1's
4300    // fetch path: only an aggregate built from roster editions at least as new as
4301    // the stored one may replace it — a withholding relay serving NO roster
4302    // editions folds an empty-but-ungapped aggregate (absence raises no gap flag),
4303    // and that must RETAIN the stored roster, never wipe standing.
4304    let newest_roster_at: i64 = editions
4305        .iter()
4306        .filter(|e| e.vsk == vsk::ROLE || e.vsk == vsk::GRANT || e.vsk == vsk::BANLIST)
4307        .map(|e| e.created_at as i64)
4308        .max()
4309        .unwrap_or(0);
4310    // Completeness gate: the `gapped` flag only covers entities present in the window.
4311    // A role/grant floored on this device but with ZERO editions fetched (aged out of
4312    // the paging reach) folds absent yet raises no gap — persisting would silently drop
4313    // it. So if any CURRENTLY-STORED entity is floored but folded no head this round,
4314    // RETAIN. A real revoke still folds a head (see select_authorized), so it persists.
4315    let stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
4316    let head_ents: std::collections::HashSet<&str> = authority.heads.iter().map(|h| h.entity_hex.as_str()).collect();
4317    let stored_complete = stored.roles.iter().all(|r| !floors.contains_key(&r.role_id) || head_ents.contains(r.role_id.as_str()))
4318        && stored.grants.iter().all(|g| {
4319            crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
4320                let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &m));
4321                !floors.contains_key(&eid) || head_ents.contains(eid.as_str())
4322            })
4323        });
4324    // `truncated` covers the case the other three can't: a COLD device (no floors,
4325    // no stored roster) folding under a plane a member has inflated past the pager.
4326    // `stored_complete` is trivially true with nothing stored, so without this the
4327    // first sync would cache a partial authority as its own baseline.
4328    if !truncated && !authority.gapped && stored_complete && newest_roster_at >= crate::db::community::get_community_roles_at(&cid_hex)? {
4329        authority_changed |= stored != authority.roles;
4330        crate::db::community::set_community_roles(&cid_hex, &authority.roles, newest_roster_at)?;
4331    }
4332    // Cache the folded invite Registry so Public/Private stays a sync LOCAL read
4333    // (v1 parity — `invite_registry` is the column every caller reads). Gated like
4334    // the roster: a truncated or gapped window folds an empty registry out of mere
4335    // absence, and persisting that under-states Public — the unsafe direction, since
4336    // it leaves a live link open behind a ban.
4337    if !truncated && !authority.gapped && !fold.gapped {
4338        if let Ok(owner) = community.owner() {
4339            let sets = live_invite_link_sets(community.id(), &owner.to_hex(), &editions, &authority, &floors);
4340            let live = flatten_link_sets(&sets);
4341            let mut before = crate::db::community::get_community_invite_registry(&cid_hex).unwrap_or_default();
4342            before.sort();
4343            if before != live {
4344                crate::db::community::set_community_invite_registry(&cid_hex, &live)?;
4345                authority_changed = true;
4346            }
4347            // The per-creator split drives "X has N active invite links" and the
4348            // first-link-flips-Public confirm; it lives in its own table.
4349            crate::db::community::replace_invite_link_sets(&cid_hex, &sets)?;
4350        }
4351    }
4352    // Roster/banlist moves are invisible in the returned community (they live in
4353    // their own columns), so callers that key a refresh off `updated` would never
4354    // repaint a promote/demote/ban. Announce from the single fold point — it covers
4355    // realtime, boot catch-up and manual sync alike.
4356    if authority_changed {
4357        crate::emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
4358    }
4359    match fold.updated {
4360        Some(u) => {
4361            crate::db::community::save_community_v2(&u)?;
4362            Ok(Some(u))
4363        }
4364        None => Ok(None),
4365    }
4366}
4367
4368/// Control-follow paging bounds: enough depth to re-anchor a long-offline floor
4369/// (H1/M8 refetch) without letting a flooding relay stall the follow queue.
4370///
4371/// Nearly free to raise: both follow loops exit the moment the fold stops being
4372/// gapped, so the cap only binds when something is genuinely missing — exactly
4373/// when paging further is what's wanted. The old ceiling of 4 (~2k editions) sat
4374/// under a plane that 100 roles + 400 grants already outgrows before counting
4375/// superseded versions, which accumulate until a compaction retires them.
4376const FOLLOW_MAX_PAGES: usize = 32;
4377const FOLLOW_PAGE: usize = 500;
4378/// Page ceiling for a COMPACTION read (CORD-06 §3: a Refounder that cannot fold
4379/// every Control Event must abort). Far above any real plane, but plane depth is
4380/// attacker-controlled — any member holds the key that mints wraps — so the read
4381/// is bounded and reports coming up short rather than compacting a partial view.
4382const COMPACT_MAX_PAGES: usize = 512;
4383
4384/// A folded control head to persist as the per-entity refuse-downgrade floor.
4385#[derive(Clone)]
4386struct FoldedHead {
4387    entity_hex: String,
4388    version: u64,
4389    self_hash: [u8; 32],
4390    inner_id: [u8; 32],
4391}
4392
4393/// The outcome of a floor-aware control fold: the updated community (if content
4394/// changed), the heads to persist as the new floor (returned even when content is
4395/// unchanged, so the floor still seeds/advances), and whether any TRACKING entity
4396/// hit an unresolvable gap — the caller's signal to page older history and re-fold
4397/// (CORD-04 H1/M8's refetch).
4398struct ControlFold {
4399    updated: Option<CommunityV2>,
4400    heads: Vec<FoldedHead>,
4401    gapped: bool,
4402}
4403
4404/// Per-entity floor: `(version, self_hash, inner_id)` of the committed head.
4405type Floors = std::collections::HashMap<String, (u64, [u8; 32], Option<[u8; 32]>)>;
4406
4407/// Fold owner-authored control editions into an updated community using the
4408/// PERSISTED per-entity version floor (refuse-downgrade). Per entity, fold with
4409/// [`version::fold`]`(floor, floor_hash)`:
4410///   - ANCHORED: adopt the chain-verified head. A `gap` ABOVE it (withheld middles)
4411///     doesn't block the verified prefix — refuse-downgrade holds for everything
4412///     applied — but flags `gapped` so the caller pages for the rest.
4413///   - UNANCHORED under a held floor: one legitimate cause is a same-version owner
4414///     fork AT the floor whose deterministic winner (lower inner id; a NULL held id
4415///     is always replaceable, mirroring v1's `decide()`) isn't our held edition —
4416///     the floor CONVERGES to the winner and the chain re-anchors on it, so every
4417///     client lands on the same head where a hash-strict floor would wedge forever.
4418///     Anything else is withholding → fail closed + `gapped`.
4419///   - BOOTSTRAPPING (`floor == 0` — a fresh joiner, or a fresh epoch after a
4420///     Refounding, since the caller epoch-filters the floor) takes the highest
4421///     signed head (author already owner-filtered).
4422/// This matches CORD-04 §1 and mirrors v1's `fold_roster`. Epoch-filtering makes a
4423/// compaction at a new epoch auto-bootstrap, converging with Armada's acceptance of
4424/// a compacted head across a dangling `prev` (Armada doesn't persist a floor, so a
4425/// Vector floor only makes Vector STRICTER locally — no wire change, honest-case
4426/// convergence preserved).
4427fn apply_control_fold(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors, authority: &AuthoritySet) -> ControlFold {
4428    use crate::community::roles::Permissions;
4429    use std::collections::BTreeMap;
4430
4431    let owner_hex = community.owner().ok().map(|o| o.to_hex());
4432
4433    let mut groups: BTreeMap<(String, [u8; 32]), Vec<&ParsedEdition>> = BTreeMap::new();
4434    for e in editions {
4435        groups.entry((e.vsk.clone(), e.entity_id)).or_default().push(e);
4436    }
4437
4438    let mut out = community.clone();
4439    let mut changed = false;
4440    let mut heads = Vec::new();
4441    let mut gapped = false;
4442    for ((vsk_code, eid), group) in &groups {
4443        // This fold applies exactly two entities: community metadata (eid ==
4444        // community_id) and channel metadata. A vsk-2 whose eid equals the community
4445        // id is excluded — the floor row keys on the entity alone, so it would share
4446        // (and corrupt) the metadata chain's floor.
4447        let is_meta = vsk_code == vsk::COMMUNITY_METADATA && *eid == community.id().0;
4448        let is_channel = vsk_code == vsk::CHANNEL_METADATA && *eid != community.id().0;
4449        if !is_meta && !is_channel {
4450            continue;
4451        }
4452        // Authority gate (CORD-04 §5): only editions whose author CURRENTLY holds the
4453        // entity's management bit are eligible. Pre-filtering before the fold means a
4454        // demoted admin's (possibly higher-version) edition can't be the head; the
4455        // highest AUTHORIZED head wins. The owner is supreme.
4456        let required = if is_meta { Permissions::MANAGE_METADATA } else { Permissions::MANAGE_CHANNELS };
4457        let authed: Vec<&ParsedEdition> = group
4458            .iter()
4459            .copied()
4460            .filter(|e| {
4461                let author = e.author.to_hex();
4462                // A banned npub's edits are dropped (CORD-04 §4), even if they still
4463                // held a bit via a not-yet-stripped grant.
4464                !authority.banned.contains(&author)
4465                    && authority.roles.is_authorized(&author, owner_hex.as_deref(), required)
4466                    // …and the CORD-04 §5 sync floor. Resolved against the Grant heads
4467                    // this same fold settled, so it works on a bootstrap where no
4468                    // persisted head exists yet.
4469                    && citation_ok_in_fold(community.id(), &authority.heads, owner_hex.as_deref(), &e.author, e.authority.as_ref())
4470            })
4471            .collect();
4472        if authed.is_empty() {
4473            continue;
4474        }
4475        let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
4476        let fold_eds: Vec<version::Edition> = authed.iter().map(|p| p.to_fold_edition()).collect();
4477        let (hi, entity_gapped) = fold_head(&fold_eds, floors.get(&entity_hex));
4478        gapped |= entity_gapped;
4479        let Some(hi) = hi else { continue };
4480
4481        let head = authed[hi];
4482        heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id });
4483        if is_meta {
4484            if let Ok(meta) = serde_json::from_str::<control::CommunityMetadata>(&head.content) {
4485                changed |= apply_community_metadata(&mut out, meta);
4486            }
4487        } else if let Ok(meta) = serde_json::from_str::<control::ChannelMetadata>(&head.content) {
4488            // vsk-2 carries no community binding (shared v1 grammar); a same-owner
4489            // cross-community replay can inject a phantom PUBLIC channel (bounded:
4490            // root-scoped key, eids don't collide). Binding is a deferred wire change.
4491            changed |= apply_channel_metadata(&mut out, ChannelId(*eid), meta);
4492        }
4493    }
4494    ControlFold { updated: changed.then_some(out), heads, gapped }
4495}
4496
4497/// Fold one entity's editions against its persisted floor into a head index (into the
4498/// input slice) plus whether a TRACKING gap was hit (the caller pages older history).
4499/// Encapsulates the W2 refuse-downgrade policy: bootstrap at floor 0 (highest signed
4500/// head, what Armada shows across a compaction's dangling prev); adopt the chain-
4501/// anchored head, paging on an upper gap; converge a same-version fork at the floor to
4502/// the lower-inner-id winner; and fail closed otherwise.
4503fn fold_head(fold_eds: &[version::Edition], floor: Option<&(u64, [u8; 32], Option<[u8; 32]>)>) -> (Option<usize>, bool) {
4504    let floor_v = floor.map(|f| f.0).unwrap_or(0);
4505    if floor_v == 0 {
4506        return (version::bootstrap_head(fold_eds, 0), false);
4507    }
4508    let floor_hash = floor.map(|f| &f.1);
4509    let held_inner = floor.and_then(|f| f.2);
4510    let result = version::fold(fold_eds, floor_v, floor_hash);
4511    if result.anchored {
4512        return (result.head, result.gap); // verified prefix; page any upper gap.
4513    }
4514    if result.head.is_none() && !result.gap {
4515        return (None, false); // everything below floor — a stale relay, no paging.
4516    }
4517    // Unanchored under a held floor: converge a same-version fork at the floor to its
4518    // deterministic winner (lower inner id; a NULL held id is always replaceable),
4519    // else fail closed.
4520    let fork = fold_eds.iter().enumerate().filter(|(_, e)| e.version == floor_v).min_by_key(|(_, e)| e.tiebreak_id);
4521    let win_hash = match fork {
4522        Some((_, w)) if floor_hash != Some(&w.self_hash) && held_inner.is_none_or(|h| w.tiebreak_id < h) => w.self_hash,
4523        _ => return (None, true), // detached from our committed head → withholding.
4524    };
4525    let re = version::fold(fold_eds, floor_v, Some(&win_hash));
4526    if !re.anchored {
4527        return (None, true);
4528    }
4529    (re.head, re.gap)
4530}
4531
4532/// The folded, delegation-AUTHORIZED control-plane authority (CORD-04): the roster
4533/// (roles + grants, owner-seeded fixpoint), the enforced banlist, and the
4534/// role/grant/banlist heads to persist as refuse-downgrade floors. The owner is
4535/// recomputed from the self-certifying community_id at each use.
4536struct AuthoritySet {
4537    roles: crate::community::roles::CommunityRoles,
4538    banned: std::collections::BTreeSet<String>,
4539    heads: Vec<FoldedHead>,
4540    gapped: bool,
4541    /// The authorized banlist `(content, version)` to persist when an authorized head
4542    /// advanced the floor. `None` when the banlist was retained (no new authorized
4543    /// head) or is empty — the caller then leaves the stored banlist untouched.
4544    banlist_persist: Option<(Vec<String>, u64)>,
4545    /// Ban HISTORY: npub hex → `created_at` (secs) of the newest authorized edition that
4546    /// named them, across every edition in the window rather than just the head. Outlives
4547    /// the ban itself so an un-ban can't resurrect a phantom (see [`fold_members`]).
4548    banned_at: std::collections::BTreeMap<String, u64>,
4549}
4550
4551impl AuthoritySet {
4552    /// Bootstrap authority for a community with no roster editions folded yet: only
4553    /// the owner is authorized (supreme), nobody banned.
4554    fn owner_only() -> Self {
4555        AuthoritySet {
4556            roles: Default::default(),
4557            banned: Default::default(),
4558            heads: vec![],
4559            gapped: false,
4560            banlist_persist: None,
4561            banned_at: Default::default(),
4562        }
4563    }
4564}
4565
4566/// Fold the roster/banlist entities (vsk 1/3/4) from the control editions into the
4567/// delegation-AUTHORIZED roster + enforced banlist (CORD-04 §2-§5). Each entity binds
4568/// to its coordinate (role at role_id, grant at grant_locator(cid, member), banlist at
4569/// banlist_locator(cid)); a content whose coordinate doesn't match is dropped. Roles
4570/// cap at the 100 lowest role_ids, a member at 64 roles, the banlist at 500. The
4571/// banlist is enforced only if its head's signer held BAN in the authorized roster.
4572fn fold_authority(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors) -> AuthoritySet {
4573    use crate::community::roles::Permissions;
4574    use std::collections::BTreeMap;
4575
4576    let cid = community.id();
4577    let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
4578    let owner = community.owner().ok();
4579    let owner_hex = owner.map(|o| o.to_hex());
4580    let banlist_eid = super::derive::banlist_locator(cid);
4581    let banlist_hex = crate::simd::hex::bytes_to_hex_32(&banlist_eid);
4582
4583    let mut groups: BTreeMap<[u8; 32], Vec<&ParsedEdition>> = BTreeMap::new();
4584    for e in editions {
4585        if e.vsk == vsk::ROLE || e.vsk == vsk::GRANT || e.vsk == vsk::BANLIST {
4586            groups.entry(e.entity_id).or_default().push(e);
4587        }
4588    }
4589
4590    // Per-entity CANDIDATE lists — every ≥floor edition of a role/grant, highest
4591    // version first (lowest inner-id as the deterministic tiebreak). CORD-04 §1: an
4592    // edition whose signer isn't authorized is SIMPLY DROPPED and the fold continues
4593    // to the next candidate, so a forged higher-version edition can't suppress the
4594    // authorized head beneath it (the author-blind collapse-to-one-head it replaces
4595    // let any member vanish a role or a member's grant). `gapped` (drives older-
4596    // paging) stays fold_head's per-entity flag.
4597    let mut role_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
4598    let mut grant_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
4599    let mut gapped = false;
4600
4601    for (eid, group) in &groups {
4602        // The banlist is folded author-aware AFTER the roster is known (below).
4603        if *eid == banlist_eid {
4604            continue;
4605        }
4606        let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
4607        let fold_eds: Vec<version::Edition> = group.iter().map(|p| p.to_fold_edition()).collect();
4608        let (_hi, entity_gapped) = fold_head(&fold_eds, floors.get(&entity_hex));
4609        gapped |= entity_gapped;
4610        let floor_v = floors.get(&entity_hex).map(|f| f.0).unwrap_or(0);
4611
4612        for p in group {
4613            // Refuse-downgrade: never consider an edition below the persisted floor.
4614            if p.version < floor_v {
4615                continue;
4616            }
4617            let head = FoldedHead { entity_hex: entity_hex.clone(), version: p.version, self_hash: p.self_hash, inner_id: p.inner_id };
4618            match p.vsk.as_str() {
4619                vsk::ROLE => {
4620                    // Bind: the content's role_id IS the coordinate; position 0 is the owner's.
4621                    if let Some(role) = super::roles::parse_role_content(&p.content) {
4622                        if role.role_id == entity_hex && role.position != 0 {
4623                            role_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: Some(role), grant: None, author: p.author, head, citation: p.authority.clone() });
4624                        }
4625                    }
4626                }
4627                vsk::GRANT => {
4628                    if let Some(mut grant) = super::roles::parse_grant_content(&p.content) {
4629                        if let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(&grant.member) {
4630                            if super::derive::grant_locator(cid, &member) == *eid {
4631                                grant.role_ids.truncate(super::roles::MAX_ROLES_PER_MEMBER);
4632                                grant_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: None, grant: Some(grant), author: p.author, head, citation: p.authority.clone() });
4633                            }
4634                        }
4635                    }
4636                }
4637                _ => {}
4638            }
4639        }
4640    }
4641    for cands in role_cands.values_mut().chain(grant_cands.values_mut()) {
4642        cands.sort_by(|a, b| b.head.version.cmp(&a.head.version).then(a.head.inner_id.cmp(&b.head.inner_id)));
4643    }
4644
4645    let empty: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
4646    // Preliminary roster (bans not yet applied) — the authority view the banlist head
4647    // is judged against.
4648    let (prelim, prelim_heads) = select_authorized(cid, &role_cands, &grant_cands, owner_hex.as_deref(), &empty);
4649
4650    // Banlist (CORD-04 §4), folded AUTHORITY-aware so its two anti-roster hazards are
4651    // both closed:
4652    //   - head selection: the head is the highest version whose author CURRENTLY holds
4653    //     BAN — an unauthorized higher-version edition can't erase existing bans
4654    //     (fail-open), and the floor never advances to one;
4655    //   - per-target: each entry is kept only if the author STRICTLY OUTRANKS that
4656    //     target (`can_act_on_member` — an admin can't ban a peer/superior, and the
4657    //     owner is unbannable);
4658    //   - withholding: when no authorized head is served, the persisted banlist is
4659    //     RETAINED (an anti-roster must not un-ban on a relay withholding the ban).
4660    let persisted_banned: Vec<String> = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
4661    // An ALREADY-banned npub can't author the banlist (a banned member vanishes, §4), or
4662    // a BAN-holder whose grant-strip hasn't yet folded could publish a list omitting their
4663    // OWN ban to un-ban themselves (removals aren't outrank-checked). Exclude them from
4664    // head eligibility, not just from the roster.
4665    let banned_authors: std::collections::HashSet<&str> = persisted_banned.iter().map(String::as_str).collect();
4666    let banlist_authored: Vec<&ParsedEdition> = groups
4667        .get(&banlist_eid)
4668        .map(|g| {
4669            g.iter()
4670                .copied()
4671                .filter(|e| {
4672                    let ah = e.author.to_hex();
4673                    !banned_authors.contains(ah.as_str())
4674                        && prelim.is_authorized(&ah, owner_hex.as_deref(), Permissions::BAN)
4675                        && citation_ok_in_fold(cid, &prelim_heads, owner_hex.as_deref(), &e.author, e.authority.as_ref())
4676                })
4677                .collect()
4678        })
4679        .unwrap_or_default();
4680    // Ban history for phantom suppression: the newest AUTHORIZED edition naming each npub,
4681    // over EVERY candidate rather than only the head — an un-ban replaces the head, so the
4682    // head alone forgets the ban that the suppression exists to remember. The owner is
4683    // skipped: they are never bannable, and a moderator listing them must not durably
4684    // suppress them past the un-ban.
4685    let mut banned_at: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();
4686    for p in &banlist_authored {
4687        for t in super::roles::parse_banlist_content(&p.content).unwrap_or_default() {
4688            if owner_hex.as_deref() == Some(t.as_str()) {
4689                continue;
4690            }
4691            let slot = banned_at.entry(t).or_insert(0);
4692            *slot = (*slot).max(p.created_at);
4693        }
4694    }
4695    let mut banlist_persist: Option<(Vec<String>, u64)> = None;
4696    let mut banlist_head: Option<FoldedHead> = None;
4697    let banned: std::collections::BTreeSet<String> = if banlist_authored.is_empty() {
4698        persisted_banned.into_iter().collect()
4699    } else {
4700        let fold_eds: Vec<version::Edition> = banlist_authored.iter().map(|p| p.to_fold_edition()).collect();
4701        let (hi, g) = fold_head(&fold_eds, floors.get(&banlist_hex));
4702        gapped |= g;
4703        match hi {
4704            Some(hi) => {
4705                let head = banlist_authored[hi];
4706                let ah = head.author.to_hex();
4707                let list: Vec<String> = super::roles::parse_banlist_content(&head.content)
4708                    .unwrap_or_default()
4709                    .into_iter()
4710                    .filter(|t| prelim.can_act_on_member(&ah, owner_hex.as_deref(), t, Permissions::BAN))
4711                    .take(super::roles::MAX_BANLIST)
4712                    .collect();
4713                banlist_head = Some(FoldedHead { entity_hex: banlist_hex.clone(), version: head.version, self_hash: head.self_hash, inner_id: head.inner_id });
4714                banlist_persist = Some((list.clone(), head.version));
4715                list.into_iter().collect()
4716            }
4717            None => persisted_banned.into_iter().collect(),
4718        }
4719    };
4720
4721    // Final roster (CORD-04 §4: a banned npub vanishes — every edition it authored is
4722    // dropped, and a grant TO a banned member carries no rank). Re-run selection with
4723    // the banned set excluded so a banned admin loses authority.
4724    let (mut authorized, mut heads) = select_authorized(cid, &role_cands, &grant_cands, owner_hex.as_deref(), &banned);
4725    if let Some(bh) = banlist_head {
4726        heads.push(bh);
4727    }
4728
4729    // Cap the AUTHORIZED community at the 100 lowest role_ids — applied AFTER
4730    // authorization, so an attacker's unauthorized roles can't consume cap slots and
4731    // evict a legitimate one (the pre-authorize cap they replace let 100 forged low-id
4732    // roles empty the roster).
4733    if authorized.roles.len() > super::roles::MAX_ROLES_PER_COMMUNITY {
4734        authorized.roles.sort_by(|a, b| a.role_id.cmp(&b.role_id));
4735        authorized.roles.truncate(super::roles::MAX_ROLES_PER_COMMUNITY);
4736        let kept: std::collections::HashSet<&str> = authorized.roles.iter().map(|r| r.role_id.as_str()).collect();
4737        authorized.grants.iter_mut().for_each(|g| g.role_ids.retain(|rid| kept.contains(rid.as_str())));
4738        authorized.grants.retain(|g| !g.role_ids.is_empty());
4739    }
4740
4741    AuthoritySet { roles: authorized, banned, heads, gapped, banlist_persist, banned_at }
4742}
4743
4744/// One candidate edition of a role/grant entity — the pool [`select_authorized`]
4745/// draws the highest AUTHORIZED head from (exactly one of `role`/`grant` is set).
4746struct AuthorityCand {
4747    role: Option<crate::community::roles::Role>,
4748    grant: Option<crate::community::roles::MemberGrant>,
4749    author: PublicKey,
4750    head: FoldedHead,
4751    /// The `vac` this edition carried (CORD-04 §5). `None` for an owner edition
4752    /// (supreme, cites nothing) or an uncited one — the latter is refused.
4753    citation: Option<crate::community::edition::AuthorityCitation>,
4754}
4755
4756/// CORD-04 §5 sync floor, resolved against the heads THIS fold pass has accepted.
4757///
4758/// Deliberately not the persisted-head helper the kick/hide paths use: this IS the
4759/// pass that establishes those heads, so an external floor would refuse every
4760/// non-owner edition on a bootstrap and the roster could never fold. Same rule the
4761/// spec gives for a dangling `prev` across a Refounding — a fresh joiner takes the
4762/// authority-verified head as its baseline, a tracking client fails closed per
4763/// entity — applied to the citation instead of the chain link.
4764fn citation_ok_in_fold(
4765    cid: &crate::community::CommunityId,
4766    heads: &[FoldedHead],
4767    owner_hex: Option<&str>,
4768    author: &PublicKey,
4769    citation: Option<&crate::community::edition::AuthorityCitation>,
4770) -> bool {
4771    let actor_hex = author.to_hex();
4772    if owner_hex == Some(actor_hex.as_str()) {
4773        return true;
4774    }
4775    let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &author.to_bytes()));
4776    let as_entity: Vec<crate::community::roster::EntityHead> = heads
4777        .iter()
4778        .map(|h| crate::community::roster::EntityHead {
4779            entity_hex: h.entity_hex.clone(),
4780            version: h.version,
4781            self_hash: h.self_hash,
4782            inner_id: h.inner_id,
4783            citation: None,
4784        })
4785        .collect();
4786    crate::community::roster::authority_citation_satisfied(&as_entity, owner_hex, &actor_hex, &grant_hex, citation)
4787}
4788
4789/// The owner-seeded delegation fixpoint (CORD-04 §1/§2), author-AWARE: per entity it
4790/// takes the highest-version candidate whose author is authorized to author it under
4791/// the roster resolved SO FAR, dropping unauthorized higher versions rather than
4792/// vanishing the entity. Authority resolves outward from the owner (proven by
4793/// `community_id`, never a Role), and the strict-outrank rule (no edition at/above its
4794/// signer's own position) keeps the fixpoint monotone, so it converges. Returns the
4795/// authorized roster plus the per-entity heads of the SELECTED editions (the floor
4796/// advances only to authorized heads — an unauthorized forgery never poisons it).
4797fn select_authorized(
4798    cid: &crate::community::CommunityId,
4799    role_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
4800    grant_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
4801    owner_hex: Option<&str>,
4802    excluded: &std::collections::BTreeSet<String>,
4803) -> (crate::community::roles::CommunityRoles, Vec<FoldedHead>) {
4804    use crate::community::roles::{CommunityRoles, Permissions};
4805    let mut accepted = CommunityRoles::default();
4806    let mut heads: Vec<FoldedHead> = Vec::new();
4807    // Jacobi iteration: authority propagates one delegation level per round, so a
4808    // generous multiple of the entity count is an ample bound. Non-convergence (never
4809    // seen for an owner-rooted chain) falls through fail-safe: only authorized editions
4810    // are ever selected.
4811    let bound = 2 * (role_cands.len() + grant_cands.len()) + 8;
4812    for _ in 0..bound {
4813        let mut next = CommunityRoles::default();
4814        let mut next_heads: Vec<FoldedHead> = Vec::new();
4815
4816        for cands in role_cands.values() {
4817            // Two gates, not one (CORD-04 §2). Minting at a position you outrank
4818            // is necessary but not sufficient: an edition REPLACES the entity, so
4819            // the author must also outrank the position standing before it.
4820            // Without that, an admin at position 5 rewrites the position-1 role
4821            // to position 9 — every check passes, since 9 is beneath them — and
4822            // a role that outranked them is now beneath them, along with everyone
4823            // holding it. Rank inversion by republish.
4824            //
4825            // The chain is replayed ASCENDING so each version is judged against
4826            // the position its own predecessor established, then the highest
4827            // admissible version wins (candidates arrive version-DESC, forks
4828            // broken by lowest inner_id — preserved by walking version groups).
4829            let mut admissible: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
4830            let mut standing: Option<u32> = None;
4831            let mut i = cands.len();
4832            while i > 0 {
4833                let hi = i;
4834                let ver = cands[i - 1].head.version;
4835                while i > 0 && cands[i - 1].head.version == ver {
4836                    i -= 1;
4837                }
4838                // One winner per version: fork siblings can't sidestep the gate.
4839                for c in cands[i..hi].iter().rev() {
4840                    let Some(role) = &c.role else { continue };
4841                    let ah = c.author.to_hex();
4842                    if excluded.contains(&ah) || role.position == 0 {
4843                        continue;
4844                    }
4845                    if !accepted.can_act_on_position(&ah, owner_hex, role.position, Permissions::MANAGE_ROLES) {
4846                        continue;
4847                    }
4848                    if let Some(prev) = standing {
4849                        if !accepted.can_act_on_position(&ah, owner_hex, prev, Permissions::MANAGE_ROLES) {
4850                            continue;
4851                        }
4852                    }
4853                    if !citation_ok_in_fold(cid, &heads, owner_hex, &c.author, c.citation.as_ref()) {
4854                        continue;
4855                    }
4856                    admissible.insert(c.head.self_hash);
4857                    standing = Some(role.position);
4858                    break;
4859                }
4860            }
4861            for c in cands {
4862                let Some(role) = &c.role else { continue };
4863                if !admissible.contains(&c.head.self_hash) {
4864                    continue;
4865                }
4866                next.roles.push(role.clone());
4867                next_heads.push(c.head.clone());
4868                break; // highest admissible candidate for this entity
4869            }
4870        }
4871        for cands in grant_cands.values() {
4872            for c in cands {
4873                let Some(grant) = &c.grant else { continue };
4874                let ah = c.author.to_hex();
4875                if excluded.contains(&ah) || excluded.contains(&grant.member) {
4876                    continue;
4877                }
4878                // The granter must outrank every granted role (resolved against the
4879                // accepted roster) AND the member — the escalation defense (CORD-04 §2).
4880                let positions: Option<Vec<u32>> = grant.role_ids.iter().map(|rid| accepted.role(rid).map(|r| r.position)).collect();
4881                let Some(positions) = positions else { continue };
4882                if !citation_ok_in_fold(cid, &heads, owner_hex, &c.author, c.citation.as_ref()) {
4883                    continue;
4884                }
4885                if positions.iter().all(|p| accepted.can_act_on_position(&ah, owner_hex, *p, Permissions::MANAGE_ROLES))
4886                    && accepted.can_act_on_member(&ah, owner_hex, &grant.member, Permissions::MANAGE_ROLES)
4887                {
4888                    // Record the head even for an EMPTY grant (a revoke is a real chain
4889                    // advance a completeness check must see), but don't carry the husk
4890                    // into the roster.
4891                    next_heads.push(c.head.clone());
4892                    if !grant.role_ids.is_empty() {
4893                        next.grants.push(grant.clone());
4894                    }
4895                    break;
4896                }
4897            }
4898        }
4899
4900        let converged = next.roles == accepted.roles && next.grants == accepted.grants;
4901        accepted = next;
4902        heads = next_heads;
4903        if converged {
4904            break;
4905        }
4906    }
4907    (accepted, heads)
4908}
4909
4910/// Apply a folded community-metadata head. Relays only overwrite when the edition
4911/// carries a non-empty list (a metadata edition that omits relays must not blank
4912/// the working set). Returns whether anything changed.
4913fn apply_community_metadata(out: &mut CommunityV2, meta: control::CommunityMetadata) -> bool {
4914    let mut changed = false;
4915    if out.name != meta.name {
4916        out.name = meta.name;
4917        changed = true;
4918    }
4919    if out.description != meta.description {
4920        out.description = meta.description;
4921        changed = true;
4922    }
4923    // Icon/banner apply verbatim, None included — an edition is the full
4924    // document, so an absent image IS a removal (editors preserve via
4925    // `CommunityV2::metadata()`).
4926    if out.icon != meta.icon {
4927        out.icon = meta.icon;
4928        changed = true;
4929    }
4930    if out.banner != meta.banner {
4931        out.banner = meta.banner;
4932        changed = true;
4933    }
4934    // Client-extensible + unknown fields ride the fold verbatim so our own
4935    // editions can carry them forward (CORD-02 §6).
4936    if out.meta_custom != meta.custom {
4937        out.meta_custom = meta.custom;
4938        changed = true;
4939    }
4940    if out.meta_extra != meta.extra {
4941        out.meta_extra = meta.extra;
4942        changed = true;
4943    }
4944    // CAP on the way in. `cap_relays` is the truncate-on-read invariant for every
4945    // other construction boundary, and the fold is a boundary like any other: an
4946    // authorized editor is not a trusted one, and an oversize list costs every
4947    // member a fan-out on each publish and the slowest of N on each fetch
4948    // (CORD-02 §6 makes trimming explicitly a client's call). Compare against the
4949    // CAPPED list too — against the raw one, an oversize edition never compares
4950    // equal, so every fold would report a change and re-save forever.
4951    let relays = crate::community::cap_relays(meta.relays);
4952    if !relays.is_empty() && out.relays != relays {
4953        out.relays = relays;
4954        changed = true;
4955    }
4956    changed
4957}
4958
4959/// Apply a folded channel-metadata head: delete removes the channel, a rename
4960/// updates an existing one, a brand-new PUBLIC channel is added, and a brand-new
4961/// PRIVATE one is recorded KEYLESS (unreadable until its key arrives over the
4962/// rekey plane or a fresh bundle). Returns whether anything changed.
4963fn apply_channel_metadata(out: &mut CommunityV2, id: ChannelId, meta: control::ChannelMetadata) -> bool {
4964    let deleted = meta.deleted.unwrap_or(false);
4965    if deleted {
4966        let before = out.channels.len();
4967        out.channels.retain(|c| c.id.0 != id.0);
4968        return out.channels.len() != before;
4969    }
4970    match out.channels.iter_mut().find(|c| c.id.0 == id.0) {
4971        Some(existing) => {
4972            let mut changed = false;
4973            if existing.name != meta.name {
4974                existing.name = meta.name;
4975                changed = true;
4976            }
4977            // vsk-2 fields Vector doesn't drive still fold + persist, so a later
4978            // local edit republishes them instead of wiping (CORD-02 §6).
4979            if existing.voice != meta.voice {
4980                existing.voice = meta.voice;
4981                changed = true;
4982            }
4983            if existing.meta_custom != meta.custom {
4984                existing.meta_custom = meta.custom;
4985                changed = true;
4986            }
4987            if existing.meta_extra != meta.extra {
4988                existing.meta_extra = meta.extra;
4989                changed = true;
4990            }
4991            // The owner's edition authoritatively declares visibility. A channel the
4992            // owner marks PUBLIC must derive from the root (key = None) — this heals a
4993            // bundle-time misclassification where an attacker set a public channel's
4994            // grant key to their own, silently addressing it at a plane only they read.
4995            // Public → private CONVERSION is DEFERRED: the flip is IGNORED here (the
4996            // record stays public) until the convert flow (key mint + cursor rebase
4997            // to the conversion's channel epoch) lands — the send side refuses to
4998            // publish one, and a foreign client's conversion won't move us.
4999            if !meta.private && (existing.private || existing.key.is_some()) {
5000                existing.private = false;
5001                existing.key = None;
5002                changed = true;
5003            }
5004            changed
5005        }
5006        None if !meta.private => {
5007            // A public channel derives its Chat Plane from the community_root at the
5008            // current root epoch (key = None); its stored epoch mirrors the root.
5009            out.channels.push(ChannelV2 {
5010                id,
5011                name: meta.name,
5012                private: false,
5013                key: None,
5014                epoch: out.root_epoch,
5015                voice: meta.voice,
5016                meta_custom: meta.custom,
5017                meta_extra: meta.extra,
5018            });
5019            true
5020        }
5021        None => {
5022            // A brand-new PRIVATE channel: record it KEYLESS at epoch 0 (the root
5023            // generation — CORD-03 §2 numbers the first private key epoch 1). The
5024            // epoch then doubles as [`follow_rekeys`]' scan cursor. Until a rotation
5025            // delivers a key, every read/send/subscribe path skips the channel; the
5026            // root-fallback in `channel_secret` is never taken for it.
5027            out.channels.push(ChannelV2 {
5028                id,
5029                name: meta.name,
5030                private: true,
5031                key: None,
5032                epoch: Epoch(0),
5033                voice: meta.voice,
5034                meta_custom: meta.custom,
5035                meta_extra: meta.extra,
5036            });
5037            true
5038        }
5039    }
5040}
5041
5042// ── Live rekey-follow (CORD-06 §2/§3) ────────────────────────────────────────
5043
5044/// The outcome of a rekey-follow pass.
5045pub struct RekeyFollow {
5046    /// The community after adopting every rotation it could catch up on, or `None`
5047    /// if nothing advanced.
5048    pub updated: Option<CommunityV2>,
5049    /// A base rotation removed us — the caller tears the local hold down (the
5050    /// updated community is not persisted in that case).
5051    pub self_removed: bool,
5052    /// An owner tombstone sits on the dissolved plane (CORD-02 §9) — the local
5053    /// flag is already set; the caller surfaces the death and stops following.
5054    pub dissolved: bool,
5055}
5056
5057/// The most archived base roots a channel-rekey lookup fans across per step. A
5058/// standalone rekey rides the minter's then-current root and a removal's rides the
5059/// PRIOR root (CORD-06 §3), so a follower whose base already advanced must look
5060/// back. A channel stranded DEEPER than this (its next-epoch crate addressed under
5061/// an older root than the fan reaches) only heals via a fresh invite bundle — the
5062/// walk is strictly sequential, so a later rotation can't be reached either.
5063const MAX_ADDRESSING_ROOTS: usize = 8;
5064
5065/// The base roots a channel rekey may be addressed under, freshest first: the
5066/// current root plus the archived priors, capped at [`MAX_ADDRESSING_ROOTS`].
5067/// CORD-06 D2: a removal-forced channel rekey rides the PRIOR root — so the
5068/// follower's fetch fan ([`follow_rekeys`]) and the stream-auth registration
5069/// (`streamauth::register_community`) MUST cover the SAME set. A plane the
5070/// fetch addresses but auth never registered is invisible on an AUTH-gating
5071/// relay: the REQ is CLOSED, the rotation crate never arrives, and the channel
5072/// wedges at its old epoch while the base advances.
5073pub(crate) fn channel_rekey_addressing_roots(cur_root: [u8; 32], cid_hex: &str) -> Vec<[u8; 32]> {
5074    let mut roots: Vec<[u8; 32]> = vec![cur_root];
5075    let mut archived = crate::db::community::held_epoch_keys(cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
5076        .unwrap_or_default();
5077    archived.sort_by(|a, b| b.0 .0.cmp(&a.0 .0));
5078    for (_, r) in archived {
5079        if !roots.contains(&r) {
5080            roots.push(r);
5081        }
5082    }
5083    roots.truncate(MAX_ADDRESSING_ROOTS);
5084    roots
5085}
5086
5087/// Follow rekeys for a held community: advance the base (root) epoch and each
5088/// Private channel's epoch as far as authorized rotations allow, adopting the
5089/// fresh key we're still a recipient of at each step and dropping a scope we've
5090/// been removed from. Persists the result. Called when a rekey wrap arrives in
5091/// realtime so a long-running bot keeps decrypting after a rotation instead of
5092/// going silent.
5093///
5094/// **Authority (CORD-06 §Authority):** a BASE rotation is honored from the owner
5095/// only — the deliberate mirror of the owner-only Refounding send (a non-owner's
5096/// ban silences + strips; the read-cut is the owner's). A CHANNEL rotation is
5097/// honored from the owner or a `MANAGE_CHANNELS` holder under the PERSISTED
5098/// roster (folded + persisted by `follow_control`), minus the banlist — so an
5099/// admin-created private channel keys up on every member.
5100///
5101/// **Addressing fans across held base roots:** each channel step queries its
5102/// next-epoch rekey address under the current root AND the archived prior roots,
5103/// so a base adopt landing before a Refounding's prior-root-addressed channel
5104/// rekeys (or before a creation delivery minted under an older root) can't
5105/// strand the channel.
5106///
5107/// **Continuity + fork resolution are spec-strict:** a rotation must extend the
5108/// exact `(epoch, key)` I hold, one epoch at a time; a same-epoch fork resolves
5109/// by the lexicographically lowest new key ([`rekey::lowest_key_winner`]), so
5110/// every follower converges. An incomplete rotation (a missing chunk) never
5111/// concludes removal — it just waits. A KEYLESS channel (announced by vsk-2, key
5112/// not yet delivered) holds no chain, so continuity is vacuous for it (CORD-06
5113/// §2: "a convergence check, not a secrecy mechanism") — authority is its
5114/// boundary; its epoch is the scan cursor, advancing past complete rotations
5115/// that exclude us so the walk converges on the channel's current epoch.
5116/// Diagnostic: run the base-rotation fetch+parse pipeline for a wedged community
5117/// and report, per rotation found at the next-epoch base plane, WHY
5118/// `follow_rekeys` did or didn't adopt it — the exact `advance_scope` gate that
5119/// tripped. Read-only. Every rotator/owner is a PUBLIC key; no secret material
5120/// is returned.
5121#[cfg(debug_assertions)]
5122pub async fn debug_explain_base_rekey<T: Transport + ?Sized>(
5123    transport: &T,
5124    community: &CommunityV2,
5125) -> Result<serde_json::Value, String> {
5126    let my_xonly = me_pk()?.to_bytes();
5127    let owner = community.owner()?;
5128    let owner_hex = owner.to_hex();
5129    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
5130    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
5131    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
5132    let held_epoch = community.root_epoch;
5133    let held_key = community.community_root;
5134    let next = Epoch(held_epoch.0.saturating_add(1));
5135    let group = base_rekey_group_key(&held_key, community.id(), next);
5136    let chunks = fetch_rekey_chunks(transport, &community.relays, &group).await?;
5137    let rotations = rekey::collect_rotations(&chunks);
5138
5139    let reports: Vec<serde_json::Value> = rotations
5140        .iter()
5141        .map(|r| {
5142            let rotator_is_owner = r.rotator == owner;
5143            // CORD-06 §Authority: a Refounding is authorized by BAN in the folded
5144            // Roster, not owner-identity — report that gate, not just owner-equality.
5145            let rotator_authorized = rotator_is_owner
5146                || (!banned.contains(&r.rotator.to_hex())
5147                    && roster.is_authorized(&r.rotator.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN));
5148            let scope_ok = r.scope.id32() == rekey::RekeyScope::Root.id32();
5149            let epoch_ok = r.new_epoch.0 == next.0;
5150            let complete = r.is_complete();
5151            let continuity = format!("{:?}", r.continuity(held_epoch, &held_key));
5152            let has_my_blob = rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &my_xonly, r.scope, r.new_epoch).is_some();
5153            // Is the OWNER a recipient? A non-owner Refounding that drops the owner
5154            // is a takeover attempt — this tells whether an "owner must be kept"
5155            // adopt-block would be safe here (it would falsely reject a legitimate
5156            // rotation that happened to exclude the owner).
5157            let owner_kept = r.rotator == owner
5158                || rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &owner.to_bytes(), r.scope, r.new_epoch).is_some();
5159            // The exact reason follow_rekeys skipped/rejected this rotation, in gate order.
5160            let verdict = if !rotator_authorized {
5161                "REJECTED: rotator holds no BAN authority in the folded roster"
5162            } else if !scope_ok {
5163                "REJECTED: scope is not Root"
5164            } else if !epoch_ok {
5165                "REJECTED: new_epoch != held+1"
5166            } else if !complete {
5167                "WAIT: rotation incomplete (missing chunk) — never concludes removal"
5168            } else if continuity != "Extends" {
5169                "REJECTED: continuity does not extend my held root (FORK/GAP)"
5170            } else if has_my_blob {
5171                "ADOPT: authorized + complete + continuous + my blob present"
5172            } else {
5173                "REMOVED: complete authorized rotation with no blob for me"
5174            };
5175            serde_json::json!({
5176                "rotator": r.rotator.to_hex(),
5177                "rotator_is_recorded_owner": rotator_is_owner,
5178                "rotator_authorized_ban": rotator_authorized,
5179                "scope_is_root": scope_ok,
5180                "new_epoch": r.new_epoch.0,
5181                "prev_epoch": r.prev_epoch.0,
5182                "declared_chunks": r.declared_chunks,
5183                "held_chunks": r.held_chunks.iter().copied().collect::<Vec<_>>(),
5184                "is_complete": complete,
5185                "continuity_vs_held_root": continuity,
5186                "my_blob_present": has_my_blob,
5187                "owner_kept": owner_kept,
5188                "blob_count": r.blobs.len(),
5189                "verdict": verdict,
5190            })
5191        })
5192        .collect();
5193
5194    Ok(serde_json::json!({
5195        "recorded_owner": owner.to_hex(),
5196        "held_root_epoch": held_epoch.0,
5197        "probing_next_epoch": next.0,
5198        "base_plane_pk": group.pk_hex(),
5199        "raw_chunks_parsed": chunks.len(),
5200        "rotations_found": rotations.len(),
5201        "rotations": reports,
5202    }))
5203}
5204
5205pub async fn follow_rekeys<T: Transport + ?Sized>(
5206    transport: &T,
5207    community: &CommunityV2,
5208    session: &SessionGuard,
5209) -> Result<RekeyFollow, String> {
5210    // Death wins every race (CORD-02 §9): a dissolved community honors no epoch advance
5211    // past its tombstone — don't adopt a rotation into a grave.
5212    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
5213    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
5214        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: true });
5215    }
5216    // An offline member must also LEARN of a death: the tombstone rides its own
5217    // public plane, which the live sub watches but no catch-up fetch touched —
5218    // without this, a member who slept through a dissolution follows (and posts
5219    // into) a grave forever. Fail-open on transport failure: availability is
5220    // never death.
5221    if is_dissolved(transport, community).await {
5222        if session.is_valid() {
5223            let _ = crate::db::community::set_community_dissolved(&cid_hex);
5224        }
5225        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: true });
5226    }
5227    let signer = crate::signer::active_signer()?;
5228    let my_pk = me_pk()?;
5229    let my_xonly = my_pk.to_bytes();
5230    let owner = community.owner()?;
5231    let owner_hex = owner.to_hex();
5232    let mut cur = community.clone();
5233    let mut changed = false;
5234
5235    // The rotator/admissibility gates read the PERSISTED roster (folded by a prior
5236    // follow_control; the worker folds control right after this rekey pass). This
5237    // is "one pass late" for the rotator-AUTHORIZATION direction (a newly-granted
5238    // admin's rotation adopts a pass late, never early — safe). It is fail-OPEN for
5239    // the base-admissibility protected-set: a superior whose grant this receiver
5240    // has not yet folded is not in `roster.grants`, so a non-owner Refounding
5241    // excluding them can be adopted within that propagation window. Bounded — the
5242    // owner is ALWAYS hard-protected below (independent of the roster) and can
5243    // counter-refound; and it is inherent to eventual consistency (one cannot gate
5244    // on a grant never seen). Tightening this (fold control before the first rekey,
5245    // or gate non-owner adoption on roster freshness) is a follow-on.
5246    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
5247    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
5248    let me_hex = my_pk.to_hex();
5249    // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
5250    // authority action (CORD-04's `vac`), so a just-demoted admin's rotation is
5251    // never honored by a lagging client." Persisted heads ARE the right floor
5252    // here (unlike the roster fold, which must resolve in-pass): a rotation is
5253    // judged against a roster we already folded, and `follow_control` — v2's only
5254    // roster writer — persists the heads in the same pass it writes the roster.
5255    // A joiner who sees a rotation before folding control simply parks it and
5256    // heals on the next follow, which runs control first.
5257    let cited_ok = |rot: &rekey::Rotation| -> bool {
5258        citation_is_synced(&cid_hex, &owner_hex, &rot.rotator.to_hex(), rot.citation.as_ref())
5259    };
5260    let channel_rotator_ok = |rotator: &PublicKey| -> bool {
5261        if *rotator == owner {
5262            return true;
5263        }
5264        let rh = rotator.to_hex();
5265        !banned.contains(&rh) && roster.is_authorized(&rh, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS)
5266    };
5267    // Concluding MY removal takes more than the bit: the rotator must strictly
5268    // outrank ME (CORD-06 §Authority — "the Rotator must strictly outrank every
5269    // removed target"), so an equal-rank admin can never silently evict a peer
5270    // (or the owner) by minting a complete rotation that skips their blob.
5271    let channel_rotator_outranks_me = |rotator: &PublicKey| -> bool {
5272        if *rotator == owner {
5273            return true;
5274        }
5275        let rh = rotator.to_hex();
5276        !banned.contains(&rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, crate::community::roles::Permissions::MANAGE_CHANNELS)
5277    };
5278    // CORD-06 §Authority: a Refounding requires the BAN permission in the folded
5279    // Roster (NOT owner-identity) — any admin holding BAN may perform it, checked
5280    // against the Roster exactly like a channel rekey checks MANAGE_CHANNELS. The
5281    // owner is always authorized. (Owner-only here silently wedged every member
5282    // whose community was refounded by a non-owner admin.)
5283    let base_rotator_ok = |rotator: &PublicKey| -> bool {
5284        if *rotator == owner {
5285            return true;
5286        }
5287        let rh = rotator.to_hex();
5288        !banned.contains(&rh) && roster.is_authorized(&rh, Some(&owner_hex), crate::community::roles::Permissions::BAN)
5289    };
5290    // Concluding MY removal via a base rotation takes more than the bit: the
5291    // rotator must strictly outrank ME with BAN (CORD-06 §Authority — "the
5292    // Rotator must strictly outrank every removed target"), so an equal-rank
5293    // admin can never evict a peer (or the owner) by minting a rotation that
5294    // skips their blob. Adoption (I hold a blob) only needs `base_rotator_ok`.
5295    let base_rotator_outranks_me = |rotator: &PublicKey| -> bool {
5296        if *rotator == owner {
5297            return true;
5298        }
5299        let rh = rotator.to_hex();
5300        !banned.contains(&rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, crate::community::roles::Permissions::BAN)
5301    };
5302
5303    // Bound the catch-up: each real step consumes a valid authorized rotation, so a
5304    // finite chain terminates naturally; the cap defends against a relay feeding a
5305    // pathological set.
5306    const MAX_STEPS: usize = 128;
5307    for _ in 0..MAX_STEPS {
5308        let mut advanced = false;
5309
5310        // The roots a channel rekey may be addressed under (re-read each pass —
5311        // a base adopt below changes the head, and its predecessor is already
5312        // archived). Shared with streamauth so the auth registration covers
5313        // exactly this fan.
5314        let addressing_roots = channel_rekey_addressing_roots(cur.community_root, &cid_hex);
5315
5316        // Private channels first: a removal-forced channel rekey rides the PRIOR
5317        // root (CORD-06 D2), so read channels before a base adopt moves it.
5318        let channel_ids: Vec<ChannelId> = cur.channels.iter().filter(|c| c.private).map(|c| c.id).collect();
5319        for cid in channel_ids {
5320            let (held_key, held_epoch) = match cur.channel(&cid) {
5321                Some(ch) => (ch.key, ch.epoch),
5322                None => continue,
5323            };
5324            let next = Epoch(held_epoch.0.saturating_add(1));
5325            let ch_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
5326            let mut batches: Vec<(Vec<rekey::RekeyChunk>, Option<(Epoch, [u8; 32])>)> = Vec::new();
5327            // root #0 = current, #1.. = archived priors (indices only — root
5328            // bytes are key material and must never reach a log).
5329            for (ri, root) in addressing_roots.iter().enumerate() {
5330                let group = channel_rekey_group_key(root, &cid, next);
5331                let chunks = match fetch_rekey_chunks(transport, &cur.relays, &group).await {
5332                    Ok(c) => c,
5333                    Err(e) => {
5334                        crate::log_warn!(
5335                            "[v2:follow {}] ch {} next e{} root#{}/{}: rekey plane fetch failed: {}",
5336                            &cid_hex[..8], &ch_hex[..8], next.0, ri, addressing_roots.len(), e
5337                        );
5338                        return Err(e);
5339                    }
5340                };
5341                if chunks.is_empty() {
5342                    continue;
5343                }
5344                crate::log_debug!(
5345                    "[v2:follow {}] ch {} next e{} root#{}/{}: {} rekey chunk(s)",
5346                    &cid_hex[..8], &ch_hex[..8], next.0, ri, addressing_roots.len(), chunks.len()
5347                );
5348                batches.push((chunks, held_key.map(|k| (held_epoch, k))));
5349            }
5350            // Keyless-adopt residual (documented, deferred hardening): a malicious
5351            // AUTHORIZED admin can fork a keyless member onto an orphan low-key
5352            // rotation nothing extends (keyed members' continuity filters it out).
5353            // Recoverable via a fresh bundle; an insider with MANAGE_CHANNELS can
5354            // exclude the member outright anyway, so the marginal harm is the wedge
5355            // outliving their demotion.
5356            match advance_scope(&batches, RekeyScope::Channel(cid), &channel_rotator_ok, &channel_rotator_outranks_me, &cited_ok, &signer, &my_xonly, next).await {
5357                Advance::Adopt { new_key } => {
5358                    if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
5359                        ch.key = Some(new_key);
5360                        ch.epoch = next;
5361                    }
5362                    crate::log_debug!("[v2:follow {}] ch {} ADOPTED e{}", &cid_hex[..8], &ch_hex[..8], next.0);
5363                    // The adopter's own multi-epoch archive (the minter archived at
5364                    // mint) — this channel's history stays readable across rotations.
5365                    // fetch_channel compensates for the CURRENT epoch, so a failed
5366                    // archive only bites after the NEXT rotation — surface it.
5367                    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) {
5368                        crate::log_warn!("v2: channel epoch-key archive failed (history across this rotation may not read back): {e}");
5369                    }
5370                    advanced = true;
5371                    changed = true;
5372                }
5373                Advance::Removed => {
5374                    match held_key {
5375                        // A complete rotation dropped my blob — cut from the channel.
5376                        Some(_) => {
5377                            cur.channels.retain(|c| c.id.0 != cid.0);
5378                        }
5379                        // Keyless scan: this epoch's rotation completed without me.
5380                        // Advance the cursor so the walk converges on the channel's
5381                        // CURRENT epoch — my entry point is its next rotation (whose
5382                        // recipients are the members at that time) or a fresh bundle.
5383                        None => {
5384                            if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
5385                                ch.epoch = next;
5386                            }
5387                        }
5388                    }
5389                    advanced = true;
5390                    changed = true;
5391                }
5392                Advance::Stay => {}
5393            }
5394        }
5395
5396        // Base rotation (Refounding): advances the root + root_epoch, re-addressing
5397        // every public channel, the guestbook, and the control plane by derivation
5398        // (refresh_subscription recomputes the author-set from the new root).
5399        {
5400            let held_epoch = cur.root_epoch;
5401            let held_key = cur.community_root;
5402            let next = Epoch(held_epoch.0.saturating_add(1));
5403            let group = base_rekey_group_key(&cur.community_root, cur.id(), next);
5404            let chunks = fetch_rekey_chunks(transport, &cur.relays, &group).await?;
5405            let batches = vec![(chunks, Some((held_epoch, held_key)))];
5406            // A non-owner Refounding may only remove members the rotator strictly
5407            // OUTRANKS. The protected set is the owner plus every grant-holder the
5408            // rotator can't act on with BAN (a peer or superior) — excluding one is
5409            // an authority-escalation takeover, so its rotation is inadmissible.
5410            // Plain members hold no grant and are always outranked by a BAN-holder,
5411            // so removing them is legitimate and needs no memberlist.
5412            let base_admissible = |r: &rekey::Rotation| -> bool {
5413                if r.rotator == owner {
5414                    return true; // the owner is supreme.
5415                }
5416                // Uncited (or citing a Grant we haven't synced) → skip entirely:
5417                // neither adopt nor conclude a removal, exactly like an
5418                // unauthorized rotation. It parks and heals on the next follow.
5419                if !cited_ok(r) {
5420                    return false;
5421                }
5422                let rotator_hex = r.rotator.to_hex();
5423                let has_blob = |xonly: &[u8; 32]| {
5424                    rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), xonly, r.scope, r.new_epoch).is_some()
5425                };
5426                // The owner is never a valid removed target.
5427                if !has_blob(&owner.to_bytes()) {
5428                    return false;
5429                }
5430                for g in &roster.grants {
5431                    if g.member == rotator_hex || g.member == owner_hex || banned.contains(&g.member) {
5432                        continue; // self, owner (checked), or an already-authorized removal.
5433                    }
5434                    // A grant-holder the rotator can't act on is a peer/superior.
5435                    if !roster.can_act_on_member(&rotator_hex, Some(&owner_hex), &g.member, crate::community::roles::Permissions::BAN) {
5436                        if let Ok(pk) = PublicKey::from_hex(&g.member) {
5437                            if !has_blob(&pk.to_bytes()) {
5438                                return false; // a peer/superior was excluded.
5439                            }
5440                        }
5441                    }
5442                }
5443                true
5444            };
5445            match advance_scope(&batches, RekeyScope::Root, &base_rotator_ok, &base_rotator_outranks_me, &base_admissible, &signer, &my_xonly, next).await {
5446                Advance::Adopt { new_key } => {
5447                    cur.community_root = new_key;
5448                    cur.root_epoch = next;
5449                    // Archive on adopt: without this, a member who lived through TWO
5450                    // Refoundings loses the middle epoch's public history (only the
5451                    // minter archived it).
5452                    if let Err(e) = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, next.0, &new_key) {
5453                        crate::log_warn!("v2: base epoch-key archive failed (this epoch's history may not read back after the next rotation): {e}");
5454                    }
5455                    advanced = true;
5456                    changed = true;
5457                }
5458                Advance::Removed => {
5459                    if !session.is_valid() {
5460                        return Err("account changed during rekey follow".to_string());
5461                    }
5462                    return Ok(RekeyFollow { updated: None, self_removed: true, dissolved: false });
5463                }
5464                Advance::Stay => {}
5465            }
5466        }
5467
5468        if !advanced {
5469            break;
5470        }
5471    }
5472
5473    if !changed {
5474        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: false });
5475    }
5476    if !session.is_valid() {
5477        return Err("account changed during rekey follow".to_string());
5478    }
5479    // A leave/delete raced this follow: saving would resurrect the community row
5480    // (the save is an upsert) with no floor rows behind it.
5481    if crate::db::community::community_protocol(community.id())?.is_none() {
5482        return Ok(RekeyFollow { updated: None, self_removed: false, dissolved: false });
5483    }
5484    crate::db::community::save_community_v2(&cur)?;
5485    // Carry my own live links across the rotation someone ELSE performed
5486    // (CORD-05 §2). The refounder refreshes only the bundles they can reach —
5487    // their own — so without this every other creator's links keep vending the
5488    // superseded root and drop new joiners onto a dead epoch, which is exactly
5489    // the stranding the stable-URL refresh exists to prevent. Best-effort and
5490    // idempotent: a creator with no links for this community returns early, and
5491    // a failure only delays the heal until the next adoption or refound.
5492    let _ = refresh_public_links(transport, &cur).await;
5493    Ok(RekeyFollow { updated: Some(cur), self_removed: false, dissolved: false })
5494}
5495
5496/// One scope's catch-up decision from the rekey chunks fetched at its next-epoch
5497/// address.
5498enum Advance {
5499    /// Adopt this fresh key for `next_epoch`.
5500    Adopt { new_key: [u8; 32] },
5501    /// A complete owner rotation at `next_epoch` dropped my blob — I'm removed.
5502    Removed,
5503    /// No owner rotation extends my held epoch (yet) — keep the current key.
5504    Stay,
5505}
5506
5507/// Fetch + parse every seal-verified 3303 chunk at a rekey plane address.
5508async fn fetch_rekey_chunks<T: Transport + ?Sized>(
5509    transport: &T,
5510    relays: &[String],
5511    group: &GroupKey,
5512) -> Result<Vec<rekey::RekeyChunk>, String> {
5513    // A rekey plane address is community_root-derived, so ANY member can seal junk
5514    // 3303s there — a flood (or, organically, a large community's own multi-chunk
5515    // rotation past the newest window) could bury the genuine owner/admin rotation
5516    // in a single fixed page. PAGE backwards (inclusive until + wrap-id dedup, the
5517    // control pager's discipline) so a buried authorized chunk is still recovered;
5518    // the seal + authority filter downstream drops the junk. Bounded — a sustained
5519    // flood past this depth degrades to "adopt one pass late", never a false state.
5520    const REKEY_PAGE: usize = 200;
5521    const REKEY_MAX_PAGES: usize = 6;
5522    let mut out = Vec::new();
5523    let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
5524    let mut until: Option<u64> = None;
5525    let mut oldest: Option<u64> = None;
5526    for _ in 0..REKEY_MAX_PAGES {
5527        let query = Query {
5528            kinds: vec![stream::KIND_WRAP],
5529            authors: vec![group.pk_hex()],
5530            until,
5531            limit: Some(REKEY_PAGE),
5532            ..Default::default()
5533        };
5534        // Authenticate AS the rekey plane key: on AUTH-gating relays (Ditto) the
5535        // shared user-authed client's REQ for a plane's events is CLOSED, so an
5536        // offline rotation catch-up would return nothing and wedge at the old
5537        // epoch. `fetch_plane` rides a connection authed as the plane itself.
5538        let wraps = transport.fetch_plane(group.keys(), &query, relays).await?;
5539        let mut fresh = 0usize;
5540        for w in &wraps {
5541            if !seen.insert(w.id) {
5542                continue;
5543            }
5544            fresh += 1;
5545            let at = w.created_at.as_secs();
5546            if oldest.is_none_or(|o| at < o) {
5547                oldest = Some(at);
5548            }
5549            if let Ok(opened) = stream::open_wrap(w, group) {
5550                if let Ok(chunk) = rekey::parse_rekey_chunk(&opened) {
5551                    out.push(chunk);
5552                }
5553            }
5554        }
5555        // Drained, or a same-second wall the pager can't step past (second-granular
5556        // until) — either way stop; the accumulated set is what advance_scope folds.
5557        if fresh == 0 || wraps.len() < REKEY_PAGE {
5558            break;
5559        }
5560        match oldest {
5561            Some(o) if o > 0 => until = Some(o),
5562            _ => break,
5563        }
5564    }
5565    Ok(out)
5566}
5567
5568/// Decide how a scope advances from per-addressing-root chunk batches (pure). Each
5569/// batch pairs the chunks fetched under one root with the continuity to demand of
5570/// them: a rotation qualifies when it's rotator-authorized (`rotator_ok`),
5571/// complete, targets the immediate `next_epoch`, and — when I hold a chain —
5572/// extends my exact `(epoch, key)`. A KEYLESS batch (`held` = None) has no chain
5573/// to extend, so it qualifies on authority + completeness alone (CORD-06 §2:
5574/// continuity is "a convergence check, not a secrecy mechanism"; the rotator's
5575/// seal authority is the boundary). Among qualifying rotations carrying my blob
5576/// the lexicographically lowest new key wins (convergent). All complete
5577/// candidates without my blob conclude Removed for a KEYED holder only when one
5578/// came from a rotator who may remove ME (`rotator_may_remove_me`, the CORD-06
5579/// strict-outrank rule) — else Stay; for a keyless holder they merely advance the
5580/// scan cursor (any bit-holder's real rotation is scan progress, never a loss).
5581async fn advance_scope<S: crate::signer::VectorSigner + ?Sized>(
5582    batches: &[(Vec<rekey::RekeyChunk>, Option<(Epoch, [u8; 32])>)],
5583    scope: RekeyScope,
5584    rotator_ok: &(dyn Fn(&PublicKey) -> bool + Sync),
5585    rotator_may_remove_me: &(dyn Fn(&PublicKey) -> bool + Sync),
5586    admissible: &(dyn Fn(&rekey::Rotation) -> bool + Sync),
5587    signer: &S,
5588    my_xonly: &[u8; 32],
5589    next_epoch: Epoch,
5590) -> Advance {
5591    let mut winners: Vec<[u8; 32]> = Vec::new();
5592    let mut saw_complete_candidate = false;
5593    let mut saw_outranking_candidate = false;
5594    let keyed = batches.iter().any(|(_, held)| held.is_some());
5595    for (chunks, held) in batches {
5596        let rotations = rekey::collect_rotations(chunks);
5597        for r in &rotations {
5598            if !rotator_ok(&r.rotator) || r.scope.id32() != scope.id32() || r.new_epoch.0 != next_epoch.0 || !r.is_complete() {
5599                continue;
5600            }
5601            if let Some((held_epoch, held_key)) = held {
5602                if r.continuity(*held_epoch, held_key) != Continuity::Extends {
5603                    continue;
5604                }
5605            }
5606            // CORD-06 §Authority: a rotator must strictly OUTRANK every removed
5607            // target. An authorized-but-inadmissible rotation (one that excludes
5608            // the owner or a peer/superior the rotator can't act on) is a takeover
5609            // attempt — skip it entirely, so it neither adopts nor concludes a
5610            // removal (it forks; the honest chain wins).
5611            if !admissible(r) {
5612                continue;
5613            }
5614            saw_complete_candidate = true;
5615            saw_outranking_candidate |= rotator_may_remove_me(&r.rotator);
5616            if let Some(blob) = rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), my_xonly, r.scope, r.new_epoch) {
5617                if let Ok(k) = rekey::open_blob(signer, &r.rotator, r.scope, r.new_epoch, blob).await {
5618                    winners.push(k);
5619                }
5620            }
5621        }
5622    }
5623    if !winners.is_empty() {
5624        // `collect_rotations` correlates on `(rotator, scope, new_epoch, prev_commit)`,
5625        // so a single rotator's blobs merge into ONE rotation (and a retried Refounding
5626        // MINT-OR-REUSES its root, so it never emits two distinct roots to fork on).
5627        // The lowest-key tiebreak engages only for CONCURRENT DISTINCT rotators racing
5628        // the same epoch (separate rotations): every follower converges on the same
5629        // lowest new key. A wrap served under two addressing roots can't double-count:
5630        // each rekey wrap opens under exactly one root's group key.
5631        let idx = rekey::lowest_key_winner(&winners).expect("winners is non-empty");
5632        return Advance::Adopt { new_key: winners[idx] };
5633    }
5634    if saw_complete_candidate && (!keyed || saw_outranking_candidate) {
5635        Advance::Removed
5636    } else {
5637        Advance::Stay
5638    }
5639}
5640
5641#[cfg(test)]
5642mod tests {
5643    use crate::ClientRelayExt;
5644    use nostr_sdk::prelude::FinalizeEvent;
5645    use super::super::super::transport::memory::MemoryRelay;
5646    use super::*;
5647    use crate::community::roles::{MemberGrant, Permissions, Role, RoleScope};
5648
5649    /// A distinct npub-shaped account-dir name (bech32 charset) per counter.
5650    fn account_name(n: u32) -> String {
5651        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
5652        let mut acct = String::from("npub1");
5653        let mut v = n as usize;
5654        for _ in 0..58 {
5655            acct.push(B[v % 32] as char);
5656            v = v / 32 + 7;
5657        }
5658        acct
5659    }
5660
5661    /// One test participant: its identity keys and its isolated account DB dir.
5662    struct Actor {
5663        keys: Keys,
5664        account: String,
5665    }
5666
5667    /// Two participants sharing one relay but isolated per-account DBs — the
5668    /// cross-account harness a real invite/join loop needs. `swap_to` mirrors a
5669    /// live `swap_session`: re-point the DB pool + rebind the identity + clear
5670    /// the per-account id caches, so account A's community is invisible to B
5671    /// until B legitimately joins.
5672    struct TestBed {
5673        _tmp: tempfile::TempDir,
5674        _guard: std::sync::MutexGuard<'static, ()>,
5675        relay: MemoryRelay,
5676        relays: Vec<String>,
5677    }
5678
5679    impl TestBed {
5680        fn new() -> (TestBed, Actor, Actor) {
5681            static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(70_000);
5682            let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
5683            crate::db::close_database();
5684            crate::db::clear_id_caches();
5685            let tmp = tempfile::tempdir().unwrap();
5686            crate::db::set_app_data_dir(tmp.path().to_path_buf());
5687
5688            let mk = || {
5689                let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5690                let account = account_name(n);
5691                std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
5692                crate::db::set_current_account(account.clone()).unwrap();
5693                crate::db::init_database(&account).unwrap();
5694                Actor { keys: Keys::generate(), account }
5695            };
5696            let owner = mk();
5697            let member = mk();
5698            let _ = crate::state::take_nostr_client();
5699            let bed = TestBed {
5700                _tmp: tmp,
5701                _guard: guard,
5702                relay: MemoryRelay::new(),
5703                relays: vec!["wss://r".to_string()],
5704            };
5705            (bed, owner, member)
5706        }
5707
5708        /// Become `actor`: swap the account DB + identity, as a real session swap.
5709        /// Bumps the session generation like production `swap_session` does — so any task a
5710        /// prior actor spawned (e.g. the migration finalize) dies at its SessionGuard check
5711        /// instead of racing this actor's DB (a cross-test flake that can't happen in prod).
5712        fn swap_to(&self, actor: &Actor) {
5713            crate::state::bump_session_generation();
5714            crate::db::set_current_account(actor.account.clone()).unwrap();
5715            crate::db::init_database(&actor.account).unwrap();
5716            crate::db::clear_id_caches();
5717            crate::state::MY_SECRET_KEY.store_from_keys(&actor.keys, &[]);
5718            crate::state::set_my_public_key(actor.keys.public_key());
5719        }
5720    }
5721
5722    /// Legacy single-actor helper (the create/send tests below).
5723    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
5724        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
5725        crate::db::close_database();
5726        crate::db::clear_id_caches();
5727        let tmp = tempfile::tempdir().unwrap();
5728        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(50_000);
5729        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5730        let acct = account_name(n);
5731        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
5732        crate::db::set_app_data_dir(tmp.path().to_path_buf());
5733        crate::db::set_current_account(acct.clone()).unwrap();
5734        crate::db::init_database(&acct).unwrap();
5735        let _ = crate::state::take_nostr_client();
5736        let owner = Keys::generate();
5737        crate::state::MY_SECRET_KEY.store_from_keys(&owner, &[]);
5738        crate::state::set_my_public_key(owner.public_key());
5739        (tmp, guard, owner)
5740    }
5741
5742    /// A transport that simulates a session swap landing DURING a fetch await —
5743    /// so a join straddling the fetch sees an invalid session and aborts.
5744    struct SwapMidFetch {
5745        inner: MemoryRelay,
5746    }
5747    #[async_trait::async_trait]
5748    impl Transport for SwapMidFetch {
5749        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
5750        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
5751            self.inner.publish(e, r).await
5752        }
5753        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
5754            self.inner.publish_durable(e, r).await
5755        }
5756        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
5757            let out = self.inner.fetch(q, r).await;
5758            crate::state::bump_session_generation();
5759            out
5760        }
5761    }
5762
5763    /// Bumps the session generation on the first `publish_durable` — the rekey
5764    /// crate a private-channel create ships before it writes anything locally.
5765    struct SwapMidPublish {
5766        inner: MemoryRelay,
5767    }
5768    #[async_trait::async_trait]
5769    impl Transport for SwapMidPublish {
5770        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
5771        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
5772            self.inner.publish(e, r).await
5773        }
5774        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
5775            let out = self.inner.publish_durable(e, r).await;
5776            crate::state::bump_session_generation();
5777            out
5778        }
5779        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
5780            self.inner.fetch(q, r).await
5781        }
5782    }
5783
5784    /// A transport whose `fetch` returns a FIXED, UNSORTED event list — modelling
5785    /// the production `LiveTransport` union (first-responding relay's batch, no
5786    /// global newest-first sort), which `MemoryRelay` hides by sorting. This is
5787    /// the only harness that can exercise the revocation-race ordering.
5788    struct FixedFetch {
5789        events: Vec<Event>,
5790    }
5791    #[async_trait::async_trait]
5792    impl Transport for FixedFetch {
5793        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
5794        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
5795            Ok(())
5796        }
5797        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
5798            Ok(())
5799        }
5800        async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
5801            Ok(self.events.clone())
5802        }
5803    }
5804
5805    /// Fetch a pending Direct Invite (kind 3313 giftwrap) addressed to `me` — the
5806    /// indexed inbox query CORD-05 §6 defines: `{1059, #p:[me], #k:["3313"]}`.
5807    async fn fetch_direct_invite(relay: &MemoryRelay, relays: &[String], me: &PublicKey) -> Event {
5808        let q = Query {
5809            kinds: vec![stream::KIND_WRAP],
5810            p_tags: vec![me.to_hex()],
5811            k_tags: vec!["3313".to_string()],
5812            ..Default::default()
5813        };
5814        relay.fetch(&q, relays).await.unwrap().into_iter().next().expect("a direct invite is waiting")
5815    }
5816
5817    #[tokio::test]
5818    async fn create_persists_and_reloads_a_v2_community() {
5819        let (_tmp, _guard, owner) = init_test_db();
5820        let relay = MemoryRelay::new();
5821        let relays = vec!["wss://r".to_string()];
5822
5823        let created = create_community(&relay, "Vectorville", relays.clone(), Some("hi".into())).await.unwrap();
5824        assert!(created.identity.verify());
5825        assert_eq!(created.owner().unwrap(), owner.public_key());
5826        assert_eq!(created.channels.len(), 1);
5827
5828        // Protocol dispatch sees it as v2, and it reloads byte-faithfully.
5829        assert_eq!(
5830            crate::db::community::community_protocol(created.id()).unwrap(),
5831            Some(crate::community::ConcordProtocol::V2)
5832        );
5833        let loaded = crate::db::community::load_community_v2(created.id()).unwrap().expect("reloads");
5834        assert_eq!(loaded.name, "Vectorville");
5835        assert_eq!(loaded.community_root, created.community_root);
5836        assert_eq!(loaded.identity, created.identity);
5837        assert_eq!(loaded.channels[0].id.0, created.channels[0].id.0);
5838        assert!(!loaded.channels[0].private);
5839
5840        // The genesis control editions + the owner Join landed on the relay.
5841        assert!(relay.count_on("wss://r") >= 3, "2 genesis editions + 1 guestbook join");
5842    }
5843
5844    #[tokio::test]
5845    async fn owner_sends_and_reads_back_a_message() {
5846        let (_tmp, _guard, _owner) = init_test_db();
5847        let relay = MemoryRelay::new();
5848        let community = create_community(&relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
5849        let general = community.channels[0].id;
5850
5851        let id1 = send_message(&relay, &community, &general, "hello world").await.unwrap();
5852        let id2 = send_message(&relay, &community, &general, "second message").await.unwrap();
5853        assert_ne!(id1, id2);
5854
5855        let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
5856        let texts: Vec<String> = page
5857            .iter()
5858            .filter_map(|f| match &f.event {
5859                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
5860                _ => None,
5861            })
5862            .collect();
5863        assert_eq!(texts, vec!["hello world", "second message"], "messages round-trip in ms order");
5864    }
5865
5866    #[tokio::test]
5867    async fn a_second_member_reads_the_public_channel_from_the_root() {
5868        // A member who holds the community_root (via an invite bundle, modeled
5869        // here by cloning the community) reads the owner's public-channel message
5870        // — public channels need no key delivery, they derive from the root.
5871        let (_tmp, _guard, _owner) = init_test_db();
5872        let relay = MemoryRelay::new();
5873        let community = create_community(&relay, "Public", vec!["wss://r".into()], None).await.unwrap();
5874        let general = community.channels[0].id;
5875        send_message(&relay, &community, &general, "everyone can read this").await.unwrap();
5876
5877        // The "member" reconstructs the same read coordinates from the root.
5878        let member_view = community.clone();
5879        let page = fetch_channel(&relay, &member_view, &general, 100).await.unwrap();
5880        assert_eq!(page.len(), 1);
5881        assert!(matches!(&page[0].event, ChatEvent::Message { .. }));
5882        assert_eq!(page[0].event.opened().rumor.content, "everyone can read this");
5883    }
5884
5885    // ── Two-actor end-to-end (the create → invite → join → message loop) ──────
5886
5887    async fn texts_in<T: crate::community::transport::Transport + ?Sized>(relay: &T, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
5888        fetch_channel(relay, community, channel, 100)
5889            .await
5890            .unwrap()
5891            .iter()
5892            .filter_map(|f| match &f.event {
5893                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
5894                _ => None,
5895            })
5896            .collect()
5897    }
5898
5899    #[tokio::test]
5900    async fn direct_invite_full_loop_owner_and_member_converse() {
5901        let (bed, owner, member) = TestBed::new();
5902
5903        // Owner creates a community, posts, and Direct-Invites the member's npub.
5904        bed.swap_to(&owner);
5905        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
5906        let general = community.channels[0].id;
5907        send_message(&bed.relay, &community, &general, "owner: welcome!").await.unwrap();
5908        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
5909
5910        // Member (a DIFFERENT account, no prior knowledge) finds + accepts the invite.
5911        bed.swap_to(&member);
5912        assert!(
5913            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
5914            "the member does not hold the community before joining"
5915        );
5916        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
5917        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
5918        assert_eq!(joined.id().0, community.id().0, "joined the same community");
5919        assert!(joined.identity.verify(), "the joiner independently verifies the owner commitment");
5920        assert_eq!(joined.owner().unwrap(), owner.keys.public_key());
5921
5922        // The member reads the owner's public-channel history and replies.
5923        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome!"]);
5924        send_message(&bed.relay, &joined, &general, "member: thanks for the invite").await.unwrap();
5925
5926        // The owner reads the member's reply.
5927        bed.swap_to(&owner);
5928        assert_eq!(
5929            texts_in(&bed.relay, &community, &general).await,
5930            vec!["owner: welcome!", "member: thanks for the invite"],
5931            "both actors' messages interleave in ms order on the shared channel"
5932        );
5933
5934        // The Guestbook memberlist now folds both participants.
5935        let members = memberlist(&bed.relay, &community).await.unwrap();
5936        assert!(members.contains(&owner.keys.public_key()), "owner is a member (genesis Join)");
5937        assert!(members.contains(&member.keys.public_key()), "member is a member (invite Join)");
5938        assert_eq!(members.len(), 2);
5939    }
5940
5941    /// Join-time ban gate: an honest client whose npub is on the authorized banlist
5942    /// refuses to join — no Guestbook Join publish, no local write — through the shared
5943    /// accept path every door (direct invite, parked, public link, migration) funnels into.
5944    #[tokio::test]
5945    async fn a_banned_member_is_refused_at_join_time() {
5946        let (bed, owner, member) = TestBed::new();
5947
5948        bed.swap_to(&owner);
5949        let community = create_community(&bed.relay, "NoEntry", bed.relays.clone(), None).await.unwrap();
5950        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
5951        set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();
5952
5953        bed.swap_to(&member);
5954        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
5955        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
5956        assert!(err.contains("banned"), "refusal names the reason: {err}");
5957        assert!(
5958            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
5959            "a refused join persists nothing"
5960        );
5961
5962        // The gate is the LAST word only for banned members: an unbanned bystander with
5963        // the same invite path still joins (the gate doesn't over-refuse).
5964        bed.swap_to(&owner);
5965        set_banlist(&bed.relay, &community, &[]).await.unwrap();
5966        bed.swap_to(&member);
5967        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
5968        assert_eq!(joined.id().0, community.id().0, "unban restores joinability");
5969    }
5970
5971    /// End-to-end member migration: a member holding a v1 community folds the owner's
5972    /// migration dissolution, opens `m`, joins the v2 twin (ban-gated), and the flip
5973    /// re-parents the stitched channel rows + stamps the fence — all from the single event.
5974    #[tokio::test]
5975    async fn member_migrates_v1_to_v2_from_the_dissolution_payload() {
5976        use crate::community::migration;
5977        let (bed, owner, member) = TestBed::new();
5978
5979        // Owner builds the v2 twin (real, verifiable on the shared relay).
5980        bed.swap_to(&owner);
5981        let v2 = create_community(&bed.relay, "Guild v2", bed.relays.clone(), None).await.unwrap();
5982        let v2_hex = crate::simd::hex::bytes_to_hex_32(&v2.identity.community_id.0);
5983        let jm = join_material(&v2);
5984
5985        // The member holds a v1 community owned by the SAME owner identity (the migration
5986        // premise) — construct + save it, and hold its server root.
5987        bed.swap_to(&member);
5988        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
5989        let v1_cid = v1.id.to_hex();
5990        v1.owner_attestation = Some({
5991            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
5992                .finalize(&owner.keys).unwrap().as_json()
5993        });
5994        crate::db::community::save_community(&v1).unwrap();
5995        let v1_channel = v1.channels[0].id.to_hex();
5996
5997        // The dissolution payload: v2 JoinMaterial sealed under the v1 server root.
5998        let m = migration::seal_m(v1.server_root_key.as_bytes(), &serde_json::to_vec(&jm).unwrap()).unwrap();
5999        let signpost = migration::MigrationSignpost {
6000            v2_community_id: v2_hex.clone(),
6001            owner_xonly: owner.keys.public_key().to_hex(),
6002            owner_salt: crate::simd::hex::bytes_to_hex_32(&v2.identity.owner_salt),
6003            relays: bed.relays.clone(),
6004            name: "Guild".into(),
6005            primary_channel: v1_channel.clone(),
6006            root_epoch: 0,
6007        };
6008        let content = migration::build_migration_content(&signpost, Some(m)).unwrap();
6009        crate::db::community::set_migration_pointer(&v1_cid, &content).unwrap();
6010
6011        // Drive the migration: opens m, joins v2 (ban-gated), flips.
6012        let flipped = migration::drive_migration(&bed.relay, &v1).await.unwrap();
6013        assert_eq!(flipped.as_deref(), Some(v2_hex.as_str()), "the flip completed to the v2 twin");
6014
6015        // Fence: the v1 community is terminally marked, and the v2 twin is held + joined.
6016        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()));
6017        assert!(crate::db::community::get_community_dissolved(&v1_cid).unwrap(), "flip also seals v1 (fence layer 0)");
6018        assert!(crate::db::community::load_community_v2(&v2.identity.community_id).unwrap().is_some(), "v2 twin held");
6019        let _ = v1_channel;
6020
6021        // Idempotent: a second drive is a no-op (already flipped).
6022        assert_eq!(migration::drive_migration(&bed.relay, &v1).await.unwrap(), None);
6023    }
6024
6025    /// The OWNER wizard end-to-end: build the twin (primary channel reuses the v1 id),
6026    /// seal + publish the carrier, flip the owner. Then a MEMBER holding the v1 community
6027    /// folds the same carrier and stitches — proving the channel-STITCH the earlier test
6028    /// couldn't (that twin had mismatched ids).
6029    #[tokio::test]
6030    async fn owner_wizard_then_member_migrate_and_stitch() {
6031        use crate::community::migration;
6032        let (bed, owner, member) = TestBed::new();
6033        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6034
6035        // Owner holds a v1 community (they created it) with one channel.
6036        bed.swap_to(&owner);
6037        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6038        let v1_cid = v1.id.to_hex();
6039        let v1_channel = v1.channels[0].id.to_hex();
6040        v1.owner_attestation = Some({
6041            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6042                .finalize(&owner.keys).unwrap().as_json()
6043        });
6044        crate::db::community::save_community(&v1).unwrap();
6045
6046        // Run the wizard.
6047        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6048        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()),
6049            "owner's own client flipped to v2");
6050        // The owner's v1 channel row re-parented to the twin (stitch), because the twin's
6051        // primary channel REUSES the v1 channel id.
6052        assert_eq!(crate::db::community::community_id_for_channel(&v1_channel).unwrap().as_deref(), Some(v2_hex.as_str()),
6053            "owner channel stitched to v2");
6054
6055        // A MEMBER holding the same v1 community folds the carrier and migrates.
6056        bed.swap_to(&member);
6057        let mut m_v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6058        // The member's v1 community must be the SAME id + root the owner published under.
6059        m_v1.id = v1.id;
6060        m_v1.server_root_key = v1.server_root_key.clone();
6061        m_v1.channels[0].id = v1.channels[0].id;
6062        m_v1.owner_attestation = v1.owner_attestation.clone();
6063        crate::db::community::save_community(&m_v1).unwrap();
6064
6065        // Fold the carrier off the relay: the dissolution arm seals, persists the pointer,
6066        // AND auto-drives the flip — the live one-event member experience, no manual step.
6067        crate::community::service::fetch_and_apply_control(&bed.relay, &m_v1).await.unwrap();
6068        assert!(crate::db::community::get_community_dissolved(&v1_cid).unwrap(), "member sees v1 sealed");
6069        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()),
6070            "the FOLD ITSELF flipped the member (auto-drive)");
6071        assert!(crate::db::community::load_community_v2(&crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&v2_hex))).unwrap().is_some(),
6072            "member holds the v2 twin");
6073        // A manual re-drive is an idempotent no-op.
6074        assert_eq!(migration::drive_migration(&bed.relay, &m_v1).await.unwrap(), None);
6075    }
6076
6077    /// The wizard records the twin in the cross-device community list, like every other v2
6078    /// join/create path. Sibling devices normally discover the twin by folding the carrier
6079    /// themselves, but one that no longer holds the v1 community has no carrier to fold, so
6080    /// the list is its only route in.
6081    #[tokio::test]
6082    async fn wizard_publishes_the_twin_to_the_cross_device_list() {
6083        use crate::community::migration;
6084        let (bed, owner, _member) = TestBed::new();
6085        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6086
6087        bed.swap_to(&owner);
6088        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6089        let v1_cid = v1.id.to_hex();
6090        v1.owner_attestation = Some({
6091            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6092                .finalize(&owner.keys).unwrap().as_json()
6093        });
6094        crate::db::community::save_community(&v1).unwrap();
6095
6096        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6097
6098        // The twin is live in the published list, so a fresh/carrier-less device finds it.
6099        let list = fetch_community_list(&bed.relay, &bed.relays).await.unwrap()
6100            .expect("the wizard published a community list");
6101        assert!(list.is_live(&v2_hex), "the twin must be live in the cross-device list");
6102        // The v1 community is NOT tombstoned there: a tombstone reads as "you left" and
6103        // `sync_community_list` would tear down a sibling's v1 row before it can fold the
6104        // carrier, stranding it. The local `migrated_to` fence is what stops v1 ghosts.
6105        assert!(
6106            !list.tombstones.iter().any(|t| t.community_id == v1_cid),
6107            "migration must not tombstone the v1 community"
6108        );
6109    }
6110
6111    /// The wizard takes the same per-cid claim the member drive does, so a double-fired
6112    /// command (or the owner's own carrier self-fold racing the wizard's phase 2→3 gap)
6113    /// cannot run two wizards: the second would re-mint a twin before the ledger lands
6114    /// (the double-mint orphan) and race its flip against the first.
6115    #[tokio::test]
6116    async fn wizard_refuses_while_a_drive_holds_the_claim() {
6117        use crate::community::migration;
6118        let (bed, owner, _member) = TestBed::new();
6119        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6120
6121        bed.swap_to(&owner);
6122        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6123        let v1_cid = v1.id.to_hex();
6124        v1.owner_attestation = Some({
6125            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6126                .finalize(&owner.keys).unwrap().as_json()
6127        });
6128        crate::db::community::save_community(&v1).unwrap();
6129
6130        // Simulate the concurrent drive holding the cid (what the live carrier fold does).
6131        migration::test_hold_drive_claim(&v1_cid);
6132        let err = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap_err();
6133        assert!(err.contains("already in progress"), "second wizard refused, got: {err}");
6134        // Refused BEFORE minting: no twin, no ledger, nothing to orphan.
6135        assert!(crate::db::community::get_migration_ledger(&v1_cid).unwrap().is_none(), "no ledger row was written");
6136        assert!(crate::db::community::get_migrated_to(&v1_cid).unwrap().is_none(), "no flip happened");
6137
6138        // Once the drive releases, the wizard runs normally.
6139        migration::test_release_drive_claim(&v1_cid);
6140        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6141        assert_eq!(crate::db::community::get_migrated_to(&v1_cid).unwrap().as_deref(), Some(v2_hex.as_str()));
6142    }
6143
6144    /// The flip runs UNDER the twin's follow lock, so it can never straddle a follow
6145    /// worker's whole-row save (which deletes channel rows absent from its pre-flip,
6146    /// channel-less struct — pruning exactly the rows the flip just re-parented).
6147    /// Proves the lock actually serializes rather than being a no-op: with the lock held
6148    /// the wizard cannot reach its flip, and it completes once released.
6149    #[tokio::test]
6150    async fn wizard_flip_waits_for_an_in_flight_follow_pass() {
6151        use crate::community::migration;
6152        let (bed, owner, _member) = TestBed::new();
6153        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6154        // Shared across the spawned wizard, so both halves see the same relay state.
6155        let relay = std::sync::Arc::new(MemoryRelay::new());
6156
6157        bed.swap_to(&owner);
6158        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6159        let v1_cid = v1.id.to_hex();
6160        let v1_channel = v1.channels[0].id.to_hex();
6161        v1.owner_attestation = Some({
6162            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6163                .finalize(&owner.keys).unwrap().as_json()
6164        });
6165        crate::db::community::save_community(&v1).unwrap();
6166
6167        // Phase 1 alone, so the twin's id (and therefore its follow lock) is known before
6168        // the flip runs — exactly what a follow worker would have loaded.
6169        let twin = create_migration_twin(
6170            &*relay, "Guild", bed.relays.clone(), None,
6171            (v1.channels[0].id, "general".to_string()),
6172        ).await.unwrap();
6173        let v2_id = twin.identity.community_id;
6174        let v2_hex = crate::simd::hex::bytes_to_hex_32(&v2_id.0);
6175        crate::db::community::set_migration_ledger(&v1_cid, &v2_hex, migration::PHASE_TWIN_MINTED, "").unwrap();
6176
6177        // A follow pass is in flight: it holds the lock across its network stage.
6178        let held = crate::community::v2::realtime::follow_lock(&v2_id).lock_owned().await;
6179
6180        let wizard = tokio::spawn({
6181            let relay = relay.clone();
6182            let v1 = v1.clone();
6183            async move { migration::migrate_community_to_v2(&*relay, &v1, unlocked).await }
6184        });
6185
6186        // The wizard runs its network phases but must BLOCK at the flip.
6187        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
6188        assert!(!wizard.is_finished(), "the flip must wait for the in-flight follow pass");
6189        assert!(
6190            crate::db::community::get_migrated_to(&v1_cid).unwrap().is_none(),
6191            "the fence must not be stamped while the follow lock is held"
6192        );
6193
6194        // The follow pass finishes; the flip proceeds.
6195        drop(held);
6196        let flipped = wizard.await.unwrap().unwrap();
6197        assert_eq!(flipped, v2_hex, "the wizard completed onto the SAME twin (resumed, never re-minted)");
6198        assert_eq!(
6199            crate::db::community::community_id_for_channel(&v1_channel).unwrap().as_deref(),
6200            Some(v2_hex.as_str()),
6201            "the channel row is stitched to the twin, not pruned"
6202        );
6203    }
6204
6205    /// THE LYNCHPIN: a banned-but-never-cut v1 member CAN open `m` (they hold the v1
6206    /// root — no read-cut ever rotated it), but the wizard cloned the v1 banlist onto the
6207    /// twin, so the ban-gated accept refuses them: no Guestbook Join, no flip, room stays
6208    /// sealed. This is the exact residual JSKitty accepted, proven enforced.
6209    #[tokio::test]
6210    async fn banned_never_cut_member_opens_m_but_cannot_migrate() {
6211        use crate::community::migration;
6212        let (bed, owner, banned) = TestBed::new();
6213        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6214
6215        // Owner's v1 community with the member on the BANLIST (never read-cut: epoch 0).
6216        bed.swap_to(&owner);
6217        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6218        let v1_cid = v1.id.to_hex();
6219        v1.owner_attestation = Some({
6220            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6221                .finalize(&owner.keys).unwrap().as_json()
6222        });
6223        crate::db::community::save_community(&v1).unwrap();
6224        crate::db::community::set_community_banlist(&v1_cid, &[banned.keys.public_key().to_hex()], 1_000).unwrap();
6225
6226        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6227
6228        // The banned member holds the same v1 (same root — never cut) and folds the carrier.
6229        bed.swap_to(&banned);
6230        let mut m_v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6231        m_v1.id = v1.id;
6232        m_v1.server_root_key = v1.server_root_key.clone();
6233        m_v1.channels[0].id = v1.channels[0].id;
6234        m_v1.owner_attestation = v1.owner_attestation.clone();
6235        crate::db::community::save_community(&m_v1).unwrap();
6236        crate::community::service::fetch_and_apply_control(&bed.relay, &m_v1).await.unwrap();
6237
6238        // They hold the pointer AND can open `m` — but the drive is REFUSED at the ban gate.
6239        let raw = crate::db::community::get_migration_pointer(&v1_cid).unwrap().expect("pointer lands");
6240        let payload = migration::parse_migration_payload(&raw).unwrap();
6241        assert!(payload.m.is_some());
6242        let err = migration::drive_migration(&bed.relay, &m_v1).await.unwrap_err();
6243        assert!(err.contains("banned"), "refused at the join-time ban gate: {err}");
6244        assert!(crate::db::community::get_migrated_to(&v1_cid).unwrap().is_none(), "no flip");
6245        assert!(
6246            crate::db::community::load_community_v2(&crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&v2_hex))).unwrap().is_none(),
6247            "banned member never acquires the v2 twin"
6248        );
6249    }
6250
6251    /// Wizard resume never double-mints: a re-run after the TWIN_MINTED ledger row exists
6252    /// completes on the SAME v2 identity — with a NON-vacuous phase-1b re-run (a sibling
6253    /// channel + a banlist entry crash-recovered end-to-end, sibling stitched). Plus the
6254    /// crash-heal: flip landed but the FLIPPED ledger write didn't → re-run reports success.
6255    #[tokio::test]
6256    async fn wizard_resume_continues_on_the_same_twin() {
6257        use crate::community::migration;
6258        let (bed, owner, banned) = TestBed::new();
6259        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6260
6261        bed.swap_to(&owner);
6262        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6263        // A second channel + a banned member make the resumed phase-1b tail REAL work.
6264        let mut sibling = v1.channels[0].clone();
6265        sibling.id = crate::community::ChannelId(crate::community::random_32());
6266        sibling.name = "offtopic".into();
6267        v1.channels.push(sibling.clone());
6268        let v1_cid = v1.id.to_hex();
6269        v1.owner_attestation = Some({
6270            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6271                .finalize(&owner.keys).unwrap().as_json()
6272        });
6273        crate::db::community::save_community(&v1).unwrap();
6274        crate::db::community::set_community_banlist(&v1_cid, &[banned.keys.public_key().to_hex()], 1_000).unwrap();
6275
6276        // Simulate a crash right after the mint: build the twin + ledger TWIN_MINTED, stop
6277        // BEFORE the sibling channel + banlist clone ever ran.
6278        let twin = create_migration_twin(&bed.relay, &v1.name, bed.relays.clone(), None, (v1.channels[0].id, "general".into())).await.unwrap();
6279        let minted_hex = crate::simd::hex::bytes_to_hex_32(&twin.identity.community_id.0);
6280        crate::db::community::set_migration_ledger(&v1_cid, &minted_hex, migration::PHASE_TWIN_MINTED, "").unwrap();
6281
6282        // The re-run resumes onto the SAME identity, re-runs 1b, and completes.
6283        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6284        assert_eq!(v2_hex, minted_hex, "no second twin was minted");
6285        let (ledger_v2, phase, _) = crate::db::community::get_migration_ledger(&v1_cid).unwrap().unwrap();
6286        assert_eq!(ledger_v2, minted_hex);
6287        assert_eq!(phase, migration::PHASE_FLIPPED);
6288        // The crash-recovered sibling stitched too, and the banlist clone landed on the wire
6289        // (folding the twin's control plane yields the banned npub).
6290        assert_eq!(
6291            crate::db::community::community_id_for_channel(&sibling.id.to_hex()).unwrap().as_deref(),
6292            Some(minted_hex.as_str()),
6293            "sibling channel re-parented by the resumed run"
6294        );
6295        let twin_reloaded = crate::db::community::load_community_v2(&twin.identity.community_id).unwrap().unwrap();
6296        let (_, _, wire_banlist) = verify_owner_root_and_reconcile(&bed.relay, twin_reloaded.clone())
6297            .await
6298            .map(|(c, h, b)| (c, h, b))
6299            .unwrap();
6300        assert!(wire_banlist.contains(&banned.keys.public_key().to_hex()),
6301            "the resumed banlist clone is folded from the twin's wire control plane");
6302
6303        // Crash-heal: roll the ledger back to CARRIER_PUBLISHED (flip landed, ledger behind)
6304        // → the re-run reports SUCCESS and heals, never "already been migrated".
6305        crate::db::community::set_migration_ledger(&v1_cid, &minted_hex, migration::PHASE_CARRIER_PUBLISHED, "").unwrap();
6306        let healed = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6307        assert_eq!(healed, minted_hex);
6308        let (_, phase, _) = crate::db::community::get_migration_ledger(&v1_cid).unwrap().unwrap();
6309        assert_eq!(phase, migration::PHASE_FLIPPED, "ledger healed to FLIPPED");
6310
6311        // Resume past a SELF-SEAL: a fold sealed the community after the carrier but
6312        // before the flip write (dissolved=1, migrated_to still NULL, ledger at
6313        // CARRIER_PUBLISHED). A wizard resume must NOT read this as a foreign dissolution.
6314        // Reuse THIS bed (a second TestBed would re-lock DB_TEST_GUARD and deadlock) with a
6315        // fresh v1 owned by the same owner.
6316        let mut v1b = crate::community::Community::create("Guild2", "general", bed.relays.clone());
6317        let v1b_cid = v1b.id.to_hex();
6318        v1b.owner_attestation = Some({
6319            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1b_cid)
6320                .finalize(&owner.keys).unwrap().as_json()
6321        });
6322        crate::db::community::save_community(&v1b).unwrap();
6323        let twin2 = create_migration_twin(&bed.relay, &v1b.name, bed.relays.clone(), None, (v1b.channels[0].id, "general".into())).await.unwrap();
6324        let twin2_hex = crate::simd::hex::bytes_to_hex_32(&twin2.identity.community_id.0);
6325        crate::db::community::set_migration_ledger(&v1b_cid, &twin2_hex, migration::PHASE_CARRIER_PUBLISHED, "").unwrap();
6326        crate::db::community::set_community_dissolved(&v1b_cid).unwrap(); // the self-seal
6327        let resumed = migration::migrate_community_to_v2(&bed.relay, &v1b, unlocked).await.unwrap();
6328        assert_eq!(resumed, twin2_hex, "resume past a self-seal completes, not false-terminal");
6329        assert_eq!(crate::db::community::get_migrated_to(&v1b_cid).unwrap().as_deref(), Some(twin2_hex.as_str()));
6330    }
6331
6332    /// The birth refound SEEDS the roster: rolling a genesis (epoch 0) twin to epoch 1 with an
6333    /// explicit member list makes those members fold into the memberlist WITHOUT any of them
6334    /// publishing a Join — the anti-ghost-town seed for not-yet-migrated v1 members (who hold
6335    /// no v2 keys). Genesis had no snapshot power; epoch 1 (owner = minting refounder) does.
6336    #[tokio::test]
6337    async fn birth_refound_seeds_an_explicit_roster() {
6338        let (bed, owner, _m) = TestBed::new();
6339        bed.swap_to(&owner);
6340        let twin = create_migration_twin(&bed.relay, "Guild", bed.relays.clone(), None,
6341            (ChannelId(crate::community::random_32()), "general".into())).await.unwrap();
6342        assert_eq!(twin.root_epoch, Epoch(0), "twin starts at genesis");
6343        // Two strangers who never join — pure seeded members.
6344        let ghost_a = Keys::generate().public_key();
6345        let ghost_b = Keys::generate().public_key();
6346
6347        let rolled = refound_at_birth(&bed.relay, &twin, &[owner.keys.public_key(), ghost_a, ghost_b]).await.unwrap();
6348        assert_eq!(rolled.root_epoch, Epoch(1), "birth refound advanced the twin to epoch 1");
6349
6350        // The memberlist folds all three from the epoch-1 snapshot, though only the owner
6351        // ever published a Join.
6352        let members = memberlist(&bed.relay, &rolled).await.unwrap();
6353        assert!(members.contains(&owner.keys.public_key()), "owner in the roster");
6354        assert!(members.contains(&ghost_a) && members.contains(&ghost_b), "never-joined members are seeded (no ghost town)");
6355
6356        // The compacted control plane still verifies (owner genesis carried to epoch 1) — a
6357        // fresh joiner at epoch 1 folds it. And a genesis-epoch snapshot has NO power: rolling
6358        // a fresh twin's snapshot only counts because the owner minted epoch 1.
6359        let (_, _, _banlist) = verify_owner_root_and_reconcile(&bed.relay, rolled.clone()).await
6360            .expect("the epoch-1 twin verifies from its compacted control plane");
6361
6362        // RESUME IDEMPOTENCE: a re-call on the already-refounded twin is a no-op (returns
6363        // epoch 1), never a double-advance to epoch 2 — the crash-between-wire-and-ledger case.
6364        let again = refound_at_birth(&bed.relay, &rolled, &[owner.keys.public_key(), ghost_a, ghost_b]).await.unwrap();
6365        assert_eq!(again.root_epoch, Epoch(1), "re-running the birth refound does not advance past epoch 1");
6366        assert_eq!(crate::db::community::load_community_v2(&twin.identity.community_id).unwrap().unwrap().root_epoch, Epoch(1));
6367    }
6368
6369    /// A banned entry in the seed list must NOT wedge the verify-back: fold_members
6370    /// subtracts the banlist, so a banned seed is never "readable" — the defensive filter drops
6371    /// it before the snapshot, so the refound still completes instead of aborting forever.
6372    #[tokio::test]
6373    async fn birth_refound_ignores_a_banned_seed_entry() {
6374        let (bed, owner, _m) = TestBed::new();
6375        bed.swap_to(&owner);
6376        let twin = create_migration_twin(&bed.relay, "Guild", bed.relays.clone(), None,
6377            (ChannelId(crate::community::random_32()), "general".into())).await.unwrap();
6378        let good = Keys::generate().public_key();
6379        let banned = Keys::generate();
6380        // Ban `banned` on the twin, then hand refound a seed list that (wrongly) includes them.
6381        set_banlist(&bed.relay, &twin, &[banned.public_key().to_hex()]).await.unwrap();
6382        let twin = crate::db::community::load_community_v2(&twin.identity.community_id).unwrap().unwrap();
6383
6384        let rolled = refound_at_birth(&bed.relay, &twin, &[owner.keys.public_key(), good, banned.public_key()]).await
6385            .expect("a banned seed entry is filtered, not a permanent verify-back wedge");
6386        assert_eq!(rolled.root_epoch, Epoch(1));
6387        let members = memberlist(&bed.relay, &rolled).await.unwrap();
6388        assert!(members.contains(&good), "the non-banned seed lands");
6389        assert!(!members.contains(&banned.public_key()), "the banned seed is not a member");
6390    }
6391
6392    /// The "late migrator never misses an epoch" property: a SEEDED-but-never-landed
6393    /// member (in the roster only via the birth snapshot, holding no keys, never posted) is a
6394    /// RECIPIENT of a subsequent OWNER refound — so a rotation that happens before they migrate
6395    /// still mints them a rekey blob to walk forward on. Verified by checking the ghost lands
6396    /// in the refound's memberlist-derived recipient set (they get a base-rekey blob).
6397    #[tokio::test]
6398    async fn a_seeded_member_receives_a_later_refound_rekey() {
6399        let (bed, owner, _m) = TestBed::new();
6400        bed.swap_to(&owner);
6401        let twin = create_migration_twin(&bed.relay, "Guild", bed.relays.clone(), None,
6402            (ChannelId(crate::community::random_32()), "general".into())).await.unwrap();
6403        let ghost = Keys::generate();
6404        // Birth refound seeds the ghost (never joins, holds no keys).
6405        let rolled = refound_at_birth(&bed.relay, &twin, &[owner.keys.public_key(), ghost.public_key()]).await.unwrap();
6406        assert!(memberlist(&bed.relay, &rolled).await.unwrap().contains(&ghost.public_key()), "ghost is seeded");
6407
6408        // A later OWNER refound (epoch 1→2) derives its rekey recipients from memberlist(),
6409        // which folds the snapshot — so the ghost IS a recipient (a base-rekey blob is minted
6410        // for them by construction) AND is re-snapshotted at epoch 2. Surviving in the epoch-2
6411        // memberlist proves both: the refound saw them as a member and carried them forward, so
6412        // a late migrator who opens `m` (epoch 1) can then walk their epoch-2 blob forward.
6413        let refounded = refound_community(&bed.relay, &rolled, &[]).await.unwrap();
6414        assert_eq!(refounded.root_epoch, Epoch(2), "the later refound advanced the epoch");
6415        assert!(
6416            memberlist(&bed.relay, &refounded).await.unwrap().contains(&ghost.public_key()),
6417            "a seeded member is a recipient of + re-seeded by a later refound (never misses an epoch)"
6418        );
6419    }
6420
6421    /// Governance survives migration: a v1 ADMIN is re-granted @admin on the twin (holds
6422    /// MANAGE_ROLES there), while a plain member is not.
6423    #[tokio::test]
6424    async fn v1_admin_stays_admin_across_migration() {
6425        use crate::community::migration;
6426        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
6427        let (bed, owner, admin) = TestBed::new();
6428        let unlocked = migration::MIGRATION_UNLOCK_AT + 1;
6429
6430        bed.swap_to(&owner);
6431        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6432        let v1_cid = v1.id.to_hex();
6433        v1.owner_attestation = Some({
6434            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6435                .finalize(&owner.keys).unwrap().as_json()
6436        });
6437        crate::db::community::save_community(&v1).unwrap();
6438        // v1 governance: one Admin role, granted to `admin`.
6439        let admin_role = Role::admin("a1".repeat(32));
6440        let roles = CommunityRoles {
6441            roles: vec![admin_role.clone()],
6442            grants: vec![MemberGrant { member: admin.keys.public_key().to_hex(), role_ids: vec![admin_role.role_id.clone()] }],
6443        };
6444        crate::db::community::set_community_roles(&v1_cid, &roles, 1_000).unwrap();
6445
6446        let v2_hex = migration::migrate_community_to_v2(&bed.relay, &v1, unlocked).await.unwrap();
6447        let twin = crate::db::community::load_community_v2(&crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&v2_hex))).unwrap().unwrap();
6448
6449        // Fold the twin's authority from the wire: the admin holds MANAGE_ROLES, a stranger doesn't.
6450        let authority = fetch_authority(&bed.relay, &twin).await;
6451        assert!(
6452            authority.roles.is_authorized(&admin.keys.public_key().to_hex(), Some(&owner.keys.public_key().to_hex()), Permissions::MANAGE_ROLES),
6453            "the v1 admin is an admin on the v2 twin"
6454        );
6455        assert!(
6456            !authority.roles.is_authorized(&Keys::generate().public_key().to_hex(), Some(&owner.keys.public_key().to_hex()), Permissions::MANAGE_ROLES),
6457            "a non-admin gains no authority"
6458        );
6459    }
6460
6461    /// The sweep converges on a PLAIN dissolution (owner-signed, no payload) but a
6462    /// non-owner tombstone (member-mintable) must NOT mark it checked — else a partial-relay
6463    /// probe returning only a stranger's record would permanently stop the sweep before the
6464    /// owner's real carrier is ever fetched.
6465    #[tokio::test]
6466    async fn sweep_marks_checked_only_on_an_owner_tombstone() {
6467        use crate::community::migration;
6468        let (bed, owner, stranger) = TestBed::new();
6469
6470        bed.swap_to(&owner);
6471        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6472        let v1_cid = v1.id.to_hex();
6473        v1.owner_attestation = Some({
6474            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1_cid)
6475                .finalize(&owner.keys).unwrap().as_json()
6476        });
6477        crate::db::community::save_community(&v1).unwrap();
6478
6479        // A STRANGER publishes a (payload-less) tombstone at the dissolved coordinate, and
6480        // the community is locally sealed (as if folded on an old build) but not yet checked.
6481        let inner = crate::community::roster::build_group_dissolved_edition(&stranger.keys, &v1.id, 500).unwrap();
6482        let outer = crate::community::roster::seal_dissolved_edition(&Keys::generate(), &inner, &v1.id).unwrap();
6483        bed.relay.publish_durable(&outer, &bed.relays).await.unwrap();
6484        crate::db::community::set_community_dissolved(&v1_cid).unwrap();
6485
6486        // Sweep: the only record is a stranger's → NOT marked checked (still a candidate).
6487        migration::sweep_dissolved_for_migration(&bed.relay).await;
6488        assert!(
6489            crate::db::community::migration_sweep_candidates().unwrap().contains(&v1_cid),
6490            "a stranger-only probe must not converge the sweep"
6491        );
6492
6493        // Now the OWNER publishes a plain dissolution → sweep marks it checked.
6494        let owner_inner = crate::community::roster::build_group_dissolved_edition(&owner.keys, &v1.id, 600).unwrap();
6495        let owner_outer = crate::community::roster::seal_dissolved_edition(&Keys::generate(), &owner_inner, &v1.id).unwrap();
6496        bed.relay.publish_durable(&owner_outer, &bed.relays).await.unwrap();
6497        migration::sweep_dissolved_for_migration(&bed.relay).await;
6498        assert!(
6499            !crate::db::community::migration_sweep_candidates().unwrap().contains(&v1_cid),
6500            "an owner plain-dissolution converges the sweep"
6501        );
6502    }
6503
6504    /// Wizard preflight refuses before the timelock and for non-owners.
6505    #[tokio::test]
6506    async fn wizard_preflight_gates_timelock_and_ownership() {
6507        use crate::community::migration;
6508        let (bed, owner, _member) = TestBed::new();
6509        bed.swap_to(&owner);
6510        let mut v1 = crate::community::Community::create("Guild", "general", bed.relays.clone());
6511        v1.owner_attestation = Some({
6512            crate::community::owner::build_owner_attestation_unsigned(owner.keys.public_key(), &v1.id.to_hex())
6513                .finalize(&owner.keys).unwrap().as_json()
6514        });
6515        crate::db::community::save_community(&v1).unwrap();
6516
6517        // Before the unlock → refused, nothing published.
6518        let err = migration::migrate_community_to_v2(&bed.relay, &v1, migration::MIGRATION_UNLOCK_AT - 1).await.unwrap_err();
6519        assert!(err.contains("not unlocked"), "{err}");
6520        assert!(crate::db::community::get_migration_ledger(&v1.id.to_hex()).unwrap().is_none(), "no ledger row before unlock");
6521    }
6522
6523    #[tokio::test]
6524    async fn public_link_full_loop() {
6525        let (bed, owner, member) = TestBed::new();
6526
6527        bed.swap_to(&owner);
6528        let community = create_community(&bed.relay, "Public Guild", bed.relays.clone(), None).await.unwrap();
6529        let general = community.channels[0].id;
6530        send_message(&bed.relay, &community, &general, "come on in").await.unwrap();
6531        // Mint a shareable link (a non-stock relay so the fragment carries it).
6532        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6533        assert!(link.url.starts_with("https://vectorapp.io/invite/"));
6534        assert!(link.url.contains('#'), "the fragment carries the token");
6535
6536        // Member joins purely from the URL string.
6537        bed.swap_to(&member);
6538        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
6539        assert_eq!(joined.id().0, community.id().0);
6540        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["come on in"]);
6541    }
6542
6543    #[test]
6544    fn bundle_of_snapshots_the_held_icon() {
6545        let owner = Keys::generate();
6546        let g = control::genesis(&owner, control::CommunityMetadata { name: "Logo".into(), ..Default::default() }, 1_000).unwrap();
6547        let mut c = CommunityV2::from_genesis(&g, "Logo", None, vec!["wss://r".into()], 0);
6548        let icon = control::ImageRef { url: "https://blossom.example/i".into(), key: "k".into(), nonce: "n".into(), hash: "h".into(), extra: Default::default() };
6549        c.icon = Some(icon.clone());
6550        let bundle = bundle_of(&c, BundleAudience::Link, None, None, None);
6551        assert_eq!(bundle.icon, Some(icon), "a parked invite renders the real logo from the mint-time snapshot");
6552    }
6553
6554    #[test]
6555    fn addressing_roots_fan_current_plus_archived_bounded_and_deduped() {
6556        // follow_rekeys' fetch fan AND streamauth's plane registration share
6557        // this. A channel rekey rides the PRIOR root (CORD-06 D2), so the set
6558        // MUST include archived roots or an AUTH-gated relay never serves the
6559        // rotation crate → the channel stalls at its old epoch.
6560        let (_tmp, _guard, _owner) = init_test_db();
6561        let cur_root = [9u8; 32];
6562        let cid = crate::community::CommunityId([1u8; 32]);
6563        let cid_hex = cid.to_hex();
6564
6565        // No archives yet → just the current root.
6566        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6567        assert_eq!(roots, vec![cur_root], "with no archived roots the fan is the current root alone");
6568
6569        // Archive two prior roots (freshest-first ordering is asserted below).
6570        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &[1u8; 32]).unwrap();
6571        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1, &[2u8; 32]).unwrap();
6572        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6573        assert_eq!(roots[0], cur_root, "current root leads");
6574        assert!(roots.contains(&[1u8; 32]) && roots.contains(&[2u8; 32]), "both archived roots are in the fan");
6575        assert_eq!(roots.len(), 3, "current + 2 archived, no dupes");
6576        // Freshest-archived-first (epoch 1 before epoch 0).
6577        assert_eq!(roots[1], [2u8; 32], "higher archived epoch is addressed before the lower");
6578
6579        // A stored root equal to the CURRENT one must not duplicate.
6580        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 2, &cur_root).unwrap();
6581        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6582        assert_eq!(roots.iter().filter(|r| **r == cur_root).count(), 1, "the current root is never duplicated");
6583
6584        // Cap: many archives truncate to MAX_ADDRESSING_ROOTS.
6585        for e in 3..20u64 {
6586            crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, e, &[e as u8; 32]).unwrap();
6587        }
6588        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
6589        assert_eq!(roots.len(), MAX_ADDRESSING_ROOTS, "the fan is bounded so a relay can't feed an unbounded walk");
6590    }
6591
6592    #[tokio::test]
6593    async fn public_link_preview_shows_live_name_and_icon_without_joining() {
6594        let (bed, owner, member) = TestBed::new();
6595
6596        bed.swap_to(&owner);
6597        let community = create_community(&bed.relay, "Soapbox", bed.relays.clone(), None).await.unwrap();
6598        // The icon lives on the Control Plane, never in the bundle — publish it
6599        // as a metadata edition so the preview must FOLD to see it.
6600        let icon = control::ImageRef {
6601            url: "https://blossom.example/soap".into(),
6602            key: "k".into(),
6603            nonce: "n".into(),
6604            hash: "h".into(),
6605            extra: Default::default(),
6606        };
6607        let mut meta = community.metadata();
6608        meta.icon = Some(icon.clone());
6609        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
6610        // An any-host base — the naddr#fragment payload is domain-agnostic.
6611        let link = mint_public_link(&bed.relay, &community, "https://armada.buzz", None, None).await.unwrap();
6612
6613        // A NON-member previews: the real name + the live icon, nothing persisted.
6614        bed.swap_to(&member);
6615        let preview = preview_public_link(&bed.relay, &link.url).await.unwrap();
6616        assert_eq!(preview.name, "Soapbox");
6617        assert_eq!(preview.icon, Some(icon), "the icon folds from the live Control Plane, not the bundle");
6618        assert!(
6619            crate::db::community::load_community_v2(preview.id()).unwrap().is_none(),
6620            "previewing must not persist a membership"
6621        );
6622    }
6623
6624    #[tokio::test]
6625    async fn a_previewed_join_reuses_the_verified_fold() {
6626        let (bed, owner, member) = TestBed::new();
6627        bed.swap_to(&owner);
6628        let community = create_community(&bed.relay, "FastJoin", bed.relays.clone(), None).await.unwrap();
6629        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6630
6631        bed.swap_to(&member);
6632        let _ = preview_public_link(&bed.relay, &link.url).await.unwrap();
6633        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
6634        assert_eq!(joined.id().0, community.id().0);
6635        assert!(joined.created_at_ms > 0, "the handoff stamps the JOIN's acquisition time, not the preview's");
6636        // The slot was CONSUMED by the join — proving the handoff path ran (a
6637        // verify re-walk would have left the preview's entry in place).
6638        assert!(VERIFIED_PREVIEW.lock().unwrap().is_none(), "the handoff slot must be consumed by the join");
6639    }
6640
6641    #[tokio::test]
6642    async fn guestbook_store_seeds_syncs_incrementally_and_matches_the_live_fold() {
6643        let (bed, owner, member) = TestBed::new();
6644        bed.swap_to(&owner);
6645        let community = create_community(&bed.relay, "GB", bed.relays.clone(), None).await.unwrap();
6646        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6647
6648        bed.swap_to(&member);
6649        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
6650
6651        // Seed from zero: the stored fold equals the authoritative live fold.
6652        let session = SessionGuard::capture();
6653        assert!(!sync_guestbook(&bed.relay, &joined, &session).await.unwrap().is_empty(), "the seed folds fresh events");
6654        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
6655        let (_, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
6656        assert!(cursor > 0, "the cursor advanced past zero");
6657        let stored: std::collections::BTreeSet<_> = stored_memberlist(&joined).unwrap().into_iter().collect();
6658        let live: std::collections::BTreeSet<_> = memberlist(&bed.relay, &joined).await.unwrap().into_iter().collect();
6659        assert_eq!(stored, live, "stored fold == live fold after the seed");
6660        assert!(stored.contains(&member.keys.public_key()));
6661
6662        // Nothing new on the plane → an idle re-sync folds nothing.
6663        assert!(sync_guestbook(&bed.relay, &joined, &session).await.unwrap().is_empty());
6664
6665        // The owner kicks the member; a CURSOR catch-up folds the kick in — no full walk.
6666        bed.swap_to(&owner);
6667        kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
6668        bed.swap_to(&member);
6669        let session = SessionGuard::capture();
6670        assert!(!sync_guestbook(&bed.relay, &joined, &session).await.unwrap().is_empty(), "the kick lands incrementally");
6671        assert!(
6672            !stored_memberlist(&joined).unwrap().contains(&member.keys.public_key()),
6673            "an owner kick removes the member from the stored fold"
6674        );
6675    }
6676
6677    #[tokio::test]
6678    async fn a_preview_then_revoke_still_refuses_the_join() {
6679        let (bed, owner, member) = TestBed::new();
6680        bed.swap_to(&owner);
6681        let community = create_community(&bed.relay, "RevokeRace", bed.relays.clone(), None).await.unwrap();
6682        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6683
6684        // Member previews (warming the verified handoff), THEN the owner revokes.
6685        bed.swap_to(&member);
6686        let p = preview_public_link(&bed.relay, &link.url).await.unwrap();
6687        assert_eq!(p.name, "RevokeRace");
6688        bed.swap_to(&owner);
6689        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
6690        bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();
6691
6692        // The join MUST refuse: the handoff skips only the root re-verify, never
6693        // the bundle re-fetch that carries the revocation gate.
6694        bed.swap_to(&member);
6695        let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
6696        assert!(err.contains("revoked"), "got: {err}");
6697    }
6698
6699    #[tokio::test]
6700    async fn a_revoked_link_refuses_to_join() {
6701        let (bed, owner, member) = TestBed::new();
6702        bed.swap_to(&owner);
6703        let community = create_community(&bed.relay, "Revoked", bed.relays.clone(), None).await.unwrap();
6704        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6705        // Owner retires the link (re-posts the coordinate as a tombstone).
6706        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
6707        bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();
6708
6709        bed.swap_to(&member);
6710        let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
6711        assert!(err.contains("revoked"), "a retired link finds the grave, not keys: {err}");
6712    }
6713
6714    #[tokio::test]
6715    async fn an_expired_direct_invite_refuses_to_join() {
6716        let (bed, owner, member) = TestBed::new();
6717        bed.swap_to(&owner);
6718        let community = create_community(&bed.relay, "Expired", bed.relays.clone(), None).await.unwrap();
6719        // Hand-mint an invite that expired in the past.
6720        let inviter = owner.keys.clone();
6721        let mut bundle = bundle_of(&community, BundleAudience::Link, Some(inviter.public_key()), Some(1_000), None);
6722        bundle.expires_at = Some(1_000); // unix ms, long past
6723        let wrap = invite::build_direct_invite(&inviter, &member.keys.public_key(), &bundle).unwrap();
6724        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
6725
6726        bed.swap_to(&member);
6727        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6728        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
6729        assert!(err.contains("expired"), "a past-expiry invite refuses to join: {err}");
6730    }
6731
6732    #[tokio::test]
6733    async fn a_tombstone_beats_a_live_bundle_regardless_of_fetch_order() {
6734        // The revocation-durability fix: if ANY signer-valid tombstone is among the
6735        // fetched events, refuse — even when a Live bundle is returned FIRST (the
6736        // production union has no newest-first sort, so a stale relay's Live can lead).
6737        let (bed, owner, member) = TestBed::new();
6738        bed.swap_to(&owner);
6739        let community = create_community(&bed.relay, "Rev", bed.relays.clone(), None).await.unwrap();
6740        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6741        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
6742
6743        // A relay union that hands back [Live, tombstone] — Live FIRST. Old
6744        // `events.first()` would join the Live; the scan-all fix must refuse.
6745        let union = FixedFetch { events: vec![link.bundle_event.clone(), tombstone] };
6746
6747        bed.swap_to(&member);
6748        let err = accept_public_link(&union, &link.url).await.unwrap_err();
6749        assert!(err.contains("revoked"), "a tombstone must beat a Live returned first: {err}");
6750    }
6751
6752    #[test]
6753    fn from_bundle_refuses_an_over_cap_bundle_before_allocating() {
6754        // The accept-side DoS bound: from_bundle (which accept_bundle calls)
6755        // rejects a >256-channel bundle via validate() BEFORE the Vec allocation.
6756        // (The Direct-Invite wire path is additionally bounded by NIP-44's 64KB
6757        // cap, which trips even earlier — but the count guard is the real defense
6758        // for the single-layer public-link bundle.)
6759        let owner = Keys::generate();
6760        let identity = super::super::control::CommunityIdentity::mint(&owner.public_key());
6761        let hex = crate::simd::hex::bytes_to_hex_32;
6762        let root = [0x11u8; 32];
6763        let mut bundle = CommunityInvite {
6764            community_id: hex(&identity.community_id.0),
6765            owner: hex(&identity.owner_xonly),
6766            owner_salt: hex(&identity.owner_salt),
6767            community_root: hex(&root),
6768            root_epoch: 0,
6769            channels: vec![],
6770            relays: vec!["wss://r".into()],
6771            name: "X".into(),
6772            icon: None,
6773            expires_at: None,
6774            creator_npub: None,
6775            label: None,
6776            extra: Default::default(),
6777        };
6778        bundle.channels = (0..=invite::MAX_BUNDLE_CHANNELS)
6779            .map(|i| {
6780                let mut id = [0u8; 32];
6781                id[..8].copy_from_slice(&(i as u64).to_be_bytes());
6782                invite::ChannelGrant { id: hex(&id), key: hex(&root), epoch: 0, name: "x".into() }
6783            })
6784            .collect();
6785        assert!(CommunityV2::from_bundle(&bundle, 0).is_err(), "an over-cap bundle is refused before allocating");
6786    }
6787
6788    #[tokio::test]
6789    async fn a_join_swap_between_fetch_and_save_aborts_and_leaves_the_other_account_clean() {
6790        // The SessionGuard straddle: a public-link accept fetches then saves. If the
6791        // account swaps in that window, the join must abort — never write A's
6792        // community into B's DB. SwapMidFetch bumps the session generation during
6793        // the fetch await, exactly as a real swap_session would.
6794        let (bed, owner, member) = TestBed::new();
6795        bed.swap_to(&owner);
6796        let community = create_community(&bed.relay, "Straddle", bed.relays.clone(), None).await.unwrap();
6797        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
6798        // A fresh swap-injecting transport holding the same bundle event.
6799        let swap_relay = SwapMidFetch { inner: MemoryRelay::new() };
6800        swap_relay.inner.publish_durable(&link.bundle_event, &bed.relays).await.unwrap();
6801
6802        bed.swap_to(&member);
6803        let err = accept_public_link(&swap_relay, &link.url).await.unwrap_err();
6804        assert!(err.contains("account changed"), "a swap mid-join must abort: {err}");
6805        assert!(
6806            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
6807            "the aborted join wrote nothing to the (member) account DB"
6808        );
6809    }
6810
6811    #[tokio::test]
6812    async fn the_owner_is_a_member_even_without_a_fetched_genesis_join() {
6813        // The owner is derived from the self-certifying community_id, so the
6814        // memberlist includes them independent of any Guestbook fetch.
6815        let (_tmp, _guard, owner) = init_test_db();
6816        let relay = MemoryRelay::new();
6817        let community = create_community(&relay, "Owned", vec!["wss://r".into()], None).await.unwrap();
6818        // A memberlist over an EMPTY guestbook (fetch a community-relay-less view)
6819        // still contains the owner.
6820        let empty = MemoryRelay::new();
6821        let members = memberlist(&empty, &community).await.unwrap();
6822        assert_eq!(members, vec![owner.public_key()], "owner present with no fetched Join");
6823    }
6824
6825    #[tokio::test]
6826    async fn an_expiring_minted_invite_refuses_after_the_deadline() {
6827        // The mint path can now produce an expiring invite, and the accept gate
6828        // trips on it (end-to-end through the real service, not a hand-built bundle).
6829        let (bed, owner, member) = TestBed::new();
6830        bed.swap_to(&owner);
6831        let community = create_community(&bed.relay, "Timed", bed.relays.clone(), None).await.unwrap();
6832        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), Some(1_000), Some("beta".into()))
6833            .await
6834            .unwrap();
6835
6836        bed.swap_to(&member);
6837        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6838        assert!(
6839            accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err().contains("expired"),
6840            "a minted expiring invite refuses past its deadline"
6841        );
6842    }
6843
6844    #[tokio::test]
6845    async fn a_member_who_leaves_drops_from_the_memberlist() {
6846        let (bed, owner, member) = TestBed::new();
6847        bed.swap_to(&owner);
6848        let community = create_community(&bed.relay, "Leaving", bed.relays.clone(), None).await.unwrap();
6849        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
6850
6851        bed.swap_to(&member);
6852        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
6853        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
6854        // Let the leave land strictly after the join.
6855        tokio::time::sleep(std::time::Duration::from_millis(2)).await;
6856        leave_community(&bed.relay, &joined).await.unwrap();
6857
6858        bed.swap_to(&owner);
6859        let members = memberlist(&bed.relay, &community).await.unwrap();
6860        assert!(members.contains(&owner.keys.public_key()));
6861        assert!(!members.contains(&member.keys.public_key()), "a member who left drops from the list");
6862    }
6863
6864    #[tokio::test]
6865    async fn a_swapped_member_cannot_see_the_owners_community_until_joining() {
6866        // Multi-account isolation: after the swap, the member's DB holds nothing
6867        // of the owner's community — the dual-stack storage is per-account.
6868        let (bed, owner, member) = TestBed::new();
6869        bed.swap_to(&owner);
6870        let community = create_community(&bed.relay, "Private-so-far", bed.relays.clone(), None).await.unwrap();
6871        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some());
6872
6873        bed.swap_to(&member);
6874        assert!(
6875            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
6876            "the owner's community must be invisible in the member's account DB"
6877        );
6878        assert_eq!(crate::db::community::list_community_ids().unwrap().len(), 0);
6879    }
6880
6881    // ── Live control-follow ──────────────────────────────────────────────────
6882
6883    /// Publish an owner-grammar channel edition straight to the control plane,
6884    /// signed by `signer` (the owner for a legit edit, a stranger for the
6885    /// authority test). `version`/`deleted` drive add-vs-rename-vs-delete.
6886    /// The entity's current head `self_hash` on the relay (highest version wins),
6887    /// so a helper can chain a new edition the way a real owner client does.
6888    async fn head_hash_on_relay(relay: &MemoryRelay, community: &CommunityV2, entity_id: &[u8; 32]) -> Option<[u8; 32]> {
6889        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
6890        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
6891        let wraps = relay.fetch(&query, &community.relays).await.ok()?;
6892        let mut head: Option<(u64, [u8; 32])> = None;
6893        for w in &wraps {
6894            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
6895                if ed.entity_id == *entity_id && head.is_none_or(|(v, _)| ed.version > v) {
6896                    head = Some((ed.version, ed.self_hash));
6897                }
6898            }
6899        }
6900        head.map(|(_, h)| h)
6901    }
6902
6903    /// The `vac` a non-owner signer must attach, read off the Grant they were
6904    /// given on the relay (CORD-04 §5). The owner cites nothing. Mirrors what a
6905    /// real client does via `my_authority_citation`, so the fixtures publish the
6906    /// shape Vector actually emits.
6907    async fn cite_on_relay(
6908        relay: &MemoryRelay,
6909        community: &CommunityV2,
6910        signer: &Keys,
6911    ) -> Option<crate::community::edition::AuthorityCitation> {
6912        if community.owner().ok() == Some(signer.public_key()) {
6913            return None;
6914        }
6915        let entity_id = crate::community::v2::derive::grant_locator(community.id(), &signer.public_key().to_bytes());
6916        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
6917        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
6918        let wraps = relay.fetch(&query, &community.relays).await.ok()?;
6919        let mut head: Option<(u64, [u8; 32])> = None;
6920        for w in &wraps {
6921            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
6922                if ed.entity_id == entity_id && head.is_none_or(|(v, _)| ed.version > v) {
6923                    head = Some((ed.version, ed.self_hash));
6924                }
6925            }
6926        }
6927        head.map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
6928    }
6929
6930    async fn publish_channel_edition(
6931        relay: &MemoryRelay,
6932        community: &CommunityV2,
6933        signer: &Keys,
6934        channel_id: &ChannelId,
6935        name: &str,
6936        private: bool,
6937        version: u64,
6938        deleted: bool,
6939    ) {
6940        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
6941        let prev = head_hash_on_relay(relay, community, &channel_id.0).await;
6942        let meta = control::ChannelMetadata { name: name.into(), private, deleted: deleted.then_some(true), ..Default::default() };
6943        let content = serde_json::to_string(&meta).unwrap();
6944        let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel_id.0, version, prev.as_ref(), &content, 1_000, None);
6945        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
6946        relay.publish(&wrap, &community.relays).await.unwrap();
6947    }
6948
6949    /// Publish an owner-grammar community-metadata edition (rename etc.), chained
6950    /// to the current relay head like a real owner client.
6951    async fn publish_community_meta(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64) {
6952        publish_community_meta_at(relay, community, signer, name, version, 1_000).await;
6953    }
6954
6955    /// As [`publish_community_meta`] with an explicit timestamp, for tests that need
6956    /// relay-side newest-first ordering (paging/eviction scenarios).
6957    async fn publish_community_meta_at(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64, at_secs: u64) {
6958        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
6959        let prev = head_hash_on_relay(relay, community, &community.id().0).await;
6960        let meta = control::CommunityMetadata { name: name.into(), ..Default::default() };
6961        let content = serde_json::to_string(&meta).unwrap();
6962        let cite = cite_on_relay(relay, community, signer).await;
6963        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());
6964        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(at_secs)).unwrap();
6965        relay.publish(&wrap, &community.relays).await.unwrap();
6966    }
6967
6968    #[test]
6969    fn metadata_apply_captures_undriven_fields_for_republish() {
6970        let owner = Keys::generate();
6971        let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
6972        let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
6973        let general = held.channels[0].id;
6974
6975        // A foreign vsk-0 head carrying custom + unknown fields folds them in…
6976        let mut custom = serde_json::Map::new();
6977        custom.insert("accent".into(), serde_json::Value::from("#89f0b6"));
6978        let mut extra = serde_json::Map::new();
6979        extra.insert("vnd_flag".into(), serde_json::Value::Bool(true));
6980        let meta = control::CommunityMetadata { name: "A".into(), custom: Some(custom.clone()), extra: extra.clone(), ..Default::default() };
6981        assert!(apply_community_metadata(&mut held, meta), "gaining custom/extra is a change");
6982        assert_eq!(held.meta_custom, Some(custom.clone()));
6983        assert_eq!(held.meta_extra, extra);
6984        // …and the next local edit's base document republishes them verbatim.
6985        assert_eq!(held.metadata().custom, Some(custom));
6986        assert_eq!(held.metadata().extra, held.meta_extra);
6987
6988        // Same contract for a vsk-2 channel head (voice included).
6989        let mut ch_custom = serde_json::Map::new();
6990        ch_custom.insert("slowmode".into(), serde_json::Value::from(30));
6991        let ch_meta = control::ChannelMetadata {
6992            name: "general".into(),
6993            private: false,
6994            voice: Some(true),
6995            deleted: None,
6996            custom: Some(ch_custom.clone()),
6997            extra: Default::default(),
6998        };
6999        assert!(apply_channel_metadata(&mut held, general, ch_meta), "gaining voice/custom is a change");
7000        let ch = held.channel(&general).unwrap();
7001        assert_eq!(ch.voice, Some(true));
7002        assert_eq!(ch.meta_custom, Some(ch_custom.clone()));
7003        let rename = { let mut d = ch.metadata(); d.name = "lounge".into(); d };
7004        assert_eq!(rename.voice, Some(true), "our rename edition carries the foreign voice flag");
7005        assert_eq!(rename.custom, Some(ch_custom));
7006    }
7007
7008    #[test]
7009    fn community_metadata_apply_sets_and_clears_images() {
7010        let owner = Keys::generate();
7011        let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
7012        let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
7013
7014        let icon = control::ImageRef {
7015            url: "https://blossom.example/i".into(),
7016            key: "k".into(),
7017            nonce: "n".into(),
7018            hash: "h".into(),
7019            extra: Default::default(),
7020        };
7021        let with_icon = control::CommunityMetadata { name: "A".into(), icon: Some(icon.clone()), ..Default::default() };
7022        assert!(apply_community_metadata(&mut held, with_icon), "gaining an icon is a change");
7023        assert_eq!(held.icon.as_ref(), Some(&icon));
7024
7025        // An edition is the FULL document: a head without the icon removes it.
7026        let without = control::CommunityMetadata { name: "A".into(), ..Default::default() };
7027        assert!(apply_community_metadata(&mut held, without), "losing the icon is a change");
7028        assert_eq!(held.icon, None);
7029    }
7030
7031    /// Publish a Role edition (vsk 1) signed by `signer`, chained to the current head.
7032    async fn publish_role(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64) {
7033        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7034        let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).unwrap();
7035        let prev = head_hash_on_relay(relay, community, &role_id).await;
7036        let content = crate::community::v2::roles::role_content_json(role).unwrap();
7037        let cite = cite_on_relay(relay, community, signer).await;
7038        let rumor = control::build_edition_rumor(signer.public_key(), vsk::ROLE, &role_id, version, prev.as_ref(), &content, 1_000, cite.as_ref());
7039        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
7040        relay.publish(&wrap, &community.relays).await.unwrap();
7041    }
7042
7043    /// Publish a Grant edition (vsk 3) signed by `signer`, at grant_locator(cid, member).
7044    async fn publish_grant(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, member: &PublicKey, role_ids: Vec<String>, version: u64) {
7045        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7046        let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
7047        let prev = head_hash_on_relay(relay, community, &eid).await;
7048        let grant = MemberGrant { member: member.to_hex(), role_ids };
7049        let content = crate::community::v2::roles::grant_content_json(&grant).unwrap();
7050        let cite = cite_on_relay(relay, community, signer).await;
7051        let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
7052        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
7053        relay.publish(&wrap, &community.relays).await.unwrap();
7054    }
7055
7056    /// Publish a Banlist edition (vsk 4) signed by `signer`, at banlist_locator(cid).
7057    async fn publish_banlist(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, banned: &[String], version: u64) {
7058        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7059        let eid = crate::community::v2::derive::banlist_locator(community.id());
7060        let prev = head_hash_on_relay(relay, community, &eid).await;
7061        let content = crate::community::v2::roles::banlist_content_json(banned).unwrap();
7062        let cite = cite_on_relay(relay, community, signer).await;
7063        let rumor = control::build_edition_rumor(signer.public_key(), vsk::BANLIST, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
7064        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
7065        relay.publish(&wrap, &community.relays).await.unwrap();
7066    }
7067
7068    fn admin_role(role_id: &str, perms: u64) -> Role {
7069        Role { role_id: role_id.into(), name: "Admin".into(), position: 1, permissions: Permissions(perms), scope: RoleScope::Server, color: 0 }
7070    }
7071
7072    // ── CORD-04 §1 author-aware fold: a seat-holder (holds community_root, so can seal
7073    // any control edition) must not be able to SUPPRESS a role or grant by forging a
7074    // higher version at its coordinate. Owner-only signers mask this entirely, so every
7075    // attacker below signs as a NON-owner member.
7076
7077    #[tokio::test]
7078    async fn a_non_owner_cannot_suppress_the_admin_role_by_forging_a_higher_version() {
7079        let (bed, owner, attacker) = TestBed::new();
7080        bed.swap_to(&owner);
7081        let community = create_community(&bed.relay, "AttackA", bed.relays.clone(), None).await.unwrap();
7082        let victim = Keys::generate().public_key();
7083        grant_admin(&bed.relay, &community, &victim).await.unwrap();
7084
7085        // The admin role sits at a deterministic, publicly-computable coordinate.
7086        let admin_rid = fetch_authority(&bed.relay, &community)
7087            .await
7088            .roles
7089            .roles
7090            .iter()
7091            .find(|r| r.permissions.contains(Permissions::ADMIN_ALL))
7092            .unwrap()
7093            .role_id
7094            .clone();
7095        // Attacker forges v2 of that exact role, stripping its powers.
7096        publish_role(
7097            &bed.relay,
7098            &community,
7099            &attacker.keys,
7100            &Role { role_id: admin_rid.clone(), name: "pwned".into(), position: 1, permissions: Permissions(0), scope: RoleScope::Server, color: 0 },
7101            2,
7102        )
7103        .await;
7104
7105        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
7106        assert!(authority.roles.is_admin(&victim.to_hex()), "the forged strip is DROPPED; the owner's admin role survives beneath it");
7107        assert!(
7108            authority.heads.iter().any(|h| h.entity_hex == admin_rid && h.version == 1),
7109            "the floor advances only to the AUTHORIZED head (owner v1)"
7110        );
7111        assert!(!authority.heads.iter().any(|h| h.version == 2), "the forged v2 never poisons the floor");
7112    }
7113
7114    #[tokio::test]
7115    async fn a_non_owner_cannot_strip_a_members_grant_by_forging_a_higher_version() {
7116        let (bed, owner, attacker) = TestBed::new();
7117        bed.swap_to(&owner);
7118        let community = create_community(&bed.relay, "AttackC", bed.relays.clone(), None).await.unwrap();
7119        let victim = Keys::generate();
7120        grant_admin(&bed.relay, &community, &victim.public_key()).await.unwrap();
7121
7122        // Attacker forges a higher-version EMPTY grant at the victim's grant coordinate.
7123        publish_grant(&bed.relay, &community, &attacker.keys, &victim.public_key(), vec![], 9).await;
7124
7125        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
7126        assert!(
7127            authority.roles.is_admin(&victim.public_key().to_hex()),
7128            "the forged strip is dropped; the owner's grant survives and the victim keeps admin"
7129        );
7130    }
7131
7132    #[tokio::test]
7133    async fn forged_low_id_roles_by_a_non_owner_never_enter_the_authorized_roster() {
7134        let (bed, owner, attacker) = TestBed::new();
7135        bed.swap_to(&owner);
7136        let community = create_community(&bed.relay, "AttackB", bed.relays.clone(), None).await.unwrap();
7137        let victim = Keys::generate().public_key();
7138        grant_admin(&bed.relay, &community, &victim).await.unwrap();
7139
7140        // Low-id roles that WOULD evict the admin from a pre-authorize cap — but they're
7141        // unauthorized, so the post-authorize cap never sees them.
7142        for i in 0u8..6 {
7143            let rid = crate::simd::hex::bytes_to_hex_32(&[i; 32]);
7144            publish_role(&bed.relay, &community, &attacker.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
7145        }
7146
7147        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
7148        assert!(authority.roles.is_admin(&victim.to_hex()), "the legit admin survives the forged flood");
7149        assert_eq!(authority.roles.roles.len(), 1, "only the owner's admin role is authorized; every forgery is dropped");
7150    }
7151
7152    /// A canonical (order-independent) fingerprint of an AuthoritySet's authorized
7153    /// roster + banlist — two clients converge iff these match.
7154    fn authority_fingerprint(a: &AuthoritySet) -> String {
7155        let mut roles = a.roles.roles.clone();
7156        roles.sort_by(|x, y| x.role_id.cmp(&y.role_id));
7157        let mut grants = a.roles.grants.clone();
7158        for g in &mut grants {
7159            g.role_ids.sort();
7160        }
7161        grants.sort_by(|x, y| x.member.cmp(&y.member));
7162        let banned: Vec<&String> = a.banned.iter().collect();
7163        serde_json::json!({ "roles": roles, "grants": grants, "banned": banned }).to_string()
7164    }
7165
7166    #[tokio::test]
7167    async fn the_v2_authority_fold_is_order_independent() {
7168        // THE core consensus property: two honest clients that receive the SAME
7169        // control editions in DIFFERENT arrival orders must resolve the IDENTICAL
7170        // authorized roster + banlist (author-aware select_authorized + banlist
7171        // fold + cap, all deterministic). A divergence here would fork the
7172        // community's moderation state between honest members.
7173        let (bed, owner, _a) = TestBed::new();
7174        bed.swap_to(&owner);
7175        let community = create_community(&bed.relay, "Determinism", bed.relays.clone(), None).await.unwrap();
7176
7177        // A rich control plane: two admins, an extra role, two grants (one of them a
7178        // grant to a member the owner then bans), a banlist, a rename, a channel.
7179        let admin1 = Keys::generate().public_key();
7180        let admin2 = Keys::generate().public_key();
7181        grant_admin(&bed.relay, &community, &admin1).await.unwrap();
7182        grant_admin(&bed.relay, &community, &admin2).await.unwrap();
7183        let mod_rid = "5c".repeat(32);
7184        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&mod_rid, Permissions::KICK | Permissions::MANAGE_MESSAGES), 1).await;
7185        let member = Keys::generate().public_key();
7186        publish_grant(&bed.relay, &community, &owner.keys, &member, vec![mod_rid.clone()], 1).await;
7187        let banned_member = Keys::generate().public_key();
7188        publish_grant(&bed.relay, &community, &owner.keys, &banned_member, vec![mod_rid], 1).await;
7189        set_banlist(&bed.relay, &community, &[banned_member.to_hex()]).await.unwrap();
7190        let meta = control::CommunityMetadata { name: "Renamed".into(), relays: community.relays.clone(), ..Default::default() };
7191        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
7192        create_public_channel(&bed.relay, &community, "extra").await.unwrap();
7193
7194        let editions = fetch_control(&bed.relay, &community).await;
7195        let floors = load_floors(&community);
7196        assert!(editions.len() >= 6, "a rich plane was built ({} editions)", editions.len());
7197
7198        let baseline = authority_fingerprint(&fold_authority(&community, &editions, &floors));
7199
7200        // Fold under many arrival permutations: reversed, and several deterministic
7201        // rotations/interleavings. Every one must match the baseline.
7202        let mut orders: Vec<Vec<ParsedEdition>> = Vec::new();
7203        let mut rev = editions.clone();
7204        rev.reverse();
7205        orders.push(rev);
7206        for shift in [1usize, 3, 5, 7] {
7207            let n = editions.len();
7208            orders.push((0..n).map(|i| editions[(i + shift) % n].clone()).collect());
7209        }
7210        // A deterministic "shuffle": interleave from both ends.
7211        let mut zip = Vec::with_capacity(editions.len());
7212        let (mut lo, mut hi) = (0isize, editions.len() as isize - 1);
7213        while lo <= hi {
7214            zip.push(editions[lo as usize].clone());
7215            if lo != hi {
7216                zip.push(editions[hi as usize].clone());
7217            }
7218            lo += 1;
7219            hi -= 1;
7220        }
7221        orders.push(zip);
7222
7223        for (i, order) in orders.iter().enumerate() {
7224            let got = authority_fingerprint(&fold_authority(&community, order, &floors));
7225            assert_eq!(got, baseline, "arrival order #{i} must resolve the identical authority (consensus)");
7226        }
7227        // Sanity: the fingerprint reflects real state (the banned member is out, the
7228        // honest admins are in).
7229        assert!(baseline.contains(&admin1.to_hex()) || baseline.contains(&member.to_hex()), "grants are present in the fingerprint");
7230        assert!(baseline.contains(&banned_member.to_hex()), "the banlist entry is in the fingerprint");
7231    }
7232
7233    /// A transport that ACKs publishes but ERRORS every fetch — a relay outage / withhold.
7234    struct FetchErrors(MemoryRelay);
7235    #[async_trait::async_trait]
7236    impl crate::community::transport::Transport for FetchErrors {
7237        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
7238        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
7239            self.0.publish(e, r).await
7240        }
7241        async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
7242            Err("relay down".to_string())
7243        }
7244        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
7245            self.0.publish_durable(e, r).await
7246        }
7247    }
7248
7249    #[tokio::test]
7250    async fn fetch_authority_retains_the_persisted_banlist_on_a_transport_error() {
7251        let (bed, owner, victim) = TestBed::new();
7252        bed.swap_to(&owner);
7253        let community = create_community(&bed.relay, "BanRetain", bed.relays.clone(), None).await.unwrap();
7254        let victim_hex = victim.keys.public_key().to_hex();
7255        // A ban is persisted locally (as a completed set_banlist + follow leaves it).
7256        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
7257        crate::db::community::set_community_banlist(&cid_hex, &[victim_hex.clone()], 1).unwrap();
7258
7259        // A relay that ERRORS on fetch must degrade FAIL-SAFE: retain the ban, never
7260        // return an empty banlist (which would silently un-ban on withheld data).
7261        let down = FetchErrors(MemoryRelay::new());
7262        let view = fetch_authority(&down, &community).await;
7263        assert!(view.banned.contains(&victim_hex), "a transport error retains the persisted banlist");
7264    }
7265
7266    #[tokio::test]
7267    async fn follow_control_retains_the_roster_when_a_floored_role_ages_out() {
7268        let (bed, owner, _m) = TestBed::new();
7269        bed.swap_to(&owner);
7270        let community = create_community(&bed.relay, "Complete", bed.relays.clone(), None).await.unwrap();
7271        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
7272        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
7273        let rid = crate::simd::hex::bytes_to_hex_32(&[0x7c; 32]);
7274
7275        // Full state on relay1: an Admin role + two grants → both fold + persist as admins.
7276        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
7277        publish_grant(&bed.relay, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
7278        publish_grant(&bed.relay, &community, &owner.keys, &b, vec![rid.clone()], 1).await;
7279        let session = crate::state::SessionGuard::capture();
7280        follow_control(&bed.relay, &community, &session).await.unwrap();
7281        assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&a.to_hex()), "seeded");
7282
7283        // relay2 serves A's grant but NOT the role (aged out of the window): the fold
7284        // drops both admins yet raises no gap. The completeness gate must RETAIN the
7285        // stored roster rather than persist the lossy one.
7286        let relay2 = MemoryRelay::new();
7287        publish_grant(&relay2, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
7288        follow_control(&relay2, &community, &session).await.unwrap();
7289        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
7290        assert!(roster.is_admin(&a.to_hex()) && roster.is_admin(&b.to_hex()), "a floored-but-unfetched role retains the stored roster");
7291    }
7292
7293    #[tokio::test]
7294    async fn an_uncited_metadata_or_banlist_edition_is_dropped() {
7295        // CORD-04 §5 covers EVERY control entity, not just the delegation chain.
7296        // Vector already gated roles and grants in-fold; metadata, channels and
7297        // the banlist resolved on permission alone, so a client one sweep behind
7298        // honored an edit from an admin whose demotion it had not read yet.
7299        let (_tmp, _guard, owner) = init_test_db();
7300        let relay = MemoryRelay::new();
7301        let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
7302        let admin = Keys::generate();
7303        let rid = "a7".repeat(32);
7304        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA | Permissions::BAN), 1).await;
7305        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid], 1).await;
7306
7307        // The admin acts WITHOUT citing (what every pre-citation client emitted).
7308        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
7309        let meta = control::CommunityMetadata { name: "Uncited Rename".into(), ..Default::default() };
7310        let rumor = control::build_edition_rumor(
7311            admin.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2,
7312            head_hash_on_relay(&relay, &community, &community.id().0).await.as_ref(),
7313            &serde_json::to_string(&meta).unwrap(), 1_000, None,
7314        );
7315        let (wrap, _) = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
7316        relay.publish(&wrap, &community.relays).await.unwrap();
7317
7318        let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
7319        let victim = Keys::generate().public_key().to_hex();
7320        let ban_rumor = control::build_edition_rumor(
7321            admin.public_key(), vsk::BANLIST, &ban_eid, 1, None,
7322            &serde_json::to_string(&vec![victim.clone()]).unwrap(), 1_000, None,
7323        );
7324        let (ban_wrap, _) = control::seal_control_edition(&ban_rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
7325        relay.publish(&ban_wrap, &community.relays).await.unwrap();
7326
7327        let session = SessionGuard::capture();
7328        let updated = follow_control(&relay, &community, &session).await.unwrap();
7329        assert!(
7330            updated.as_ref().is_none_or(|c| c.name != "Uncited Rename"),
7331            "an uncited metadata edit must not be honored",
7332        );
7333        let authority = fetch_authority(&relay, &community).await;
7334        assert!(!authority.banned.contains(&victim), "an uncited banlist edition must not be honored");
7335        // The positive case (this same admin, citing, lands) is
7336        // `an_authorized_admin_edits_metadata_but_a_demoted_one_cannot` — its
7337        // helper cites, so it proves the gate is the CITATION and not the
7338        // permission. Re-proving it here would need a fresh chain anyway: a
7339        // cited edition chaining onto the rejected one above is gapped, not
7340        // refused.
7341    }
7342
7343    #[tokio::test]
7344    async fn an_authorized_admin_edits_metadata_but_a_demoted_one_cannot() {
7345        // CORD-04 §5: an admin holding MANAGE_METADATA renames the community; once the
7346        // owner revokes the grant, the (now unauthorized) admin's further edit drops
7347        // and the name holds at the last authorized state.
7348        let (_tmp, _guard, owner) = init_test_db();
7349        let relay = MemoryRelay::new();
7350        let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
7351        let admin = Keys::generate();
7352        let rid = "a1".repeat(32);
7353        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
7354        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
7355        publish_community_meta(&relay, &community, &admin, "Admin Rename", 2).await;
7356
7357        let session = SessionGuard::capture();
7358        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("admin edit authorized");
7359        assert_eq!(updated.name, "Admin Rename", "an admin with MANAGE_METADATA renames");
7360
7361        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke
7362        publish_community_meta(&relay, &community, &admin, "Demoted Rename", 3).await;
7363        let _ = follow_control(&relay, &community, &session).await.unwrap();
7364        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7365        assert_eq!(held.name, "Admin Rename", "a demoted admin's edit is dropped; the name holds");
7366    }
7367
7368    #[tokio::test]
7369    async fn a_roleless_member_cannot_edit_metadata() {
7370        let (_tmp, _guard, _owner) = init_test_db();
7371        let relay = MemoryRelay::new();
7372        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
7373        let stranger = Keys::generate();
7374        publish_community_meta(&relay, &community, &stranger, "Hijacked", 2).await;
7375        let session = SessionGuard::capture();
7376        assert!(
7377            follow_control(&relay, &community, &session).await.unwrap().is_none(),
7378            "a roleless member's metadata edit never folds"
7379        );
7380    }
7381
7382    #[tokio::test]
7383    async fn a_self_signed_grant_is_not_authority() {
7384        // The self-promotion defense: a member self-signs both a role and a grant of
7385        // it to themselves. authorize_delegation drops both (their signer never traces
7386        // to the owner), so their metadata edit stays unauthorized.
7387        let (_tmp, _guard, _owner) = init_test_db();
7388        let relay = MemoryRelay::new();
7389        let community = create_community(&relay, "NoSelfPromo", vec!["wss://r".into()], None).await.unwrap();
7390        let rogue = Keys::generate();
7391        let rid = "b2".repeat(32);
7392        publish_role(&relay, &community, &rogue, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
7393        publish_grant(&relay, &community, &rogue, &rogue.public_key(), vec![rid.clone()], 1).await;
7394        publish_community_meta(&relay, &community, &rogue, "Seized", 2).await;
7395        let session = SessionGuard::capture();
7396        assert!(
7397            follow_control(&relay, &community, &session).await.unwrap().is_none(),
7398            "a self-signed grant confers no authority"
7399        );
7400    }
7401
7402    #[tokio::test]
7403    async fn the_banlist_is_enforced_only_from_a_ban_holder() {
7404        let (_tmp, _guard, owner) = init_test_db();
7405        let relay = MemoryRelay::new();
7406        let community = create_community(&relay, "Bans", vec!["wss://r".into()], None).await.unwrap();
7407        let target = "cc".repeat(32);
7408
7409        // A non-BAN-holder's banlist edition is folded but NOT enforced.
7410        let rogue = Keys::generate();
7411        publish_banlist(&relay, &community, &rogue, &[target.clone()], 1).await;
7412        let floors = load_floors(&community);
7413        let editions = fetch_control(&relay, &community).await;
7414        let authority = fold_authority(&community, &editions, &floors);
7415        assert!(authority.banned.is_empty(), "a non-owner (no BAN) banlist is not enforced");
7416
7417        // The owner (supreme, holds BAN) bans the target: now enforced.
7418        publish_banlist(&relay, &community, &owner, &[target.clone()], 2).await;
7419        let editions = fetch_control(&relay, &community).await;
7420        let authority = fold_authority(&community, &editions, &floors);
7421        assert!(authority.banned.contains(&target), "the owner's banlist is enforced");
7422    }
7423
7424    #[tokio::test]
7425    async fn a_banned_admin_loses_all_authority() {
7426        // CORD-04 §4: a banned npub vanishes — even holding an un-stripped grant, a
7427        // banned admin's authority is dropped and their edits refused.
7428        let (_tmp, _guard, owner) = init_test_db();
7429        let relay = MemoryRelay::new();
7430        let community = create_community(&relay, "BanAuth", vec!["wss://r".into()], None).await.unwrap();
7431        let admin = Keys::generate();
7432        let rid = "e5".repeat(32);
7433        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
7434        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
7435        publish_banlist(&relay, &community, &owner, &[admin.public_key().to_hex()], 1).await; // ban, grant left intact
7436        publish_community_meta(&relay, &community, &admin, "Banned Rename", 2).await;
7437
7438        let session = SessionGuard::capture();
7439        assert!(
7440            follow_control(&relay, &community, &session).await.unwrap().is_none(),
7441            "a banned admin's edit is dropped even with an unstripped grant"
7442        );
7443        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
7444        assert!(authority.banned.contains(&admin.public_key().to_hex()));
7445        assert!(
7446            !authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
7447            "a banned admin holds no bit"
7448        );
7449    }
7450
7451    #[tokio::test]
7452    async fn a_ban_holder_cannot_ban_a_superior_or_the_owner() {
7453        // CORD-04 §3/§5: BAN needs the bit AND a strict outrank of the target. A mod
7454        // (pos 2, holds BAN) can ban a lower member but NOT a superior admin (pos 1)
7455        // and NOT the owner (supreme, unbannable).
7456        let (_tmp, _guard, owner) = init_test_db();
7457        let relay = MemoryRelay::new();
7458        let community = create_community(&relay, "Ranks", vec!["wss://r".into()], None).await.unwrap();
7459        let admin = Keys::generate();
7460        let moder = Keys::generate();
7461        let stranger = Keys::generate();
7462        let (admin_rid, mod_rid) = ("a1".repeat(32), "b2".repeat(32));
7463        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;
7464        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;
7465        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![admin_rid], 1).await;
7466        publish_grant(&relay, &community, &owner, &moder.public_key(), vec![mod_rid], 1).await;
7467        publish_banlist(&relay, &community, &moder, &[admin.public_key().to_hex(), owner.public_key().to_hex(), stranger.public_key().to_hex()], 1).await;
7468
7469        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
7470        assert!(!authority.banned.contains(&admin.public_key().to_hex()), "a mod cannot ban a superior admin");
7471        assert!(!authority.banned.contains(&owner.public_key().to_hex()), "nobody can ban the owner");
7472        assert!(authority.banned.contains(&stranger.public_key().to_hex()), "the mod CAN ban a lower-ranked member");
7473    }
7474
7475    #[tokio::test]
7476    async fn an_unauthorized_higher_banlist_cannot_unban() {
7477        // CORD-04 §4 anti-roster fail-CLOSED: a rogue's higher-version empty banlist
7478        // must not erase the owner's ban (author-aware head selection + persisted
7479        // banlist retention).
7480        let (_tmp, _guard, owner) = init_test_db();
7481        let relay = MemoryRelay::new();
7482        let community = create_community(&relay, "NoUnban", vec!["wss://r".into()], None).await.unwrap();
7483        let target = "cc".repeat(32);
7484        publish_banlist(&relay, &community, &owner, &[target.clone()], 1).await;
7485        let session = SessionGuard::capture();
7486        follow_control(&relay, &community, &session).await.unwrap(); // persists the ban
7487
7488        let rogue = Keys::generate();
7489        publish_banlist(&relay, &community, &rogue, &[], 2).await; // unauthorized higher, empty
7490        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
7491        assert!(authority.banned.contains(&target), "an unauthorized higher banlist cannot un-ban");
7492    }
7493
7494    #[tokio::test]
7495    async fn the_community_list_syncs_a_membership_to_a_fresh_device() {
7496        // CORD-02 §8: create publishes the 13302; a fresh device (community dropped
7497        // locally, the 13302 + genesis still on the relay) rehydrates it on sync.
7498        let (_tmp, _guard, _owner) = init_test_db();
7499        let relay = MemoryRelay::new();
7500        let relays = vec!["wss://r".to_string()];
7501        let community = create_community(&relay, "Synced", relays.clone(), None).await.unwrap();
7502        crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
7503        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none());
7504
7505        let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
7506        assert_eq!(rehydrated.len(), 1, "the left-behind membership rehydrates");
7507        assert_eq!(rehydrated[0].id().0, community.id().0);
7508        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some(), "and is now held locally");
7509    }
7510
7511    #[tokio::test]
7512    async fn a_leave_tombstones_the_membership_so_sync_does_not_rejoin() {
7513        let (_tmp, _guard, _owner) = init_test_db();
7514        let relay = MemoryRelay::new();
7515        let relays = vec!["wss://r".to_string()];
7516        let community = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
7517        leave_community(&relay, &community).await.unwrap(); // tombstones the 13302 + deletes
7518
7519        let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
7520        assert!(rehydrated.is_empty(), "a tombstoned membership is not rejoined on sync");
7521    }
7522
7523    #[tokio::test]
7524    async fn accepting_the_same_bundle_twice_is_idempotent() {
7525        // A bot restart or a duplicate invite delivery: accepting the SAME bundle
7526        // again must upsert cleanly — same community_id, no duplicate channels, no
7527        // corruption, the keys unchanged.
7528        let (bed, owner, member) = TestBed::new();
7529        bed.swap_to(&owner);
7530        let community = create_community(&bed.relay, "Idem", bed.relays.clone(), None).await.unwrap();
7531        create_public_channel(&bed.relay, &community, "extra").await.unwrap();
7532        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7533        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
7534
7535        bed.swap_to(&member);
7536        let first = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
7537        let channels_after_first = first.channels.len();
7538        let root_after_first = first.community_root;
7539
7540        // Accept the identical bundle again (restart / redelivery).
7541        let second = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
7542        assert_eq!(second.id().0, first.id().0, "same community_id");
7543        assert_eq!(second.channels.len(), channels_after_first, "no duplicate channels on re-accept");
7544        assert_eq!(second.community_root, root_after_first, "root unchanged");
7545
7546        // The persisted state is a single clean community with the expected channels.
7547        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7548        assert_eq!(reloaded.channels.len(), channels_after_first, "the DB holds one clean channel set");
7549        assert_eq!(crate::db::community::list_community_ids().unwrap().iter().filter(|id| id.0 == community.id().0).count(), 1, "exactly one community row");
7550    }
7551
7552    #[tokio::test]
7553    async fn a_severed_member_can_be_unbanned_and_re_admitted() {
7554        // The full moderation HEAL lifecycle: ban (banlist + grant strip + refound)
7555        // severs a member; the owner then unbans + sends a FRESH invite carrying the
7556        // NEW root; the member rejoins at the new epoch and converses again. Proves
7557        // a ban is reversible end-to-end, not a one-way door.
7558        let (bed, owner, member) = TestBed::new();
7559        bed.swap_to(&owner);
7560        let mut community = create_community(&bed.relay, "Redeemable", bed.relays.clone(), None).await.unwrap();
7561        let general = community.channels[0].id;
7562        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
7563        send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();
7564
7565        bed.swap_to(&member);
7566        let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
7567        let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
7568        assert!(texts_in(&bed.relay, &joined, &general).await.contains(&"owner: welcome".to_string()));
7569
7570        // Owner bans the member (CORD-04 §6 three-removal) → refound severs them.
7571        bed.swap_to(&owner);
7572        set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();
7573        grant_roles(&bed.relay, &community, &member.keys.public_key(), vec![]).await.unwrap();
7574        community = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
7575        assert_eq!(community.root_epoch, Epoch(1));
7576        send_message(&bed.relay, &community, &general, "owner: after the ban").await.unwrap();
7577
7578        // The member's follow concludes severance (no blob at the new epoch).
7579        bed.swap_to(&member);
7580        let session = SessionGuard::capture();
7581        assert!(follow_rekeys(&bed.relay, &joined, &session).await.unwrap().self_removed, "the member is cryptographically severed");
7582
7583        // Owner unbans + re-invites: build the fresh epoch-1 bundle (accept it
7584        // directly, so the test picks the NEW invite unambiguously rather than an
7585        // arbitrary one of the two pending 3313s).
7586        bed.swap_to(&owner);
7587        set_banlist(&bed.relay, &community, &[]).await.unwrap();
7588        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7589        assert_eq!(community.root_epoch, Epoch(1), "the owner's bundle carries epoch 1");
7590        let fresh_bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
7591
7592        // Member accepts the fresh invite → rejoins at epoch 1, reads current + posts.
7593        bed.swap_to(&member);
7594        let rejoined = accept_parked_invite(&bed.relay, &fresh_bundle, None).await.unwrap();
7595        assert_eq!(rejoined.root_epoch, Epoch(1), "rejoined at the current epoch");
7596        assert_eq!(rejoined.community_root, community.community_root, "holds the NEW root");
7597        let seen = texts_in(&bed.relay, &rejoined, &general).await;
7598        assert!(seen.contains(&"owner: after the ban".to_string()), "reads post-ban history with the new root");
7599        send_message(&bed.relay, &rejoined, &general, "member: i am back").await.unwrap();
7600
7601        bed.swap_to(&owner);
7602        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7603        assert!(
7604            texts_in(&bed.relay, &community, &general).await.contains(&"member: i am back".to_string()),
7605            "the re-admitted member converses again at the new epoch"
7606        );
7607        // And they're back in the memberlist.
7608        let members = memberlist(&bed.relay, &community).await.unwrap();
7609        assert!(members.contains(&member.keys.public_key()), "the re-admitted member is in the list");
7610    }
7611
7612    #[tokio::test]
7613    async fn dissolution_blocks_a_join() {
7614        // CORD-02 §9: the owner dissolves; a would-be joiner resolves the grave and
7615        // refuses to join.
7616        let (bed, owner, member) = TestBed::new();
7617        bed.swap_to(&owner);
7618        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
7619        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7620        let bundle_json = serde_json::to_string(&bundle).unwrap();
7621        dissolve_community(&bed.relay, &community).await.unwrap();
7622        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the owner's local hold is sealed");
7623
7624        bed.swap_to(&member);
7625        let err = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap_err();
7626        assert!(err.contains("dissolved"), "a join refuses a dissolved community: {err}");
7627    }
7628
7629    #[tokio::test]
7630    async fn only_the_owner_can_dissolve() {
7631        let (bed, owner, member) = TestBed::new();
7632        bed.swap_to(&owner);
7633        let community = create_community(&bed.relay, "Mine", bed.relays.clone(), None).await.unwrap();
7634        bed.swap_to(&member);
7635        assert!(dissolve_community(&bed.relay, &community).await.is_err(), "only the owner can dissolve");
7636        assert!(!is_dissolved(&bed.relay, &community).await, "and no tombstone was published");
7637    }
7638
7639    #[tokio::test]
7640    async fn a_foreign_tombstone_is_not_death() {
7641        // A non-owner sealing the dissolved plane is noise (verify_dissolved is
7642        // owner-gated), so the community is not treated as dead.
7643        let (_tmp, _guard, _owner) = init_test_db();
7644        let relay = MemoryRelay::new();
7645        let community = create_community(&relay, "Safe", vec!["wss://r".into()], None).await.unwrap();
7646        let rogue = Keys::generate();
7647        let rumor = crate::community::v2::dissolution::dissolved_tombstone_rumor(rogue.public_key(), community.id(), 1_000);
7648        let wrap = crate::community::v2::dissolution::seal_dissolved(&rumor, community.id(), &rogue, Timestamp::from_secs(1_000)).unwrap();
7649        relay.publish(&wrap, &community.relays).await.unwrap();
7650        assert!(!is_dissolved(&relay, &community).await, "a foreign-signed tombstone is not death");
7651    }
7652
7653    #[tokio::test]
7654    async fn a_public_channel_reads_history_across_a_refounding() {
7655        // CORD-03 §3: after a Refounding rolls the base root, a Public channel's
7656        // pre-rotation messages stay readable (the prior epoch's root is archived and
7657        // the read fans out across held epochs).
7658        let (_tmp, _guard, _owner) = init_test_db();
7659        let relay = MemoryRelay::new();
7660        let community = create_community(&relay, "History", vec!["wss://r".into()], None).await.unwrap();
7661        let general = community.channels[0].id;
7662        send_message(&relay, &community, &general, "before the refounding").await.unwrap();
7663
7664        let refounded = refound_community(&relay, &community, &[]).await.unwrap();
7665        assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
7666        send_message(&relay, &refounded, &general, "after the refounding").await.unwrap();
7667
7668        let texts = texts_in(&relay, &refounded, &general).await;
7669        assert!(texts.contains(&"before the refounding".to_string()), "the epoch-0 message is still readable");
7670        assert!(texts.contains(&"after the refounding".to_string()), "the epoch-1 message reads too");
7671    }
7672
7673    #[tokio::test]
7674    async fn refounding_aborts_when_control_state_is_withheld() {
7675        // B1 coverage gate (CORD-06 §3): a relay serving none of the committed control
7676        // heads must ABORT the Refounding — never silently drop state (e.g. unban a
7677        // member at the new epoch a fresh joiner bootstraps).
7678        let (_tmp, _guard, owner) = init_test_db();
7679        let relay = MemoryRelay::new();
7680        let community = create_community(&relay, "Withheld", vec!["wss://good".into()], None).await.unwrap();
7681        publish_banlist(&relay, &community, &owner, &["cc".repeat(32)], 1).await;
7682        let session = SessionGuard::capture();
7683        follow_control(&relay, &community, &session).await.unwrap(); // seed the banlist floor
7684
7685        // Re-point the held community to an EMPTY relay + save, so the Refounding (which
7686        // reloads fresh state) fetches none of the committed heads.
7687        let mut moved = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
7688        moved.relays = vec!["wss://empty".into()];
7689        crate::db::community::save_community_v2(&moved).unwrap();
7690
7691        let err = refound_community(&relay, &moved, &[]).await.unwrap_err();
7692        assert!(err.contains("was not served"), "a withheld control head aborts the refounding: {err}");
7693        assert_eq!(
7694            crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
7695            Epoch(0),
7696            "the epoch did NOT advance (zero published state)"
7697        );
7698    }
7699
7700    #[tokio::test]
7701    async fn refounding_rolls_the_root_and_severs_a_removed_member() {
7702        // CORD-06 §3: the owner re-founds, removing a member. The base root rolls, the
7703        // epoch advances, and the removed member's rekey-follow concludes they're cut.
7704        let (bed, owner, member) = TestBed::new();
7705        bed.swap_to(&owner);
7706        let community = create_community(&bed.relay, "Refound", bed.relays.clone(), None).await.unwrap();
7707        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7708        let bundle_json = serde_json::to_string(&bundle).unwrap();
7709        bed.swap_to(&member);
7710        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7711
7712        bed.swap_to(&owner);
7713        let refounded = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
7714        assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
7715        assert_ne!(refounded.community_root, community.community_root, "the base root rolled");
7716        // The owner still reads the compacted control plane at the new epoch.
7717        assert_eq!(
7718            crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
7719            Epoch(1),
7720            "the owner committed the new epoch"
7721        );
7722
7723        // The removed member, following rekeys, is severed (no blob in the rotation).
7724        // Guard captured AFTER the swap: it must belong to the ACTING account (the harness
7725        // swap now bumps the generation exactly like a production swap_session).
7726        bed.swap_to(&member);
7727        let session = SessionGuard::capture();
7728        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
7729        assert!(follow.self_removed, "the removed member is cut by the re-founding");
7730    }
7731
7732    #[tokio::test]
7733    async fn a_ban_holding_admin_can_re_found_but_not_evict_a_superior() {
7734        // CORD-06 §Authority: a Refounding requires BAN, not owner-identity. A
7735        // non-owner admin granted BAN CAN re-found (and every member follows it —
7736        // see the receive-side test), but the "strictly outrank every removed
7737        // target" rule still holds: they can't use it to evict the owner.
7738        let (bed, owner, member) = TestBed::new();
7739        bed.swap_to(&owner);
7740        let community = create_community(&bed.relay, "Guarded", bed.relays.clone(), None).await.unwrap();
7741        let rid = "b0".repeat(32);
7742        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7743        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
7744        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7745        let bundle_json = serde_json::to_string(&bundle).unwrap();
7746        bed.swap_to(&member);
7747        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7748        // Fold the roster so this member's own DB reflects their BAN grant (the
7749        // authority check reads the folded Roster, not the bundle).
7750        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7751        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7752        // Can't evict the owner (no one outranks the owner).
7753        assert!(refound_community(&bed.relay, &joined, &[owner.keys.public_key()]).await.is_err(), "a BAN-holder can't re-found to evict the owner");
7754        // But CAN re-found removing a plain member they outrank (here, nobody).
7755        assert!(refound_community(&bed.relay, &joined, &[]).await.is_ok(), "a BAN-holding admin can re-found");
7756    }
7757
7758    #[tokio::test]
7759    async fn follow_rekeys_adopts_an_authorized_non_owner_base_rotation() {
7760        // A BAN-holding ADMIN (not the owner) re-founds, and every member must
7761        // follow it — owner-only receive silently strands members whose community
7762        // was refounded by an admin (CORD-06 §Authority: "a Refounding requires
7763        // BAN", checked against the folded Roster).
7764        let (bed, owner, me) = TestBed::new();
7765        let admin = Keys::generate();
7766        bed.swap_to(&owner);
7767        let community = create_community(&bed.relay, "AdminRefound", bed.relays.clone(), None).await.unwrap();
7768        let rid = "b0".repeat(32);
7769        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7770        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
7771
7772        // I (a plain member) join, then fold the roster so I know the admin holds BAN.
7773        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7774        let bundle_json = serde_json::to_string(&bundle).unwrap();
7775        bed.swap_to(&me);
7776        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7777        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7778        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7779
7780        // The admin re-founds keeping the owner + me — the owner must always be a
7781        // recipient of a non-owner Refounding.
7782        let new_root = [0xC7; 32];
7783        publish_base_rotation(&bed.relay, &joined, &admin, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
7784
7785        let updated = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap().updated
7786            .expect("an authorized admin's Refounding is adopted");
7787        assert_eq!(updated.root_epoch, Epoch(1), "advanced past the admin's rotation");
7788        assert_eq!(updated.community_root, new_root, "adopted the admin's fresh root");
7789    }
7790
7791    #[tokio::test]
7792    async fn adopting_someone_elses_rotation_refreshes_my_own_live_links() {
7793        // CORD-05 §2: a link shared once keeps working across rotations, because
7794        // its bundle is re-posted behind the same URL. The Refounder can only
7795        // refresh the bundles they hold signer secrets for — their OWN — so
7796        // every other creator has to heal their links when they ADOPT the
7797        // rotation. Without that, an admin's links keep vending the superseded
7798        // root and drop new joiners onto a dead epoch, which is precisely the
7799        // stranding the stable-URL refresh exists to prevent.
7800        let (bed, owner, me) = TestBed::new();
7801        bed.swap_to(&owner);
7802        let community = create_community(&bed.relay, "LinkHeal", bed.relays.clone(), None).await.unwrap();
7803        let rid = "b1".repeat(32);
7804        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7805        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
7806
7807        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7808        let bundle_json = serde_json::to_string(&bundle).unwrap();
7809        bed.swap_to(&me);
7810        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7811        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7812        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7813
7814        // I mint a link of my own at the CURRENT epoch.
7815        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
7816        let vended_before = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
7817        assert_eq!(vended_before.root_epoch, 0, "my link vends the epoch I minted it at");
7818
7819        // The OWNER re-founds. Their refresh can't touch my bundle: only I hold
7820        // its signer secret.
7821        let new_root = [0xD4; 32];
7822        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
7823
7824        let updated = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap().updated
7825            .expect("the owner's Refounding is adopted");
7826        assert_eq!(updated.root_epoch, Epoch(1), "I advanced to the new epoch");
7827
7828        let vended_after = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
7829        assert_eq!(vended_after.root_epoch, 1, "my link must now vend the NEW epoch, not strand its joiners");
7830        assert_eq!(
7831            crate::simd::hex::hex_to_bytes_32(&vended_after.community_root),
7832            new_root,
7833            "and the new root behind the same URL",
7834        );
7835    }
7836
7837    #[tokio::test]
7838    async fn follow_rekeys_refuses_a_refounding_that_excludes_the_owner() {
7839        // Authority escalation: a BAN-admin can't use a Refounding to evict the
7840        // OWNER (no one outranks the owner). Excluding them makes the rotation
7841        // inadmissible — members fork-reject it rather than migrate to the coup.
7842        let (bed, owner, me) = TestBed::new();
7843        let admin = Keys::generate();
7844        bed.swap_to(&owner);
7845        let community = create_community(&bed.relay, "NoCoup", bed.relays.clone(), None).await.unwrap();
7846        let rid = "b0".repeat(32);
7847        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7848        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
7849
7850        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7851        let bundle_json = serde_json::to_string(&bundle).unwrap();
7852        bed.swap_to(&me);
7853        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7854        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7855        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7856
7857        // The admin re-founds delivering to me but NOT the owner — a takeover.
7858        publish_base_rotation(&bed.relay, &joined, &admin, &[me.keys.public_key()], &[0xEE; 32], &joined.community_root).await;
7859        let follow = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap();
7860        assert!(follow.updated.is_none() && !follow.self_removed, "an owner-excluding Refounding is not adopted");
7861    }
7862
7863    #[tokio::test]
7864    async fn follow_rekeys_refuses_a_refounding_that_excludes_a_peer_admin() {
7865        // Authority escalation: two equal-rank BAN-admins — neither strictly
7866        // outranks the other, so one can't Refound the other out. Excluding a
7867        // peer makes the rotation inadmissible.
7868        let (bed, owner, me) = TestBed::new();
7869        let admin_a = Keys::generate();
7870        let admin_b = Keys::generate(); // the peer admin the rotation excludes.
7871        bed.swap_to(&owner);
7872        let community = create_community(&bed.relay, "Peers", bed.relays.clone(), None).await.unwrap();
7873        let rid = "b0".repeat(32);
7874        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
7875        // Both A and B hold the SAME role (same position 1) → peers.
7876        publish_grant(&bed.relay, &community, &owner.keys, &admin_a.public_key(), vec![rid.clone()], 1).await;
7877        publish_grant(&bed.relay, &community, &owner.keys, &admin_b.public_key(), vec![rid], 1).await;
7878
7879        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7880        let bundle_json = serde_json::to_string(&bundle).unwrap();
7881        bed.swap_to(&me);
7882        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7883        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7884        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7885
7886        // Admin A re-founds keeping the owner + me but EXCLUDING peer admin B.
7887        publish_base_rotation(&bed.relay, &joined, &admin_a, &[owner.keys.public_key(), me.keys.public_key()], &[0xDD; 32], &joined.community_root).await;
7888
7889        let follow = follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap();
7890        assert!(follow.updated.is_none() && !follow.self_removed, "excluding an equal-rank peer admin is inadmissible");
7891    }
7892
7893    #[tokio::test]
7894    async fn a_retried_refounding_reuses_the_same_root() {
7895        // B1 idempotency: minting for the same (scope, epoch) twice yields the SAME
7896        // root, so a retried Refounding re-delivers one root — never a double-mint fork.
7897        let (_tmp, _guard, _owner) = init_test_db();
7898        let relay = MemoryRelay::new();
7899        let community = create_community(&relay, "Retry", vec!["wss://r".into()], None).await.unwrap();
7900        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
7901        let first = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
7902        let second = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
7903        assert_eq!(first, second, "a retry reuses the archived root, never double-mints");
7904    }
7905
7906    #[tokio::test]
7907    async fn a_mid_rank_admin_cannot_demote_a_role_that_outranks_them() {
7908        // CORD-04 §2 rank inversion. Minting at a position you outrank is
7909        // necessary but NOT sufficient: an edition replaces the entity, so a
7910        // gate that only reads the NEW position lets an admin at position 5
7911        // rewrite the position-1 role to position 9. Every check passes (9 is
7912        // beneath them), and the role that outranked them — plus everyone
7913        // holding it — is now beneath them.
7914        let (bed, owner, attacker) = TestBed::new();
7915        bed.swap_to(&owner);
7916        let community = create_community(&bed.relay, "Ranks", bed.relays.clone(), None).await.unwrap();
7917
7918        // A senior role at position 1, and a mid role at position 5 the attacker holds.
7919        let senior = "a1".repeat(32);
7920        let mid = "a5".repeat(32);
7921        publish_role(&bed.relay, &community, &owner.keys,
7922            &Role { role_id: senior.clone(), name: "Senior".into(), position: 1, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0 }, 1).await;
7923        publish_role(&bed.relay, &community, &owner.keys,
7924            &Role { role_id: mid.clone(), name: "Mid".into(), position: 5, permissions: Permissions(Permissions::MANAGE_ROLES), scope: RoleScope::Server, color: 0 }, 1).await;
7925        publish_grant(&bed.relay, &community, &owner.keys, &attacker.keys.public_key(), vec![mid.clone()], 1).await;
7926
7927        // The attacker republishes the SENIOR role, dropping it beneath themselves.
7928        publish_role(&bed.relay, &community, &attacker.keys,
7929            &Role { role_id: senior.clone(), name: "Senior".into(), position: 9, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0 }, 2).await;
7930
7931        let authority = fetch_authority(&bed.relay, &community).await;
7932        let folded_senior = authority.roles.role(&senior).expect("the senior role survives the fold");
7933        assert_eq!(
7934            folded_senior.position, 1,
7935            "a role may only be repositioned by someone who outranks where it STOOD, not just where it lands",
7936        );
7937    }
7938
7939    #[tokio::test]
7940    async fn a_non_owner_admins_edition_cites_its_grant_and_the_owners_does_not() {
7941        // CORD-04 §5. Armada's reader REQUIRES this on every non-owner control
7942        // edition (`citationOk`: "a non-owner action MUST cite its grant"), so
7943        // an uncited Vector admin's ban/role/channel edit was silently dropped
7944        // by every Armada client — only the owner's actions crossed. The
7945        // citation must name the actor's OWN grant coordinate, at the version
7946        // and edition hash the verifier can match against a grant it holds.
7947        let (bed, owner, admin) = TestBed::new();
7948        bed.swap_to(&owner);
7949        let community = create_community(&bed.relay, "Cited", bed.relays.clone(), None).await.unwrap();
7950        let rid = "c1".repeat(32);
7951        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::MANAGE_METADATA), 1).await;
7952        publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;
7953
7954        // The owner's own edition carries NO citation: their rank is the id.
7955        let owner_meta = control::CommunityMetadata { name: "By Owner".into(), relays: community.relays.clone(), ..Default::default() };
7956        edit_community_metadata(&bed.relay, &community, &owner_meta).await.unwrap();
7957        let owner_ed = fetch_control(&bed.relay, &community).await.into_iter()
7958            .filter(|e| e.author == owner.keys.public_key() && e.vsk == vsk::COMMUNITY_METADATA)
7959            .max_by_key(|e| e.version).expect("the owner's metadata edition");
7960        assert!(owner_ed.authority.is_none(), "the owner cites nothing — rank comes from the community id");
7961
7962        // The admin JOINS and folds — the citation names the grant head their own
7963        // client has actually synced, so the fold must have persisted it.
7964        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
7965        let bundle_json = serde_json::to_string(&bundle).unwrap();
7966        bed.swap_to(&admin);
7967        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
7968        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
7969        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
7970        set_banlist(&bed.relay, &joined, &["ee".repeat(32)]).await.unwrap();
7971
7972        let ban_ed = fetch_control(&bed.relay, &joined).await.into_iter()
7973            .find(|e| e.author == admin.keys.public_key() && e.vsk == vsk::BANLIST)
7974            .expect("the admin's banlist edition");
7975        let cite = ban_ed.authority.as_ref().expect("a non-owner MUST cite its grant");
7976        assert_eq!(
7977            cite.entity_id,
7978            crate::community::v2::derive::grant_locator(community.id(), &admin.keys.public_key().to_bytes()),
7979            "the citation must name the ACTOR'S OWN grant coordinate",
7980        );
7981        assert!(cite.version >= 1, "pinned to a real grant version");
7982    }
7983
7984    #[tokio::test]
7985    async fn a_folded_metadata_edition_cannot_push_the_relay_set_past_the_cap() {
7986        // `cap_relays` is the truncate-on-read invariant everywhere else, and the
7987        // fold is a boundary like any other: MANAGE_METADATA makes an editor
7988        // authorized, not trusted. An oversize list costs every member a fan-out
7989        // per publish and the slowest of N per fetch — and Armada caps at 5, so
7990        // an uncapped fold also splits the two clients' operative sets.
7991        let (_tmp, _guard, _owner) = init_test_db();
7992        let relay = MemoryRelay::new();
7993        let community = create_community(&relay, "Fanout", vec!["wss://a".into()], None).await.unwrap();
7994
7995        let many: Vec<String> = (0..30).map(|i| format!("wss://r{i}")).collect();
7996        let meta = control::CommunityMetadata { name: "Fanout".into(), relays: many, ..Default::default() };
7997        edit_community_metadata(&relay, &community, &meta).await.unwrap();
7998
7999        let updated = follow_control(&relay, &community, &SessionGuard::capture()).await.unwrap()
8000            .expect("the metadata edition is folded");
8001        assert_eq!(
8002            updated.relays.len(),
8003            crate::community::MAX_COMMUNITY_RELAYS,
8004            "a folded relay list must be truncated, never adopted whole",
8005        );
8006
8007        // …and the fold must SETTLE: comparing an oversize edition against the
8008        // capped working set would never be equal, so every later fold would
8009        // report a change and re-save forever.
8010        let again = follow_control(&relay, &updated, &SessionGuard::capture()).await.unwrap();
8011        assert!(again.is_none(), "re-folding the same oversize edition must be a no-op");
8012    }
8013
8014    #[tokio::test]
8015    async fn adopting_a_rotation_writes_no_registry_where_i_never_minted() {
8016        // One Invite List spans every community, so "I hold links" must never be
8017        // read as "I hold links HERE". A member with links elsewhere adopting a
8018        // rotation would otherwise publish an empty Registry edition into this
8019        // community — a control-plane write and a version bump on a coordinate
8020        // they never owned, every rotation, forever.
8021        let (bed, owner, me) = TestBed::new();
8022        bed.swap_to(&owner);
8023        let host = create_community(&bed.relay, "Host", bed.relays.clone(), None).await.unwrap();
8024        let elsewhere = create_community(&bed.relay, "Elsewhere", bed.relays.clone(), None).await.unwrap();
8025        let rid = "b2".repeat(32);
8026        publish_role(&bed.relay, &host, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
8027        publish_grant(&bed.relay, &host, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
8028
8029        let bundle = bundle_of(&host, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
8030        let bundle_json = serde_json::to_string(&bundle).unwrap();
8031        bed.swap_to(&me);
8032        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8033        let _ = follow_control(&bed.relay, &joined, &SessionGuard::capture()).await;
8034        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
8035
8036        // My only link lives in a DIFFERENT community.
8037        mint_public_link(&bed.relay, &elsewhere, "https://other", None, None).await.unwrap();
8038
8039        let before = bed.relay.stored_count();
8040        let new_root = [0xE1; 32];
8041        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
8042        let rotation_events = bed.relay.stored_count() - before;
8043
8044        let after_adopt = bed.relay.stored_count();
8045        follow_rekeys(&bed.relay, &joined, &SessionGuard::capture()).await.unwrap();
8046        assert_eq!(
8047            bed.relay.stored_count(),
8048            after_adopt,
8049            "adopting a rotation must publish NOTHING when I minted no links here",
8050        );
8051        assert!(rotation_events > 0, "the rotation itself did publish (guards the counter)");
8052    }
8053
8054    #[tokio::test]
8055    async fn an_expired_link_stops_keeping_the_community_public() {
8056        // CORD-05 §1/§5: expiry is the one way a link dies with no user action.
8057        // A joiner is refused by `InviteBundle::expired`, so leaving the link in
8058        // the Registry states a door that isn't there — the aggregate never
8059        // empties and the community reads Public forever, silently inverting
8060        // every gate that hangs off that reading.
8061        let (_tmp, _guard, _owner) = init_test_db();
8062        let relay = MemoryRelay::new();
8063        let community = create_community(&relay, "Lapsing", vec!["wss://r".into()], None).await.unwrap();
8064
8065        // A link that lapsed a minute ago.
8066        let past = now_ms() - 60_000;
8067        mint_public_link(&relay, &community, "https://x", Some(past), None).await.unwrap();
8068        assert!(
8069            !community_is_public(&relay, &community).await,
8070            "an already-expired link must never read as a live door",
8071        );
8072
8073        // …and one that hasn't, to prove the filter isn't just dropping everything.
8074        mint_public_link(&relay, &community, "https://y", Some(now_ms() + 600_000), None).await.unwrap();
8075        assert!(community_is_public(&relay, &community).await, "an unexpired link is still live");
8076    }
8077
8078    #[tokio::test]
8079    async fn minting_a_link_makes_the_community_public_and_revoke_makes_it_private() {
8080        // CORD-05 §5: the Registry is the Public/Private source of truth. Minting a
8081        // link publishes it (Public); retiring the last link empties it (Private).
8082        let (_tmp, _guard, _owner) = init_test_db();
8083        let relay = MemoryRelay::new();
8084        let community = create_community(&relay, "Invitable", vec!["wss://r".into()], None).await.unwrap();
8085        assert!(!community_is_public(&relay, &community).await, "a fresh community is Private");
8086
8087        let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
8088        assert!(community_is_public(&relay, &community).await, "a live link makes it Public");
8089        let list = fetch_invite_list(&relay, &community.relays).await.unwrap().expect("the 13303 list was published");
8090        assert_eq!(list.entries.len(), 1, "the minted link is recorded across devices");
8091
8092        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
8093        revoke_public_link(&relay, &community, &token_hex).await.unwrap();
8094        assert!(!community_is_public(&relay, &community).await, "retiring the last link makes it Private again");
8095        let after = fetch_invite_list(&relay, &community.relays).await.unwrap().unwrap();
8096        assert!(after.entries.is_empty() && after.tombstones.len() == 1, "the link is tombstoned in the invite list");
8097    }
8098
8099    #[tokio::test]
8100    async fn the_registry_is_cached_locally_so_public_private_is_a_sync_read() {
8101        // Every caller reads the `invite_registry` COLUMN, never the async fold. v2
8102        // published the Registry to the plane but never mirrored it locally, so every
8103        // v2 community read Private no matter how many live links it had.
8104        let (_tmp, _guard, _owner) = init_test_db();
8105        let relay = MemoryRelay::new();
8106        let community = create_community(&relay, "Cached", vec!["wss://r".into()], None).await.unwrap();
8107        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
8108        let cached = || crate::db::community::get_community_invite_registry(&cid_hex).unwrap();
8109        // The per-creator split is a SEPARATE table, and it drives the "first link flips
8110        // the community Public" confirm — an empty one re-asks on every later link.
8111        let per_creator = || crate::db::community::get_invite_link_sets(&cid_hex).unwrap();
8112        assert!(cached().is_empty(), "a fresh community caches an empty registry");
8113        assert!(per_creator().is_empty(), "…and no per-creator sets");
8114
8115        let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
8116        assert!(!cached().is_empty(), "minting caches the registry, so the UI reads Public without folding");
8117        let sets = per_creator();
8118        assert_eq!(sets.len(), 1, "the minting creator gets a set");
8119        assert_eq!(sets[0].locators.len(), 1, "carrying exactly their one live link");
8120
8121        // Both caches must SHRINK too — a union-only mirror would strand it Public.
8122        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
8123        revoke_public_link(&relay, &community, &token_hex).await.unwrap();
8124        assert!(cached().is_empty(), "retiring the last link empties the cache back to Private");
8125        assert!(per_creator().is_empty(), "…and clears the per-creator sets");
8126    }
8127
8128    #[tokio::test]
8129    async fn a_rogue_registry_fork_cannot_retire_the_owners_live_link() {
8130        // Registries are coordinate-bound to their creator, but `fold_head` picks an
8131        // equal-version winner AUTHOR-BLIND, by lowest inner id — and an author grinds
8132        // that freely by varying content. Folding before authorising would let any
8133        // member occupy the owner's registry head, fail the authority check, and drop
8134        // the whole registry: a live invite link silently retired, flipping the
8135        // community to Private and steering a moderator into the wrong ban remedy.
8136        let (_tmp, _guard, owner) = init_test_db();
8137        let relay = MemoryRelay::new();
8138        let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
8139        mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
8140        assert!(community_is_public(&relay, &community).await, "a live link makes it Public");
8141
8142        let cid = community.id();
8143        let control = control_group_key(&community.community_root, cid, community.root_epoch);
8144        let eid = crate::community::v2::derive::invite_links_locator(cid, &owner.public_key().to_bytes());
8145
8146        let query = Query {
8147            kinds: vec![stream::KIND_WRAP],
8148            authors: vec![control.pk_hex()],
8149            limit: Some(FOLLOW_PAGE),
8150            ..Default::default()
8151        };
8152        let wraps = relay.fetch(&query, &community.relays).await.unwrap();
8153        let target = wraps
8154            .iter()
8155            .filter_map(|w| control::open_control_edition(w, &control).ok().map(|(e, _)| e))
8156            .filter(|e| e.entity_id == eid)
8157            .max_by_key(|e| e.version)
8158            .expect("the owner published a registry");
8159
8160        // Grind a same-version fork under the owner's coordinate that OUTRANKS the
8161        // real head on the tiebreak (~2 tries against a uniform id).
8162        let rogue = Keys::generate();
8163        let mut planted = false;
8164        for n in 0..4_000u64 {
8165            let content = format!("[{{\"token\":\"{n:032x}\",\"url\":\"https://evil\",\"expires_at\":0}}]");
8166            let rumor = control::build_edition_rumor(
8167                rogue.public_key(),
8168                vsk::INVITE_LINKS,
8169                &eid,
8170                target.version,
8171                target.prev_hash.as_ref(),
8172                &content,
8173                9_000,
8174                None,
8175            );
8176            let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
8177            let (ed, _) = control::open_control_edition(&w, &control).unwrap();
8178            if ed.inner_id < target.inner_id {
8179                relay.publish(&w, &community.relays).await.unwrap();
8180                planted = true;
8181                break;
8182            }
8183        }
8184        assert!(planted, "the test needs a fork that wins the tiebreak");
8185
8186        assert!(
8187            community_is_public(&relay, &community).await,
8188            "an unauthorised fork must not retire the owner's live link"
8189        );
8190    }
8191
8192    #[tokio::test]
8193    async fn a_registry_from_a_non_create_invite_holder_does_not_make_it_public() {
8194        // The CREATE_INVITE gate: a rogue publishing a registry can't fake Public.
8195        let (_tmp, _guard, owner) = init_test_db();
8196        let relay = MemoryRelay::new();
8197        let community = create_community(&relay, "Gated", vec!["wss://r".into()], None).await.unwrap();
8198        let rogue = Keys::generate();
8199        // Rogue publishes a registry edition at THEIR coordinate with a fake signer.
8200        let eid = crate::community::v2::derive::invite_links_locator(community.id(), &rogue.public_key().to_bytes());
8201        let content = crate::community::v2::invite::build_registry_content(&[Keys::generate().public_key()]);
8202        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
8203        let rumor = control::build_edition_rumor(rogue.public_key(), vsk::INVITE_LINKS, &eid, 1, None, &content, 1_000, None);
8204        let (wrap, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(1_000)).unwrap();
8205        relay.publish(&wrap, &community.relays).await.unwrap();
8206        let _ = owner;
8207        assert!(!community_is_public(&relay, &community).await, "a non-CREATE_INVITE registry is ignored");
8208    }
8209
8210    #[tokio::test]
8211    async fn full_lifecycle_e2e() {
8212        // The whole stack end to end across two accounts: create -> Public link ->
8213        // owner grants an admin -> member joins + reads history -> admin edits metadata
8214        // (authorized fold) -> owner bans the member (CORD-04 §6: banlist + strip +
8215        // Refounding) -> the banned member is severed AND stays banned across the new
8216        // epoch -> pre-ban history still reads -> owner dissolves -> sealed.
8217        let (bed, owner, member) = TestBed::new();
8218
8219        bed.swap_to(&owner);
8220        let community = create_community(&bed.relay, "Lifecycle", bed.relays.clone(), None).await.unwrap();
8221        let general = community.channels[0].id;
8222        send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();
8223
8224        // Public link → the community reads Public.
8225        let _minted = mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
8226        assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");
8227
8228        // Owner defines + grants an Admin role (MANAGE_METADATA among the bits).
8229        let rid = "aa".repeat(32);
8230        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
8231        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
8232
8233        // Member joins from the bundle + reads the owner's message.
8234        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
8235        let bundle_json = serde_json::to_string(&bundle).unwrap();
8236        bed.swap_to(&member);
8237        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8238        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome"]);
8239        // The admin renames the community.
8240        publish_community_meta(&bed.relay, &joined, &member.keys, "Lifecycle Renamed", 2).await;
8241
8242        // Owner follows: the admin's rename folds (authorized).
8243        bed.swap_to(&owner);
8244        let session = SessionGuard::capture();
8245        let updated = follow_control(&bed.relay, &community, &session).await.unwrap().expect("the admin edit folds");
8246        assert_eq!(updated.name, "Lifecycle Renamed", "an authorized admin's metadata edit is honored");
8247
8248        // Ban the member (the three-removal composition, in order).
8249        set_banlist(&bed.relay, &updated, &[member.keys.public_key().to_hex()]).await.unwrap();
8250        grant_roles(&bed.relay, &updated, &member.keys.public_key(), vec![]).await.unwrap();
8251        let refounded = refound_community(&bed.relay, &updated, &[member.keys.public_key()]).await.unwrap();
8252        assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
8253        // The ban survives the Refounding (the banlist head compacted forward).
8254        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8255        assert!(post.banned.contains(&member.keys.public_key().to_hex()), "the ban survives the re-founding");
8256        // Pre-ban history still reads across the new epoch.
8257        assert!(
8258            texts_in(&bed.relay, &refounded, &general).await.contains(&"owner: welcome".to_string()),
8259            "pre-refounding history stays readable"
8260        );
8261
8262        // The banned member's rekey-follow concludes they're severed. Guard captured AFTER
8263        // the swap (the harness swap bumps the generation like production).
8264        bed.swap_to(&member);
8265        let session = SessionGuard::capture();
8266        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
8267        assert!(follow.self_removed, "the banned member is cryptographically cut");
8268
8269        // Owner dissolves → sealed.
8270        bed.swap_to(&owner);
8271        dissolve_community(&bed.relay, &refounded).await.unwrap();
8272        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
8273    }
8274
8275    /// The deep two-account e2e the way a real deployment runs: owner (A) + member (B)
8276    /// over one shared relay, create → channels (public + private) → converse both ways →
8277    /// persist (get_messages-level) → react/edit/delete → moderate (ban/unban) → dissolve.
8278    /// Every account, community, channel, and action is LOGGED (run with --nocapture) so it
8279    /// doubles as a reference transcript and a re-runnable regression.
8280    #[tokio::test]
8281    async fn a_forged_edition_cannot_suppress_a_role_across_a_refounding() {
8282        // A member forges a higher-version role edition at the admin coordinate before a
8283        // refounding. The compaction must carry the AUTHORIZED floor head, not the
8284        // author-blind version tip — else the forgery is re-anchored, honest folders drop
8285        // it, and the admin role vanishes at the new epoch (silent suppression).
8286        let (bed, owner, member) = TestBed::new();
8287        let attacker = Keys::generate();
8288        bed.swap_to(&owner);
8289        let community = create_community(&bed.relay, "NoSuppress", bed.relays.clone(), None).await.unwrap();
8290        let rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
8291        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
8292        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
8293        // Owner folds → the authorized role/grant heads are floored.
8294        let session = SessionGuard::capture();
8295        follow_control(&bed.relay, &community, &session).await.unwrap();
8296        assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member.keys.public_key().to_hex()), "member is admin pre-attack");
8297
8298        // The attacker (a non-owner) forges v2 of the admin role, chaining onto v1.
8299        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;
8300
8301        // Owner refounds (keeping everyone).
8302        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
8303        assert_eq!(refounded.root_epoch, Epoch(1), "root rolled");
8304
8305        // Post-refound, the admin role SURVIVES (the authorized floor head was carried).
8306        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8307        assert!(post.roles.is_admin(&member.keys.public_key().to_hex()), "the admin role survives the refounding despite the forgery");
8308    }
8309
8310    #[tokio::test]
8311    async fn memberlist_survives_a_refounding_via_the_snapshot() {
8312        // A silent survivor (didn't re-post at the new epoch) must stay in the memberlist
8313        // after a refounding — the owner's 3312 snapshot re-seeds them (CORD-02 §5).
8314        let (bed, owner, member) = TestBed::new();
8315        bed.swap_to(&owner);
8316        let community = create_community(&bed.relay, "Snapshot", bed.relays.clone(), None).await.unwrap();
8317
8318        // Member joins (a Guestbook Join at epoch 0).
8319        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
8320        bed.swap_to(&member);
8321        accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
8322        bed.swap_to(&owner);
8323        assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "member present pre-refound");
8324
8325        // Owner refounds keeping everyone (removed = []); survivors are snapshotted to epoch 1.
8326        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
8327        assert_eq!(refounded.root_epoch, Epoch(1), "the root rolled");
8328
8329        // The member is STILL a member at epoch 1 purely via the snapshot (never re-posted).
8330        let members = memberlist(&bed.relay, &refounded).await.unwrap();
8331        assert!(members.contains(&member.keys.public_key()), "a silent survivor stays a member after the refounding");
8332        assert!(members.contains(&owner.keys.public_key()), "owner is always a member");
8333    }
8334
8335    #[tokio::test]
8336    async fn e2e_two_accounts_channels_converse_moderate() {
8337        use crate::community::v2::inbound::{apply_chat_to_state, persist_chat};
8338        use nostr_sdk::prelude::ToBech32;
8339        let (bed, a, b) = TestBed::new();
8340        let (a_npub, b_npub) = (a.keys.public_key().to_bech32().unwrap(), b.keys.public_key().to_bech32().unwrap());
8341        let (a_hex, b_hex) = (a.keys.public_key().to_hex(), b.keys.public_key().to_hex());
8342        println!("\n===== Concord v2 deep e2e =====");
8343        println!("[acct] A (owner)  = {a_npub}");
8344        println!("[acct] B (member) = {b_npub}");
8345
8346        // ── A creates the community + a PRIVATE channel + two extra PUBLIC channels ──
8347        bed.swap_to(&a);
8348        let mut community = create_community(&bed.relay, "Deep E2E", bed.relays.clone(), None).await.unwrap();
8349        let general = community.channels[0].id;
8350        println!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
8351
8352        // A PRIVATE channel via the REAL create path: an independent key minted at
8353        // channel-epoch 1, delivered over the rekey plane (A is the only member yet),
8354        // then announced (vsk 2) — later carried to B in the join bundle.
8355        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
8356        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8357        let priv_ch = community.channel(&priv_id).unwrap();
8358        assert!(priv_ch.private && priv_ch.key.is_some() && priv_ch.epoch == Epoch(1), "born-private: keyed at epoch 1");
8359        println!("[channel] +private #mods {} (native create: key over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&priv_id.0));
8360
8361        // Two more PUBLIC channels via the real create path.
8362        let announcements = create_public_channel(&bed.relay, &community, "announcements").await.unwrap();
8363        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8364        let random = create_public_channel(&bed.relay, &community, "random").await.unwrap();
8365        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8366        println!("[channel] +public #announcements {} · #random {}", crate::simd::hex::bytes_to_hex_32(&announcements.0), crate::simd::hex::bytes_to_hex_32(&random.0));
8367        assert_eq!(community.channels.len(), 4, "general + mods + announcements + random");
8368
8369        // A talks in a few channels.
8370        let m1 = send_message(&bed.relay, &community, &general, "A: welcome to the deep e2e").await.unwrap();
8371        send_message(&bed.relay, &community, &announcements, "A: read the rules").await.unwrap();
8372        send_message(&bed.relay, &community, &priv_id, "A: mods-only channel").await.unwrap();
8373        println!("[msg] A posted in #general / #announcements / #mods");
8374
8375        // ── A grants B admin, mints a public link, B joins from the bundle ──
8376        let admin_rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
8377        publish_role(&bed.relay, &community, &a.keys, &admin_role(&admin_rid, Permissions::ADMIN_ALL), 1).await;
8378        publish_grant(&bed.relay, &community, &a.keys, &b.keys.public_key(), vec![admin_rid], 1).await;
8379        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
8380        assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");
8381        println!("[invite] granted B @admin · minted link {}", link.url);
8382
8383        // A private channel is readable only by granted role-holders (CORD-03), so
8384        // B is added to its access list before the bundle is minted.
8385        grant_channel_access(&bed.relay, &community, &priv_id, &b.keys.public_key()).await.unwrap();
8386        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(b.keys.public_key()), Some(a.keys.public_key()), None, None)).unwrap();
8387        bed.swap_to(&b);
8388        let mut b_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8389        println!("[join] B joined; sees {} channels", b_view.channels.len());
8390        assert_eq!(b_view.channels.len(), 4, "B receives all four channels (incl. the private one's key) in the bundle");
8391        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");
8392        assert!(texts_in(&bed.relay, &b_view, &general).await.contains(&"A: welcome to the deep e2e".to_string()), "B reads A's #general history");
8393        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");
8394        // B folds the control plane (persisting the roster) — the live worker does
8395        // this right after any join; B's admin standing gates B's channel ops below.
8396        let session_b = SessionGuard::capture();
8397        if let Some(fresh) = follow_control(&bed.relay, &b_view, &session_b).await.unwrap() {
8398            b_view = fresh;
8399        }
8400        println!("[follow] B folded control (roster persisted: B is @admin)");
8401
8402        // ── Conversation both ways + persistence (get_messages-level) ──
8403        send_message(&bed.relay, &b_view, &general, "B: thanks, glad to be here").await.unwrap();
8404        send_message(&bed.relay, &b_view, &priv_id, "B: mods checking in").await.unwrap();
8405        println!("[msg] B replied in #general + #mods");
8406        // Persist B's own #general view into the shared store (what sync/live ingest does)
8407        // and confirm it reads back via STATE — get_messages parity.
8408        let my_pk = b.keys.public_key();
8409        let gh = crate::simd::hex::bytes_to_hex_32(&general.0);
8410        for f in fetch_channel(&bed.relay, &b_view, &general, 100).await.unwrap() {
8411            let outcome = { let mut st = crate::state::STATE.lock().await; apply_chat_to_state(&mut st, &f.event, &gh, &my_pk) };
8412            if let Some(o) = outcome { persist_chat(&gh, &o).await; }
8413        }
8414        assert!(crate::db::events::event_exists(&m1).unwrap(), "A's message persisted into B's shared store (get_messages backfill)");
8415        println!("[persist] #general history persisted into the shared events store");
8416
8417        // B (admin) reacts to + the author edits/deletes — the chat-op surface.
8418        send_reaction(&bed.relay, &b_view, &general, &m1, &a_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
8419        bed.swap_to(&a);
8420        let m_edit = send_message(&bed.relay, &community, &general, "A: this will be edited").await.unwrap();
8421        send_edit(&bed.relay, &community, &general, &m_edit, "A: edited!").await.unwrap();
8422        let m_del = send_message(&bed.relay, &community, &general, "A: this will be deleted").await.unwrap();
8423        send_delete(&bed.relay, &community, &general, &m_del, super::super::kind::MESSAGE).await.unwrap();
8424        println!("[ops] reaction + edit + delete round-tripped");
8425
8426        // ── B creates a channel as admin, A folds it in ──
8427        bed.swap_to(&b);
8428        let bugs = create_public_channel(&bed.relay, &b_view, "bug-reports").await.unwrap();
8429        println!("[channel] B(admin) +public #bug-reports {}", crate::simd::hex::bytes_to_hex_32(&bugs.0));
8430        bed.swap_to(&a);
8431        let session = SessionGuard::capture();
8432        if let Some(updated) = follow_control(&bed.relay, &community, &session).await.unwrap() {
8433            community = updated;
8434        }
8435        assert!(community.channels.iter().any(|c| c.id.0 == bugs.0), "A folds in B's authorized new channel");
8436        println!("[follow] A folded in B's #bug-reports (now {} channels)", community.channels.len());
8437
8438        // ── A creates a SECOND private channel while B is already a member. B is
8439        // NOT on its access list, so B learns the channel exists (control-follow,
8440        // keyless) and gets no key: CORD-03's private channel is readable only by
8441        // granted role-holders, never by every member. B keys up if and when A
8442        // grants them the channel's access role and vends the key ──
8443        let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
8444        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8445        send_message(&bed.relay, &community, &vault, "A: vault is open").await.unwrap();
8446        println!("[channel] +private #vault {} (B is unentitled — no delivery)", crate::simd::hex::bytes_to_hex_32(&vault.0));
8447        bed.swap_to(&b);
8448        let session_b2 = SessionGuard::capture();
8449        if let Some(fresh) = follow_control(&bed.relay, &b_view, &session_b2).await.unwrap() {
8450            b_view = fresh;
8451        }
8452        let ch = b_view.channel(&vault).expect("B recorded the announced private channel");
8453        assert!(ch.private && ch.key.is_none() && ch.epoch == Epoch(0), "B's record is keyless at cursor 0");
8454        let rf = follow_rekeys(&bed.relay, &b_view, &session_b2).await.unwrap();
8455        if let Some(fresh) = rf.updated {
8456            b_view = fresh;
8457        }
8458        let ch = b_view.channel(&vault).expect("still recorded");
8459        assert!(ch.key.is_none(), "an unentitled member is never delivered the key");
8460        assert!(
8461            texts_in(&bed.relay, &b_view, &vault).await.is_empty(),
8462            "and reads nothing from it"
8463        );
8464        assert!(
8465            send_message(&bed.relay, &b_view, &vault, "B: in the vault").await.is_err(),
8466            "an unentitled member cannot post into the channel either"
8467        );
8468        bed.swap_to(&a);
8469        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8470        println!("[private] #vault stayed sealed to the unentitled B (no key, no read, no send)");
8471
8472        // ── Members ──
8473        let members = memberlist(&bed.relay, &community).await.unwrap();
8474        let member_hexes: std::collections::BTreeSet<String> = members.iter().map(|m| m.to_hex()).collect();
8475        assert!(member_hexes.contains(&a_hex) && member_hexes.contains(&b_hex), "A + B both in the memberlist");
8476        println!("[members] {} members: A + B present", members.len());
8477
8478        // ── Moderate: ban B (banlist + strip + refound), verify severance + survival ──
8479        set_banlist(&bed.relay, &community, &[b_hex.clone()]).await.unwrap();
8480        grant_roles(&bed.relay, &community, &b.keys.public_key(), vec![]).await.unwrap();
8481        let refounded = refound_community(&bed.relay, &community, &[b.keys.public_key()]).await.unwrap();
8482        assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
8483        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8484        assert!(post.banned.contains(&b_hex), "the ban survives the refounding");
8485        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");
8486        assert!(
8487            texts_in(&bed.relay, &refounded, &priv_id).await.iter().any(|t| t == "A: mods-only channel"),
8488            "PRIVATE history reads across the channel's own rotation (per-channel multi-epoch archive)"
8489        );
8490        println!("[ban] B banned; root rolled to epoch 1; ban survives; pre-ban history intact (public + private)");
8491        // B concludes it's severed.
8492        bed.swap_to(&b);
8493        let session_b3 = SessionGuard::capture();
8494        assert!(follow_rekeys(&bed.relay, &b_view, &session_b3).await.unwrap().self_removed, "B is cryptographically cut by the ban-refound");
8495        println!("[ban] B's rekey-follow: self_removed = true (severed)");
8496
8497        // ── Unban: A lifts the ban ──
8498        bed.swap_to(&a);
8499        set_banlist(&bed.relay, &refounded, &[]).await.unwrap();
8500        let after_unban = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
8501        assert!(!after_unban.banned.contains(&b_hex), "the unban clears B from the banlist");
8502        println!("[unban] B removed from the banlist (re-invitable)");
8503
8504        // ── Dissolve ──
8505        dissolve_community(&bed.relay, &refounded).await.unwrap();
8506        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
8507        println!("[dissolve] community sealed (read-only)\n===== e2e PASS =====\n");
8508    }
8509
8510    /// The same scenario on a REAL relay with TWO throwaway accounts, off by default. It
8511    /// LOGS both nsecs (+ every id) so you can inspect the run and RE-RUN against the same
8512    /// accounts by exporting `VECTOR_E2E_NSEC_A` / `_B`. Set `VECTOR_E2E_LOG=<path>` to also
8513    /// append the transcript to a file, `VECTOR_E2E_RELAY=<url>` to pick the relay.
8514    ///   cargo test -p vector-core -- --ignored --nocapture live_e2e_two_accounts
8515    #[tokio::test]
8516    #[ignore]
8517    async fn live_e2e_two_accounts() {
8518        use crate::community::transport::LiveTransport;
8519        use nostr_sdk::prelude::ToBech32;
8520
8521        let relay = std::env::var("VECTOR_E2E_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
8522        let relays = vec![relay.clone()];
8523        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
8524        crate::db::close_database();
8525        crate::db::clear_id_caches();
8526        let tmp = tempfile::tempdir().unwrap();
8527        crate::db::set_app_data_dir(tmp.path().to_path_buf());
8528
8529        // Throwaway (or bring-your-own via env for a re-run against the same accounts).
8530        let a = std::env::var("VECTOR_E2E_NSEC_A").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);
8531        let b = std::env::var("VECTOR_E2E_NSEC_B").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);
8532
8533        let log = |line: String| {
8534            println!("{line}");
8535            if let Ok(p) = std::env::var("VECTOR_E2E_LOG") {
8536                use std::io::Write;
8537                if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {
8538                    let _ = writeln!(f, "{line}");
8539                }
8540            }
8541        };
8542        log(format!("===== LIVE Concord v2 e2e on {relay} ====="));
8543        log(format!("VECTOR_E2E_NSEC_A={}  ({})", a.secret_key().to_bech32().unwrap(), a.public_key().to_bech32().unwrap()));
8544        log(format!("VECTOR_E2E_NSEC_B={}  ({})", b.secret_key().to_bech32().unwrap(), b.public_key().to_bech32().unwrap()));
8545
8546        for k in [&a, &b] {
8547            let npub = k.public_key().to_bech32().unwrap();
8548            std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
8549            crate::db::set_current_account(npub.clone()).unwrap();
8550            crate::db::init_database(&npub).unwrap();
8551        }
8552        // One relay connection: a v2 wrap is pre-signed (ephemeral p-key) and its seal is
8553        // signed by MY_SECRET_KEY, so publishing needs no per-account client signer.
8554        let client = crate::nostr_client_builder().build();
8555        client.add_managed_relay(relay.as_str()).await.ok();
8556        client.connect().await;
8557        crate::state::set_nostr_client(client);
8558        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
8559        let become_acct = |k: &Keys| {
8560            let npub = k.public_key().to_bech32().unwrap();
8561            crate::db::set_current_account(npub.clone()).unwrap();
8562            crate::db::init_database(&npub).unwrap();
8563            crate::db::clear_id_caches();
8564            crate::state::MY_SECRET_KEY.store_from_keys(k, &[]);
8565            crate::state::set_my_public_key(k.public_key());
8566        };
8567        let settle = || tokio::time::sleep(std::time::Duration::from_secs(2));
8568
8569        // A: create + a channel + grant B admin + mint link.
8570        become_acct(&a);
8571        let mut community = create_community(&transport, "Live E2E", relays.clone(), None).await.expect("create");
8572        let general = community.channels[0].id;
8573        log(format!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0)));
8574        send_message(&transport, &community, &general, "A: live hello").await.expect("send");
8575        let ann = create_public_channel(&transport, &community, "announcements").await.expect("channel");
8576        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8577        log(format!("[channel] +public #announcements {}", crate::simd::hex::bytes_to_hex_32(&ann.0)));
8578        grant_admin(&transport, &community, &b.public_key()).await.expect("grant admin");
8579        let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint");
8580        log(format!("[invite] B granted @admin · link {}", link.url));
8581        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(a.public_key()), None, None)).unwrap();
8582        settle().await;
8583
8584        // B: join + read A's history + reply.
8585        become_acct(&b);
8586        let b_view = accept_parked_invite(&transport, &bundle_json, None).await.expect("join");
8587        log(format!("[join] B joined; {} channels", b_view.channels.len()));
8588        settle().await;
8589        let page = fetch_channel(&transport, &b_view, &general, 50).await.expect("fetch");
8590        let seen: Vec<String> = page.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
8591        log(format!("[read] B sees #general: {seen:?}"));
8592        assert!(seen.iter().any(|t| t == "A: live hello"), "B reads A's message over the real relay");
8593        send_message(&transport, &b_view, &general, "B: live reply").await.expect("reply");
8594
8595        // B posts a NIP-22 kind-1111 THREADED REPLY to A's message (the shape Armada
8596        // sends) directly onto the chat plane — proving the cross-client thread
8597        // RECEIVE path works live, not just in the offline fixture.
8598        let hello = page.iter().find(|f| f.event.opened().rumor.content == "A: live hello").expect("A's message");
8599        let hello_id = hello.event.opened().rumor_id.to_hex();
8600        let bkeys = crate::state::MY_SECRET_KEY.to_keys().unwrap();
8601        let cgroup = channel_group_key(&b_view.community_root, &general, b_view.root_epoch);
8602        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());
8603        let (reply_wrap, _) = chat::seal_chat_rumor(&reply_rumor, &cgroup, &bkeys, Timestamp::from_secs(now_ms() / 1000), false).expect("seal 1111");
8604        transport.publish(&reply_wrap, &b_view.relays).await.expect("publish 1111");
8605        log("[thread] B published a kind-1111 threaded reply to A's message".to_string());
8606        settle().await;
8607
8608        // A reads the thread reply back, rendered inline with A's message as parent.
8609        become_acct(&a);
8610        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8611        let a_page = fetch_channel(&transport, &community, &general, 50).await.expect("A fetch");
8612        let thread = a_page.iter().find(|f| f.event.opened().rumor.content == "B: threaded reply to hello").expect("A sees the 1111");
8613        if let chat::ChatEvent::Message { reply_to, opened, .. } = &thread.event {
8614            assert_eq!(opened.rumor.kind.as_u16(), super::super::kind::COMMENT, "wire kind preserved as 1111");
8615            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");
8616        } else {
8617            panic!("the 1111 parsed as a Message");
8618        }
8619        log("[thread] A read B's threaded reply, parent resolved — cross-client 1111 interop OK".to_string());
8620        become_acct(&b);
8621        settle().await;
8622
8623        // A: create a PRIVATE channel while B is already a member — B is a recipient
8624        // of the creation delivery, so B keys up from the rekey plane over the real
8625        // relay (no bundle involved), then the two converse on it.
8626        become_acct(&a);
8627        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8628        let vault = create_private_channel(&transport, &community, "vault").await.expect("private channel");
8629        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8630        send_message(&transport, &community, &vault, "A: vault live").await.expect("vault send");
8631        log(format!("[channel] +private #vault {} (key delivered over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&vault.0)));
8632        settle().await;
8633
8634        become_acct(&b);
8635        let session_b = SessionGuard::capture();
8636        let mut b_view = crate::db::community::load_community_v2(b_view.id()).unwrap().unwrap();
8637        if let Some(fresh) = follow_control(&transport, &b_view, &session_b).await.expect("B control follow") {
8638            b_view = fresh;
8639        }
8640        if let Some(fresh) = follow_rekeys(&transport, &b_view, &session_b).await.expect("B rekey follow").updated {
8641            b_view = fresh;
8642        }
8643        let vch = b_view.channel(&vault).expect("B folded the vault");
8644        assert!(vch.key.is_some() && vch.epoch == Epoch(1), "B adopted the vault key from the live rekey plane");
8645        let vseen = texts_in(&transport, &b_view, &vault).await;
8646        log(format!("[read] B sees #vault: {vseen:?}"));
8647        assert!(vseen.iter().any(|t| t == "A: vault live"), "B reads the private channel with the ADOPTED key");
8648        send_message(&transport, &b_view, &vault, "B: in the live vault").await.expect("vault reply");
8649        settle().await;
8650
8651        become_acct(&a);
8652        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8653        assert!(
8654            texts_in(&transport, &community, &vault).await.iter().any(|t| t == "B: in the live vault"),
8655            "A reads B's private reply"
8656        );
8657        log("[private] two-way #vault conversation over the live relay".to_string());
8658
8659        // A: ban B (three-removal) + dissolve.
8660        set_banlist(&transport, &community, &[b.public_key().to_hex()]).await.expect("banlist");
8661        grant_roles(&transport, &community, &b.public_key(), vec![]).await.expect("strip");
8662        let refounded = refound_community(&transport, &community, &[b.public_key()]).await.expect("refound");
8663        log(format!("[ban] B banned; root → epoch {}", refounded.root_epoch.0));
8664        settle().await;
8665        dissolve_community(&transport, &refounded).await.expect("dissolve");
8666        log("[dissolve] community sealed".to_string());
8667        log("===== LIVE e2e PASS =====".to_string());
8668    }
8669
8670    #[tokio::test]
8671    async fn an_offline_member_learns_of_a_dissolution_on_catch_up() {
8672        // The tombstone rides its own public plane, watched live — an OFFLINE
8673        // member's catch-up must fetch it too, or they follow (and post into) a
8674        // grave forever.
8675        let (bed, owner, member) = TestBed::new();
8676        bed.swap_to(&owner);
8677        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
8678        let general = community.channels[0].id;
8679        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
8680
8681        bed.swap_to(&member);
8682        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
8683        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
8684
8685        // The owner dissolves while the member sleeps.
8686        bed.swap_to(&owner);
8687        dissolve_community(&bed.relay, &community).await.unwrap();
8688
8689        // The member's catch-up learns of the death, seals, and refuses to post.
8690        bed.swap_to(&member);
8691        let session = SessionGuard::capture();
8692        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
8693        assert!(follow.dissolved, "the catch-up surfaces the tombstone");
8694        assert!(!follow.self_removed && follow.updated.is_none());
8695        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
8696        assert!(crate::db::community::get_community_dissolved(&cid_hex).unwrap(), "sealed read-only locally");
8697        let err = send_message(&bed.relay, &joined, &general, "into the void").await.unwrap_err();
8698        assert!(err.contains("dissolved"), "sends refuse a grave: {err}");
8699        // Subsequent follows take the local fast path — still dissolved, no churn.
8700        let again = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
8701        assert!(again.dissolved && again.updated.is_none());
8702    }
8703
8704    #[tokio::test]
8705    async fn a_wide_community_survives_refoundings_and_an_offline_member_converges() {
8706        // Scale stress: MANY private channels, each rotated on every Refounding.
8707        // A member offline across two refoundings must converge on all of them
8708        // (the per-channel rotation fan in refound + the follow's channel×root×step
8709        // loops stay bounded) with every channel's history readable.
8710        const PRIV_CHANNELS: usize = 6;
8711        let (bed, owner, member) = TestBed::new();
8712        bed.swap_to(&owner);
8713        let mut community = create_community(&bed.relay, "Wide", bed.relays.clone(), None).await.unwrap();
8714        let mut priv_ids = Vec::new();
8715        for i in 0..PRIV_CHANNELS {
8716            let id = create_private_channel(&bed.relay, &community, &format!("priv{i}")).await.unwrap();
8717            community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8718            send_message(&bed.relay, &community, &id, &format!("priv{i} epoch0")).await.unwrap();
8719            priv_ids.push(id);
8720        }
8721        // Private channels are readable only by granted role-holders (CORD-03).
8722        for id in &priv_ids {
8723            grant_channel_access(&bed.relay, &community, id, &member.keys.public_key()).await.unwrap();
8724        }
8725        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();
8726
8727        // Member joins at epoch 0 with all channel keys, then goes offline.
8728        bed.swap_to(&member);
8729        let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8730        assert_eq!(member_view.channels.iter().filter(|c| c.private && c.key.is_some()).count(), PRIV_CHANNELS, "joined with all private keys");
8731
8732        // Two refoundings (each rotates the base + every private channel).
8733        bed.swap_to(&owner);
8734        for epoch in 1..=2u64 {
8735            community = refound_community(&bed.relay, &community, &[]).await.unwrap();
8736            assert_eq!(community.root_epoch, Epoch(epoch));
8737            for id in &priv_ids {
8738                send_message(&bed.relay, &community, id, &format!("{} epoch{epoch}", crate::simd::hex::bytes_to_hex_32(&id.0))).await.unwrap();
8739            }
8740        }
8741
8742        // Member returns: bounded follow to quiescence.
8743        bed.swap_to(&member);
8744        let session = SessionGuard::capture();
8745        let mut passes = 0;
8746        loop {
8747            passes += 1;
8748            assert!(passes <= 8, "a wide catch-up must converge, not churn (pass {passes})");
8749            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8750            let rk = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
8751            assert!(!rk.self_removed);
8752            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8753            let ctl = follow_control(&bed.relay, &cur, &session).await.unwrap();
8754            if rk.updated.is_none() && ctl.is_none() {
8755                break;
8756            }
8757        }
8758        let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8759        assert_eq!(caught_up.root_epoch, Epoch(2), "walked both refoundings");
8760        // Every private channel converged to the owner's current key + reads all epochs.
8761        for id in &priv_ids {
8762            let mine = caught_up.channel(id).expect("channel survived");
8763            let theirs = community.channel(id).unwrap();
8764            assert_eq!(mine.key, theirs.key, "channel {} converged on the owner key", crate::simd::hex::bytes_to_hex_32(&id.0));
8765            assert_eq!(mine.epoch, theirs.epoch, "…at the same epoch");
8766            let texts = texts_in(&bed.relay, &caught_up, id).await;
8767            let id_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
8768            assert!(texts.iter().any(|t| t.contains("epoch0")), "channel {id_hex} reads epoch-0 history");
8769            for epoch in 1..=2u64 {
8770                assert!(texts.iter().any(|t| t.contains(&format!("epoch{epoch}"))), "channel {id_hex} reads epoch-{epoch} history");
8771            }
8772        }
8773    }
8774
8775    #[tokio::test]
8776    async fn an_offline_member_catches_up_across_three_refoundings() {
8777        // The deep offline-online scenario: a member sleeps through THREE
8778        // Refoundings, per-refound private-channel rotations, a mid-life private
8779        // channel CREATED while they slept, a public channel, a rename, and a
8780        // ban — then returns and converges by follow alone (no rejoin).
8781        use nostr_sdk::prelude::ToBech32;
8782        let (bed, owner, member) = TestBed::new();
8783        bed.swap_to(&owner);
8784        let mut community = create_community(&bed.relay, "Sleeper", bed.relays.clone(), None).await.unwrap();
8785        let general = community.channels[0].id;
8786        let mods = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
8787        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8788        send_message(&bed.relay, &community, &general, "epoch0: hello").await.unwrap();
8789        send_message(&bed.relay, &community, &mods, "epoch0: mods secret").await.unwrap();
8790        // Private channels are readable only by granted role-holders (CORD-03).
8791        grant_channel_access(&bed.relay, &community, &mods, &member.keys.public_key()).await.unwrap();
8792        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();
8793
8794        // Member joins at epoch 0, then goes OFFLINE.
8795        bed.swap_to(&member);
8796        let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
8797        assert_eq!(member_view.root_epoch, Epoch(0));
8798
8799        // While they sleep, the owner reshapes everything across three epochs.
8800        bed.swap_to(&owner);
8801        let stranger = Keys::generate();
8802        for epoch in 1..=3u64 {
8803            community = refound_community(&bed.relay, &community, &[]).await.unwrap();
8804            assert_eq!(community.root_epoch, Epoch(epoch));
8805            send_message(&bed.relay, &community, &general, &format!("epoch{epoch}: general news")).await.unwrap();
8806            send_message(&bed.relay, &community, &mods, &format!("epoch{epoch}: mods word")).await.unwrap();
8807        }
8808        let news = create_public_channel(&bed.relay, &community, "news").await.unwrap();
8809        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8810        let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
8811        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8812        // The sleeper is on this channel's access list, so the refoundings that
8813        // follow deliver its key to them (CORD-03).
8814        grant_channel_access(&bed.relay, &community, &vault, &member.keys.public_key()).await.unwrap();
8815        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
8816        send_message(&bed.relay, &community, &vault, "epoch3: vault opened").await.unwrap();
8817        set_banlist(&bed.relay, &community, &[stranger.public_key().to_hex()]).await.unwrap();
8818        let meta = control::CommunityMetadata { name: "Sleeper Reborn".into(), relays: community.relays.clone(), ..Default::default() };
8819        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
8820
8821        // The member RETURNS: rekey+control follow to quiescence (the worker's
8822        // loop, driven explicitly). Bounded — convergence must be fast.
8823        bed.swap_to(&member);
8824        let session = SessionGuard::capture();
8825        let mut passes = 0;
8826        loop {
8827            passes += 1;
8828            assert!(passes <= 6, "catch-up must converge, not churn");
8829            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8830            let rekeyed = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
8831            assert!(!rekeyed.self_removed, "the member was never removed");
8832            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8833            let controlled = follow_control(&bed.relay, &cur, &session).await.unwrap();
8834            if rekeyed.updated.is_none() && controlled.is_none() {
8835                break;
8836            }
8837        }
8838        let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
8839
8840        // Base + name converged.
8841        assert_eq!(caught_up.root_epoch, Epoch(3), "walked all three refoundings");
8842        assert_eq!(caught_up.community_root, community.community_root, "landed on the owner's root");
8843        assert_eq!(caught_up.name, "Sleeper Reborn");
8844        // Channels: renamed set incl. the mid-sleep public + private ones.
8845        assert!(caught_up.channels.iter().any(|c| c.id.0 == news.0), "folded the new public channel");
8846        let m = caught_up.channel(&mods).expect("mods survived");
8847        let owner_mods = community.channel(&mods).unwrap();
8848        assert_eq!(m.epoch, owner_mods.epoch, "mods walked every per-refound rotation");
8849        assert_eq!(m.key, owner_mods.key, "…to the owner's exact key");
8850        let v = caught_up.channel(&vault).expect("vault folded in");
8851        // The sleeper is on vault's access list, but it was created AFTER the last
8852        // refounding — no rotation followed the grant, so no blob was ever
8853        // addressed to them. They hold the channel keyless until the grant's own
8854        // key vend lands (CORD-05 §6), which is what a rekey-only walk cannot do.
8855        assert!(v.private && v.key.is_none(), "vault folds in keyless: entitled, but never delivered");
8856        // Banlist survived the compactions.
8857        let cid_hex = crate::simd::hex::bytes_to_hex_32(&caught_up.id().0);
8858        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap();
8859        assert!(banned.contains(&stranger.public_key().to_hex()), "the ban folded through");
8860        // History reads across EVERY epoch (public via base-root archive, private
8861        // via the per-channel archive built during the walk).
8862        let gen_texts = texts_in(&bed.relay, &caught_up, &general).await;
8863        for epoch in 0..=3u64 {
8864            let needle = if epoch == 0 { "epoch0: hello".to_string() } else { format!("epoch{epoch}: general news") };
8865            assert!(gen_texts.contains(&needle), "general history spans epoch {epoch}: {gen_texts:?}");
8866        }
8867        let mods_texts = texts_in(&bed.relay, &caught_up, &mods).await;
8868        for epoch in 0..=3u64 {
8869            let needle = if epoch == 0 { "epoch0: mods secret".to_string() } else { format!("epoch{epoch}: mods word") };
8870            assert!(mods_texts.contains(&needle), "private history spans epoch {epoch}: {mods_texts:?}");
8871        }
8872        // Keyless (above) means unreadable — a rekey walk cannot substitute for the
8873        // key vend that a grant carries.
8874        assert!(texts_in(&bed.relay, &caught_up, &vault).await.is_empty());
8875        // And the member can still speak.
8876        send_message(&bed.relay, &caught_up, &general, "member: good morning").await.unwrap();
8877        bed.swap_to(&owner);
8878        assert!(
8879            texts_in(&bed.relay, &community, &general).await.contains(&"member: good morning".to_string()),
8880            "the caught-up member converses at the new epoch ({})",
8881            member.keys.public_key().to_bech32().unwrap()
8882        );
8883    }
8884
8885    /// Seal `n` messages onto a community's #general, one per second starting at
8886    /// `base_secs` (distinct wrap seconds so relay-side `until` paging engages).
8887    async fn flood_general(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, n: usize, base_secs: u64) {
8888        let general = community.channels[0].id;
8889        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
8890        for i in 0..n {
8891            let at = base_secs + i as u64;
8892            let rumor = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, &format!("msg {i}"), None, &[], vec![], at * 1000);
8893            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, author, Timestamp::from_secs(at), false).unwrap();
8894            relay.publish(&wrap, &community.relays).await.unwrap();
8895        }
8896    }
8897
8898    #[tokio::test]
8899    async fn the_history_walk_pages_past_a_multi_page_burst() {
8900        // A bot offline through 120 messages must catch ALL of them, not the
8901        // newest page — the v1 sync-gap class, closed by until-paging.
8902        let (_tmp, _guard, owner) = init_test_db();
8903        let relay = MemoryRelay::new();
8904        let community = create_community(&relay, "Burst", vec!["wss://r".into()], None).await.unwrap();
8905        let general = community.channels[0].id;
8906        flood_general(&relay, &community, &owner, 120, 10_000).await;
8907
8908        let all = fetch_channel_history(&relay, &community, &general, 50, 8, None, crate::community::transport::Evidence::Quorum, |_| true).await.unwrap();
8909        assert_eq!(all.len(), 120, "the walk pages the whole burst");
8910        // Oldest→newest, no duplicates.
8911        let contents: Vec<String> = all.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
8912        assert_eq!(contents.first().map(String::as_str), Some("msg 0"));
8913        assert_eq!(contents.last().map(String::as_str), Some("msg 119"));
8914        let unique: std::collections::HashSet<&String> = contents.iter().collect();
8915        assert_eq!(unique.len(), 120, "wrap-id + rumor-id dedup holds across page boundaries");
8916
8917        // The single-page fetch stays a single page.
8918        let one = fetch_channel(&relay, &community, &general, 50).await.unwrap();
8919        assert_eq!(one.len(), 50, "fetch_channel is one newest page");
8920        assert_eq!(one.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
8921    }
8922
8923    #[tokio::test]
8924    async fn the_history_walk_stops_when_the_caller_is_caught_up() {
8925        let (_tmp, _guard, owner) = init_test_db();
8926        let relay = MemoryRelay::new();
8927        let community = create_community(&relay, "Caught", vec!["wss://r".into()], None).await.unwrap();
8928        let general = community.channels[0].id;
8929        flood_general(&relay, &community, &owner, 120, 10_000).await;
8930
8931        // The caller says "I hold everything" after the first page — no deeper fetch.
8932        let mut pages = 0usize;
8933        let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, crate::community::transport::Evidence::Quorum, |_| {
8934            pages += 1;
8935            false
8936        })
8937        .await
8938        .unwrap();
8939        assert_eq!(pages, 1, "the early stop is consulted once");
8940        assert_eq!(got.len(), 50, "only the newest page is fetched");
8941        assert_eq!(got.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
8942    }
8943
8944    #[tokio::test]
8945    async fn a_same_second_history_wall_terminates_instead_of_looping() {
8946        // 60 messages in ONE second with a 25-wrap page: a second-granular
8947        // `until` can never page past the wall — the walk must step over it
8948        // (bounded loss, logged) rather than spin.
8949        let (_tmp, _guard, owner) = init_test_db();
8950        let relay = MemoryRelay::new();
8951        let community = create_community(&relay, "Wall", vec!["wss://r".into()], None).await.unwrap();
8952        let general = community.channels[0].id;
8953        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
8954        for i in 0..60usize {
8955            let rumor = chat::build_message_rumor(owner.public_key(), &general, community.root_epoch, &format!("burst {i}"), None, &[], vec![], 5_000_000 + i as u64);
8956            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &owner, Timestamp::from_secs(5_000), false).unwrap();
8957            relay.publish(&wrap, &community.relays).await.unwrap();
8958        }
8959        let got = fetch_channel_history(&relay, &community, &general, 25, 8, None, crate::community::transport::Evidence::Quorum, |_| true).await.unwrap();
8960        assert!(got.len() >= 25, "at least the relay page is read");
8961        assert!(got.len() <= 60, "sane bound");
8962        // Termination is the assertion: reaching here means the wall didn't loop.
8963    }
8964
8965    #[tokio::test]
8966    async fn a_grant_revoke_survives_a_withholding_relay() {
8967        // Floor persistence on the delegation plane: after the owner revokes an admin,
8968        // a relay serving only the OLD (still owner-signed) grant can't resurrect it.
8969        let (_tmp, _guard, owner) = init_test_db();
8970        let relay = MemoryRelay::new();
8971        let community = create_community(&relay, "Revoke", vec!["wss://good".into()], None).await.unwrap();
8972        let admin = Keys::generate();
8973        let rid = "d4".repeat(32);
8974        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
8975        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
8976        let session = SessionGuard::capture();
8977        follow_control(&relay, &community, &session).await.unwrap(); // seed floors incl. the grant at v1
8978        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke → grant floor v2
8979        follow_control(&relay, &community, &session).await.unwrap();
8980
8981        // A stale relay serves only the grant prefix (v1, the live grant).
8982        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
8983        let mut stale = community.clone();
8984        stale.relays = vec!["wss://stale".into()];
8985        let floors = load_floors(&community);
8986        let editions = fetch_control(&relay, &stale).await;
8987        let authority = fold_authority(&stale, &editions, &floors);
8988        assert!(
8989            !authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
8990            "the persisted grant floor refuses the rolled-back (re-granted) view"
8991        );
8992    }
8993
8994    /// Load the current-epoch floors for a community (test mirror of follow_control).
8995    fn load_floors(community: &CommunityV2) -> Floors {
8996        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
8997        crate::db::community::get_all_edition_heads_full(&cid_hex)
8998            .unwrap_or_default()
8999            .into_iter()
9000            .filter(|(_, f)| f.0 == community.root_epoch.0)
9001            .map(|(e, f)| (e, (f.1, f.2, f.3)))
9002            .collect()
9003    }
9004
9005    /// Fetch + open every control edition at a community's control plane (test helper).
9006    async fn fetch_control(relay: &MemoryRelay, community: &CommunityV2) -> Vec<ParsedEdition> {
9007        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9008        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
9009        relay
9010            .fetch(&q, &community.relays)
9011            .await
9012            .unwrap_or_default()
9013            .iter()
9014            .filter_map(|w| control::open_control_edition(w, &group).ok().map(|(ed, _)| ed))
9015            .collect()
9016    }
9017
9018    #[tokio::test]
9019    async fn follow_control_is_a_noop_on_a_freshly_created_community() {
9020        let (_tmp, _guard, _owner) = init_test_db();
9021        let relay = MemoryRelay::new();
9022        let community = create_community(&relay, "Fresh", vec!["wss://r".into()], None).await.unwrap();
9023        let session = SessionGuard::capture();
9024        // Only the genesis editions exist; folding them reproduces the held view.
9025        assert!(follow_control(&relay, &community, &session).await.unwrap().is_none());
9026    }
9027
9028    #[tokio::test]
9029    async fn follow_control_adds_a_new_public_channel_and_re_subscribes_it() {
9030        let (_tmp, _guard, owner) = init_test_db();
9031        let relay = MemoryRelay::new();
9032        let community = create_community(&relay, "Grow", vec!["wss://r".into()], None).await.unwrap();
9033        let new_id = ChannelId([0x5a; 32]);
9034        publish_channel_edition(&relay, &community, &owner, &new_id, "announcements", false, 1, false).await;
9035
9036        let session = SessionGuard::capture();
9037        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("a new channel changed the view");
9038        assert_eq!(updated.channels.len(), 2);
9039        let added = updated.channel(&new_id).expect("the new channel folded in");
9040        assert_eq!(added.name, "announcements");
9041        assert!(!added.private);
9042        assert_eq!(added.key, None, "a public channel derives from the root (no stored key)");
9043
9044        // The new channel is now in the realtime author-set (it would be subscribed).
9045        let authors = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
9046        let addr = channel_group_key(&updated.community_root, &new_id, updated.root_epoch).pk();
9047        assert!(authors.contains(&addr), "the added channel joins the live subscription");
9048
9049        // Persisted: a reload sees it too.
9050        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9051        assert!(reloaded.channel(&new_id).is_some());
9052    }
9053
9054    #[tokio::test]
9055    async fn follow_control_renames_the_community_and_an_existing_channel() {
9056        let (_tmp, _guard, owner) = init_test_db();
9057        let relay = MemoryRelay::new();
9058        let community = create_community(&relay, "Old Name", vec!["wss://r".into()], None).await.unwrap();
9059        let general = community.channels[0].id;
9060        // A v2 metadata edition renames the community; a v2 channel edition renames #general.
9061        publish_community_meta(&relay, &community, &owner, "New Name", 2).await;
9062        publish_channel_edition(&relay, &community, &owner, &general, "lobby", false, 2, false).await;
9063
9064        let session = SessionGuard::capture();
9065        let updated = follow_control(&relay, &community, &session).await.unwrap().unwrap();
9066        assert_eq!(updated.name, "New Name");
9067        assert_eq!(updated.channel(&general).unwrap().name, "lobby");
9068        assert_eq!(updated.channels.len(), 1, "a rename doesn't add a channel");
9069    }
9070
9071    #[tokio::test]
9072    async fn follow_control_deletes_a_channel() {
9073        let (_tmp, _guard, owner) = init_test_db();
9074        let relay = MemoryRelay::new();
9075        let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
9076        let extra = ChannelId([0x77; 32]);
9077        let session = SessionGuard::capture();
9078
9079        // The channel is first added and folded into the held view.
9080        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
9081        let with_extra = follow_control(&relay, &community, &session).await.unwrap().expect("added");
9082        assert!(with_extra.channel(&extra).is_some());
9083
9084        // Then it's tombstoned — the delete (higher version) folds the held one back out.
9085        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
9086        let updated = follow_control(&relay, &with_extra, &session).await.unwrap().expect("removed");
9087        assert!(updated.channel(&extra).is_none(), "a deleted channel folds out");
9088        assert_eq!(updated.channels.len(), 1, "only #general remains");
9089    }
9090
9091    /// Re-inject only the OLD prefix (every edition at/below `max_version`) of a
9092    /// community's control plane onto a second relay URL — the withholding-relay
9093    /// simulation: everything it serves is genuinely owner-signed, just stale.
9094    async fn inject_stale_prefix(relay: &MemoryRelay, community: &CommunityV2, max_version: u64, stale_relay: &str) {
9095        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9096        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
9097        let wraps = relay.fetch(&query, &community.relays).await.unwrap();
9098        for w in &wraps {
9099            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
9100                if ed.version <= max_version {
9101                    relay.inject(w, &[stale_relay.to_string()]);
9102                }
9103            }
9104        }
9105    }
9106
9107    #[tokio::test]
9108    async fn a_withholding_relay_cannot_roll_back_a_rename() {
9109        // W2 persisted floor: after adopting the owner's v2 rename, a relay serving
9110        // only the (owner-signed) v1 genesis must not revert the held name.
9111        let (_tmp, _guard, owner) = init_test_db();
9112        let relay = MemoryRelay::new();
9113        let community = create_community(&relay, "Original", vec!["wss://good".into()], None).await.unwrap();
9114        publish_community_meta(&relay, &community, &owner, "Renamed", 2).await;
9115
9116        let session = SessionGuard::capture();
9117        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("rename adopted");
9118        assert_eq!(updated.name, "Renamed");
9119
9120        // The stale relay holds only the genesis prefix; point the follow at it.
9121        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
9122        let mut stale_view = updated.clone();
9123        stale_view.relays = vec!["wss://stale".into()];
9124        assert!(
9125            follow_control(&relay, &stale_view, &session).await.unwrap().is_none(),
9126            "a stale-only relay must not change the held view"
9127        );
9128        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9129        assert_eq!(held.name, "Renamed", "the persisted floor refuses the rollback");
9130    }
9131
9132    #[tokio::test]
9133    async fn a_withholding_relay_cannot_resurrect_a_deleted_channel() {
9134        let (_tmp, _guard, owner) = init_test_db();
9135        let relay = MemoryRelay::new();
9136        let community = create_community(&relay, "Prune2", vec!["wss://good".into()], None).await.unwrap();
9137        let extra = ChannelId([0x44; 32]);
9138        let session = SessionGuard::capture();
9139
9140        // A same-content metadata edit: no visible change (None), but the floor must
9141        // still advance to v2 (so the genesis metadata can't re-present below).
9142        publish_community_meta(&relay, &community, &owner, "Prune2", 2).await;
9143        assert!(follow_control(&relay, &community, &session).await.unwrap().is_none());
9144
9145        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
9146        let with_extra = follow_control(&relay, &community, &session).await.unwrap().expect("added");
9147        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
9148        let pruned = follow_control(&relay, &with_extra, &session).await.unwrap().expect("removed");
9149        assert!(pruned.channel(&extra).is_none());
9150
9151        // The stale relay serves the add (v1) but withholds the delete (v2).
9152        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
9153        let mut stale_view = pruned.clone();
9154        stale_view.relays = vec!["wss://stale".into()];
9155        assert!(
9156            follow_control(&relay, &stale_view, &session).await.unwrap().is_none(),
9157            "the withheld delete must not resurrect the channel"
9158        );
9159        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9160        assert!(held.channel(&extra).is_none(), "the deleted channel stays deleted");
9161    }
9162
9163    #[tokio::test]
9164    async fn a_new_epoch_bootstraps_past_an_old_epoch_floor() {
9165        // The Armada-convergence carve-out: a Refounding compacts the chain and
9166        // re-wraps a detached head at the NEW epoch's control plane. The old epoch's
9167        // floor must not block it — epoch-filtering makes the entity bootstrap.
9168        let (_tmp, _guard, owner) = init_test_db();
9169        let relay = MemoryRelay::new();
9170        let community = create_community(&relay, "Before", vec!["wss://good".into()], None).await.unwrap();
9171        let session = SessionGuard::capture();
9172        publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
9173        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("edit adopted");
9174        assert_eq!(updated.name, "Edited");
9175
9176        // Refounding lands (epoch bump saved by the rekey path); the compacted head
9177        // arrives DETACHED (high version, no prev) on the new epoch's plane.
9178        let mut refounded = updated.clone();
9179        refounded.root_epoch = crate::community::Epoch(1);
9180        crate::db::community::save_community_v2(&refounded).unwrap();
9181        publish_community_meta(&relay, &refounded, &owner, "Compacted", 5).await;
9182
9183        let adopted = follow_control(&relay, &refounded, &session).await.unwrap().expect("compacted head adopted");
9184        assert_eq!(adopted.name, "Compacted", "a fresh epoch bootstraps despite the dangling prev");
9185        // The persisted floor is stamped with the epoch the FOLD ran under.
9186        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9187        let heads = crate::db::community::get_all_edition_heads_epoched(&cid_hex).unwrap();
9188        assert!(
9189            heads.get(&cid_hex).is_some_and(|(e, v, _)| *e == 1 && *v == 5),
9190            "the adopted head carries the fold's epoch + version"
9191        );
9192    }
9193
9194    #[tokio::test]
9195    async fn a_same_version_owner_fork_at_the_floor_converges_to_the_deterministic_winner() {
9196        // Two owner-signed editions at the SAME version (publish retry / two owner
9197        // devices): every client must land on the lower-inner-id winner. A hash-strict
9198        // floor would wedge here forever while Armada converges — the floor must
9199        // CONVERGE instead (the v1 decide() rule).
9200        let (_tmp, _guard, owner) = init_test_db();
9201        let relay = MemoryRelay::new();
9202        let community = create_community(&relay, "Fork", vec!["wss://r".into()], None).await.unwrap();
9203        let session = SessionGuard::capture();
9204        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9205        let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9206
9207        publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
9208        let ours = follow_control(&relay, &community, &session).await.unwrap().expect("ours adopted");
9209        assert_eq!(ours.name, "Ours");
9210
9211        // Our committed v2 edition's tiebreak id.
9212        let our_inner = {
9213            let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
9214            let wraps = relay.fetch(&q, &community.relays).await.unwrap();
9215            wraps
9216                .iter()
9217                .find_map(|w| {
9218                    control::open_control_edition(w, &group)
9219                        .ok()
9220                        .filter(|(ed, _)| ed.version == 2 && ed.vsk == vsk::COMMUNITY_METADATA)
9221                        .map(|(ed, _)| ed.inner_id)
9222                })
9223                .unwrap()
9224        };
9225
9226        // Craft the concurrent fork so it WINS the deterministic tiebreak (vary the
9227        // authored timestamp until its inner id is lower).
9228        let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
9229        let content = serde_json::to_string(&meta).unwrap();
9230        let mut ts = 2_000u64;
9231        let fork_wrap = loop {
9232            let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
9233            let inner = rumor.id.unwrap().to_bytes();
9234            if inner < our_inner {
9235                break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
9236            }
9237            ts += 1;
9238        };
9239        relay.publish(&fork_wrap, &community.relays).await.unwrap();
9240
9241        let converged = follow_control(&relay, &ours, &session).await.unwrap().expect("fork winner adopted");
9242        assert_eq!(converged.name, "Theirs", "the floor converges to the lower-inner-id winner");
9243        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9244        let held = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap();
9245        assert!(held.is_some_and(|h| h < our_inner), "the persisted floor's tiebreak key moved to the winner");
9246    }
9247
9248    #[tokio::test]
9249    async fn an_anchored_prefix_applies_while_a_gap_above_awaits_the_missing_link() {
9250        // v2 chains to the floor; v4 arrives but its v3 link is withheld. The
9251        // chain-verified prefix (v2) applies NOW — refuse-downgrade holds for it —
9252        // while the detached v4 waits. When v3 lands, the chain heals to v4.
9253        let (_tmp, _guard, owner) = init_test_db();
9254        let relay = MemoryRelay::new();
9255        let community = create_community(&relay, "Prefix", vec!["wss://r".into()], None).await.unwrap();
9256        let session = SessionGuard::capture();
9257        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9258
9259        publish_community_meta(&relay, &community, &owner, "Two", 2).await;
9260        let v2_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9261
9262        // Craft v3 (held back) and v4 (published, chained to the withheld v3).
9263        let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
9264        let r3 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 3, Some(&v2_hash), &c3, 3_000, None);
9265        let (w3, _) = control::seal_control_edition(&r3, &group, &owner, Timestamp::from_secs(3_000)).unwrap();
9266        let (ed3, _) = control::open_control_edition(&w3, &group).unwrap();
9267        let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
9268        let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&ed3.self_hash), &c4, 4_000, None);
9269        let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(4_000)).unwrap();
9270        relay.publish(&w4, &community.relays).await.unwrap();
9271
9272        let updated = follow_control(&relay, &community, &session).await.unwrap().expect("the verified prefix applies");
9273        assert_eq!(updated.name, "Two", "the anchored prefix lands; the detached v4 does not");
9274
9275        relay.publish(&w3, &community.relays).await.unwrap();
9276        let healed = follow_control(&relay, &updated, &session).await.unwrap().expect("the chain heals");
9277        assert_eq!(healed.name, "Four", "once the link arrives, the head advances past the prefix");
9278    }
9279
9280    #[tokio::test]
9281    async fn paging_rescues_a_floor_link_evicted_from_the_newest_window() {
9282        // The held floor is v2; the owner publishes v3, then a flood of foreign junk
9283        // wraps fills the newest window, then v4. Page 1 sees only v4 (detached →
9284        // gapped); paging older must recover v3 (and the floor link) and heal to v4.
9285        let (_tmp, _guard, owner) = init_test_db();
9286        let relay = MemoryRelay::new();
9287        let community = create_community(&relay, "Paged", vec!["wss://r".into()], None).await.unwrap();
9288        let session = SessionGuard::capture();
9289        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9290
9291        publish_community_meta(&relay, &community, &owner, "Two", 2).await;
9292        let base = follow_control(&relay, &community, &session).await.unwrap().expect("floor at v2");
9293        publish_community_meta(&relay, &base, &owner, "Three", 3).await; // ts 1_000 (old)
9294        let v3_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9295
9296        // Rogue flood occupying the newest window (sealed to the control plane, but
9297        // non-owner — the authority gate drops them; they only crowd the page).
9298        let rogue = Keys::generate();
9299        for i in 0..(FOLLOW_PAGE as u64 - 1) {
9300            let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xCC; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 4_000 + i, None);
9301            let (w, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(4_000 + i)).unwrap();
9302            relay.publish(&w, &community.relays).await.unwrap();
9303        }
9304        // v4 chained to the real v3 (crafted directly: the flood also blinds the
9305        // helper's own newest-window head lookup), timestamped newest of all.
9306        let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
9307        let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&v3_hash), &c4, 10_000, None);
9308        let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(10_000)).unwrap();
9309        relay.publish(&w4, &community.relays).await.unwrap();
9310
9311        let healed = follow_control(&relay, &base, &session).await.unwrap().expect("paging recovered the chain");
9312        assert_eq!(healed.name, "Four", "the gap paged past the flood to the floor link");
9313    }
9314
9315    #[tokio::test]
9316    async fn a_follow_after_delete_does_not_resurrect_the_community() {
9317        // A leave/delete racing an in-flight follow: the follow must not re-insert
9318        // the community row or floor rows past delete_community's wipe.
9319        let (_tmp, _guard, owner) = init_test_db();
9320        let relay = MemoryRelay::new();
9321        let community = create_community(&relay, "Gone", vec!["wss://r".into()], None).await.unwrap();
9322        publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
9323        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9324        crate::db::community::delete_community(&cid_hex).unwrap();
9325
9326        let session = SessionGuard::capture();
9327        assert!(
9328            follow_control(&relay, &community, &session).await.unwrap().is_none(),
9329            "a follow racing a delete is a no-op"
9330        );
9331        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
9332        assert!(crate::db::community::edition_head_entity_ids(&cid_hex).unwrap().is_empty(), "no orphan floor rows");
9333    }
9334
9335    #[tokio::test]
9336    async fn a_rekey_follow_after_delete_does_not_resurrect_the_community() {
9337        // The rekey sibling of the follow_control guard: an owner rotation adopted
9338        // mid-race must not upsert the community row back after a leave/delete.
9339        let (_tmp, _guard, owner) = init_test_db();
9340        let relay = MemoryRelay::new();
9341        let community = create_community(&relay, "GoneKeys", vec!["wss://r".into()], None).await.unwrap();
9342        let new_root = [0xB2; 32];
9343        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
9344        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9345        crate::db::community::delete_community(&cid_hex).unwrap();
9346
9347        let session = SessionGuard::capture();
9348        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
9349        assert!(follow.updated.is_none() && !follow.self_removed, "a rekey follow racing a delete adopts nothing");
9350        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
9351    }
9352
9353    #[tokio::test]
9354    async fn a_joiner_bootstraps_the_highest_head_across_a_lost_middle_edition() {
9355        // {v1, v3} on the relays with v2 lost at publish time (a rate-limiting relay
9356        // that still ACKed): the genesis anchors, so an anchored-prefix-first fold
9357        // would take v1 and SEED the joiner's floor there — pinning them below the
9358        // head Armada shows, forever. A joiner (floor 0) must bootstrap v3.
9359        let (bed, owner, member) = TestBed::new();
9360        bed.swap_to(&owner);
9361        let community = create_community(&bed.relay, "Skip", bed.relays.clone(), None).await.unwrap();
9362        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9363        let genesis_hash = head_hash_on_relay(&bed.relay, &community, &community.id().0).await.unwrap();
9364
9365        // v2 is crafted but NEVER published; v3 chains to it and is published.
9366        let c2 = serde_json::to_string(&control::CommunityMetadata { name: "Two".into(), ..Default::default() }).unwrap();
9367        let r2 = control::build_edition_rumor(owner.keys.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &c2, 2_000, None);
9368        let (w2, _) = control::seal_control_edition(&r2, &group, &owner.keys, Timestamp::from_secs(2_000)).unwrap();
9369        let (ed2, _) = control::open_control_edition(&w2, &group).unwrap();
9370        let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
9371        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);
9372        let (w3, _) = control::seal_control_edition(&r3, &group, &owner.keys, Timestamp::from_secs(3_000)).unwrap();
9373        bed.relay.publish(&w3, &community.relays).await.unwrap();
9374
9375        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
9376        let bundle_json = serde_json::to_string(&bundle).unwrap();
9377        bed.swap_to(&member);
9378        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
9379        assert_eq!(joined.name, "Three", "the joiner bootstraps the highest signed head, not the anchored stale prefix");
9380        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
9381        let head = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap();
9382        assert!(head.is_some_and(|(v, _)| v == 3), "the seeded floor is the bootstrap head");
9383    }
9384
9385    #[tokio::test]
9386    async fn a_losing_same_version_fork_cannot_replace_the_held_floor() {
9387        // The refusal half of fork convergence: a relay withholding OUR committed
9388        // floor edition while serving only a same-version fork with a HIGHER inner
9389        // id must be treated as withholding — held state and floor unchanged.
9390        let (_tmp, _guard, owner) = init_test_db();
9391        let relay = MemoryRelay::new();
9392        let community = create_community(&relay, "Fork2", vec!["wss://good".into()], None).await.unwrap();
9393        let session = SessionGuard::capture();
9394        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
9395        let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();
9396
9397        publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
9398        let ours = follow_control(&relay, &community, &session).await.unwrap().expect("ours adopted");
9399        assert_eq!(ours.name, "Ours");
9400        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9401        let held_before = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
9402        let our_inner = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap().unwrap();
9403
9404        // Grind the fork to LOSE the tiebreak (higher inner id), then serve it —
9405        // with the genesis but WITHOUT our v2 — from a withholding relay.
9406        let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
9407        let content = serde_json::to_string(&meta).unwrap();
9408        let mut ts = 5_000u64;
9409        let fork_wrap = loop {
9410            let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
9411            if rumor.id.unwrap().to_bytes() > our_inner {
9412                break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
9413            }
9414            ts += 1;
9415        };
9416        inject_stale_prefix(&relay, &community, 1, "wss://stale").await; // genesis only
9417        relay.inject(&fork_wrap, &["wss://stale".to_string()]);
9418        let mut stale_view = ours.clone();
9419        stale_view.relays = vec!["wss://stale".into()];
9420
9421        assert!(
9422            follow_control(&relay, &stale_view, &session).await.unwrap().is_none(),
9423            "a losing fork served without our floor edition changes nothing"
9424        );
9425        let held_after = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
9426        assert_eq!(held_after, held_before, "the floor row is untouched");
9427        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9428        assert_eq!(held.name, "Ours", "the held state is untouched");
9429    }
9430
9431    #[tokio::test]
9432    async fn follow_control_ignores_a_non_owner_edition() {
9433        // A member holds the community_root, so they CAN seal a control edition —
9434        // but they aren't the owner, so the authority gate drops it (first cut:
9435        // owner-only). The rogue channel must never appear.
9436        let (_tmp, _guard, _owner) = init_test_db();
9437        let relay = MemoryRelay::new();
9438        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
9439        let rogue = Keys::generate();
9440        let rogue_id = ChannelId([0x99; 32]);
9441        publish_channel_edition(&relay, &community, &rogue, &rogue_id, "backdoor", false, 1, false).await;
9442
9443        let session = SessionGuard::capture();
9444        assert!(
9445            follow_control(&relay, &community, &session).await.unwrap().is_none(),
9446            "a non-owner control edition is not folded"
9447        );
9448    }
9449
9450    #[tokio::test]
9451    async fn follow_control_records_a_new_private_channel_keyless_and_unreadable() {
9452        // A Private channel's key rides the rekey plane, not the control edition —
9453        // control-follow records it KEYLESS (epoch 0, the rekey-scan cursor), and
9454        // every read/send path refuses it until the key lands (never the root plane).
9455        let (_tmp, _guard, owner) = init_test_db();
9456        let relay = MemoryRelay::new();
9457        let community = create_community(&relay, "Priv", vec!["wss://r".into()], None).await.unwrap();
9458        let priv_id = ChannelId([0x33; 32]);
9459        publish_channel_edition(&relay, &community, &owner, &priv_id, "mods", true, 1, false).await;
9460
9461        let session = SessionGuard::capture();
9462        let updated = follow_control(&relay, &community, &session)
9463            .await
9464            .unwrap()
9465            .expect("the keyless record is a change");
9466        let ch = updated.channel(&priv_id).expect("the private channel is recorded");
9467        assert!(ch.private && ch.key.is_none(), "recorded keyless");
9468        assert_eq!(ch.epoch, Epoch(0), "epoch 0 = the root generation (scan cursor)");
9469        assert!(updated.channel_read_coords(ch).is_empty(), "unreadable until keyed");
9470        assert!(
9471            fetch_channel(&relay, &updated, &priv_id, 50).await.unwrap().is_empty(),
9472            "a keyless fetch returns empty (and never queries the root plane)"
9473        );
9474        assert!(
9475            send_message(&relay, &updated, &priv_id, "nope").await.is_err(),
9476            "a keyless send refuses"
9477        );
9478        // The keyless record round-trips (the stored placeholder never surfaces
9479        // as a real key).
9480        let reloaded = crate::db::community::load_community_v2(updated.id()).unwrap().unwrap();
9481        let rch = reloaded.channel(&priv_id).unwrap();
9482        assert!(rch.private && rch.key.is_none() && rch.epoch == Epoch(0), "keyless survives reload");
9483        // And a bundle minted while keyless never carries the placeholder — a
9484        // MEMBER audience, so it's the keyless filter proving it (the link
9485        // filter would drop the channel for the weaker reason).
9486        let bundle = bundle_of(&reloaded, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
9487        assert!(
9488            !bundle.channels.iter().any(|c| c.id == crate::simd::hex::bytes_to_hex_32(&priv_id.0)),
9489            "an ungrantable keyless channel stays out of invite bundles"
9490        );
9491    }
9492
9493    #[tokio::test]
9494    async fn a_link_bundle_never_carries_a_private_channel_key() {
9495        // A link's audience holds no Role by construction (CORD-05), so a HELD
9496        // private key must never ride a link bundle — anyone with the URL would
9497        // get the channel. A member bundle carries it; a link bundle only the
9498        // public channels.
9499        let (_tmp, _guard, _owner) = init_test_db();
9500        let relay = MemoryRelay::new();
9501        let community = create_community(&relay, "Leak", vec!["wss://r".into()], None).await.unwrap();
9502        create_private_channel(&relay, &community, "mods").await.unwrap();
9503        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9504        let priv_hex = held
9505            .channels
9506            .iter()
9507            .find(|c| c.private)
9508            .map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0))
9509            .expect("the private channel is held WITH its key");
9510
9511        let link = bundle_of(&held, BundleAudience::Link, None, None, None);
9512        assert!(
9513            !link.channels.iter().any(|c| c.id == priv_hex),
9514            "a held private key must never ride a link bundle"
9515        );
9516        assert!(
9517            link.channels.iter().any(|c| c.id != priv_hex),
9518            "the public channels still ride it"
9519        );
9520
9521        // A member bundle grants it only to the ENTITLED. An unrelated npub holds
9522        // no scoped role, so it gets nothing; the creator (granted the companion
9523        // access role at create) gets the key.
9524        let stranger = bundle_of(&held, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
9525        assert!(
9526            !stranger.channels.iter().any(|c| c.id == priv_hex),
9527            "an unentitled member gets no private key"
9528        );
9529        let mine = bundle_of(&held, BundleAudience::Member(me_pk().unwrap()), None, None, None);
9530        assert!(
9531            mine.channels.iter().any(|c| c.id == priv_hex),
9532            "the creator is entitled via the companion access role"
9533        );
9534    }
9535
9536    #[tokio::test]
9537    async fn a_private_channel_mints_its_access_role_and_entitlement_follows_the_grant() {
9538        // CORD-03/04: the roles scoped to a channel ARE its access list. Proven
9539        // against a NON-owner so the owner-is-always-entitled rule can't carry it.
9540        let (_tmp, _guard, _owner) = init_test_db();
9541        let relay = MemoryRelay::new();
9542        let community = create_community(&relay, "Scoped", vec!["wss://r".into()], None).await.unwrap();
9543        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
9544        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9545        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9546
9547        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
9548        let access = roster.channel_roles(&chan_hex);
9549        assert_eq!(access.len(), 1, "the channel minted exactly one access role");
9550        assert!(
9551            access[0].permissions == crate::community::roles::Permissions::empty(),
9552            "the access role confers READ access (key possession), never authority"
9553        );
9554        assert_eq!(access[0].name, "mods", "named for its channel");
9555
9556        // A stranger holds no scoped role: unentitled, and no key rides their bundle.
9557        let stranger = Keys::generate().public_key();
9558        let owner_hex = community.owner().unwrap().to_hex();
9559        assert!(!roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]));
9560
9561        // Granting the access role entitles them; revoking un-entitles them. Both
9562        // proven through the roster, which is what routes keys.
9563        let role_id = access[0].role_id.clone();
9564        assert!(
9565            roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, std::slice::from_ref(&role_id), &[]),
9566            "the grant overlay entitles before the fold catches up"
9567        );
9568
9569        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9570        grant_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
9571        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
9572        assert!(
9573            after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
9574            "the grant landed in the local roster (the fold runs later)"
9575        );
9576        let vend = bundle_of(&held, BundleAudience::Member(stranger), None, None, None);
9577        assert!(
9578            vend.channels.iter().any(|c| c.id == chan_hex),
9579            "a now-entitled member's bundle carries the channel key"
9580        );
9581
9582        revoke_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
9583        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
9584        assert!(
9585            !after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
9586            "the revoke dropped the access role"
9587        );
9588        let rotated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9589        assert_eq!(
9590            rotated.channel(&priv_id).unwrap().epoch,
9591            Epoch(2),
9592            "the revoke rotated the channel — a removal that doesn't rekey severs nobody"
9593        );
9594
9595        // The access summary a bot reads back: roles, holders, and key state.
9596        let access = crate::VectorCore.channel_access(&cid_hex, &chan_hex).unwrap();
9597        assert_eq!(access["private"], true);
9598        assert_eq!(access["readable"], true, "we minted it, so we hold its key");
9599        assert_eq!(access["roles"].as_array().unwrap().len(), 1, "one access role");
9600        let holders = access["members"].as_array().unwrap();
9601        let me_npub = {
9602            use nostr_sdk::prelude::ToBech32;
9603            me_pk().unwrap().to_bech32().unwrap()
9604        };
9605        assert_eq!(holders.len(), 1, "only the creator holds it — the revoked member is gone");
9606        assert_eq!(holders[0], serde_json::json!(me_npub), "and that holder is the creator");
9607    }
9608
9609    #[tokio::test]
9610    async fn a_vended_key_parks_until_the_fold_proves_the_grant_then_adopts() {
9611        // JSKitty's race: the vend can land BEFORE the control fold that proves
9612        // the grant. It must park quietly (a lagging fold is not an anomaly) and
9613        // be adopted on the re-judge once the roster catches up.
9614        let (bed, owner, member) = TestBed::new();
9615        bed.swap_to(&owner);
9616        let community = create_community(&bed.relay, "Vend", bed.relays.clone(), None).await.unwrap();
9617        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
9618        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9619        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9620        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9621        let real_key = held.channel(&priv_id).unwrap().key.unwrap();
9622        let owner_hex = community.owner().unwrap().to_hex();
9623
9624        // Judge as the MEMBER — the owner is always entitled, so only a non-owner
9625        // can exercise the grant rule at all.
9626        bed.swap_to(&member);
9627        let me = member.keys.public_key().to_hex();
9628        // Their fold has the channel (control-follow records it keyless) but not
9629        // yet the grant that entitles them.
9630        let mut member_view = held.clone();
9631        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9632            c.key = None;
9633            c.epoch = Epoch(0);
9634        }
9635
9636        // Ungranted → PARK, never refuse: this is exactly the "not synced enough
9637        // to judge" case, and it must stay quiet and retryable.
9638        let empty = crate::community::roles::CommunityRoles::default();
9639        assert!(matches!(
9640            judge_channel_key_vend(&member_view, &empty, &priv_id, Epoch(1), &owner_hex),
9641            VendVerdict::Park(_)
9642        ));
9643
9644        // A channel our fold says is PUBLIC never heals — that's a spoof shape.
9645        let mut public_view = member_view.clone();
9646        if let Some(c) = public_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9647            c.private = false;
9648        }
9649        assert!(matches!(
9650            judge_channel_key_vend(&public_view, &empty, &priv_id, Epoch(1), &owner_hex),
9651            VendVerdict::Refuse(_)
9652        ));
9653
9654        // An unknown channel parks (our fold may simply be behind), never refuses.
9655        assert!(matches!(
9656            judge_channel_key_vend(&member_view, &empty, &ChannelId([0x77; 32]), Epoch(1), &owner_hex),
9657            VendVerdict::Park(_)
9658        ));
9659
9660        // Park the vend, then re-judge with a roster that still lacks our grant:
9661        // it must SURVIVE, not be discarded.
9662        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
9663        crate::db::community::set_community_roles(&cid_hex, &empty, 0).unwrap();
9664        crate::db::community::save_community_v2(&member_view).unwrap();
9665        let session = SessionGuard::capture();
9666        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9667        assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "unprovable vend adopts nothing");
9668        assert_eq!(
9669            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
9670            1,
9671            "and stays parked for the next fold"
9672        );
9673
9674        // The fold catches up: our grant lands, so the same vend now adopts.
9675        let access = crate::community::roles::Role {
9676            role_id: "44".repeat(32),
9677            name: "mods".into(),
9678            position: u32::MAX - 1,
9679            permissions: crate::community::roles::Permissions::empty(),
9680            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
9681            color: 0,
9682        };
9683        let folded = crate::community::roles::CommunityRoles {
9684            grants: vec![crate::community::roles::MemberGrant { member: me.clone(), role_ids: vec![access.role_id.clone()] }],
9685            roles: vec![access],
9686        };
9687        crate::db::community::set_community_roles(&cid_hex, &folded, 1).unwrap();
9688        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9689        let adopted = absorb_parked_channel_keys(&reloaded, &session);
9690        assert_eq!(adopted.len(), 1, "the re-judge adopts once the grant folds");
9691
9692        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9693        let ch = after.channel(&priv_id).unwrap();
9694        assert_eq!(ch.key, Some(real_key), "adopted the vended key");
9695        assert_eq!(ch.epoch, Epoch(1));
9696        assert!(
9697            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
9698            "and the park is discharged"
9699        );
9700    }
9701
9702    #[tokio::test]
9703    async fn a_vend_at_epoch_zero_is_adopted_onto_a_keyless_channel() {
9704        // Live cross-client finding: a peer that mints born-private channels at
9705        // epoch 0 vends epoch 0, which collides with our keyless cursor (also 0).
9706        // The monotonic guard (`new > current`) would refuse the only key we are
9707        // ever offered, and refuse it SILENTLY. First delivery is not a rotation.
9708        let (bed, owner, member) = TestBed::new();
9709        bed.swap_to(&owner);
9710        let community = create_community(&bed.relay, "EpochZero", bed.relays.clone(), None).await.unwrap();
9711        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
9712        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9713        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9714        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9715        let vended = [0x5a; 32];
9716        let owner_hex = community.owner().unwrap().to_hex();
9717
9718        bed.swap_to(&member);
9719        // The member's view: channel known, keyless, parked at the epoch-0 cursor.
9720        let mut member_view = held.clone();
9721        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9722            c.key = None;
9723            c.epoch = Epoch(0);
9724        }
9725        crate::db::community::save_community_v2(&member_view).unwrap();
9726
9727        // Entitle them, then park a vend AT EPOCH 0 (what the peer actually sends).
9728        let access = crate::community::roles::Role {
9729            role_id: "77".repeat(32),
9730            name: "mods".into(),
9731            position: u32::MAX - 1,
9732            permissions: crate::community::roles::Permissions::empty(),
9733            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
9734            color: 0,
9735        };
9736        let roster = crate::community::roles::CommunityRoles {
9737            grants: vec![crate::community::roles::MemberGrant {
9738                member: member.keys.public_key().to_hex(),
9739                role_ids: vec![access.role_id.clone()],
9740            }],
9741            roles: vec![access],
9742        };
9743        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
9744        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &vended, &owner_hex).unwrap();
9745
9746        let session = SessionGuard::capture();
9747        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9748        let adopted = absorb_parked_channel_keys(&reloaded, &session);
9749        assert_eq!(adopted.len(), 1, "an epoch-0 vend onto a keyless channel is adopted");
9750
9751        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9752        let ch = after.channel(&priv_id).unwrap();
9753        assert_eq!(ch.key, Some(vended), "the key actually landed on the row");
9754        assert_eq!(ch.epoch, Epoch(0), "at the epoch the vendor named");
9755        assert!(
9756            !after.channel_read_coords(ch).is_empty(),
9757            "and the channel is readable — the whole point"
9758        );
9759        assert!(
9760            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
9761            "the park is discharged"
9762        );
9763    }
9764
9765    #[tokio::test]
9766    async fn a_wildly_ahead_vend_epoch_is_refused_not_seated() {
9767        // The channel head is MONOTONIC, so over-advancing it can never be walked
9768        // back: every genuine rotation afterwards lands at head+1, reads as stale,
9769        // and the channel dies for us with no heal path at all. An entitled
9770        // insider vending a garbage key costs isolation (accepted); one vending a
9771        // garbage EPOCH would cost the channel permanently, which is not.
9772        let (bed, owner, member) = TestBed::new();
9773        bed.swap_to(&owner);
9774        let community = create_community(&bed.relay, "Poison", bed.relays.clone(), None).await.unwrap();
9775        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
9776        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9777        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9778        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9779        let owner_hex = community.owner().unwrap().to_hex();
9780
9781        bed.swap_to(&member);
9782        let mut member_view = held.clone();
9783        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9784            c.key = None;
9785            c.epoch = Epoch(0);
9786        }
9787        crate::db::community::save_community_v2(&member_view).unwrap();
9788        let access = crate::community::roles::Role {
9789            role_id: "99".repeat(32),
9790            name: "mods".into(),
9791            position: u32::MAX - 1,
9792            permissions: crate::community::roles::Permissions::empty(),
9793            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
9794            color: 0,
9795        };
9796        let roster = crate::community::roles::CommunityRoles {
9797            grants: vec![crate::community::roles::MemberGrant {
9798                member: member.keys.public_key().to_hex(),
9799                role_ids: vec![access.role_id.clone()],
9800            }],
9801            roles: vec![access],
9802        };
9803        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
9804        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9805
9806        // Everything else about this vend is valid — only the epoch is absurd.
9807        assert!(matches!(
9808            judge_channel_key_vend(&reloaded, &roster, &priv_id, Epoch(1 << 40), &owner_hex),
9809            VendVerdict::Refuse(_)
9810        ));
9811        // REFUSED, not parked: a row nothing can ever discharge is its own leak.
9812        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1 << 40, &[0xEE; 32], &owner_hex).unwrap();
9813        let session = SessionGuard::capture();
9814        assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "a poison epoch adopts nothing");
9815        assert!(
9816            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
9817            "and the row is discharged rather than parked forever"
9818        );
9819        // The head is untouched, so the genuine vend still lands afterwards.
9820        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9821        assert_eq!(after.channel(&priv_id).unwrap().epoch, Epoch(0), "head never advanced");
9822        assert!(matches!(
9823            judge_channel_key_vend(&after, &roster, &priv_id, Epoch(1), &owner_hex),
9824            VendVerdict::Accept
9825        ));
9826    }
9827
9828    #[tokio::test]
9829    async fn a_channel_rename_lands_locally_without_waiting_for_the_fold() {
9830        // The fold is the authority but runs later, so publishing alone leaves the
9831        // edit reading back stale — it looks like the rename silently failed.
9832        let (_tmp, _guard, _owner) = init_test_db();
9833        let relay = MemoryRelay::new();
9834        let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
9835        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
9836        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9837        let key_before = held.channel(&priv_id).unwrap().key;
9838
9839        let mut meta = held.channel(&priv_id).unwrap().metadata();
9840        meta.name = "staff".into();
9841        edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();
9842
9843        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9844        let ch = after.channel(&priv_id).unwrap();
9845        assert_eq!(ch.name, "staff", "the rename is visible immediately");
9846        assert!(ch.private, "and privacy survives the edit");
9847        assert_eq!(ch.key, key_before, "as does the key — a rename is not a rotation");
9848    }
9849
9850    #[tokio::test]
9851    async fn a_squatted_park_row_cannot_suppress_the_genuine_vend() {
9852        // Parking is reachable by ANY npub that can gift-wrap us — the bundle
9853        // self-certifies and its inputs are public for a public community. With a
9854        // single slot per channel, a stranger could pre-park and the admin's real
9855        // vend would be a silent no-op, leaving the member keyless with no retry.
9856        // Candidates + judge-them-all is what closes that.
9857        let (bed, owner, member) = TestBed::new();
9858        bed.swap_to(&owner);
9859        let community = create_community(&bed.relay, "Squat", bed.relays.clone(), None).await.unwrap();
9860        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
9861        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9862        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
9863        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9864        let real_key = held.channel(&priv_id).unwrap().key.unwrap();
9865        let owner_hex = community.owner().unwrap().to_hex();
9866
9867        bed.swap_to(&member);
9868        let mut member_view = held.clone();
9869        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
9870            c.key = None;
9871            c.epoch = Epoch(0);
9872        }
9873        crate::db::community::save_community_v2(&member_view).unwrap();
9874        let access = crate::community::roles::Role {
9875            role_id: "aa".repeat(32),
9876            name: "mods".into(),
9877            position: u32::MAX - 1,
9878            permissions: crate::community::roles::Permissions::empty(),
9879            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
9880            color: 0,
9881        };
9882        let roster = crate::community::roles::CommunityRoles {
9883            grants: vec![crate::community::roles::MemberGrant {
9884                member: member.keys.public_key().to_hex(),
9885                role_ids: vec![access.role_id.clone()],
9886            }],
9887            roles: vec![access],
9888        };
9889        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
9890
9891        // A stranger squats FIRST, at a higher epoch than the genuine vend.
9892        let stranger = Keys::generate().public_key().to_hex();
9893        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 9, &[0xBA; 32], &stranger).unwrap();
9894        // The admin's real vend arrives after, at the true epoch.
9895        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
9896        assert_eq!(
9897            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
9898            2,
9899            "the squatter never displaces the genuine vend — both are candidates"
9900        );
9901
9902        let session = SessionGuard::capture();
9903        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9904        let adopted = absorb_parked_channel_keys(&reloaded, &session);
9905        assert_eq!(adopted.len(), 1, "exactly one adoption");
9906
9907        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9908        let ch = after.channel(&priv_id).unwrap();
9909        assert_eq!(ch.key, Some(real_key), "the OWNER's key won, not the squatter's");
9910        assert_eq!(ch.epoch, Epoch(1), "at the genuine epoch");
9911        assert!(
9912            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
9913            "and every candidate for the channel is discharged"
9914        );
9915    }
9916
9917    #[tokio::test]
9918    async fn revoking_without_a_folded_access_role_refuses_instead_of_evicting_everyone() {
9919        // With no access role folded, the retained-set filter matches NOBODY, so
9920        // the rotation would cut off every legitimately entitled member while the
9921        // Grant it published revoked nothing. Reachable with no attacker: the
9922        // channel was made on another admin's client and its role hasn't folded.
9923        let (_tmp, _guard, _owner) = init_test_db();
9924        let relay = MemoryRelay::new();
9925        let community = create_community(&relay, "NoRole", vec!["wss://r".into()], None).await.unwrap();
9926        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
9927        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
9928        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9929        let before = held.channel(&priv_id).unwrap().epoch;
9930
9931        // Neither the cache nor the plane serves the access role — a withholding
9932        // relay, or a channel minted on another admin's client. (Wiping only the
9933        // cache is no longer enough: the revoke re-fetches authority first.)
9934        crate::db::community::set_community_roles(&cid_hex, &crate::community::roles::CommunityRoles::default(), 0).unwrap();
9935        let mut blind = held.clone();
9936        blind.relays = vec!["wss://empty".into()];
9937        let err = revoke_channel_access(&relay, &blind, &priv_id, &Keys::generate().public_key())
9938            .await
9939            .unwrap_err();
9940        assert!(err.contains("has not folded"), "refuses with a retryable reason: {err}");
9941
9942        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
9943        assert_eq!(after.channel(&priv_id).unwrap().epoch, before, "and rotates nothing");
9944    }
9945
9946    // ── Live rekey-follow ────────────────────────────────────────────────────
9947
9948    /// Publish an owner-grammar base rotation (Refounding) delivering `new_root`
9949    /// to each recipient. `rotator` is the seal signer (owner for a legit rotation,
9950    /// a stranger for the authority test); `prev_key` is the root it claims to
9951    /// extend (mismatch → a fork).
9952    async fn publish_base_rotation(
9953        relay: &MemoryRelay,
9954        community: &CommunityV2,
9955        rotator: &Keys,
9956        recipients: &[PublicKey],
9957        new_root: &[u8; 32],
9958        prev_key: &[u8; 32],
9959    ) {
9960        let new_epoch = Epoch(community.root_epoch.0 + 1);
9961        let prev_epoch = community.root_epoch;
9962        let prev_commit = super::super::derive::epoch_key_commitment(prev_epoch, prev_key);
9963        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
9964        let blobs: Vec<_> = recipients
9965            .iter()
9966            .map(|r| rekey::build_blob_local(rotator.secret_key(), &rotator.public_key().to_bytes(), r, RekeyScope::Root, new_epoch, new_root).unwrap())
9967            .collect();
9968        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();
9969        for e in &events {
9970            relay.publish(e, &community.relays).await.unwrap();
9971        }
9972    }
9973
9974    /// Attach a Private channel (key + epoch) to a held community and persist it.
9975    fn add_private_channel(community: &mut CommunityV2, id: ChannelId, key: [u8; 32], epoch: Epoch) {
9976        community.channels.push(ChannelV2 { id, name: "mods".into(), private: true, key: Some(key), epoch, voice: None, meta_custom: None, meta_extra: Default::default() });
9977        crate::db::community::save_community_v2(community).unwrap();
9978    }
9979
9980    #[tokio::test]
9981    async fn follow_rekeys_is_a_noop_without_rotations() {
9982        let (_tmp, _guard, _owner) = init_test_db();
9983        let relay = MemoryRelay::new();
9984        let community = create_community(&relay, "Still", vec!["wss://r".into()], None).await.unwrap();
9985        let session = SessionGuard::capture();
9986        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
9987        assert!(follow.updated.is_none() && !follow.self_removed, "no rotation → nothing to adopt");
9988    }
9989
9990    #[tokio::test]
9991    async fn follow_rekeys_adopts_an_owner_base_rotation() {
9992        let (_tmp, _guard, owner) = init_test_db();
9993        let relay = MemoryRelay::new();
9994        let community = create_community(&relay, "Refound", vec!["wss://r".into()], None).await.unwrap();
9995        let new_root = [0xB1; 32];
9996        // Owner rotates the base to epoch 1, delivering the new root to me.
9997        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
9998
9999        let session = SessionGuard::capture();
10000        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
10001        assert_eq!(updated.root_epoch, Epoch(1), "advanced one epoch");
10002        assert_eq!(updated.community_root, new_root, "adopted the fresh root");
10003        // The public channel now reads under the NEW root/epoch (its address moved).
10004        let addr = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
10005        let general = updated.channels[0].id;
10006        let new_chat = channel_group_key(&new_root, &general, Epoch(1)).pk();
10007        assert!(addr.contains(&new_chat), "the public channel re-addresses under the new root");
10008    }
10009
10010    #[tokio::test]
10011    async fn follow_rekeys_adopts_an_owner_private_channel_rotation() {
10012        let (_tmp, _guard, owner) = init_test_db();
10013        let relay = MemoryRelay::new();
10014        let mut community = create_community(&relay, "PrivRot", vec!["wss://r".into()], None).await.unwrap();
10015        let priv_id = ChannelId([0x33; 32]);
10016        add_private_channel(&mut community, priv_id, [0x44; 32], Epoch(0));
10017
10018        // Owner rotates the private channel to epoch 1 with a fresh key, delivered to me.
10019        let new_key = [0x55; 32];
10020        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &[0x44; 32]);
10021        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
10022        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();
10023        let events = rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &prev_commit, &[blob], 2_000, None).unwrap();
10024        for e in &events {
10025            relay.publish(e, &community.relays).await.unwrap();
10026        }
10027
10028        let session = SessionGuard::capture();
10029        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
10030        let ch = updated.channel(&priv_id).unwrap();
10031        assert_eq!(ch.epoch, Epoch(1), "the private channel advanced an epoch");
10032        assert_eq!(ch.key, Some(new_key), "adopted the fresh channel key");
10033        assert_eq!(updated.root_epoch, Epoch(0), "the base is untouched by a channel rotation");
10034    }
10035
10036    #[tokio::test]
10037    async fn follow_rekeys_ignores_a_non_owner_rotation() {
10038        // A member holds the community_root, so they can derive the rekey group key
10039        // and mint a rotation — but they aren't the owner, so it's not adopted.
10040        let (_tmp, _guard, _owner) = init_test_db();
10041        let relay = MemoryRelay::new();
10042        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
10043        let rogue = Keys::generate();
10044        publish_base_rotation(&relay, &community, &rogue, &[rogue.public_key()], &[0xEE; 32], &community.community_root).await;
10045
10046        let session = SessionGuard::capture();
10047        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
10048        assert!(follow.updated.is_none() && !follow.self_removed, "a non-owner rotation is not adopted");
10049    }
10050
10051    #[tokio::test]
10052    async fn follow_rekeys_ignores_a_rotation_off_the_wrong_prev() {
10053        // A rotation whose prevcommit doesn't match the key I hold is a fork, not an
10054        // extension — never adopted (would splice me onto an unrelated chain).
10055        let (_tmp, _guard, owner) = init_test_db();
10056        let relay = MemoryRelay::new();
10057        let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
10058        // prev_key ≠ the real community_root → the continuity check reads Fork.
10059        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &[0xB2; 32], &[0x00; 32]).await;
10060
10061        let session = SessionGuard::capture();
10062        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
10063        assert!(follow.updated.is_none(), "a fork off the wrong prev is not adopted");
10064    }
10065
10066    #[tokio::test]
10067    async fn follow_rekeys_holds_on_an_incomplete_rotation() {
10068        // A 2-chunk rotation with only chunk 1 present can never conclude — not an
10069        // adoption, and crucially NOT a removal (a missing chunk might carry my blob).
10070        let (_tmp, _guard, owner) = init_test_db();
10071        let relay = MemoryRelay::new();
10072        let community = create_community(&relay, "Partial", vec!["wss://r".into()], None).await.unwrap();
10073        let new_epoch = Epoch(1);
10074        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
10075        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
10076        // Chunk 1 of a declared 2, carrying someone else's blob (not mine).
10077        let other = Keys::generate();
10078        let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &other.public_key(), RekeyScope::Root, new_epoch, &[0xB3; 32]).unwrap();
10079        let rumor = rekey::build_rekey_rumor(owner.public_key(), RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[blob], 1, 2, 2_000, None).unwrap();
10080        let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &owner, Timestamp::from_secs(2_000)).unwrap();
10081        relay.publish(&wrap, &community.relays).await.unwrap();
10082
10083        let session = SessionGuard::capture();
10084        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
10085        assert!(follow.updated.is_none() && !follow.self_removed, "an incomplete rotation neither adopts nor removes");
10086    }
10087
10088    #[tokio::test]
10089    async fn follow_rekeys_removes_a_member_dropped_by_a_base_rotation() {
10090        // Realistic two-actor removal: the owner Refounds the base and delivers the
10091        // new root to a THIRD party, not the member — a complete rotation with no
10092        // blob for the member is a removal.
10093        let (bed, owner, member) = TestBed::new();
10094        bed.swap_to(&owner);
10095        let community = create_community(&bed.relay, "Evict", bed.relays.clone(), None).await.unwrap();
10096        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
10097
10098        bed.swap_to(&member);
10099        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
10100        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
10101
10102        // Owner rotates, delivering only to a stranger (the member is dropped).
10103        bed.swap_to(&owner);
10104        let stranger = Keys::generate();
10105        publish_base_rotation(&bed.relay, &community, &owner.keys, &[stranger.public_key()], &[0xC4; 32], &community.community_root).await;
10106
10107        // The member's follow concludes removal (a complete rotation without their blob).
10108        bed.swap_to(&member);
10109        let session = SessionGuard::capture();
10110        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
10111        assert!(follow.self_removed, "a complete base rotation dropping the member removes them");
10112        assert!(follow.updated.is_none(), "a removed member adopts nothing");
10113    }
10114
10115    #[tokio::test]
10116    async fn follow_rekeys_finds_a_channel_rekey_under_an_archived_prior_root() {
10117        // PROTO-B2 regression: a Refounding's channel rekeys ride the PRIOR root
10118        // (CORD-06 §3). A follower who adopted the BASE first (the live window:
10119        // the base crate landed and was walked before the channel crates) must
10120        // still find them — the lookup fans across the archived roots, not just
10121        // the current one.
10122        let (_tmp, _guard, owner) = init_test_db();
10123        let relay = MemoryRelay::new();
10124        let mut community = create_community(&relay, "Strand", vec!["wss://r".into()], None).await.unwrap();
10125        let root0 = community.community_root;
10126        let priv_id = ChannelId([0x33; 32]);
10127        let key1 = [0x44; 32];
10128        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10129
10130        // The refounder's channel rekey (1 → 2), sealed + addressed under the PRIOR
10131        // root (root0), delivering the fresh key to me.
10132        let key2 = [0x55; 32];
10133        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10134        let group = channel_rekey_group_key(&root0, &priv_id, Epoch(2));
10135        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();
10136        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() {
10137            relay.publish(&e, &community.relays).await.unwrap();
10138        }
10139
10140        // Simulate the base having ALREADY advanced (the stranding order): the head
10141        // moved to a fresh root while root0 sits in the epoch-key archive (where
10142        // genesis put it).
10143        community.community_root = [0xB7; 32];
10144        community.root_epoch = Epoch(1);
10145        crate::db::community::save_community_v2(&community).unwrap();
10146
10147        let session = SessionGuard::capture();
10148        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the prior-root crate is found");
10149        let ch = updated.channel(&priv_id).unwrap();
10150        assert_eq!(ch.epoch, Epoch(2), "the channel advanced despite the moved base");
10151        assert_eq!(ch.key, Some(key2), "adopted the key delivered under the prior root");
10152    }
10153
10154    #[tokio::test]
10155    async fn follow_rekeys_keyless_cursor_walks_past_an_excluding_rotation_then_adopts() {
10156        // A keyless private channel (announced by vsk-2, key not yet held) has no
10157        // chain, so its epoch is a scan cursor: a complete rotation that excludes
10158        // us advances the cursor (never a removal — we were never in); a later
10159        // rotation that includes us is the entry point.
10160        let (_tmp, _guard, owner) = init_test_db();
10161        let relay = MemoryRelay::new();
10162        let mut community = create_community(&relay, "Cursor", vec!["wss://r".into()], None).await.unwrap();
10163        let priv_id = ChannelId([0x66; 32]);
10164        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() });
10165        crate::db::community::save_community_v2(&community).unwrap();
10166        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10167        assert!(community.channel(&priv_id).unwrap().key.is_none(), "keyless survives the round-trip");
10168
10169        // Epoch 1: the creation delivery went to a stranger only (pre-dates us).
10170        let stranger = Keys::generate();
10171        let key1 = [0x71; 32];
10172        let pc1 = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
10173        let g1 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
10174        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();
10175        for e in rekey::build_rekey_chunks_local(&owner, &g1, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &pc1, &[b1], 2_000, None).unwrap() {
10176            relay.publish(&e, &community.relays).await.unwrap();
10177        }
10178        // Epoch 2: a later rotation includes ME (e.g. a removal-forced re-mint whose
10179        // recipient set is the CURRENT members).
10180        let key2 = [0x72; 32];
10181        let pc2 = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10182        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10183        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();
10184        for e in rekey::build_rekey_chunks_local(&owner, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc2, &[b2], 2_100, None).unwrap() {
10185            relay.publish(&e, &community.relays).await.unwrap();
10186        }
10187
10188        // ONE follow: the cursor walks 0→1 (excluded, still keyless) and 1→2 (my
10189        // blob — adopt), because each real step re-loops.
10190        let session = SessionGuard::capture();
10191        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the walk lands on the included epoch");
10192        let ch = updated.channel(&priv_id).unwrap();
10193        assert_eq!(ch.epoch, Epoch(2), "cursor walked through the excluding epoch to the included one");
10194        assert_eq!(ch.key, Some(key2), "adopted the delivery that includes us");
10195    }
10196
10197    #[tokio::test]
10198    async fn follow_rekeys_honors_an_admin_channel_rotation_but_never_a_strangers() {
10199        // CORD-06 §Authority: a CHANNEL rekey is honored from the owner or a
10200        // MANAGE_CHANNELS holder under the persisted roster — so an admin-run
10201        // rotation keys members up; a mere keyholder's forgery never does.
10202        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10203        let (_tmp, _guard, _owner) = init_test_db();
10204        let relay = MemoryRelay::new();
10205        let mut community = create_community(&relay, "AdminRot", vec!["wss://r".into()], None).await.unwrap();
10206        let priv_id = ChannelId([0x88; 32]);
10207        let key1 = [0x91; 32];
10208        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10209
10210        // Persist a roster granting `admin` the Admin role (MANAGE_CHANNELS ⊂ ADMIN_ALL).
10211        let admin = Keys::generate();
10212        let role = Role::admin("aa".repeat(32));
10213        let roster = CommunityRoles {
10214            roles: vec![role.clone()],
10215            grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
10216        };
10217        seed_roster_with_heads(&community, &roster, 1_000);
10218
10219        // The ADMIN rotates the channel 1 → 2, delivering to me: adopted.
10220        let key2 = [0x92; 32];
10221        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10222        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10223        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
10224        let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10225        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() {
10226            relay.publish(&e, &community.relays).await.unwrap();
10227        }
10228        let session = SessionGuard::capture();
10229        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("an admin rotation is honored");
10230        assert_eq!(updated.channel(&priv_id).unwrap().key, Some(key2), "adopted the admin's key");
10231
10232        // A STRANGER (keyholder, no roster standing) rotates 2 → 3: refused.
10233        let rogue = Keys::generate();
10234        let key3 = [0x93; 32];
10235        let pc3 = super::super::derive::epoch_key_commitment(Epoch(2), &key2);
10236        let g3 = channel_rekey_group_key(&updated.community_root, &priv_id, Epoch(3));
10237        let rb = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(3), &key3).unwrap();
10238        for e in rekey::build_rekey_chunks_local(&rogue, &g3, RekeyScope::Channel(priv_id), Epoch(3), Epoch(2), &pc3, &[rb], 2_100, None).unwrap() {
10239            relay.publish(&e, &updated.relays).await.unwrap();
10240        }
10241        let follow = follow_rekeys(&relay, &updated, &session).await.unwrap();
10242        assert!(follow.updated.is_none(), "a stranger's channel rotation is never adopted");
10243    }
10244
10245    #[tokio::test]
10246    async fn a_non_outranking_admins_rotation_never_concludes_my_removal() {
10247        // CORD-06 §Authority: the Rotator must strictly OUTRANK every removed
10248        // target. An equal-rank bit-holder's complete rotation that skips my blob
10249        // must read Stay (my record survives); the OWNER's reads Removed. Needs a
10250        // two-account bed: the follower must be a NON-owner admin.
10251        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10252        let (bed, owner, member) = TestBed::new();
10253        bed.swap_to(&owner);
10254        let community = create_community(&bed.relay, "Outrank", bed.relays.clone(), None).await.unwrap();
10255
10256        // The MEMBER's device: holds the community + the private channel, with a
10257        // persisted roster granting the member AND a peer the same Admin role.
10258        bed.swap_to(&member);
10259        let mut held = community.clone();
10260        let priv_id = ChannelId([0xAB; 32]);
10261        let key1 = [0xA1; 32];
10262        add_private_channel(&mut held, priv_id, key1, Epoch(1));
10263        let peer = Keys::generate();
10264        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10265        let role = Role::admin("bb".repeat(32));
10266        let roster = CommunityRoles {
10267            roles: vec![role.clone()],
10268            grants: vec![
10269                MemberGrant { member: peer.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
10270                MemberGrant { member: member.keys.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
10271            ],
10272        };
10273        crate::db::community::set_community_roles(&cid_hex, &roster, 1_000).unwrap();
10274
10275        // The equal-rank PEER rotates 1 → 2 delivering only to themselves.
10276        let key2 = [0xA2; 32];
10277        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10278        let g2 = channel_rekey_group_key(&held.community_root, &priv_id, Epoch(2));
10279        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();
10280        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() {
10281            bed.relay.publish(&e, &held.relays).await.unwrap();
10282        }
10283        let session = SessionGuard::capture();
10284        let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
10285        assert!(follow.updated.is_none(), "an equal-rank rotation excluding me is Stay, never my removal");
10286        let reloaded = crate::db::community::load_community_v2(held.id()).unwrap().unwrap();
10287        assert!(reloaded.channel(&priv_id).is_some(), "my channel record survives the peer's rotation");
10288
10289        // The OWNER's rotation excluding me IS a removal (owner outranks everyone).
10290        let key3 = [0xA3; 32];
10291        let stranger = Keys::generate();
10292        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();
10293        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() {
10294            bed.relay.publish(&e, &held.relays).await.unwrap();
10295        }
10296        let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
10297        let updated = follow.updated.expect("the owner's removal folds");
10298        assert!(updated.channel(&priv_id).is_none(), "the owner's exclusion cuts my channel record");
10299    }
10300
10301    #[tokio::test]
10302    async fn converting_a_public_channel_to_private_is_refused() {
10303        // The conversion (CORD-03 §2) is a key rotation this build doesn't mint yet:
10304        // the producer refuses the flag flip, so no reader is left unkeyable.
10305        let (_tmp, _guard, _owner) = init_test_db();
10306        let relay = MemoryRelay::new();
10307        let community = create_community(&relay, "NoConvert", vec!["wss://r".into()], None).await.unwrap();
10308        let general = community.channels[0].id;
10309        let meta = control::ChannelMetadata { name: "general".into(), private: true, voice: None, deleted: None, custom: None, extra: Default::default() };
10310        let err = edit_channel_metadata(&relay, &community, &general, &meta).await.unwrap_err();
10311        assert!(err.contains("not supported"), "conversion is refused at the producer: {err}");
10312        // A rename of the same public channel still works.
10313        let meta = control::ChannelMetadata { name: "lobby".into(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() };
10314        edit_channel_metadata(&relay, &community, &general, &meta).await.unwrap();
10315    }
10316
10317    /// Publish a 13302 (signed by `me`) carrying a leave tombstone for `cid_hex` at
10318    /// `removed_at` — simulating a sibling device having left that community.
10319    async fn publish_remote_tombstone(relay: &MemoryRelay, me: &Keys, relays: &[String], cid_hex: &str, removed_at: u64) {
10320        let doc = super::super::list::CommunityList {
10321            entries: vec![],
10322            tombstones: vec![super::super::list::Tombstone { community_id: cid_hex.to_string(), removed_at, extra: Default::default() }],
10323            extra: Default::default(),
10324        };
10325        let event = super::super::list::build_list_event(me, &doc).unwrap();
10326        relay.publish(&event, relays).await.unwrap();
10327    }
10328
10329    #[tokio::test]
10330    async fn joining_one_community_does_not_resurrect_a_sibling_left_community() {
10331        // W1 (send side): a sibling device left X (a remote tombstone). Joining a
10332        // DIFFERENT community must not re-add X to the 13302 with added_at=now,
10333        // which would silently undo the leave everywhere.
10334        let (_tmp, _guard, me) = init_test_db();
10335        let relay = MemoryRelay::new();
10336        let x = create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
10337        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
10338
10339        // A sibling leaves X: a remote tombstone strictly newer than X's add.
10340        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;
10341
10342        // Now join a different community Y → republish(just_joined = Y).
10343        let y = create_community(&relay, "Y", vec!["wss://r".into()], None).await.unwrap();
10344        republish_community_list(&relay, Some(y.id())).await.unwrap();
10345
10346        // X must still read as LEFT in the published list; Y must be live.
10347        let list = fetch_community_list(&relay, &x.relays).await.unwrap().unwrap();
10348        assert!(!list.is_live(&x_hex), "joining Y did not resurrect the sibling-left X");
10349        assert!(list.is_live(&crate::simd::hex::bytes_to_hex_32(&y.id().0)), "Y is live");
10350    }
10351
10352    #[tokio::test]
10353    async fn sync_tears_down_a_community_a_sibling_left() {
10354        // W1 (receive side): a community still held locally that the synced 13302
10355        // shows tombstoned-and-not-live is torn down, so a leave propagates.
10356        let (_tmp, _guard, me) = init_test_db();
10357        let relay = MemoryRelay::new();
10358        let x = create_community(&relay, "Leaveme", vec!["wss://r".into()], None).await.unwrap();
10359        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
10360        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "held before sync");
10361
10362        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;
10363        sync_community_list(&relay, &x.relays).await.unwrap();
10364        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the sibling's leave tore X down locally");
10365    }
10366
10367    #[tokio::test]
10368    async fn a_rejoined_community_survives_a_stale_tombstone_on_sync() {
10369        // The re-join case must NOT be torn down: a fresh join re-adds live (beating
10370        // the tombstone), so a later sync keeps it.
10371        let (_tmp, _guard, me) = init_test_db();
10372        let relay = MemoryRelay::new();
10373        let x = create_community(&relay, "Rejoin", vec!["wss://r".into()], None).await.unwrap();
10374        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
10375        // A stale tombstone from a prior leave (OLDER than the current hold's re-add).
10376        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, 1).await;
10377        // Re-record the membership (a re-join) → live entry at now >> 1.
10378        republish_community_list(&relay, Some(x.id())).await.unwrap();
10379        sync_community_list(&relay, &x.relays).await.unwrap();
10380        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "a re-joined community is not torn down by a stale tombstone");
10381    }
10382
10383    #[tokio::test]
10384    async fn a_failed_remote_fetch_never_clobbers_the_published_list() {
10385        // W2: a transient fetch failure during republish must not drive the
10386        // replaceable-event write (which would drop other entries / regress seeds).
10387        let (_tmp, _guard, _me) = init_test_db();
10388        let good = MemoryRelay::new();
10389        let community = create_community(&good, "Seeded", vec!["wss://r".into()], None).await.unwrap();
10390        assert!(fetch_community_list(&good, &community.relays).await.unwrap().is_some());
10391
10392        // A transport whose fetch always errors: republish must bail, publishing nothing.
10393        struct FetchErrors;
10394        #[async_trait::async_trait]
10395        impl Transport for FetchErrors {
10396            async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
10397            async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
10398                panic!("republish must NOT publish when the remote fetch failed");
10399            }
10400            async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
10401                Ok(())
10402            }
10403            async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
10404                Err("relay unreachable".to_string())
10405            }
10406        }
10407        // Returns Ok (best-effort) but must not have published (the panic guards it).
10408        republish_community_list(&FetchErrors, Some(community.id())).await.unwrap();
10409    }
10410
10411    #[tokio::test]
10412    async fn a_granted_member_survives_a_refounding_even_with_no_guestbook_join() {
10413        // B1 regression: refound_community's recipient set = memberlist. A member
10414        // the owner GRANTED a role to but who never left a (surviving) Guestbook
10415        // Join — a lurking admin, or one whose Join aged out of the window — must
10416        // still be a rekey recipient, or the Refounding SEVERS them. The folded
10417        // roster's granted members are the consensus-complete backstop.
10418        let (_tmp, _guard, owner) = init_test_db();
10419        let relay = MemoryRelay::new();
10420        let community = create_community(&relay, "Backstop", vec!["wss://r".into()], None).await.unwrap();
10421
10422        // A lurker gets an admin grant but publishes NO Guestbook Join and no chat.
10423        let lurker = Keys::generate();
10424        let rid = "b1".repeat(32);
10425        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
10426        publish_grant(&relay, &community, &owner, &lurker.public_key(), vec![rid.clone()], 1).await;
10427
10428        // memberlist includes the lurker purely via the roster backstop.
10429        let members = memberlist(&relay, &community).await.unwrap();
10430        assert!(members.contains(&lurker.public_key()), "a granted member with no Join is still a member");
10431
10432        // A banned grantee whose grant wasn't stripped is NOT re-admitted.
10433        let banned_grantee = Keys::generate();
10434        publish_grant(&relay, &community, &owner, &banned_grantee.public_key(), vec![rid], 1).await;
10435        set_banlist(&relay, &community, &[banned_grantee.public_key().to_hex()]).await.unwrap();
10436        let members = memberlist(&relay, &community).await.unwrap();
10437        assert!(members.contains(&lurker.public_key()), "the honest grantee still counts");
10438        assert!(!members.contains(&banned_grantee.public_key()), "a banned grantee is not re-admitted by the union");
10439
10440        // And the Refounding actually delivers the new root to the lurker.
10441        let refounded = refound_community(&relay, &community, &[]).await.unwrap();
10442        assert_eq!(refounded.root_epoch, Epoch(1));
10443        let base_group = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
10444        let chunks = fetch_rekey_chunks(&relay, &community.relays, &base_group).await.unwrap();
10445        let rotations = rekey::collect_rotations(&chunks);
10446        let lurker_x = lurker.public_key().to_bytes();
10447        let delivered = rotations.iter().any(|r| {
10448            rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &lurker_x, r.scope, r.new_epoch).is_some()
10449        });
10450        assert!(delivered, "the Refounding delivered the new root to the granted lurker");
10451    }
10452
10453    #[tokio::test]
10454    async fn the_memberlist_pages_past_a_guestbook_flood() {
10455        // The roleless-member half of B1: >500 Guestbook events must not evict an
10456        // honest member's Join from the counted set (an insider can flood throwaway
10457        // Joins to force exactly this). The pager sees them all.
10458        let (_tmp, _guard, _owner) = init_test_db();
10459        let relay = MemoryRelay::new();
10460        let community = create_community(&relay, "GBFlood", vec!["wss://r".into()], None).await.unwrap();
10461        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
10462
10463        // An honest member's Join (oldest), then 600 throwaway Joins on top.
10464        let honest = Keys::generate();
10465        let join = guestbook::build_join_rumor(honest.public_key(), None, 1_000);
10466        let (w, _) = guestbook::seal_guestbook_rumor(&join, &gb, &honest, Timestamp::from_secs(1)).unwrap();
10467        relay.publish(&w, &community.relays).await.unwrap();
10468        for i in 0..600u64 {
10469            let throwaway = Keys::generate();
10470            let j = guestbook::build_join_rumor(throwaway.public_key(), None, 2_000 + i);
10471            let (w, _) = guestbook::seal_guestbook_rumor(&j, &gb, &throwaway, Timestamp::from_secs(2 + i)).unwrap();
10472            relay.publish(&w, &community.relays).await.unwrap();
10473        }
10474
10475        let members = memberlist(&relay, &community).await.unwrap();
10476        assert!(members.contains(&honest.public_key()), "the honest member's aged-out Join is still counted past the flood");
10477    }
10478
10479    #[tokio::test]
10480    async fn a_rekey_plane_flood_cannot_bury_a_genuine_rotation() {
10481        // An insider floods the next-epoch rekey address (community_root-derived,
10482        // so any member can seal there) with >200 junk 3303s to push the owner's
10483        // genuine rotation out of a single fetch window. The paginated fetch must
10484        // still recover it and adopt.
10485        let (_tmp, _guard, owner) = init_test_db();
10486        let relay = MemoryRelay::new();
10487        let community = create_community(&relay, "Flooded", vec!["wss://r".into()], None).await.unwrap();
10488        let new_root = [0xD9; 32];
10489        let new_epoch = Epoch(1);
10490        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
10491
10492        // The GENUINE owner rotation lands first (oldest).
10493        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
10494
10495        // Then a member floods 260 well-formed-but-unauthorized junk chunks ON TOP
10496        // (newer), burying the genuine one past the 200 newest.
10497        let rogue = Keys::generate();
10498        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
10499        for i in 0..260u64 {
10500            let blob = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &rogue.public_key(), RekeyScope::Root, new_epoch, &[0xEE; 32]).unwrap();
10501            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();
10502            let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &rogue, Timestamp::from_secs(3_000 + i)).unwrap();
10503            relay.publish(&wrap, &community.relays).await.unwrap();
10504        }
10505
10506        let session = SessionGuard::capture();
10507        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the genuine rotation is recovered past the flood");
10508        assert_eq!(updated.root_epoch, Epoch(1));
10509        assert_eq!(updated.community_root, new_root, "adopted the owner's root, not a junk one");
10510    }
10511
10512    #[tokio::test]
10513    async fn a_swap_during_create_private_channel_aborts_without_a_write() {
10514        // create_private_channel publishes the key crate, then the channel
10515        // edition, then whole-row-saves. A swap anywhere in that window must
10516        // abort — never mint a channel into the swapped-in account, and never
10517        // leave a half-published key crate adopted locally.
10518        let (bed, owner, _member) = TestBed::new();
10519        bed.swap_to(&owner);
10520        let community = create_community(&bed.relay, "SwapCreate", bed.relays.clone(), None).await.unwrap();
10521        let before = crate::db::community::load_community_v2(community.id()).unwrap().unwrap().channels.len();
10522
10523        // The key-crate publish inside create bumps the generation mid-flight.
10524        let swap_relay = SwapMidPublish { inner: MemoryRelay::new() };
10525        let err = create_private_channel(&swap_relay, &community, "ghost").await.unwrap_err();
10526        assert!(err.contains("account changed"), "a swap mid-create aborts: {err}");
10527        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10528        assert_eq!(after.channels.len(), before, "no channel row was written");
10529        assert!(!after.channels.iter().any(|c| c.name == "ghost"), "the ghost channel never persisted");
10530    }
10531
10532    #[tokio::test]
10533    async fn an_uncited_admin_rotation_is_not_adopted() {
10534        // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
10535        // authority action, so a just-demoted admin's rotation is never honored by
10536        // a lagging client." An uncited rotation is skipped entirely — neither
10537        // adopted nor allowed to conclude a removal.
10538        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10539        let (_tmp, _guard, _owner) = init_test_db();
10540        let relay = MemoryRelay::new();
10541        let mut community = create_community(&relay, "Uncited", vec!["wss://r".into()], None).await.unwrap();
10542        let priv_id = ChannelId([0x8A; 32]);
10543        let key1 = [0x93; 32];
10544        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10545
10546        let admin = Keys::generate();
10547        let role = Role::admin("cf".repeat(32));
10548        let roster = CommunityRoles {
10549            roles: vec![role.clone()],
10550            grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
10551        };
10552        seed_roster_with_heads(&community, &roster, 1_000);
10553
10554        let key2 = [0x94; 32];
10555        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10556        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10557        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
10558        let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10559        // Authorized admin, correct continuity, my blob present — but NO citation.
10560        for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, None).unwrap() {
10561            relay.publish(&e, &community.relays).await.unwrap();
10562        }
10563
10564        let out = follow_rekeys(&relay, &community, &SessionGuard::capture()).await.unwrap();
10565        assert!(out.updated.is_none(), "an uncited rotation is not adopted");
10566
10567        // The SAME rotation, cited, is adopted — proving the refusal was the
10568        // citation and not the rank or the continuity.
10569        let cited = my_authority_citation(&community, &admin.public_key());
10570        assert!(cited.is_some(), "the seeded head yields a citation");
10571        let blob2 = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
10572        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() {
10573            relay.publish(&e, &community.relays).await.unwrap();
10574        }
10575        let out = follow_rekeys(&relay, &community, &SessionGuard::capture()).await.unwrap();
10576        assert!(out.updated.is_some(), "the cited rotation IS adopted");
10577    }
10578
10579    #[tokio::test]
10580    async fn two_admins_racing_a_channel_rotation_converge_on_one_key() {
10581        // CORD-06 §Failure-and-races: two DISTINCT authorized rotators mint the
10582        // same channel epoch concurrently (reachable — both hold MANAGE_CHANNELS).
10583        // Every follower must converge on the SAME key (the lexicographically
10584        // lowest), so the community never permanently forks. (Retaining the losing
10585        // fork's key for its race-window messages needs a multi-key-per-epoch
10586        // archive — a deferred refinement shared with v1; convergence, the
10587        // security-critical property, is what this pins.)
10588        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
10589        let (_tmp, _guard, _owner) = init_test_db();
10590        let relay = MemoryRelay::new();
10591        let mut community = create_community(&relay, "Race", vec!["wss://r".into()], None).await.unwrap();
10592        let priv_id = ChannelId([0xC0; 32]);
10593        let key1 = [0xC1; 32];
10594        add_private_channel(&mut community, priv_id, key1, Epoch(1));
10595
10596        // Two admins (a, b) both hold the Admin role; I hold the channel key.
10597        let (a, b) = (Keys::generate(), Keys::generate());
10598        let role = Role::admin("ce".repeat(32));
10599        let roster = CommunityRoles {
10600            roles: vec![role.clone()],
10601            grants: [&a, &b].iter().map(|k| MemberGrant { member: k.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }).collect(),
10602        };
10603        seed_roster_with_heads(&community, &roster, 1_000);
10604
10605        // Both rotate 1 → 2, each delivering their OWN fresh key to me, off the
10606        // same prevcommit — a genuine same-epoch fork.
10607        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
10608        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
10609        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
10610        let key_a = [0x0A; 32];
10611        let key_b = [0xFB; 32]; // higher — a's must win regardless of publish order
10612        for (signer, k) in [(&a, &key_a), (&b, &key_b)] {
10613            let blob = rekey::build_blob_local(signer.secret_key(), &signer.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), k).unwrap();
10614            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() {
10615                relay.publish(&e, &community.relays).await.unwrap();
10616            }
10617        }
10618
10619        let session = SessionGuard::capture();
10620        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopts a winner");
10621        let adopted = updated.channel(&priv_id).unwrap().key.unwrap();
10622        assert_eq!(adopted, key_a, "converges on the lexicographically lowest key (deterministic across clients)");
10623
10624        // A SECOND follower (fresh, holding the same epoch-1 key) converges identically.
10625        let mut peer = community.clone();
10626        if let Some(c) = peer.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
10627            c.key = Some(key1);
10628            c.epoch = Epoch(1);
10629        }
10630        // Re-run the same fold from the peer's identical starting point → same winner.
10631        let updated2 = follow_rekeys(&relay, &peer, &session).await.unwrap().updated.expect("peer adopts");
10632        assert_eq!(updated2.channel(&priv_id).unwrap().key.unwrap(), key_a, "every follower lands on the identical key");
10633    }
10634
10635    #[tokio::test]
10636    async fn create_private_channel_refuses_a_member_without_manage_channels() {
10637        // The local mirror of the reader's gate: an unauthorized member is refused
10638        // BEFORE any publish (no floor pollution, no orphan key crate).
10639        let (bed, owner, member) = TestBed::new();
10640        bed.swap_to(&owner);
10641        let community = create_community(&bed.relay, "Gate", bed.relays.clone(), None).await.unwrap();
10642        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
10643
10644        bed.swap_to(&member);
10645        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
10646        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
10647        let err = create_private_channel(&bed.relay, &joined, "sneaky").await.unwrap_err();
10648        assert!(err.contains("MANAGE_CHANNELS"), "refused with the permission it lacks: {err}");
10649        let err = create_public_channel(&bed.relay, &joined, "sneaky-too").await.unwrap_err();
10650        assert!(err.contains("MANAGE_CHANNELS"), "public creation gates identically: {err}");
10651    }
10652
10653    // ── Audit regressions ────────────────────────────────────────────────────
10654
10655    #[tokio::test]
10656    async fn accept_rejects_a_bundle_with_a_forged_community_root() {
10657        // The eclipse: community_id commits only to (owner, salt) — both semi-public
10658        // — so a forged invite pairs the REAL triple with an attacker root, and every
10659        // plane derives from it. The join-time owner-genesis check must refuse.
10660        let (bed, owner, member) = TestBed::new();
10661        bed.swap_to(&owner);
10662        let community = create_community(&bed.relay, "Real", bed.relays.clone(), None).await.unwrap();
10663
10664        let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
10665        let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
10666        forged.community_root = fake.clone();
10667        for ch in &mut forged.channels {
10668            ch.key = fake.clone();
10669        }
10670        let attacker = Keys::generate();
10671        let wrap = invite::build_direct_invite(&attacker, &member.keys.public_key(), &forged).unwrap();
10672        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
10673
10674        bed.swap_to(&member);
10675        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
10676        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
10677        assert!(err.contains("could not verify"), "a forged root fails the owner-genesis check: {err}");
10678        assert!(
10679            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
10680            "a rejected join persists nothing"
10681        );
10682    }
10683
10684    #[tokio::test]
10685    async fn accept_verifies_a_rotated_plane_whose_metadata_head_is_admin_signed() {
10686        // CORD-06 compaction re-wraps CURRENT heads with their original signatures,
10687        // so a rotated plane whose metadata an admin last edited carries no
10688        // owner-signed vsk-0. The join anchor there is the community-bound metadata
10689        // head plus any owner-signed edition under the same root.
10690        let (bed, owner, member) = TestBed::new();
10691        bed.swap_to(&owner);
10692        let community = create_community(&bed.relay, "Rotated", bed.relays.clone(), None).await.unwrap();
10693        let general = community.channels[0].id;
10694
10695        let mut rotated = community.clone();
10696        rotated.community_root = [0x5A; 32];
10697        rotated.root_epoch = Epoch(1);
10698        let admin = Keys::generate();
10699        publish_community_meta(&bed.relay, &rotated, &admin, "Rotated", 3).await;
10700        publish_channel_edition(&bed.relay, &rotated, &owner.keys, &general, "general", false, 2, false).await;
10701
10702        bed.swap_to(&member);
10703        let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
10704        let session = SessionGuard::capture();
10705        let joined = accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap();
10706        assert_eq!(joined.root_epoch, Epoch(1), "the rotated root is adopted");
10707    }
10708
10709    #[tokio::test]
10710    async fn only_an_actual_join_publishes_a_guestbook_join() {
10711        // A Guestbook Join is a member's own word that they JOINED. A re-accept of
10712        // a held community and a cross-device key sync (announce_join=false) must
10713        // both stay silent — each re-publish renders as "<user> has joined" spam.
10714        let (bed, owner, member) = TestBed::new();
10715        bed.swap_to(&owner);
10716        let community = create_community(&bed.relay, "Quiet", bed.relays.clone(), None).await.unwrap();
10717
10718        let gb_pk = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk_hex();
10719        async fn gb_count(relay: &MemoryRelay, gb_pk: &str, relays: &[String]) -> usize {
10720            let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb_pk.to_string()], ..Default::default() };
10721            relay.fetch(&q, relays).await.map(|v| v.len()).unwrap_or(0)
10722        }
10723        let baseline = gb_count(&bed.relay, &gb_pk, &bed.relays).await; // the owner's creation Join
10724
10725        bed.swap_to(&member);
10726        let bundle = bundle_of(&community, BundleAudience::Link, None, None, None);
10727        let session = SessionGuard::capture();
10728        accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap();
10729        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a first join announces exactly once");
10730
10731        accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap();
10732        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a re-accept of a held community stays silent");
10733
10734        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
10735        crate::db::community::delete_community(&cid_hex).unwrap();
10736        accept_bundle(&bed.relay, &session, &bundle, None, false).await.unwrap();
10737        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a cross-device key sync is not a membership event");
10738    }
10739
10740    #[tokio::test]
10741    async fn accept_refuses_a_rotated_plane_with_no_owner_signed_edition() {
10742        // The fallback's second half is load-bearing: a community-bound metadata
10743        // head alone is self-signable by anyone who knows the (public) community_id.
10744        let (bed, owner, member) = TestBed::new();
10745        bed.swap_to(&owner);
10746        let community = create_community(&bed.relay, "NoOwner", bed.relays.clone(), None).await.unwrap();
10747
10748        let mut rotated = community.clone();
10749        rotated.community_root = [0x5B; 32];
10750        rotated.root_epoch = Epoch(1);
10751        let attacker = Keys::generate();
10752        publish_community_meta(&bed.relay, &rotated, &attacker, "NoOwner", 3).await;
10753
10754        bed.swap_to(&member);
10755        let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
10756        let session = SessionGuard::capture();
10757        let err = accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap_err();
10758        assert!(err.contains("could not verify"), "no owner-signed edition → refuse: {err}");
10759    }
10760
10761    #[tokio::test]
10762    async fn accept_requires_the_strict_owner_genesis_on_an_epoch_zero_plane() {
10763        // The fallback applies to rotated planes only: at epoch 0 the spec guarantees
10764        // an owner-signed genesis, so owner material without it stays insufficient.
10765        let (bed, owner, member) = TestBed::new();
10766        bed.swap_to(&owner);
10767        let community = create_community(&bed.relay, "Strict", bed.relays.clone(), None).await.unwrap();
10768        let general = community.channels[0].id;
10769
10770        let mut fake = community.clone();
10771        fake.community_root = [0x5C; 32]; // epoch stays 0
10772        let admin = Keys::generate();
10773        publish_community_meta(&bed.relay, &fake, &admin, "Strict", 2).await;
10774        publish_channel_edition(&bed.relay, &fake, &owner.keys, &general, "general", false, 2, false).await;
10775
10776        bed.swap_to(&member);
10777        let bundle = bundle_of(&fake, BundleAudience::Link, None, None, None);
10778        let session = SessionGuard::capture();
10779        let err = accept_bundle(&bed.relay, &session, &bundle, None, true).await.unwrap_err();
10780        assert!(err.contains("could not verify"), "epoch 0 demands the owner genesis: {err}");
10781    }
10782
10783    #[tokio::test]
10784    async fn follow_control_heals_a_bundle_misclassified_public_channel() {
10785        // A bundle can set a PUBLIC channel's grant key to the attacker's, so the
10786        // joiner addresses it at a plane only the attacker reads. The owner's genuine
10787        // public:false edition must override it on follow.
10788        let (_tmp, _guard, _owner) = init_test_db();
10789        let relay = MemoryRelay::new();
10790        let community = create_community(&relay, "Heal", vec!["wss://r".into()], None).await.unwrap();
10791        let general = community.channels[0].id;
10792        let mut poisoned = community.clone();
10793        poisoned.channels[0].private = true;
10794        poisoned.channels[0].key = Some([0x66; 32]);
10795        crate::db::community::save_community_v2(&poisoned).unwrap();
10796
10797        let session = SessionGuard::capture();
10798        let healed = follow_control(&relay, &poisoned, &session).await.unwrap().expect("healed");
10799        let ch = healed.channel(&general).unwrap();
10800        assert!(!ch.private, "the owner's public declaration overrides the bundle");
10801        assert_eq!(ch.key, None, "a healed public channel derives from the root");
10802    }
10803
10804    #[tokio::test]
10805    async fn a_deleted_channel_does_not_resurrect_on_reload() {
10806        // save_community_v2 must prune orphan channel rows, or a control-follow delete
10807        // reappears (with a stale key) on the next reload.
10808        let (_tmp, _guard, owner) = init_test_db();
10809        let relay = MemoryRelay::new();
10810        let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
10811        let extra = ChannelId([0x77; 32]);
10812        let session = SessionGuard::capture();
10813        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
10814        let with_extra = follow_control(&relay, &community, &session).await.unwrap().unwrap();
10815        assert!(with_extra.channel(&extra).is_some());
10816        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
10817        let after = follow_control(&relay, &with_extra, &session).await.unwrap().unwrap();
10818        assert!(after.channel(&extra).is_none());
10819
10820        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
10821        assert!(reloaded.channel(&extra).is_none(), "a deleted channel must not resurrect on reload");
10822        assert_eq!(reloaded.channels.len(), 1);
10823    }
10824
10825    #[tokio::test]
10826    async fn a_channel_owned_by_another_community_is_skipped_not_clobbered() {
10827        // channel_id is the sole DB primary key, so a bundle/replay reusing another
10828        // community's channel_id must NOT overwrite that row. It's skipped (not an
10829        // error — erroring would wedge all of this community's control persistence).
10830        let (_tmp, _guard, _owner) = init_test_db();
10831        let relay = MemoryRelay::new();
10832        let a = create_community(&relay, "A", vec!["wss://r".into()], None).await.unwrap();
10833        let a_channel = a.channels[0].id;
10834        let mut b = create_community(&relay, "B", vec!["wss://r".into()], None).await.unwrap();
10835        let b_channel = b.channels[0].id;
10836        // B's set includes a phantom whose id collides with A's channel.
10837        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() });
10838
10839        crate::db::community::save_community_v2(&b).expect("save succeeds, the phantom is skipped");
10840        // A's channel row is untouched.
10841        let a_reloaded = crate::db::community::load_community_v2(a.id()).unwrap().unwrap();
10842        assert!(!a_reloaded.channels.iter().any(|c| c.private), "A's channel is untouched");
10843        assert_eq!(a_reloaded.channels[0].id.0, a_channel.0);
10844        // B keeps its own channel but never acquired a row for the foreign id.
10845        let b_reloaded = crate::db::community::load_community_v2(b.id()).unwrap().unwrap();
10846        assert!(b_reloaded.channel(&b_channel).is_some(), "B's own channel persists");
10847        assert!(b_reloaded.channel(&a_channel).is_none(), "the foreign-owned channel is skipped, not stolen");
10848    }
10849
10850    /// A single relay that CAPS every query below the page size (modelling a real
10851    /// relay's maxFilterLimit) and honors `until` — so the join-verify walk MUST
10852    /// paginate to reach an old genesis. MemoryRelay can't model this (it unions then
10853    /// truncates the whole set), which is why a MemoryRelay flood test gives false
10854    /// confidence about the production `LiveTransport` behaviour.
10855    struct CappedRelay {
10856        events: Vec<Event>,
10857        cap: usize,
10858    }
10859    #[async_trait::async_trait]
10860    impl Transport for CappedRelay {
10861        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> { self.fetch(query, relays).await }
10862        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
10863            Ok(())
10864        }
10865        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
10866            Ok(())
10867        }
10868        async fn fetch(&self, q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
10869            let mut m: Vec<Event> = self
10870                .events
10871                .iter()
10872                .filter(|e| q.authors.is_empty() || q.authors.contains(&e.pubkey.to_hex()))
10873                .filter(|e| q.until.is_none_or(|u| e.created_at.as_secs() <= u))
10874                .cloned()
10875                .collect();
10876            m.sort_by(|a, b| b.created_at.cmp(&a.created_at)); // newest first
10877            m.truncate(self.cap.min(q.limit.unwrap_or(usize::MAX)));
10878            Ok(m)
10879        }
10880    }
10881
10882    #[tokio::test]
10883    async fn refound_aborts_when_the_control_plane_cannot_be_read_in_full() {
10884        // CORD-06 §3: a Refounder that cannot fold every Control Event must abort.
10885        // `until` is inclusive, so a page-wide block of same-second wraps is a wall
10886        // no cursor steps past — everything older (the genesis editions, a Banlist)
10887        // is unreachable. Compacting THAT view carries only what was read into the
10888        // new epoch, dropping the rest for every member, permanently. Any member can
10889        // build the wall: the plane key comes from the community root they hold.
10890        let (_tmp, _guard, _owner) = init_test_db();
10891        let memory = MemoryRelay::new();
10892        let community = create_community(&memory, "Walled", vec!["wss://r".into()], None).await.unwrap();
10893        let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
10894
10895        let rogue = Keys::generate();
10896        let mut events: Vec<Event> = Vec::new();
10897        for i in 0..FOLLOW_PAGE {
10898            let content = format!("{{\"name\":\"junk{i}\",\"private\":false}}");
10899            let rumor = control::build_edition_rumor(
10900                rogue.public_key(),
10901                vsk::CHANNEL_METADATA,
10902                &[0xAB; 32],
10903                1,
10904                None,
10905                &content,
10906                9_000,
10907                None,
10908            );
10909            let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
10910            events.push(w);
10911        }
10912        let relay = CappedRelay { events, cap: FOLLOW_PAGE };
10913
10914        let err = refound_community(&relay, &community, &[])
10915            .await
10916            .expect_err("a plane that can't be read whole must never be compacted");
10917        assert!(err.contains("too deep to read in full"), "unexpected error: {err}");
10918    }
10919
10920    #[tokio::test]
10921    async fn verify_pages_a_capped_relay_past_a_flood_to_the_genesis() {
10922        // The join-verify DoS mitigation, tested against a relay that caps below PAGE
10923        // (production behaviour MemoryRelay hides): a rogue root-holder buries the
10924        // genesis under junk, and the `until`-walk must page past it. Uses fixed OLD
10925        // timestamps so `until = now` includes everything and the walk is deterministic.
10926        let (_tmp, _guard, owner) = init_test_db();
10927        let meta = control::CommunityMetadata { name: "Capped".into(), relays: vec!["wss://r".into()], ..Default::default() };
10928        let g = control::genesis(&owner, meta, 1_000).unwrap();
10929        let community = CommunityV2::from_genesis(&g, "Capped", None, vec!["wss://r".into()], 1_000);
10930
10931        let control = control_group_key(&community.community_root, community.id(), community.root_epoch);
10932        let rogue = Keys::generate();
10933        let mut events: Vec<Event> = g.wraps.to_vec();
10934        for i in 0..250u64 {
10935            let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xAB; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 1_001 + i, None);
10936            let (wrap, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(1_001 + i)).unwrap();
10937            events.push(wrap);
10938        }
10939        // Cap 100/query forces the walk across ~3 pages down to the genesis at ts 1000.
10940        let relay = CappedRelay { events, cap: 100 };
10941        let verified = verify_owner_root_and_reconcile(&relay, community.clone()).await;
10942        assert!(verified.is_ok(), "the until-walk pages a capped relay past the flood to the genesis: {:?}", verified.err());
10943    }
10944
10945    #[tokio::test]
10946    async fn accept_parked_invite_joins_from_the_stored_bundle() {
10947        // The 3313 receive path: an invite is parked as its bundle JSON, then accepted
10948        // from the stored bundle (re-verifying the owner root over the network).
10949        let (bed, owner, member) = TestBed::new();
10950        bed.swap_to(&owner);
10951        let community = create_community(&bed.relay, "Parked", bed.relays.clone(), None).await.unwrap();
10952        let general = community.channels[0].id;
10953        send_message(&bed.relay, &community, &general, "owner: hi").await.unwrap();
10954        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
10955        let bundle_json = serde_json::to_string(&bundle).unwrap();
10956        let inviter_hex = owner.keys.public_key().to_hex();
10957
10958        bed.swap_to(&member);
10959        let joined = accept_parked_invite(&bed.relay, &bundle_json, Some(&inviter_hex)).await.unwrap();
10960        assert_eq!(joined.id().0, community.id().0, "joined the community from the parked bundle");
10961        assert!(joined.identity.verify());
10962        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: hi"]);
10963        // The join seeded the verified fold as the member's initial floor, so their
10964        // first follow can't roll below the state the join just showed.
10965        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
10966        assert!(
10967            crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().is_some(),
10968            "the joiner's control floor is seeded from the join-time fold"
10969        );
10970
10971        // The Guestbook memberlist now folds both participants.
10972        bed.swap_to(&owner);
10973        let members = memberlist(&bed.relay, &community).await.unwrap();
10974        assert!(members.contains(&member.keys.public_key()), "the parked-invite joiner is a member");
10975    }
10976
10977    #[tokio::test]
10978    async fn accept_parked_invite_rejects_a_forged_root() {
10979        // A forged-root parked bundle (real identity triple, attacker-chosen root) fails
10980        // accept — the shared accept path re-verifies the owner root, so a parked invite
10981        // gets the same eclipse protection as a live one.
10982        let (_tmp, _guard, _owner) = init_test_db();
10983        let relay = MemoryRelay::new();
10984        let community = create_community(&relay, "Real", vec!["wss://r".into()], None).await.unwrap();
10985        let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
10986        let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
10987        forged.community_root = fake.clone();
10988        for ch in &mut forged.channels {
10989            ch.key = fake.clone();
10990        }
10991        let bundle_json = serde_json::to_string(&forged).unwrap();
10992
10993        let err = accept_parked_invite(&relay, &bundle_json, None).await.unwrap_err();
10994        assert!(err.contains("could not verify"), "a forged-root parked bundle fails definitively: {err}");
10995    }
10996
10997    #[test]
10998    fn v2_and_v1_bundles_are_distinguishable_by_parse() {
10999        // The protocol discriminator the facade list/accept relies on: a v2 bundle
11000        // (self-certifying: owner + owner_salt + community_root) parses; a v1-shaped
11001        // one does not, so a parked invite routes to the right accept path.
11002        let owner = Keys::generate();
11003        let identity = super::super::control::CommunityIdentity::mint(&owner.public_key());
11004        let hex = crate::simd::hex::bytes_to_hex_32;
11005        let v2 = invite::CommunityInvite {
11006            community_id: hex(&identity.community_id.0),
11007            owner: hex(&identity.owner_xonly),
11008            owner_salt: hex(&identity.owner_salt),
11009            community_root: hex(&[0x11; 32]),
11010            root_epoch: 0,
11011            channels: vec![],
11012            relays: vec!["wss://r".into()],
11013            name: "V2".into(),
11014            icon: None,
11015            expires_at: None,
11016            creator_npub: None,
11017            label: None,
11018            extra: Default::default(),
11019        };
11020        let v2_json = serde_json::to_string(&v2).unwrap();
11021        assert!(invite::CommunityInvite::from_bundle_json(&v2_json).is_ok(), "a real v2 bundle parses");
11022        let v1_like = r#"{"community_id":"aa","name":"X","relays":[]}"#;
11023        assert!(invite::CommunityInvite::from_bundle_json(v1_like).is_err(), "a v1 bundle is not a v2 bundle");
11024    }
11025
11026    #[tokio::test]
11027    async fn verify_rejects_a_cross_community_owner_edition_replay() {
11028        // The eclipse-via-replay: an owner-signed edition from community X (eid == X.id)
11029        // rewrapped onto a FORGED community T's fake control plane must NOT authenticate
11030        // T. T's genesis has eid == T.id, so X's edition — a genuine owner signature but
11031        // a different eid — is not a valid proof of T's root. This is why "any owner
11032        // edition" is unsound and the eid==community_id genesis pin is required.
11033        let (_tmp, _guard, owner) = init_test_db();
11034
11035        // Community X (real), owned by `owner`.
11036        let gx = control::genesis(&owner, control::CommunityMetadata { name: "X".into(), ..Default::default() }, 1_000).unwrap();
11037        let x_control = control_group_key(&gx.community_root, &gx.identity.community_id, Epoch(0));
11038        let (_ed, opened) = control::open_control_edition(&gx.wraps[0], &x_control).unwrap();
11039
11040        // Forged community T: the real owner triple but an ATTACKER-chosen root.
11041        let t_identity = control::CommunityIdentity::mint(&owner.public_key());
11042        let fake_root = [0xEE; 32];
11043        let t = CommunityV2 {
11044            identity: t_identity,
11045            community_root: fake_root,
11046            root_epoch: Epoch(0),
11047            name: "T".into(),
11048            description: None,
11049            icon: None,
11050            banner: None,
11051            meta_custom: None,
11052            meta_extra: Default::default(),
11053            relays: vec!["wss://r".into()],
11054            channels: vec![],
11055            dissolved: false,
11056            created_at_ms: 0,
11057        };
11058        // Rewrap X's owner-signed genesis onto T's fake control plane (the attacker
11059        // controls the fake root, so they can derive its control group key).
11060        let t_control = control_group_key(&fake_root, t.id(), t.root_epoch);
11061        let (replayed, _) = stream::rewrap_seal(&opened.seal, &t_control, Timestamp::from_secs(1_000)).unwrap();
11062        let relay = MemoryRelay::new();
11063        relay.publish(&replayed, &t.relays).await.unwrap();
11064
11065        let verified = verify_owner_root_and_reconcile(&relay, t.clone()).await;
11066        assert!(verified.is_err(), "a cross-community owner-edition replay must not authenticate a forged root");
11067    }
11068
11069    /// LIVE smoke test (network) — ignored by default. Creates a v2 community on a
11070    /// REAL relay via `LiveTransport`, sends a message, fetches it back, and mints
11071    /// a public link. A fresh throwaway identity in an isolated temp data dir, so
11072    /// it never touches real accounts. Run explicitly:
11073    /// ```sh
11074    /// cargo test -p vector-core -- --ignored --nocapture live_smoke
11075    /// ```
11076    #[tokio::test]
11077    #[ignore = "hits a real relay over the network"]
11078    async fn live_smoke_create_send_fetch_on_a_real_relay() {
11079        use crate::community::transport::LiveTransport;
11080        use nostr_sdk::prelude::ToBech32;
11081
11082        let relay = std::env::var("VECTOR_SMOKE_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
11083        let relays = vec![relay.clone()];
11084
11085        // Isolated account + data dir (a fresh throwaway key — never a real account).
11086        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
11087        crate::db::close_database();
11088        crate::db::clear_id_caches();
11089        let tmp = tempfile::tempdir().unwrap();
11090        // Bring your own key (VECTOR_SMOKE_NSEC) to create a community you can log
11091        // into elsewhere; otherwise a fresh throwaway.
11092        let keys = match std::env::var("VECTOR_SMOKE_NSEC") {
11093            Ok(n) => Keys::parse(&n).expect("VECTOR_SMOKE_NSEC is not a valid nsec"),
11094            Err(_) => Keys::generate(),
11095        };
11096        let npub = keys.public_key().to_bech32().unwrap();
11097        // Off by default (never leak secrets from a committed test); set
11098        // VECTOR_SMOKE_PRINT_NSEC=1 to print the owner nsec for cross-client login.
11099        if std::env::var("VECTOR_SMOKE_PRINT_NSEC").is_ok() {
11100            println!("[smoke] OWNER nsec (throwaway — do NOT reuse): {}", keys.secret_key().to_bech32().unwrap());
11101        }
11102        std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
11103        crate::db::set_app_data_dir(tmp.path().to_path_buf());
11104        crate::db::set_current_account(npub.clone()).unwrap();
11105        crate::db::init_database(&npub).unwrap();
11106        crate::state::MY_SECRET_KEY.store_from_keys(&keys, &[]);
11107        crate::state::set_my_public_key(keys.public_key());
11108        println!("[smoke] throwaway identity {npub}");
11109
11110        // A live client (LiveTransport rides the global NOSTR_CLIENT + warms relays).
11111        let client = crate::nostr_client_builder().build();
11112        client.add_managed_relay(relay.as_str()).await.ok();
11113        client.connect().await;
11114        crate::state::set_nostr_client(client);
11115        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
11116
11117        // Create → send → fetch-back → verify.
11118        let community = create_community(&transport, "V2 Live Smoke", relays.clone(), None).await.expect("create");
11119        let general = community.channels[0].id;
11120        println!("[smoke] created community {} on {relay}", crate::simd::hex::bytes_to_hex_32(&community.id().0));
11121
11122        let text = "hello from a Vector Concord v2 live smoke test";
11123        let sent_id = send_message(&transport, &community, &general, text).await.expect("send");
11124        println!("[smoke] sent message {sent_id}");
11125
11126        // Give the relay a moment to store + be ready to serve it.
11127        tokio::time::sleep(std::time::Duration::from_secs(3)).await;
11128
11129        let page = fetch_channel(&transport, &community, &general, 50).await.expect("fetch");
11130        let texts: Vec<String> = page
11131            .iter()
11132            .filter_map(|f| match &f.event {
11133                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
11134                _ => None,
11135            })
11136            .collect();
11137        println!("[smoke] fetched {} message(s) back: {texts:?}", texts.len());
11138        assert!(texts.contains(&text.to_string()), "the message did not round-trip through the real relay");
11139
11140        // Mint a shareable v2 link (the thing a bot hands out).
11141        let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint link");
11142        println!("[smoke] invite link: {}", link.url);
11143        println!("[smoke] PASS — v2 create+send+fetch+invite round-tripped on {relay}");
11144    }
11145
11146    #[tokio::test]
11147    async fn chat_ops_react_edit_delete_round_trip() {
11148        let (bed, owner, _member) = TestBed::new();
11149        bed.swap_to(&owner);
11150        let community = create_community(&bed.relay, "Ops", bed.relays.clone(), None).await.unwrap();
11151        let general = community.channels[0].id;
11152        let me_hex = owner.keys.public_key().to_hex();
11153
11154        let msg_id = send_message(&bed.relay, &community, &general, "original").await.unwrap();
11155        send_reaction(&bed.relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, ":fire:", Some(("fire", "https://e/f.png")))
11156            .await
11157            .unwrap();
11158        send_edit(&bed.relay, &community, &general, &msg_id, "edited").await.unwrap();
11159        send_delete(&bed.relay, &community, &general, &msg_id, super::super::kind::MESSAGE).await.unwrap();
11160
11161        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11162        let target = crate::simd::hex::hex_to_bytes_32(&msg_id);
11163        let mut saw = (false, false, false);
11164        for f in &page {
11165            match &f.event {
11166                ChatEvent::Reaction { target: t, emoji, emoji_url, .. } if *t == target => {
11167                    assert_eq!(emoji, ":fire:");
11168                    assert_eq!(emoji_url.as_deref(), Some("https://e/f.png"));
11169                    saw.0 = true;
11170                }
11171                ChatEvent::Edit { target: t, new_content, .. } if *t == target => {
11172                    assert_eq!(new_content, "edited");
11173                    saw.1 = true;
11174                }
11175                ChatEvent::Delete { target: t, .. } if *t == target => saw.2 = true,
11176                _ => {}
11177            }
11178        }
11179        assert!(saw.0 && saw.1 && saw.2, "reaction/edit/delete all round-trip: {saw:?}");
11180    }
11181
11182    #[tokio::test]
11183    async fn a_typing_signal_rides_the_ephemeral_wrap_and_is_never_stored() {
11184        let (bed, owner, _member) = TestBed::new();
11185        bed.swap_to(&owner);
11186        let community = create_community(&bed.relay, "Typ", bed.relays.clone(), None).await.unwrap();
11187        let general = community.channels[0].id;
11188        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
11189
11190        // A live subscriber sees the 21059 wrap and it opens as Typing…
11191        let mut sub = bed.relay.subscribe(Query {
11192            kinds: vec![stream::KIND_WRAP_EPHEMERAL],
11193            authors: vec![group.pk_hex()],
11194            ..Default::default()
11195        });
11196        send_typing(&bed.relay, &community, &general).await.unwrap();
11197        let wrap = sub.try_recv().expect("the typing wrap streams to a live subscriber");
11198        let opened = match chat::open_chat_event(&wrap, &group, &general, community.root_epoch) {
11199            Ok(ChatEvent::Typing { opened }) => opened,
11200            other => panic!("the ephemeral wrap must open as a Typing event, got {other:?}"),
11201        };
11202
11203        // …while nothing durable is stored (relays never keep the ephemeral tier),
11204        // so channel history stays free of typing noise…
11205        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11206        assert!(page.iter().all(|f| !matches!(f.event, ChatEvent::Typing { .. })));
11207
11208        // …and no scrub key is retained (there is no durable wrap to ever delete).
11209        assert!(
11210            crate::db::community::get_message_key(&opened.rumor_id.to_hex()).unwrap().is_none(),
11211            "ephemeral sends must not retain scrub keys"
11212        );
11213    }
11214
11215    #[tokio::test]
11216    async fn a_durable_send_retains_the_wrap_scrub_key_and_full_delete_nukes_the_relay_copy() {
11217        let (bed, owner, _member) = TestBed::new();
11218        bed.swap_to(&owner);
11219        let community = create_community(&bed.relay, "Nuke", bed.relays.clone(), None).await.unwrap();
11220        let general = community.channels[0].id;
11221        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
11222
11223        let id = send_message(&bed.relay, &community, &general, "scrub me").await.unwrap();
11224
11225        // Retained: the row maps the rumor id to the exact published wrap, holds the
11226        // key that SIGNED that wrap (same-author NIP-09), and the relay set.
11227        let (keys, outer_hex, relays) =
11228            crate::db::community::get_message_key(&id).unwrap().expect("a durable send retains its scrub key");
11229        assert_eq!(relays, community.relays);
11230        let wrap_query = Query {
11231            kinds: vec![stream::KIND_WRAP],
11232            authors: vec![group.pk_hex()],
11233            ..Default::default()
11234        };
11235        let wraps = bed.relay.fetch(&wrap_query, &community.relays).await.unwrap();
11236        let wrap = wraps.iter().find(|w| w.id.to_hex() == outer_hex).expect("retained outer id is the published wrap");
11237        assert_eq!(keys.public_key(), wrap.pubkey, "retained key is the wrap's author");
11238
11239        // Reactions ride the same retention (revoke_reaction's relay-nuke layer).
11240        let me_hex = owner.keys.public_key().to_hex();
11241        let rid = send_reaction(&bed.relay, &community, &general, &id, &me_hex, super::super::kind::MESSAGE, "🔥", None)
11242            .await
11243            .unwrap();
11244        assert!(crate::db::community::get_message_key(&rid).unwrap().is_some(), "reaction sends retain too");
11245
11246        // The shared v1 delete path (Layer 1 of delete_community_message / revoke_reaction)
11247        // scrubs the wrap off the relay via the retained key, then consumes the row.
11248        crate::community::service::delete_message(&bed.relay, &id).await.unwrap();
11249        assert!(crate::db::community::get_message_key(&id).unwrap().is_none(), "key consumed after the scrub");
11250        let after = bed.relay.fetch(&wrap_query, &community.relays).await.unwrap();
11251        assert!(!after.iter().any(|w| w.id.to_hex() == outer_hex), "wrap scrubbed from the relay");
11252    }
11253
11254    #[tokio::test]
11255    async fn backfill_heals_scrub_keys_for_own_pre_retention_messages_only() {
11256        let (bed, owner, _member) = TestBed::new();
11257        bed.swap_to(&owner);
11258        let community = create_community(&bed.relay, "Heal", bed.relays.clone(), None).await.unwrap();
11259        let general = community.channels[0].id;
11260        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
11261
11262        // Simulate a pre-retention / other-device send: our message on the relay,
11263        // but no local mapping row.
11264        let id = send_message(&bed.relay, &community, &general, "old send").await.unwrap();
11265        crate::db::community::delete_message_key(&id).unwrap();
11266        assert!(crate::db::community::get_message_key(&id).unwrap().is_none());
11267
11268        // A stranger member's message rides the same channel.
11269        let mkeys = Keys::generate();
11270        let rumor = chat::build_message_rumor(mkeys.public_key(), &general, community.root_epoch, "foreign", None, &[], vec![], 6_000);
11271        let foreign_id = rumor.id.unwrap().to_hex();
11272        let (fw, _) = chat::seal_chat_rumor(&rumor, &group, &mkeys, Timestamp::from_secs(6), false).unwrap();
11273        bed.relay.publish(&fw, &community.relays).await.unwrap();
11274
11275        // One history open re-derives the mapping for the OWN message…
11276        fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11277        let (keys, _outer, relays) =
11278            crate::db::community::get_message_key(&id).unwrap().expect("backfill heals own unretained rows");
11279        assert_eq!(keys.public_key(), group.pk(), "healed key is the wrap's signing key");
11280        assert_eq!(relays, community.relays);
11281
11282        // …and never manufactures one for a foreign author.
11283        assert!(crate::db::community::get_message_key(&foreign_id).unwrap().is_none());
11284
11285        // The healed row is a working full delete: the shared path scrubs the wrap.
11286        crate::community::service::delete_message(&bed.relay, &id).await.unwrap();
11287        let left = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11288        assert!(
11289            !left.iter().any(|f| f.event.opened().rumor_id.to_hex() == id),
11290            "healed message scrubbed from the relay"
11291        );
11292    }
11293
11294    #[tokio::test]
11295    async fn send_chat_message_threads_the_reply_and_extra_tags() {
11296        let (bed, owner, _member) = TestBed::new();
11297        bed.swap_to(&owner);
11298        let community = create_community(&bed.relay, "Re", bed.relays.clone(), None).await.unwrap();
11299        let general = community.channels[0].id;
11300        let me_hex = owner.keys.public_key().to_hex();
11301
11302        let parent_id = send_message(&bed.relay, &community, &general, "parent").await.unwrap();
11303        let imeta = nostr_sdk::prelude::Tag::custom(
11304            "imeta",
11305            ["url https://e/blob".to_string(), "m image/png".to_string()],
11306        );
11307        let child_id = send_chat_message(
11308            &bed.relay, &community, &general, "child",
11309            Some((parent_id.as_str(), me_hex.as_str())), &[], vec![imeta],
11310        )
11311        .await
11312        .unwrap();
11313
11314        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
11315        let child = page
11316            .iter()
11317            .find_map(|f| match &f.event {
11318                ChatEvent::Message { opened, reply_to, .. } if opened.rumor_id.to_hex() == child_id => Some((opened, reply_to)),
11319                _ => None,
11320            })
11321            .expect("the reply message round-trips");
11322        let reply = child.1.as_ref().expect("the reply reference is carried");
11323        assert_eq!(crate::simd::hex::bytes_to_hex_32(&reply.id), parent_id);
11324        assert_eq!(reply.author, Some(owner.keys.public_key()));
11325        assert!(
11326            child.0.rumor.tags.iter().any(|t| t.kind() == "imeta"),
11327            "the imeta attachment tag rides the rumor verbatim"
11328        );
11329    }
11330
11331    #[tokio::test]
11332    async fn a_kick_needs_kick_authority_and_removes_the_target() {
11333        let (bed, owner, member) = TestBed::new();
11334        bed.swap_to(&owner);
11335        let community = create_community(&bed.relay, "Kick", bed.relays.clone(), None).await.unwrap();
11336
11337        // The target announces a Join (as an accepted invite would).
11338        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
11339        let join = guestbook::build_join_rumor(member.keys.public_key(), None, 2_000);
11340        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(2)).unwrap();
11341        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
11342        let before = memberlist(&bed.relay, &community).await.unwrap();
11343        assert!(before.contains(&member.keys.public_key()), "the join lands first");
11344
11345        // An unprivileged member's kick of the owner is refused locally…
11346        bed.swap_to(&member);
11347        let err = kick_member(&bed.relay, &community, &owner.keys.public_key()).await.unwrap_err();
11348        assert!(err.contains("not authorized"), "unprivileged kick refused: {err}");
11349
11350        // …and the owner (supreme, no grant needed) kicks the member out.
11351        bed.swap_to(&owner);
11352        kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11353        let after = memberlist(&bed.relay, &community).await.unwrap();
11354        assert!(!after.contains(&member.keys.public_key()), "the kicked member leaves the fold");
11355        assert!(after.contains(&owner.keys.public_key()), "the owner remains");
11356    }
11357
11358    #[tokio::test]
11359    async fn a_rejoin_survives_a_stale_kick_and_an_uncaught_up_store() {
11360        // The self-eviction race: on a REJOIN the guestbook store starts empty while the
11361        // control fold has already re-derived the member's old ban mark, so the MEMBERLIST
11362        // legitimately excludes them for that window. A stale Kick landing there used to
11363        // read as an authorized eviction and the client nuked its own community.
11364        let (bed, owner, member) = TestBed::new();
11365        bed.swap_to(&owner);
11366        let community = create_community(&bed.relay, "Rejoin", bed.relays.clone(), None).await.unwrap();
11367        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11368        let (o, m) = (owner.keys.public_key(), member.keys.public_key());
11369        let join = |at: u64, id: u8| guestbook::GuestbookEvent {
11370            rumor_id: [id; 32],
11371            entry: guestbook::GuestbookEntry::Join { member: m, invited_by: None, at_ms: at },
11372        };
11373        let kick = |at: u64, id: u8| guestbook::GuestbookEvent {
11374            rumor_id: [id; 32],
11375            entry: guestbook::GuestbookEntry::Kick { actor: o, target: m, citation: None, at_ms: at },
11376        };
11377
11378        // An authorized kick after their join stands.
11379        crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2)], 2).unwrap();
11380        assert!(stored_kick_verdict(&community, &m), "an authorized kick after the join is honored");
11381
11382        // A rejoin supersedes it — latest entry wins (CORD-02 §5).
11383        crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2), join(3_000, 3)], 3).unwrap();
11384        assert!(!stored_kick_verdict(&community, &m), "a Join newer than the kick clears the verdict");
11385
11386        // The catch-up window itself: nothing folded yet decides nothing.
11387        crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
11388        assert!(!stored_kick_verdict(&community, &m), "an empty store is not an eviction");
11389
11390        // And the memberlist is NOT a substitute: with the store empty it excludes them,
11391        // which is exactly the false positive this verdict replaced.
11392        assert!(
11393            !stored_memberlist(&community).unwrap().contains(&m),
11394            "the memberlist excludes an un-caught-up member — why it can't gate a kick"
11395        );
11396    }
11397
11398    /// Seed a roster the way production does: `follow_control` writes the roster
11399    /// AND the folded edition heads in one pass, so a citation against a grant is
11400    /// resolvable. Seeding the roster alone yields a client that can never satisfy
11401    /// any `vac` — a shape no v2 production path produces.
11402    fn seed_roster_with_heads(community: &CommunityV2, roster: &crate::community::roles::CommunityRoles, at: i64) {
11403        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11404        crate::db::community::set_community_roles(&cid_hex, roster, at).unwrap();
11405        for g in &roster.grants {
11406            let Some(m) = crate::simd::hex::hex_to_bytes_32_checked(&g.member) else { continue };
11407            let eid = super::super::derive::grant_locator(community.id(), &m);
11408            let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
11409            crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, 1, &[0xA1; 32], &[0xA2; 32], community.root_epoch.0).unwrap();
11410        }
11411    }
11412
11413    /// Publish an edition CITING a specific grant version (CORD-04 §5's `vac`).
11414    async fn publish_grant_citing(
11415        relay: &MemoryRelay,
11416        community: &CommunityV2,
11417        signer: &Keys,
11418        member: &PublicKey,
11419        role_ids: Vec<String>,
11420        version: u64,
11421        citation: Option<&crate::community::edition::AuthorityCitation>,
11422    ) {
11423        let group = control_group_key(&community.community_root, community.id(), community.root_epoch);
11424        let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
11425        let prev = head_hash_on_relay(relay, community, &eid).await;
11426        let grant = MemberGrant { member: member.to_hex(), role_ids };
11427        let content = crate::community::v2::roles::grant_content_json(&grant).unwrap();
11428        let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, citation);
11429        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
11430        relay.publish(&wrap, &community.relays).await.unwrap();
11431    }
11432
11433    #[tokio::test]
11434    async fn an_uncited_admin_edition_is_not_folded_but_a_cited_one_is() {
11435        // CORD-04 §5 on the CONTROL PLANE: "a verifier won't act on the edition
11436        // until it has synced at least that Grant". The citation resolves against
11437        // the heads THIS fold accepted — an external floor would refuse every
11438        // non-owner edition on a bootstrap and the roster could never fold.
11439        let (bed, owner, admin) = TestBed::new();
11440        bed.swap_to(&owner);
11441        let community = create_community(&bed.relay, "Cited", bed.relays.clone(), None).await.unwrap();
11442        let admin_pk = admin.keys.public_key();
11443        let rid = "c3".repeat(32);
11444        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::admin().0), 1).await;
11445        publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![rid.clone()], 1).await;
11446
11447        // The admin grants a bystander, citing NOTHING.
11448        // A LOWER role (position 5) — an admin at position 1 may grant beneath
11449        // themselves but never at their own rank (equal cannot act on equal).
11450        let low_rid = "c4".repeat(32);
11451        let mut low = admin_role(&low_rid, Permissions::admin().0);
11452        low.position = 5;
11453        publish_role(&bed.relay, &community, &owner.keys, &low, 1).await;
11454
11455        let bystander = Keys::generate().public_key();
11456        publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![low_rid.clone()], 1, None).await;
11457        let view = fetch_authority(&bed.relay, &community).await;
11458        assert!(
11459            !view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
11460            "an uncited non-owner edition is not folded"
11461        );
11462        // The owner's own editions still fold — supreme cites nothing.
11463        assert!(view.roles.is_admin(&admin_pk.to_hex()), "the owner-authored grant folds");
11464
11465        // Same edition, now citing the admin's real grant: honored. (follow_control
11466        // is what PERSISTS the folded heads a citation is built from.)
11467        let _ = follow_control(&bed.relay, &community, &SessionGuard::capture()).await;
11468        let entity_id = crate::community::v2::derive::grant_locator(community.id(), &admin_pk.to_bytes());
11469        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11470        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
11471        let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex).unwrap().unwrap();
11472        let cite = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
11473        publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![low_rid], 2, Some(&cite)).await;
11474
11475        let view = fetch_authority(&bed.relay, &community).await;
11476        assert!(
11477            view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
11478            "the same edition WITH its synced citation folds"
11479        );
11480    }
11481
11482    #[tokio::test]
11483    async fn a_join_landing_inside_the_ban_window_survives_the_unban() {
11484        // The invite is deliberately ungated, so a fresh Join can arrive seconds
11485        // BEFORE the unban edition. It must reach the store (banned = a fold
11486        // verdict, not a storage verdict) so the unban resurrects the member —
11487        // dropped at ingest, they stayed invisible forever.
11488        let (bed, owner, member) = TestBed::new();
11489        bed.swap_to(&owner);
11490        let community = create_community(&bed.relay, "Window", bed.relays.clone(), None).await.unwrap();
11491        let member_pk = member.keys.public_key();
11492        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11493
11494        // Locally banned (edition folded at t=1000s), with the outliving mark.
11495        crate::db::community::set_community_banlist(&cid_hex, &[member_pk.to_hex()], 1_000).unwrap();
11496        crate::db::community::merge_community_ban_marks(&cid_hex, &[(member_pk.to_hex(), 1_000u64)].into_iter().collect()).unwrap();
11497
11498        // Their Join lands 60s after the ban mark, while the banlist still says banned.
11499        let join = guestbook::GuestbookEvent {
11500            rumor_id: [9u8; 32],
11501            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_060_000 },
11502        };
11503        assert!(ingest_guestbook_event(&community, join, 1_060).unwrap(), "stored while banned");
11504        assert!(
11505            !stored_memberlist(&community).unwrap().contains(&member_pk),
11506            "while banned, the fold keeps them out"
11507        );
11508
11509        // The unban folds: same store, no refetch needed — the Join resurrects them.
11510        crate::db::community::set_community_banlist(&cid_hex, &[], 2_000).unwrap();
11511        assert!(
11512            stored_memberlist(&community).unwrap().contains(&member_pk),
11513            "after the unban the raced Join makes them a member again"
11514        );
11515    }
11516
11517    #[tokio::test]
11518    async fn a_stale_root_admin_write_is_refused_not_misdirected() {
11519        // The ban→unban race: a Ban's refound buries the old root over several
11520        // publishes while a concurrently-issued command still holds the
11521        // pre-commit struct. That unban used to land on the buried control
11522        // plane — "succeeding" while no reader would ever fold it — and a
11523        // concurrently-minted invite stranded its joiner on the dead epoch.
11524        let (bed, owner, member) = TestBed::new();
11525        bed.swap_to(&owner);
11526        let community = create_community(&bed.relay, "Race", bed.relays.clone(), None).await.unwrap();
11527        let member_pk = member.keys.public_key();
11528
11529        set_banlist(&bed.relay, &community, &[member_pk.to_hex()]).await.unwrap();
11530        let _rotated = refound_community(&bed.relay, &community, &[member_pk]).await.unwrap();
11531
11532        // The stale-struct unban is REFUSED (retryable), never misdirected.
11533        let err = set_banlist(&bed.relay, &community, &[]).await.unwrap_err();
11534        assert!(err.contains("re-founded"), "unban: {err}");
11535        // A stale invite must not mint dead-epoch key material.
11536        let err = send_direct_invite(&bed.relay, &community, &member_pk, None, None).await.unwrap_err();
11537        assert!(err.contains("re-founded"), "invite: {err}");
11538        // Neither is a kick allowed to ride the buried guestbook.
11539        let err = kick_member(&bed.relay, &community, &member_pk).await.unwrap_err();
11540        assert!(err.contains("re-founded"), "kick: {err}");
11541
11542        // The retry path: a fresh load lands the unban on the LIVING plane.
11543        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
11544        set_banlist(&bed.relay, &fresh, &[]).await.unwrap();
11545        let view = fetch_authority(&bed.relay, &fresh).await;
11546        assert!(view.banned.is_empty(), "the retried unban actually unbans");
11547    }
11548
11549    #[tokio::test]
11550    async fn an_uncited_kick_from_an_admin_is_not_honored() {
11551        // CORD-04 §5: a non-owner authority action must name the Grant it acts
11552        // under, and the reader refuses until it holds that Grant. Emitting the
11553        // `vac` without checking it buys nothing — a demoted admin's kick would
11554        // still land on any client that hadn't synced the demotion.
11555        let (bed, owner, member) = TestBed::new();
11556        bed.swap_to(&owner);
11557        let community = create_community(&bed.relay, "Uncited", bed.relays.clone(), None).await.unwrap();
11558        let admin = Keys::generate();
11559        let member_pk = member.keys.public_key();
11560        grant_admin(&bed.relay, &community, &admin.public_key()).await.unwrap();
11561
11562        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11563        let view = fetch_authority(&bed.relay, &community).await;
11564        crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();
11565
11566        let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
11567        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
11568        let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex).unwrap().unwrap();
11569        let cite = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };
11570
11571        let joined = guestbook::GuestbookEvent {
11572            rumor_id: [1u8; 32],
11573            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_000 },
11574        };
11575        let kick = |citation, id: u8, at| guestbook::GuestbookEvent {
11576            rumor_id: [id; 32],
11577            entry: guestbook::GuestbookEntry::Kick { actor: admin.public_key(), target: member_pk, citation, at_ms: at },
11578        };
11579        let roles = crate::db::community::get_community_roles(&cid_hex).unwrap();
11580        let empty_bans = std::collections::BTreeSet::new();
11581        let empty_marks = std::collections::BTreeMap::new();
11582        let fold = |evs: &[guestbook::GuestbookEvent]| {
11583            fold_members(&community, evs, Default::default(), &roles, &empty_bans, &empty_marks).unwrap()
11584        };
11585
11586        assert!(
11587            fold(&[joined.clone(), kick(None, 2, 2_000)]).contains(&member_pk),
11588            "an uncited kick from an admin is not honored"
11589        );
11590        assert!(
11591            !fold(&[joined, kick(Some(cite), 3, 3_000)]).contains(&member_pk),
11592            "the same kick WITH its synced citation removes them"
11593        );
11594    }
11595
11596    #[tokio::test]
11597    async fn kicking_an_admin_strips_their_roles_first() {
11598        // CORD-04 §6 composition: Role Removal THEN the directive. Kicking without the
11599        // strip leaves the target out of the memberlist but still holding every
11600        // management bit, so every client keeps honoring their control editions.
11601        let (bed, owner, member) = TestBed::new();
11602        bed.swap_to(&owner);
11603        let community = create_community(&bed.relay, "Compose", bed.relays.clone(), None).await.unwrap();
11604        let member_pk = member.keys.public_key();
11605        let member_hex = member_pk.to_hex();
11606        let owner_hex = owner.keys.public_key().to_hex();
11607
11608        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11609        assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member_hex));
11610
11611        kick_member(&bed.relay, &community, &member_pk).await.unwrap();
11612
11613        let view = fetch_authority(&bed.relay, &community).await;
11614        assert!(!view.roles.is_admin(&member_hex), "the kick stripped their rank");
11615        assert!(
11616            !view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES),
11617            "a kicked admin holds no bit"
11618        );
11619        assert!(
11620            !memberlist(&bed.relay, &community).await.unwrap().contains(&member_pk),
11621            "and the directive still removed them"
11622        );
11623    }
11624
11625    #[tokio::test]
11626    async fn grant_admin_mints_one_deterministic_role_and_revoke_strips_it() {
11627        let (bed, owner, member) = TestBed::new();
11628        bed.swap_to(&owner);
11629        let community = create_community(&bed.relay, "Adm", bed.relays.clone(), None).await.unwrap();
11630        let member_pk = member.keys.public_key();
11631        let member_hex = member_pk.to_hex();
11632        let owner_hex = owner.keys.public_key().to_hex();
11633
11634        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11635        let view = fetch_authority(&bed.relay, &community).await;
11636        assert!(view.roles.is_admin(&member_hex), "the grant folds as admin");
11637        assert!(view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES));
11638
11639        // A second grant (any device) converges on the SAME role entity — and a
11640        // repeat is a no-op, not a version bump.
11641        let second = Keys::generate().public_key();
11642        grant_admin(&bed.relay, &community, &second).await.unwrap();
11643        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11644        let view = fetch_authority(&bed.relay, &community).await;
11645        assert_eq!(view.roles.roles.len(), 1, "one Admin role, never a fork");
11646        assert!(view.roles.is_admin(&member_hex) && view.roles.is_admin(&second.to_hex()));
11647        let grant = view.roles.grants.iter().find(|g| g.member == member_hex).unwrap();
11648        assert_eq!(grant.role_ids.len(), 1, "no duplicate role id in the grant");
11649
11650        // Revoke strips ONLY the admin role and de-authorizes.
11651        revoke_admin(&bed.relay, &community, &member_pk).await.unwrap();
11652        let view = fetch_authority(&bed.relay, &community).await;
11653        assert!(!view.roles.is_admin(&member_hex), "revoked");
11654        assert!(view.roles.is_admin(&second.to_hex()), "the other admin is untouched");
11655        assert!(!view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::KICK));
11656    }
11657
11658    #[tokio::test]
11659    async fn follow_control_persists_the_roster_for_sync_local_reads() {
11660        let (bed, owner, member) = TestBed::new();
11661        bed.swap_to(&owner);
11662        let community = create_community(&bed.relay, "Persist", bed.relays.clone(), None).await.unwrap();
11663        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
11664        let member_hex = member.keys.public_key().to_hex();
11665        grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11666
11667        // The passive follow folds + persists; the read is then LOCAL (v1 parity).
11668        let session = crate::state::SessionGuard::capture();
11669        follow_control(&bed.relay, &community, &session).await.unwrap();
11670        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
11671        assert!(roster.is_admin(&member_hex), "the persisted roster reads back without a fetch");
11672
11673        // A withholding relay serves nothing — an empty fold raises no gap flag, and
11674        // the stored roster must be RETAINED, never wiped.
11675        let withholding = MemoryRelay::new();
11676        let _ = follow_control(&withholding, &community, &session).await;
11677        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
11678        assert!(roster.is_admin(&member_hex), "withholding never shrinks standing");
11679
11680        // A real revocation (a NEWER grant edition) does replace it.
11681        revoke_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11682        follow_control(&bed.relay, &community, &session).await.unwrap();
11683        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
11684        assert!(!roster.is_admin(&member_hex), "the revoke folds + persists");
11685    }
11686
11687    #[tokio::test]
11688    async fn grant_admin_is_refused_for_a_non_owner_and_publishes_nothing() {
11689        let (bed, owner, member) = TestBed::new();
11690        bed.swap_to(&owner);
11691        let community = create_community(&bed.relay, "NoSquat", bed.relays.clone(), None).await.unwrap();
11692
11693        bed.swap_to(&member);
11694        let err = grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap_err();
11695        assert!(err.contains("owner"), "refused before any publish: {err}");
11696
11697        // The deterministic admin-role entity stays unsquatted — the owner's later
11698        // legitimate mint is version 1 and folds cleanly.
11699        bed.swap_to(&owner);
11700        let view = fetch_authority(&bed.relay, &community).await;
11701        assert!(view.roles.roles.is_empty(), "no role edition landed");
11702        grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
11703        let view = fetch_authority(&bed.relay, &community).await;
11704        assert!(view.roles.is_admin(&member.keys.public_key().to_hex()));
11705    }
11706
11707    #[tokio::test]
11708    async fn grant_admin_merges_other_roles_and_refuses_a_withheld_grant() {
11709        let (bed, owner, member) = TestBed::new();
11710        bed.swap_to(&owner);
11711        let community = create_community(&bed.relay, "Merge", bed.relays.clone(), None).await.unwrap();
11712        let member_pk = member.keys.public_key();
11713
11714        // The member already holds a Mod role, granted through the real send path
11715        // (so this device's floors track both entities).
11716        let mod_rid = crate::simd::hex::bytes_to_hex_32(&[0x66; 32]);
11717        set_role(&bed.relay, &community, &admin_role(&mod_rid, Permissions::BAN)).await.unwrap();
11718        grant_roles(&bed.relay, &community, &member_pk, vec![mod_rid.clone()]).await.unwrap();
11719
11720        // A relay that withholds the control plane must refuse the merge — a blind
11721        // push would erase the Mod role at a higher version.
11722        let withholding = MemoryRelay::new();
11723        let err = grant_admin(&withholding, &community, &member_pk).await.unwrap_err();
11724        assert!(err.contains("could not be fetched"), "withheld grant refused: {err}");
11725
11726        // Against the full relay the merge preserves the Mod role.
11727        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
11728        let view = fetch_authority(&bed.relay, &community).await;
11729        let grant = view.roles.grants.iter().find(|g| g.member == member_pk.to_hex()).unwrap();
11730        assert_eq!(grant.role_ids.len(), 2, "admin ADDED to the existing grant, not replacing it");
11731        assert!(grant.role_ids.contains(&mod_rid));
11732    }
11733
11734    #[tokio::test]
11735    async fn fetch_authority_reflects_a_granted_admin() {
11736        let (bed, owner, member) = TestBed::new();
11737        bed.swap_to(&owner);
11738        let community = create_community(&bed.relay, "Auth", bed.relays.clone(), None).await.unwrap();
11739        let rid = crate::simd::hex::bytes_to_hex_32(&[0x5a; 32]);
11740        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
11741        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
11742
11743        let view = fetch_authority(&bed.relay, &community).await;
11744        let member_hex = member.keys.public_key().to_hex();
11745        assert!(view.roles.is_admin(&member_hex), "the granted member folds as admin");
11746        assert!(
11747            view.roles.is_authorized(&member_hex, Some(&owner.keys.public_key().to_hex()), Permissions::KICK),
11748            "an ADMIN_ALL grant carries KICK"
11749        );
11750        assert!(view.banned.is_empty());
11751    }
11752}