Skip to main content

vector_core/community/
raid.rs

1//! Raid assessment: which members read as people, and which read as spawned identities.
2//!
3//! A sybil raid never looks like spam from one account. It looks like one message each
4//! from a hundred fresh accounts, so per-sender rate limits and per-account reputation
5//! both miss it entirely. What survives is the COHORT: many distinct senders posting the
6//! same shape inside one window, from identities that were minted minutes ago. This module
7//! folds those signals into a per-member verdict plus the reasons behind it, so a moderator
8//! sees why before acting — the output drives a rotation's retain set, and a wrong call
9//! there evicts a real member.
10//!
11//! Conviction rests on cohort evidence, never on freshness alone: a community that just
12//! posted an invite link is *supposed* to see a burst of quiet new accounts.
13
14use std::collections::{HashMap, HashSet};
15
16/// Below this length a shared message is too generic to convict on ("gm", "lol", "+1"),
17/// so a cohort of that shape needs [`RaidParams::short_text_factor`] times the members.
18const MIN_SKELETON_LEN: usize = 8;
19
20/// A shared line shorter than this is a pleasantry ("thank you", "good morning"), so its
21/// cohort must clear [`RaidParams::short_text_factor`] times the size.
22const COHORT_PAYLOAD_LEN: usize = 12;
23
24/// Collapse a message to the shape a raid script repeats. Case, punctuation, spacing and
25/// digit variation are all one line of attacker code to randomise, so none of them may
26/// carry weight.
27///
28/// A `:shortcode:` that renders as an image is dropped rather than flattened to its name:
29/// three people answering with the same reaction is a community, not a cohort, and leaving
30/// the name in convicts them on a skeleton nobody typed. See [`skeleton_with`] for the
31/// resolution that decides which codes are images.
32pub fn skeleton(text: &str) -> String {
33    skeleton_with(text, &HashSet::new())
34}
35
36/// [`skeleton`] against a set of shortcodes that actually render as images. A `:code:`
37/// outside the set reaches the reader as literal text, so it stays in the skeleton —
38/// otherwise wrapping the payload in colons hides a cohort in plain sight.
39pub fn skeleton_with(text: &str, known: &HashSet<String>) -> String {
40    strip_shortcodes(text, known)
41        .chars()
42        .filter(|c| c.is_alphanumeric() && !c.is_numeric())
43        .flat_map(|c| c.to_lowercase())
44        .collect()
45}
46
47/// Remove `:name:` runs that stand in for an image: one this account can render, or a
48/// short name a unicode set plausibly carries. A long unresolved run is prose in a
49/// costume — `:buycheapcoinsnow:` renders as itself — so its text is kept. A lone `:`
50/// or an unclosed code is left alone.
51fn strip_shortcodes(text: &str, known: &HashSet<String>) -> String {
52    let mut out = String::with_capacity(text.len());
53    let mut rest = text;
54    while let Some(open) = rest.find(':') {
55        out.push_str(&rest[..open]);
56        let after = &rest[open + 1..];
57        let close = after.find(':').filter(|end| {
58            *end > 0 && after[..*end].chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '+')
59        });
60        match close {
61            Some(end) => {
62                let name = &after[..end];
63                if !known.contains(name) && name.chars().count() >= MIN_SKELETON_LEN {
64                    out.push_str(name);
65                }
66                rest = &after[end + 1..];
67            }
68            None => {
69                out.push(':');
70                rest = after;
71            }
72        }
73    }
74    out.push_str(rest);
75    out
76}
77
78/// Tunables for [`assess`]. The defaults are the shape of a real raid; a moderator can
79/// widen them from the panel when a wave is slower or quieter than the norm.
80#[derive(Debug, Clone)]
81pub struct RaidParams {
82    /// A join newer than this reads as "just now".
83    pub fresh_join_secs: u64,
84    /// Tenure at which a member is trusted on age alone (with some volume).
85    pub trusted_tenure_secs: u64,
86    /// Messages that, with tenure or variety, make a member trusted.
87    pub trusted_messages: u64,
88    /// Distinct message shapes that read as real conversation.
89    pub trusted_distinct: u64,
90    /// At or below this, a member has effectively not spoken.
91    pub quiet_messages: u64,
92    /// Distinct senders sharing one skeleton before it counts as a cohort.
93    pub min_cohort: usize,
94    /// Multiplier on `min_cohort` for skeletons under `MIN_SKELETON_LEN`.
95    pub short_text_factor: usize,
96    /// How far apart two joins may be and still belong to the same burst.
97    pub burst_gap_secs: u64,
98    /// A cohort is the senders inside its densest window of this span: a raid lands as
99    /// one burst, and the same words hours apart are a conversation.
100    pub cohort_span_secs: u64,
101    /// Joins in one window before it reads as a burst rather than a busy afternoon.
102    pub min_burst: usize,
103    /// Shortcodes that render as images here; anything else in colons is read as text.
104    pub known_shortcodes: HashSet<String>,
105}
106
107impl Default for RaidParams {
108    fn default() -> Self {
109        Self {
110            fresh_join_secs: 24 * 60 * 60,
111            trusted_tenure_secs: 7 * 24 * 60 * 60,
112            trusted_messages: 5,
113            trusted_distinct: 3,
114            quiet_messages: 2,
115            min_cohort: 3,
116            short_text_factor: 3,
117            burst_gap_secs: 10 * 60,
118            cohort_span_secs: 15 * 60,
119            min_burst: 5,
120            known_shortcodes: HashSet::new(),
121        }
122    }
123}
124
125/// What the caller knows about one member before any judgement is applied.
126#[derive(Debug, Clone, Default)]
127pub struct MemberSignals {
128    pub npub: String,
129    /// Guestbook join, ms. `0` = unknown (predates the store, or the Join was lost).
130    pub joined_at_ms: u64,
131    /// Invite label they joined through, when the Guestbook carried the attribution.
132    pub invite_label: Option<String>,
133    pub messages: u64,
134    /// First and last posting times, seconds. `0` when they have never posted.
135    pub first_secs: u64,
136    pub last_secs: u64,
137    /// Their texts from the recent window only — the cohort evidence.
138    pub texts: Vec<String>,
139    /// When each of `texts` was sent, seconds, index for index. Missing or `0` = unknown,
140    /// which never splits a cohort.
141    pub text_secs: Vec<u64>,
142    pub is_owner: bool,
143    pub is_admin: bool,
144    pub is_me: bool,
145}
146
147/// Where a member lands. Only [`Verdict::Suspect`] is pre-selected for removal.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
149#[serde(rename_all = "lowercase")]
150pub enum Verdict {
151    /// The owner, yourself, or a role-holder: never removable from this panel.
152    Protected,
153    /// Real history behind them. Kept by default, and never auto-selected.
154    Trusted,
155    /// Not enough either way — the moderator decides.
156    Neutral,
157    /// Cohort evidence convicts them.
158    Suspect,
159}
160
161/// One member's verdict with the evidence that produced it.
162#[derive(Debug, Clone, serde::Serialize)]
163pub struct MemberAssessment {
164    pub npub: String,
165    pub verdict: Verdict,
166    /// Ordering weight only — the verdict is decided by rules, not by a threshold.
167    pub score: u32,
168    pub reasons: Vec<String>,
169    pub joined_at_ms: u64,
170    pub invite_label: Option<String>,
171    pub messages: u64,
172    /// Distinct message shapes seen in the recent window.
173    pub distinct: u64,
174    /// Other members who posted a shape this member also posted.
175    pub cohort: u64,
176    /// Seconds between their first trace (join or first post) and `now`.
177    pub tenure_secs: u64,
178    pub last_secs: u64,
179    pub is_owner: bool,
180    pub is_admin: bool,
181    pub is_me: bool,
182}
183
184/// Cap on the npubs carried per cohort. The panel shows the count and the sample; a
185/// 500-strong cluster would otherwise put 30KB of bech32 through the IPC boundary for
186/// nothing.
187const COHORT_SAMPLE_CAP: usize = 24;
188
189/// A duplicate-text cluster: the evidence a raid actually leaves behind.
190#[derive(Debug, Clone, serde::Serialize)]
191pub struct Cohort {
192    /// A representative verbatim message, for display.
193    pub sample: String,
194    /// The true size, which `members` may be a truncated sample of.
195    pub size: usize,
196    pub members: Vec<String>,
197}
198
199/// The whole picture for one community.
200#[derive(Debug, Clone, serde::Serialize)]
201pub struct RaidReport {
202    pub members: Vec<MemberAssessment>,
203    pub suspects: usize,
204    pub trusted: usize,
205    pub protected: usize,
206    pub cohorts: Vec<Cohort>,
207    /// Members whose joins landed inside the convicted burst window.
208    pub burst_size: usize,
209    /// Start/end of that window, ms. Absent when no burst was found.
210    pub burst_from_ms: u64,
211    pub burst_to_ms: u64,
212    /// True when the cohort evidence is strong enough to call this a raid rather
213    /// than a busy day.
214    pub raid_detected: bool,
215}
216
217/// The distinct senders inside the densest `span_secs` window of one shape (earliest such
218/// window on a tie). Unknown times (`0`) sit in every window, so they never split a cohort.
219fn densest_senders(mut at: Vec<(u64, &str)>, span_secs: u64) -> HashSet<String> {
220    let unknown: Vec<&str> = at.iter().filter(|(t, _)| *t == 0).map(|(_, n)| *n).collect();
221    at.retain(|(t, _)| *t != 0);
222    at.sort();
223    let mut inside: HashMap<&str, usize> = HashMap::new();
224    let (mut best, mut best_len, mut start) = ((0usize, 0usize), 0usize, 0usize);
225    for end in 0..at.len() {
226        *inside.entry(at[end].1).or_insert(0) += 1;
227        while at[end].0.saturating_sub(at[start].0) > span_secs {
228            if let Some(n) = inside.get_mut(at[start].1) {
229                *n -= 1;
230                if *n == 0 {
231                    inside.remove(at[start].1);
232                }
233            }
234            start += 1;
235        }
236        if inside.len() > best_len {
237            best_len = inside.len();
238            best = (start, end + 1);
239        }
240    }
241    at[best.0..best.1].iter().map(|(_, n)| *n).chain(unknown).map(str::to_string).collect()
242}
243
244/// Judge every member against the cohort evidence. `now_secs` is the clock the
245/// caller reads once, so a long assessment can't drift mid-pass.
246pub fn assess(signals: &[MemberSignals], now_secs: u64, p: &RaidParams) -> RaidReport {
247    // ── Cohorts: skeleton → the distinct members who posted it ───────────────
248    let mut said: HashMap<String, Vec<(u64, &str)>> = HashMap::new();
249    let mut sample_of: HashMap<String, String> = HashMap::new();
250    // How many times each member posted each shape: the line must be most of what a member
251    // wrote for the cohort to hold them.
252    let mut repeats: HashMap<(&str, String), u64> = HashMap::new();
253    for s in signals {
254        for (i, t) in s.texts.iter().enumerate() {
255            let sk = skeleton_with(t, &p.known_shortcodes);
256            if sk.is_empty() {
257                continue;
258            }
259            said.entry(sk.clone()).or_default().push((s.text_secs.get(i).copied().unwrap_or(0), s.npub.as_str()));
260            *repeats.entry((s.npub.as_str(), sk.clone())).or_insert(0) += 1;
261            sample_of.entry(sk).or_insert_with(|| t.clone());
262        }
263    }
264    let by_skeleton: HashMap<String, HashSet<String>> =
265        said.into_iter().map(|(sk, at)| (sk, densest_senders(at, p.cohort_span_secs))).collect();
266    let volume: HashMap<&str, u64> = signals.iter().map(|s| (s.npub.as_str(), s.messages)).collect();
267    // A cohort convicts on two counts, not one. Size alone would hang a community
268    // catchphrase on whoever repeats it, so the cluster must ALSO be thin: a script
269    // gives each identity one line, while regulars who happen to share a greeting have
270    // hundreds of other messages between them. A short skeleton is cheap coincidence on
271    // top of that, so it clears a higher size bar.
272    let convicting = |sk: &str, members: &HashSet<String>| -> bool {
273        let need = if sk.chars().count() < COHORT_PAYLOAD_LEN {
274            p.min_cohort.saturating_mul(p.short_text_factor)
275        } else {
276            p.min_cohort
277        };
278        if members.len() < need {
279            return false;
280        }
281        let thin = members
282            .iter()
283            .filter(|n| volume.get(n.as_str()).copied().unwrap_or(0) <= p.quiet_messages)
284            .count();
285        thin * 2 >= members.len()
286    };
287
288    let mut cohorts: Vec<Cohort> = Vec::new();
289    // npub → the largest convicting cohort they belong to (excluding themselves).
290    let mut cohort_of: HashMap<String, u64> = HashMap::new();
291    for (sk, members) in &by_skeleton {
292        if !convicting(sk, members) {
293            continue;
294        }
295        let peers = members.len().saturating_sub(1) as u64;
296        for m in members {
297            let own = repeats.get(&(m.as_str(), sk.clone())).copied().unwrap_or(0);
298            if own.saturating_mul(2) < volume.get(m.as_str()).copied().unwrap_or(0) {
299                continue;
300            }
301            let e = cohort_of.entry(m.clone()).or_insert(0);
302            *e = (*e).max(peers);
303        }
304        let mut list: Vec<String> = members.iter().cloned().collect();
305        list.sort();
306        let size = list.len();
307        list.truncate(COHORT_SAMPLE_CAP);
308        cohorts.push(Cohort { sample: sample_of.get(sk).cloned().unwrap_or_default(), size, members: list });
309    }
310    cohorts.sort_by_key(|c| std::cmp::Reverse(c.size));
311
312    // ── Join burst: the densest run of joins within `burst_gap_secs` ─────────
313    let mut joins: Vec<(u64, &str)> = signals
314        .iter()
315        .filter(|s| s.joined_at_ms > 0 && !s.is_owner)
316        .map(|s| (s.joined_at_ms, s.npub.as_str()))
317        .collect();
318    joins.sort_by_key(|(at, _)| *at);
319    let gap_ms = p.burst_gap_secs.saturating_mul(1000);
320    let mut best: (usize, usize) = (0, 0); // [start, end) into `joins`
321    let mut start = 0usize;
322    for end in 0..joins.len() {
323        while joins[end].0.saturating_sub(joins[start].0) > gap_ms {
324            start += 1;
325        }
326        if end + 1 - start > best.1 - best.0 {
327            best = (start, end + 1);
328        }
329    }
330    let burst: HashSet<&str> = if best.1 - best.0 >= p.min_burst {
331        joins[best.0..best.1].iter().map(|(_, n)| *n).collect()
332    } else {
333        HashSet::new()
334    };
335    let (burst_from_ms, burst_to_ms) = if burst.is_empty() {
336        (0, 0)
337    } else {
338        (joins[best.0].0, joins[best.1 - 1].0)
339    };
340    // A burst only convicts its silent members once the noisy ones are already
341    // convicted — otherwise a freshly-posted invite link reads as an attack.
342    let burst_convicted = burst.iter().filter(|n| cohort_of.contains_key(**n)).count() >= p.min_cohort;
343
344    // ── Per-member verdicts ──────────────────────────────────────────────────
345    let now_ms = now_secs.saturating_mul(1000);
346    let mut members: Vec<MemberAssessment> = Vec::with_capacity(signals.len());
347    for s in signals {
348        let distinct: u64 = s.texts.iter().map(|t| skeleton_with(t, &p.known_shortcodes)).filter(|sk| !sk.is_empty()).collect::<HashSet<_>>().len() as u64;
349        let cohort = cohort_of.get(&s.npub).copied().unwrap_or(0);
350        let in_burst = burst.contains(s.npub.as_str());
351        // Oldest trace wins: a member whose Join was lost still has their first post.
352        let first_seen_secs = match (s.joined_at_ms / 1000, s.first_secs) {
353            (0, f) => f,
354            (j, 0) => j,
355            (j, f) => j.min(f),
356        };
357        let tenure_secs = if first_seen_secs == 0 { 0 } else { now_secs.saturating_sub(first_seen_secs) };
358        let fresh = s.joined_at_ms > 0 && now_ms.saturating_sub(s.joined_at_ms) <= p.fresh_join_secs.saturating_mul(1000);
359
360        let mut reasons: Vec<String> = Vec::new();
361        let mut score: u32 = 0;
362
363        let verdict = if s.is_owner || s.is_me || s.is_admin {
364            if s.is_owner {
365                reasons.push("Community owner".into());
366            } else if s.is_me {
367                reasons.push("You".into());
368            } else {
369                reasons.push("Holds a role".into());
370            }
371            Verdict::Protected
372        } else {
373            if cohort > 0 {
374                score += 40 + (cohort.min(50) as u32);
375                reasons.push(format!("Posted the same message as {cohort} other member{}", if cohort == 1 { "" } else { "s" }));
376            }
377            if in_burst && burst_convicted {
378                score += 15;
379                reasons.push(format!("Joined in a burst of {}", burst.len()));
380            }
381            if fresh {
382                score += 10;
383                reasons.push("Joined in the last 24h".into());
384            }
385            if s.messages == 0 {
386                score += 5;
387                reasons.push("Has never posted".into());
388            } else if s.messages <= p.quiet_messages {
389                score += 5;
390                reasons.push(format!("Only {} message{}", s.messages, if s.messages == 1 { "" } else { "s" }));
391            }
392            if s.messages >= 2 && distinct == 1 {
393                score += 10;
394                reasons.push("Repeats one message".into());
395            }
396
397            let long_tenure = tenure_secs >= p.trusted_tenure_secs;
398            let talks = s.messages >= p.trusted_messages;
399            let varied = distinct >= p.trusted_distinct;
400
401            // Trust is checked BEFORE the cohort, so a member with real history is
402            // never unticked by default. The asymmetry is deliberate: a missed raider
403            // is one click to add, an evicted two-year member is not recoverable.
404            if talks && (long_tenure || varied) {
405                // The row already prints the numbers; this says what they earned.
406                reasons.clear();
407                reasons.push(if long_tenure && talks {
408                    "Long-standing, active member".to_string()
409                } else {
410                    "Varied conversation history".to_string()
411                });
412                Verdict::Trusted
413            } else if cohort > 0 || (in_burst && burst_convicted && s.messages == 0) {
414                Verdict::Suspect
415            } else {
416                Verdict::Neutral
417            }
418        };
419
420        members.push(MemberAssessment {
421            npub: s.npub.clone(),
422            verdict,
423            score,
424            reasons,
425            joined_at_ms: s.joined_at_ms,
426            invite_label: s.invite_label.clone(),
427            messages: s.messages,
428            distinct,
429            cohort,
430            tenure_secs,
431            last_secs: s.last_secs,
432            is_owner: s.is_owner,
433            is_admin: s.is_admin,
434            is_me: s.is_me,
435        });
436    }
437
438    // Suspects first, then by evidence weight — the panel's default reading order
439    // is "what do I need to look at".
440    members.sort_by(|a, b| {
441        let rank = |v: Verdict| match v {
442            Verdict::Suspect => 0,
443            Verdict::Neutral => 1,
444            Verdict::Trusted => 2,
445            Verdict::Protected => 3,
446        };
447        rank(a.verdict).cmp(&rank(b.verdict)).then(b.score.cmp(&a.score)).then(a.npub.cmp(&b.npub))
448    });
449
450    let suspects = members.iter().filter(|m| m.verdict == Verdict::Suspect).count();
451    let trusted = members.iter().filter(|m| m.verdict == Verdict::Trusted).count();
452    let protected = members.iter().filter(|m| m.verdict == Verdict::Protected).count();
453    RaidReport {
454        raid_detected: suspects >= p.min_cohort && !cohorts.is_empty(),
455        members,
456        suspects,
457        trusted,
458        protected,
459        cohorts,
460        burst_size: burst.len(),
461        burst_from_ms,
462        burst_to_ms,
463    }
464}
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469
470    const HOUR: u64 = 3_600;
471    const DAY: u64 = 86_400;
472
473    fn member(npub: &str) -> MemberSignals {
474        MemberSignals { npub: npub.to_string(), ..Default::default() }
475    }
476
477    /// now = a fixed clock so every case reads the same age.
478    const NOW: u64 = 1_700_000_000;
479
480    fn raider(npub: &str, at_secs: u64, text: &str) -> MemberSignals {
481        MemberSignals {
482            npub: npub.to_string(),
483            joined_at_ms: at_secs * 1000,
484            messages: 1,
485            first_secs: at_secs,
486            last_secs: at_secs,
487            texts: vec![text.to_string()],
488            ..Default::default()
489        }
490    }
491
492    fn regular(npub: &str, joined_days_ago: u64, messages: u64, texts: &[&str]) -> MemberSignals {
493        let joined = NOW - joined_days_ago * DAY;
494        MemberSignals {
495            npub: npub.to_string(),
496            joined_at_ms: joined * 1000,
497            messages,
498            first_secs: joined,
499            last_secs: NOW - HOUR,
500            texts: texts.iter().map(|t| t.to_string()).collect(),
501            ..Default::default()
502        }
503    }
504
505    #[test]
506    fn skeleton_ignores_the_cheap_variations() {
507        assert_eq!(skeleton("Hello World!"), skeleton("hello,   world"));
508        assert_eq!(skeleton("hello world 123"), skeleton("HELLO WORLD 4567"));
509        assert_ne!(skeleton("hello world"), skeleton("goodbye world"));
510    }
511
512    #[test]
513    fn a_payload_wrapped_in_colons_still_has_a_skeleton() {
514        assert_eq!(skeleton(":buycheapcoinsnow:"), "buycheapcoinsnow");
515        // Short codes read as emoji even unresolved; a rendering pack silences the rest.
516        assert!(skeleton(":fire:").is_empty());
517        assert!(skeleton(":+1:").is_empty());
518        assert_eq!(skeleton("nice one :fire:"), skeleton("nice one"));
519        let known = HashSet::from(["buycheapcoinsnow".to_string()]);
520        assert!(skeleton_with(":buycheapcoinsnow:", &known).is_empty());
521    }
522
523    #[test]
524    fn a_cohort_hiding_behind_shortcode_colons_still_convicts() {
525        let mut signals: Vec<MemberSignals> = (0..40)
526            .map(|i| raider(&format!("npub_raider_{i}"), NOW - 60, ":freeairdropclaimnow:"))
527            .collect();
528        signals.push(regular("npub_owner", 400, 900, &["morning all", "shipping today", "nice one"]));
529        signals[40].is_owner = true;
530
531        let r = assess(&signals, NOW, &RaidParams::default());
532        assert!(r.raid_detected, "colons must not blind the cohort");
533        assert_eq!(r.suspects, 40);
534    }
535
536    #[test]
537    fn a_hundred_fresh_npubs_saying_one_thing_is_a_raid() {
538        let mut signals: Vec<MemberSignals> = (0..100)
539            .map(|i| raider(&format!("npub_raider_{i}"), NOW - 60, "hello world"))
540            .collect();
541        signals.push(regular("npub_owner", 400, 900, &["morning all", "shipping today", "nice one"]));
542        signals[100].is_owner = true;
543
544        let r = assess(&signals, NOW, &RaidParams::default());
545        assert!(r.raid_detected, "cohort of 100 identical posts must convict");
546        assert_eq!(r.suspects, 100, "every raider, and only the raiders");
547        assert_eq!(r.members.iter().filter(|m| m.verdict == Verdict::Protected).count(), 1);
548        assert_eq!(r.cohorts.len(), 1);
549        assert_eq!(r.cohorts[0].size, 100, "the true size survives the display cap");
550    }
551
552    #[test]
553    fn a_quiet_newcomer_alone_is_not_convicted() {
554        let signals = vec![
555            regular("npub_old", 400, 900, &["morning all", "shipping today", "nice one"]),
556            MemberSignals {
557                npub: "npub_new".into(),
558                joined_at_ms: (NOW - 600) * 1000,
559                messages: 1,
560                first_secs: NOW - 500,
561                last_secs: NOW - 500,
562                texts: vec!["hey everyone, glad to be here".into()],
563                ..Default::default()
564            },
565        ];
566        let r = assess(&signals, NOW, &RaidParams::default());
567        assert_eq!(r.suspects, 0, "freshness alone must never convict");
568        assert_eq!(r.members.iter().find(|m| m.npub == "npub_new").unwrap().verdict, Verdict::Neutral);
569    }
570
571    #[test]
572    fn an_invite_link_burst_of_real_people_is_not_a_raid() {
573        // Twenty newcomers inside ten minutes, each saying something of their own.
574        let greetings = [
575            "hi there", "glad to join", "hello from berlin", "whats up", "found this via nostr",
576            "hey all", "good to be here", "long time lurker", "anyone here into rust", "morning",
577            "just joined, what is this about", "greetings", "hello hello", "howdy folks",
578            "nice community", "reading the pins now", "is there a channel for dev talk",
579            "coming over from the other group", "hola", "yo",
580        ];
581        let signals: Vec<MemberSignals> = (0..20)
582            .map(|i| {
583                let at = NOW - 300 + i * 10;
584                MemberSignals {
585                    npub: format!("npub_person_{i}"),
586                    joined_at_ms: at * 1000,
587                    messages: 1,
588                    first_secs: at,
589                    last_secs: at,
590                    texts: vec![greetings[i as usize].to_string()],
591                    ..Default::default()
592                }
593            })
594            .collect();
595        let r = assess(&signals, NOW, &RaidParams::default());
596        assert_eq!(r.suspects, 0, "a burst with no duplicate text is just a busy afternoon");
597        assert!(!r.raid_detected);
598    }
599
600    #[test]
601    fn silent_members_of_a_convicted_burst_are_caught_too() {
602        let mut signals: Vec<MemberSignals> = (0..10)
603            .map(|i| raider(&format!("npub_loud_{i}"), NOW - 120 + i, "buy cheap coins now"))
604            .collect();
605        // Same wave, never spoke — the sleeper accounts a text-only rule misses.
606        for i in 0..5 {
607            let at = NOW - 100 + i;
608            signals.push(MemberSignals {
609                npub: format!("npub_silent_{i}"),
610                joined_at_ms: at * 1000,
611                ..Default::default()
612            });
613        }
614        let r = assess(&signals, NOW, &RaidParams::default());
615        assert_eq!(r.suspects, 15, "the whole wave, loud and silent");
616    }
617
618    #[test]
619    fn short_shared_text_needs_a_bigger_cohort() {
620        // "gm" from four people is a morning, not an attack.
621        let signals: Vec<MemberSignals> =
622            (0..4).map(|i| raider(&format!("npub_{i}"), NOW - 60 + i, "gm")).collect();
623        let r = assess(&signals, NOW, &RaidParams::default());
624        assert_eq!(r.suspects, 0, "min_cohort * short_text_factor = 9 needed for a 2-char skeleton");
625
626        let many: Vec<MemberSignals> =
627            (0..12).map(|i| raider(&format!("npub_{i}"), NOW - 60 + i, "gm")).collect();
628        assert_eq!(assess(&many, NOW, &RaidParams::default()).suspects, 12);
629    }
630
631    #[test]
632    fn tenure_and_variety_earn_trust_that_survives_a_raid() {
633        let mut signals: Vec<MemberSignals> = (0..20)
634            .map(|i| raider(&format!("npub_raider_{i}"), NOW - 60, "hello world"))
635            .collect();
636        // This veteran ALSO said "hello world" once, so they sit inside the convicted
637        // cohort. Tenure still wins: the default selection must not evict them.
638        signals.push(regular("npub_veteran", 90, 400, &["morning", "on it", "shipped", "hello world"]));
639        let r = assess(&signals, NOW, &RaidParams::default());
640        let vet = r.members.iter().find(|m| m.npub == "npub_veteran").unwrap();
641        assert_eq!(vet.verdict, Verdict::Trusted, "cohort membership must not outrank real history");
642        assert_eq!(vet.cohort, 0, "one line in four hundred is a member echoing the room, not the wave");
643        assert!(vet.reasons.iter().any(|s| s.contains("Long-standing")));
644        assert_eq!(r.suspects, 20, "the raiders, and only the raiders");
645    }
646
647    #[test]
648    fn role_holders_and_self_are_never_selectable() {
649        let mut admin = member("npub_admin");
650        admin.is_admin = true;
651        admin.joined_at_ms = (NOW - 60) * 1000;
652        admin.texts = vec!["hello world".into()];
653        admin.messages = 1;
654        let mut me = member("npub_me");
655        me.is_me = true;
656        let mut signals = vec![admin, me];
657        signals.extend((0..10).map(|i| raider(&format!("npub_r{i}"), NOW - 60, "hello world")));
658
659        let r = assess(&signals, NOW, &RaidParams::default());
660        assert_eq!(r.members.iter().find(|m| m.npub == "npub_admin").unwrap().verdict, Verdict::Protected);
661        assert_eq!(r.members.iter().find(|m| m.npub == "npub_me").unwrap().verdict, Verdict::Protected);
662        assert_eq!(r.suspects, 10, "protection wins over cohort evidence");
663    }
664
665    #[test]
666    fn the_same_thank_you_hours_apart_is_not_a_cohort() {
667        let mut signals: Vec<MemberSignals> = (0..3)
668            .map(|i| {
669                let mut r = raider(&format!("npub_new_{i}"), NOW - 12 * HOUR + i * 60, "thank you");
670                r.text_secs = vec![NOW - 12 * HOUR + i * 60];
671                r
672            })
673            .collect();
674        let mut chatty = regular("npub_chatty", 2, 60, &["Thank you", "piano", "violin", "python"]);
675        chatty.text_secs = vec![NOW - HOUR, NOW - 2 * HOUR, NOW - 2 * HOUR, NOW - 2 * HOUR];
676        signals.push(chatty);
677        let r = assess(&signals, NOW, &RaidParams::default());
678        assert_eq!(r.suspects, 0);
679        assert!(!r.raid_detected);
680    }
681
682    #[test]
683    fn one_payload_spread_over_hours_is_not_a_cohort() {
684        let signals: Vec<MemberSignals> = (0..6)
685            .map(|i| {
686                let at = NOW - 20 * HOUR + i * 3 * HOUR;
687                let mut r = raider(&format!("npub_r{i}"), at, "free airdrop claim it now");
688                r.text_secs = vec![at];
689                r
690            })
691            .collect();
692        assert_eq!(assess(&signals, NOW, &RaidParams::default()).suspects, 0);
693    }
694
695    #[test]
696    fn a_burst_of_one_payload_is_still_a_cohort() {
697        let signals: Vec<MemberSignals> = (0..6)
698            .map(|i| {
699                let at = NOW - HOUR + i * 30;
700                let mut r = raider(&format!("npub_r{i}"), at, "free airdrop claim it now");
701                r.text_secs = vec![at];
702                r
703            })
704            .collect();
705        assert_eq!(assess(&signals, NOW, &RaidParams::default()).suspects, 6);
706    }
707
708    #[test]
709    fn suspects_sort_ahead_of_everyone_else() {
710        let mut signals = vec![regular("npub_old", 400, 900, &["a", "b", "c", "d", "e"])];
711        signals.extend((0..5).map(|i| raider(&format!("npub_r{i}"), NOW - 60, "free airdrop here")));
712        let r = assess(&signals, NOW, &RaidParams::default());
713        assert!(r.members[0].verdict == Verdict::Suspect);
714        assert_eq!(r.members.last().unwrap().npub, "npub_old");
715    }
716
717    #[test]
718    fn a_community_catchphrase_shared_by_regulars_is_not_a_cohort() {
719        // Five long-standing members who all greet with the same line. Same skeleton,
720        // same count as a small raid — but every one of them has real volume behind it.
721        let signals: Vec<MemberSignals> = (0..5)
722            .map(|i| regular(&format!("npub_regular_{i}"), 200, 400, &["gm vectorians", "on it", "shipped it", "nice"]))
723            .collect();
724        let r = assess(&signals, NOW, &RaidParams::default());
725        assert!(r.cohorts.is_empty(), "a shared phrase between chatty members is not evidence");
726        assert_eq!(r.suspects, 0);
727    }
728
729    #[test]
730    fn one_line_identities_still_convict_beside_a_chatty_member() {
731        // The raid wave, plus one regular who happens to use the same words. The cohort
732        // is still overwhelmingly thin, so it convicts — and the regular stays trusted.
733        let mut signals: Vec<MemberSignals> = (0..30)
734            .map(|i| raider(&format!("npub_r{i}"), NOW - 90 + i, "claim your free airdrop"))
735            .collect();
736        signals.push(regular("npub_regular", 200, 400, &["claim your free airdrop", "lol", "sure", "ok"]));
737        let r = assess(&signals, NOW, &RaidParams::default());
738        assert_eq!(r.suspects, 30);
739        assert_eq!(r.members.iter().find(|m| m.npub == "npub_regular").unwrap().verdict, Verdict::Trusted);
740    }
741
742    #[test]
743    fn shared_emoji_reactions_never_form_a_cohort() {
744        // Three regulars answering with the same custom emoji is a community, not a raid.
745        let signals: Vec<MemberSignals> = (0..6)
746            .map(|i| raider(&format!("npub_{i}"), NOW - 300 + i, ":vector_logo:"))
747            .collect();
748        let p = RaidParams { known_shortcodes: HashSet::from(["vector_logo".to_string()]), ..Default::default() };
749        let r = assess(&signals, NOW, &p);
750        assert_eq!(r.suspects, 0);
751        assert!(r.cohorts.is_empty(), "an emoji-only message carries no convicting content");
752    }
753
754    #[test]
755    fn a_shortcode_does_not_hide_the_text_around_it() {
756        assert_eq!(skeleton("free airdrop :fire: click here"), skeleton("free airdrop click here"));
757        assert_eq!(skeleton(":smile:"), "");
758        // A bare colon is punctuation, not an unterminated shortcode.
759        assert_eq!(skeleton("note: buy now"), skeleton("note buy now"));
760        assert!(!skeleton("ratio 3:1 wins").is_empty());
761    }
762
763    #[test]
764    fn an_empty_community_assesses_cleanly() {
765        let r = assess(&[], NOW, &RaidParams::default());
766        assert_eq!(r.suspects, 0);
767        assert!(!r.raid_detected);
768        assert_eq!(r.burst_size, 0);
769    }
770}