Skip to main content

vector_core/community/policy/
engine.rs

1//! `evaluate` — the pure conviction engine (§1, §3.2, §5).
2//!
3//! Signals in, report out. No I/O, no keys, no capability checks, no clock: the
4//! caller passes `now`. Two clients holding the same inputs reach byte-identical
5//! conclusions, which is the whole reason the engine convicts and never
6//! sentences.
7
8use super::combine::run_pipeline;
9use super::document::{ArmScope, Enforcement, Exempt, ExemptPatterns, Match, Policy, Ratio, Rule, Rung};
10use super::matchers::{cancel_exempt_hits, keyword_hits, link_hits};
11use super::normalize::{self, EmojiCodes};
12use super::types::*;
13use std::collections::{BTreeMap, BTreeSet};
14
15// ── Inputs ───────────────────────────────────────────────────────────────────
16
17/// One message in the evaluation corpus.
18#[derive(Debug, Clone)]
19pub struct MessageSignal {
20    pub id: MessageId,
21    pub author: SubjectId,
22    pub channel: Hash32,
23    /// Inner ms timestamp — the corpus orders and clamps on this.
24    pub at_ms: u64,
25    pub text: String,
26    /// p-tags: the only thing that counts as a mention (inline `@name` is
27    /// renderer-dependent).
28    pub mentions: u32,
29}
30
31/// What the caller knows about one member before any judgement.
32#[derive(Debug, Clone)]
33pub struct MemberSignal {
34    pub subject: SubjectId,
35    /// Guestbook join, ms. `None` = unknown; with no first post either, tenure
36    /// is Indeterminate and the member is never convicted on tenure.
37    pub joined_at_ms: Option<u64>,
38    /// Roles held, by eid — shields key on permissions, never on names.
39    pub roles: Vec<Hash32>,
40    /// Holds a role carrying any moderation permission bit.
41    pub is_staff: bool,
42    /// Everything they have ever said here, not just inside the window.
43    /// Standing is historical by nature: a regular of two years who had a quiet
44    /// week is still a regular, and a window-only count would make them re-earn
45    /// their standing every week. A declared input, so the engine stays pure.
46    pub lifetime_messages: u64,
47    /// Their FIRST post ever, ms. Tenure is the oldest trace of someone, and
48    /// the window can only see a few days of it — a member whose Join was lost
49    /// (or who joined long after they started posting) would otherwise have
50    /// their tenure capped at the window's width and read as a newcomer.
51    pub first_post_ms: Option<u64>,
52}
53
54/// Everything `evaluate` reads. The caller owns fetching, decryption and the
55/// clock; the engine owns only arithmetic.
56#[derive(Debug, Clone)]
57pub struct Signals {
58    pub owner: SubjectId,
59    pub members: Vec<MemberSignal>,
60    /// The corpus, newest-first clamping applied per policy window inside.
61    pub messages: Vec<MessageSignal>,
62    pub channels: Vec<Hash32>,
63    pub relays: Vec<RelayCoverage>,
64    pub requested_from: u64,
65    pub requested_to: u64,
66    pub confirmed_from: u64,
67    pub confirmed_to: u64,
68    pub roster_version: Hash32,
69}
70
71/// Who is evaluating. A member's client runs only stateless rules — word and
72/// link filters over the message in front of it — because everything else needs
73/// history it may not hold and authority it does not have. Admins and
74/// moderation bots run everything.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum EvalMode {
77    Member,
78    Admin,
79}
80
81/// A policy plus the hash of the exact bytes it arrived as. The hash is never
82/// recomputed from a re-serialization — a client that re-encodes JSON has
83/// changed the policy.
84#[derive(Debug, Clone)]
85pub struct LoadedPolicy {
86    pub hash: Hash32,
87    pub policy: Policy,
88    pub activated_at: Option<u64>,
89}
90
91// ── Evaluation ───────────────────────────────────────────────────────────────
92
93/// Evaluate every policy against the signals. Pure: same inputs, same bytes.
94pub fn evaluate(signals: &Signals, policies: &[LoadedPolicy], overrides: &[Override], now_ms: u64) -> ModerationReport {
95    evaluate_as(signals, policies, overrides, now_ms, EvalMode::Admin)
96}
97
98/// [`evaluate`] with an explicit evaluator role.
99pub fn evaluate_as(
100    signals: &Signals,
101    policies: &[LoadedPolicy],
102    overrides: &[Override],
103    now_ms: u64,
104    mode: EvalMode,
105) -> ModerationReport {
106    let mut reports: Vec<PolicyReport> =
107        policies.iter().map(|p| evaluate_one(signals, p, overrides, now_ms, mode)).collect();
108    reports.sort_by_key(|a| a.policy_hash.0);
109
110    // Report-level coverage spans the UNION of every evaluated policy's clamped
111    // corpus: policies declare different windows, so one field cannot describe
112    // just one of them.
113    let mut observed_from = u64::MAX;
114    let mut observed_to = 0u64;
115    let mut per_channel: BTreeMap<[u8; 32], (u32, u64, u64)> = BTreeMap::new();
116    for lp in policies {
117        for m in clamp_corpus(&signals.messages, &lp.policy, now_ms) {
118            observed_from = observed_from.min(m.at_ms);
119            observed_to = observed_to.max(m.at_ms);
120            let e = per_channel.entry(m.channel.0).or_insert((0, u64::MAX, 0));
121            e.0 += 1;
122            e.1 = e.1.min(m.at_ms);
123            e.2 = e.2.max(m.at_ms);
124        }
125    }
126    let mut channels: Vec<ChannelCoverage> = signals
127        .channels
128        .iter()
129        .map(|c| {
130            let (messages, from, to) = per_channel.get(&c.0).copied().unwrap_or((0, 0, 0));
131            ChannelCoverage { channel: *c, messages, from: if from == u64::MAX { 0 } else { from }, to }
132        })
133        .collect();
134    channels.sort_by_key(|a| a.channel.0);
135    let mut relays = signals.relays.clone();
136    relays.sort_by(|a, b| a.url.as_bytes().cmp(b.url.as_bytes()));
137
138    let widest_hours = policies.iter().map(|p| p.policy.window.hours).max().unwrap_or(0);
139    let complete = !relays.is_empty()
140        && relays.iter().all(|r| r.eose)
141        && signals.confirmed_from <= now_ms.saturating_sub(widest_hours.saturating_mul(3_600_000));
142
143    ModerationReport {
144        engine_version: caps::ENGINE_VERSION,
145        bundle_version: caps::BUNDLE_VERSION,
146        roster_version: signals.roster_version,
147        override_hash: override_hash(overrides),
148        evaluated_at: now_ms,
149        window: WindowCoverage {
150            requested_from: signals.requested_from,
151            requested_to: signals.requested_to,
152            confirmed_from: signals.confirmed_from,
153            confirmed_to: signals.confirmed_to,
154            observed_from: if observed_from == u64::MAX { 0 } else { observed_from },
155            observed_to,
156            channels,
157            relays,
158            complete,
159        },
160        policies: reports,
161    }
162}
163
164/// The corpus a policy reads: newest `max_messages` within `[now - hours, now)`,
165/// ordered by inner timestamp, ties by message id ascending.
166fn clamp_corpus<'a>(messages: &'a [MessageSignal], policy: &Policy, now_ms: u64) -> Vec<&'a MessageSignal> {
167    let floor = now_ms.saturating_sub(policy.window.hours.saturating_mul(3_600_000));
168    let mut in_window: Vec<&MessageSignal> = messages.iter().filter(|m| m.at_ms >= floor && m.at_ms < now_ms).collect();
169    in_window.sort_by(|a, b| a.at_ms.cmp(&b.at_ms).then_with(|| a.id.0.cmp(&b.id.0)));
170    if in_window.len() > policy.window.max_messages {
171        in_window.drain(..in_window.len() - policy.window.max_messages);
172    }
173    in_window
174}
175
176struct RuleOutcome {
177    convictions: Vec<Conviction>,
178    citations: Vec<Citation>,
179    unknown: Vec<SubjectId>,
180    state: RuleState,
181}
182
183fn evaluate_one(
184    signals: &Signals,
185    lp: &LoadedPolicy,
186    overrides: &[Override],
187    now_ms: u64,
188    mode: EvalMode,
189) -> PolicyReport {
190    // An INERT policy evaluated NOTHING, and says so: an empty subject list must
191    // never read as "everyone is clean".
192    if let Err(reason) = lp.policy.validate() {
193        return PolicyReport {
194            policy_hash: lp.hash,
195            inert: Some(reason),
196            activated_at: lp.activated_at,
197            coverage_complete: false,
198            rule_status: vec![],
199            subjects: vec![],
200            subjects_truncated: 0,
201            citations: vec![],
202        };
203    }
204
205    let policy = &lp.policy;
206    let corpus = clamp_corpus(&signals.messages, policy, now_ms);
207    let codes = EmojiCodes::from_policy(policy.emoji_codes.iter());
208    let exempt_channels: BTreeSet<[u8; 32]> = policy
209        .exempt
210        .channels
211        .iter()
212        .filter_map(|c| crate::simd::hex::hex_to_bytes_32_checked(c))
213        .collect();
214
215    // Shields gate BEFORE conviction, and only Protected/Trusted gate.
216    let shields = compute_shields(signals, policy, &corpus, &codes, now_ms);
217
218    let mut all_convictions: Vec<Conviction> = Vec::new();
219    let mut all_citations: Vec<Citation> = Vec::new();
220    let mut rule_status: Vec<RuleStatus> = Vec::new();
221    // armed_by counts convictions BEFORE suppression, folding and top-N.
222    let mut convicted_by_rule: BTreeMap<&str, BTreeSet<[u8; 32]>> = BTreeMap::new();
223
224    // Only the people who are HERE can be convicted, or arm anything. The
225    // corpus outlives membership — a banned raider's messages stay in local
226    // storage long after the rotation removed them — so without this the engine
227    // re-litigates people a moderator cannot act on, and last night's attack
228    // keeps arming rules against whoever is still here today. Scores are
229    // present tense; so is the evidence behind them.
230    let member_set: BTreeSet<[u8; 32]> = signals.members.iter().map(|m| m.subject.0).collect();
231
232    for rule in &policy.rules {
233        let mut out = evaluate_rule(rule, policy, signals, &corpus, &codes, &exempt_channels, &shields, lp, now_ms, mode);
234        out.convictions.retain(|c| member_set.contains(&c.subject.0));
235        let mut subjects: BTreeSet<[u8; 32]> = BTreeSet::new();
236        for c in &out.convictions {
237            subjects.insert(c.subject.0);
238        }
239        convicted_by_rule.insert(rule.id.as_str(), subjects);
240        rule_status.push(RuleStatus { rule_id: rule.id.clone(), state: out.state, unknown_subjects: out.unknown });
241        all_convictions.extend(out.convictions);
242        all_citations.extend(out.citations);
243    }
244
245    // Drop convictions whose rule was armed by another that did not fire.
246    all_convictions.retain(|c| {
247        let Some(rule) = policy.rules.iter().find(|r| r.id == c.rule_id) else { return true };
248        let Some(arm) = &rule.armed_by else { return true };
249        // Any one of the named rules arms it: an aggravator that hangs off a
250        // single detector goes silent for every raid that detector cannot see.
251        std::iter::once(&arm.rule).chain(arm.also.iter()).any(|id| {
252            match convicted_by_rule.get(id.as_str()) {
253                Some(s) => match arm.scope {
254                    ArmScope::Subject => s.contains(&c.subject.0),
255                    ArmScope::Community => s.len() as u32 >= arm.min_subjects.unwrap_or(1),
256                },
257                None => false,
258            }
259        })
260    });
261
262    // Pardons: reported, never combined, and their citations are suppressed too
263    // (otherwise a pardon leaves the content consumer still hiding forgiven
264    // messages).
265    let mut pardoned: BTreeSet<[u8; 32]> = BTreeSet::new();
266    for c in &mut all_convictions {
267        if overrides.iter().any(|o| o.matches(c, &lp.hash, now_ms)) {
268            c.suppressed = true;
269            for cid in &c.citations {
270                pardoned.insert(cid.0);
271            }
272        }
273    }
274    for cit in &mut all_citations {
275        if pardoned.contains(&cit.id.0) {
276            cit.suppressed = true;
277        }
278    }
279
280    // Group by subject, run the frozen pipeline, keep what the report must be
281    // able to justify.
282    let mut by_subject: BTreeMap<[u8; 32], Vec<Conviction>> = BTreeMap::new();
283    for c in all_convictions {
284        by_subject.entry(c.subject.0).or_default().push(c);
285    }
286    let mut subjects: Vec<SubjectReport> = Vec::new();
287    for (subject_bytes, mut convictions) in by_subject {
288        let subject = SubjectId(subject_bytes);
289        let score = run_pipeline(&mut convictions);
290        convictions.sort_by(|a, b| a.rule_id.cmp(&b.rule_id).then_with(|| a.scope.cmp(&b.scope)));
291        truncate_convictions(&mut convictions);
292        subjects.push(SubjectReport {
293            subject,
294            shield: shields.get(&subject_bytes).copied().unwrap_or(Shield::None),
295            confidence: score.confidence,
296            proven: score.proven,
297            band: score.band,
298            convictions,
299        });
300    }
301    // A subject is emitted with any conviction OR a non-None shield: a shielded
302    // subject is confidence-0 by construction, so omitting them would delete the
303    // field that explains their immunity.
304    for (bytes, shield) in &shields {
305        if *shield != Shield::None && !subjects.iter().any(|s| s.subject.0 == *bytes) {
306            subjects.push(SubjectReport {
307                subject: SubjectId(*bytes),
308                shield: *shield,
309                confidence: 0,
310                proven: 0,
311                band: super::combine::band(0),
312                convictions: vec![],
313            });
314        }
315    }
316    subjects.sort_by_key(|a| a.subject.0);
317
318    // Citations are a SET holding exactly what retained convictions reference.
319    let retained: BTreeSet<[u8; 32]> =
320        subjects.iter().flat_map(|s| s.convictions.iter()).flat_map(|c| c.citations.iter()).map(|c| c.0).collect();
321    all_citations.retain(|c| retained.contains(&c.id.0));
322    all_citations.sort_by_key(|a| a.id.0);
323    all_citations.dedup_by(|a, b| a.id == b.id);
324
325    let floor = now_ms.saturating_sub(policy.window.hours.saturating_mul(3_600_000));
326    PolicyReport {
327        policy_hash: lp.hash,
328        inert: None,
329        activated_at: lp.activated_at,
330        coverage_complete: signals.confirmed_from <= floor && signals.relays.iter().all(|r| r.eose),
331        rule_status,
332        subjects,
333        subjects_truncated: 0,
334        citations: all_citations,
335    }
336}
337
338/// Retain every conviction that entered EITHER pipeline, then fill to the cap
339/// from the rest in retain order — a report must always justify both scores.
340fn truncate_convictions(convictions: &mut Vec<Conviction>) {
341    if convictions.len() <= caps::MAX_CONVICTIONS_STORED_PER_SUBJECT {
342        return;
343    }
344    let mut order: Vec<usize> = (0..convictions.len()).collect();
345    order.sort_by(|&a, &b| {
346        let (ca, cb) = (&convictions[a], &convictions[b]);
347        let ea = ca.combined || ca.proven_combined;
348        let eb = cb.combined || cb.proven_combined;
349        eb.cmp(&ea)
350            .then_with(|| cb.tier_weight.cmp(&ca.tier_weight))
351            .then_with(|| ca.rule_id.cmp(&cb.rule_id))
352            .then_with(|| ca.scope.cmp(&cb.scope))
353    });
354    let exempt = order.iter().filter(|&&i| convictions[i].combined || convictions[i].proven_combined).count();
355    let keep = exempt.max(caps::MAX_CONVICTIONS_STORED_PER_SUBJECT);
356    let keep_set: BTreeSet<usize> = order.into_iter().take(keep).collect();
357    let mut i = 0usize;
358    convictions.retain(|_| {
359        let k = keep_set.contains(&i);
360        i += 1;
361        k
362    });
363}
364
365fn compute_shields(
366    signals: &Signals,
367    policy: &Policy,
368    corpus: &[&MessageSignal],
369    codes: &EmojiCodes,
370    now_ms: u64,
371) -> BTreeMap<[u8; 32], Shield> {
372    let bar = policy.shields.trusted;
373    let mut volume: BTreeMap<[u8; 32], u64> = BTreeMap::new();
374    let mut variety: BTreeMap<[u8; 32], BTreeSet<String>> = BTreeMap::new();
375    let mut first_post: BTreeMap<[u8; 32], u64> = BTreeMap::new();
376    for m in corpus {
377        *volume.entry(m.author.0).or_insert(0) += 1;
378        let sk = normalize::skeleton(&m.text, codes);
379        if !sk.is_empty() {
380            variety.entry(m.author.0).or_default().insert(sk);
381        }
382        let e = first_post.entry(m.author.0).or_insert(u64::MAX);
383        *e = (*e).min(m.at_ms);
384    }
385    let mut out = BTreeMap::new();
386    for member in &signals.members {
387        let b = member.subject.0;
388        // Protected: the owner, plus holders of a moderation permission bit —
389        // never mere role membership.
390        if member.subject == signals.owner || member.is_staff {
391            out.insert(b, Shield::Protected);
392            continue;
393        }
394        // Tenure = now minus the OLDEST trace of them: their Join, their first
395        // post ever, or the earliest thing they said inside the window —
396        // whichever reaches furthest back. Unknown only when nothing does.
397        let window_first = first_post.get(&b).copied().filter(|v| *v != u64::MAX);
398        let candidates = [member.joined_at_ms, member.first_post_ms, window_first];
399        let oldest = candidates.into_iter().flatten().min();
400        let Some(oldest) = oldest else {
401            out.insert(b, Shield::Indeterminate);
402            continue;
403        };
404        let tenure = now_ms.saturating_sub(oldest) / 1000;
405        let vol = volume.get(&b).copied().unwrap_or(0);
406        let var = variety.get(&b).map(|s| s.len() as u64).unwrap_or(0);
407        // Three paths to standing (§5.3): a role the community granted, long
408        // tenure with any activity, or tenure with volume and variety. Every
409        // path carries a tenure floor, so none of them is farmable in a day.
410        // Volume is LIFETIME (standing is historical); variety is the window's
411        // (how someone speaks now is what tells a person from a script).
412        let lifetime = member.lifetime_messages.max(vol);
413        let by_role = bar.roles_trust && !member.roles.is_empty();
414        let by_veteran = tenure >= bar.veteran_secs && lifetime >= 1;
415        let by_active = tenure >= bar.tenure_secs && lifetime >= bar.messages && var >= bar.distinct;
416        out.insert(b, if by_role || by_veteran || by_active { Shield::Trusted } else { Shield::None });
417    }
418    out
419}
420
421#[allow(clippy::too_many_arguments)]
422fn evaluate_rule(
423    rule: &Rule,
424    policy: &Policy,
425    signals: &Signals,
426    corpus: &[&MessageSignal],
427    codes: &EmojiCodes,
428    exempt_channels: &BTreeSet<[u8; 32]>,
429    shields: &BTreeMap<[u8; 32], Shield>,
430    lp: &LoadedPolicy,
431    _now_ms: u64,
432    mode: EvalMode,
433) -> RuleOutcome {
434    let mut out =
435        RuleOutcome { convictions: vec![], citations: vec![], unknown: vec![], state: RuleState::Evaluated };
436
437    // A member's client judges only what it can judge from one message. Saying
438    // so is the point: a silent skip would read as "clean".
439    if mode == EvalMode::Member && !rule.matcher.is_stateless() {
440        out.state = RuleState::RequiresHistory;
441        return out;
442    }
443
444    // A declared-but-unimplemented normalizer is unevaluated, never approximated.
445    if let Match::Keyword { normalize: n, .. } | Match::Regex { normalize: n, .. } | Match::Repeat { normalize: n, .. } =
446        &rule.matcher
447    {
448        if !normalize::is_available(*n) {
449            out.state = RuleState::UnknownType;
450            return out;
451        }
452    }
453
454    let exempt_roles: BTreeSet<[u8; 32]> = policy
455        .exempt
456        .roles
457        .iter()
458        .chain(rule.exempt.roles.iter())
459        .filter_map(|r| crate::simd::hex::hex_to_bytes_32_checked(r))
460        .collect();
461    let rule_exempt_channels: BTreeSet<[u8; 32]> = rule
462        .exempt
463        .channels
464        .iter()
465        .filter_map(|c| crate::simd::hex::hex_to_bytes_32_checked(c))
466        .chain(exempt_channels.iter().copied())
467        .collect();
468    let exempts: Vec<&ExemptPatterns> = policy.exempt.patterns.iter().chain(rule.exempt.patterns.iter()).collect();
469
470    let subject_exempt = |s: &SubjectId| -> bool {
471        signals
472            .members
473            .iter()
474            .find(|m| m.subject == *s)
475            .is_some_and(|m| m.roles.iter().any(|r| exempt_roles.contains(&r.0)))
476    };
477
478    match &rule.matcher {
479        Match::Keyword { .. } | Match::Regex { .. } | Match::Link { .. } | Match::Mentions {} => {
480            content_rule(rule, policy, corpus, codes, &rule_exempt_channels, &exempts, shields, lp, &subject_exempt, &mut out);
481        }
482        Match::TenureLt { secs } => {
483            for member in &signals.members {
484                if subject_exempt(&member.subject) || gated(shields, &member.subject, rule, 0) {
485                    continue;
486                }
487                match member.joined_at_ms {
488                    // Unknown tenure is per-subject unknown — never a conviction.
489                    None => out.unknown.push(member.subject),
490                    Some(joined) => {
491                        let age = _now_ms.saturating_sub(joined) / 1000;
492                        if age < *secs {
493                            push_direct(rule, lp, member.subject, &mut out);
494                        }
495                    }
496                }
497            }
498        }
499        Match::MessagesLte { n } => {
500            for member in &signals.members {
501                if subject_exempt(&member.subject) || gated(shields, &member.subject, rule, 0) {
502                    continue;
503                }
504                let count = corpus.iter().filter(|m| m.author == member.subject).count() as u32;
505                if count <= *n {
506                    push_direct(rule, lp, member.subject, &mut out);
507                }
508            }
509        }
510        Match::Repeat { .. } | Match::Rate { .. } => {
511            window_rule(rule, corpus, codes, &rule_exempt_channels, shields, lp, &subject_exempt, &mut out);
512        }
513        Match::Cohort { min, quiet_max, short_factor, thin_ratio } => {
514            cohort_rule(
515                rule, corpus, codes, &rule_exempt_channels, shields, lp, &subject_exempt, signals,
516                *min, *quiet_max, *short_factor, thin_ratio.unwrap_or(Ratio { num: 1, denom: 2 }), &mut out,
517            );
518        }
519        Match::JoinBurst { gap_secs, min } => {
520            join_burst_rule(rule, signals, shields, lp, &subject_exempt, *gap_secs, *min, &mut out);
521        }
522    }
523    out
524}
525
526/// Does a shield stop this rule convicting this subject?
527fn gated(shields: &BTreeMap<[u8; 32], Shield>, subject: &SubjectId, rule: &Rule, rung_pierces: usize) -> bool {
528    match shields.get(&subject.0).copied().unwrap_or(Shield::None) {
529        Shield::Protected => true,
530        // Trusted gates EXCEPT against a rung declaring pierces_trusted.
531        Shield::Trusted => rung_pierces == 0 && !rule.pierces_trusted,
532        Shield::None | Shield::Indeterminate => false,
533    }
534}
535
536fn push_direct_with(
537    rule: &Rule,
538    lp: &LoadedPolicy,
539    subject: SubjectId,
540    mut citations: Vec<Citation>,
541    out: &mut RuleOutcome,
542) {
543    citations.sort_by_key(|a| a.id.0);
544    citations.dedup_by(|a, b| a.id == b.id);
545    let citation_count = citations.len() as u32;
546    let earliest = citations.iter().map(|c| c.at).min().unwrap_or(0);
547    let latest = citations.iter().map(|c| c.at).max().unwrap_or(0);
548    citations.truncate(caps::MAX_CITATIONS_PER_CONVICTION);
549    let ids: Vec<CitationId> = citations.iter().map(|c| c.id).collect();
550    out.citations.extend(citations);
551    push_direct(rule, lp, subject, out);
552    if let Some(c) = out.convictions.last_mut() {
553        c.citations = ids;
554        c.citation_count = citation_count;
555        c.earliest_citation_at = earliest;
556        c.latest_citation_at = latest;
557    }
558}
559
560fn push_direct(rule: &Rule, lp: &LoadedPolicy, subject: SubjectId, out: &mut RuleOutcome) {
561    let severity = rule.severity.expect("validated: direct form carries a severity");
562    let weight = rule.weight.expect("validated: direct form carries a weight");
563    out.convictions.push(Conviction {
564        id: conviction_id(&lp.hash, &rule.id, Scope::Whole, 0, &subject),
565        subject,
566        rule_id: rule.id.clone(),
567        scope: Scope::Whole,
568        rung: 0,
569        hits: 1,
570        severity,
571        basis: rule.matcher.basis(),
572        tier_weight: weight,
573        // Citation-less by nature: no content timestamps to compare against a
574        // policy activation, so the honest answer is Unknown.
575        retroactive: Retroactive::Unknown,
576        suppressed: false,
577        folded: false,
578        folded_into: None,
579        combined: false,
580        proven_combined: false,
581        citations: vec![],
582        citation_count: 0,
583        earliest_citation_at: 0,
584        latest_citation_at: 0,
585        family: rule.matcher.builtin_family().map(|s| s.to_string()).or_else(|| rule.family.clone()),
586        evidence: vec![],
587    });
588}
589
590#[allow(clippy::too_many_arguments)]
591fn content_rule(
592    rule: &Rule,
593    _policy: &Policy,
594    corpus: &[&MessageSignal],
595    codes: &EmojiCodes,
596    exempt_channels: &BTreeSet<[u8; 32]>,
597    exempts: &[&ExemptPatterns],
598    shields: &BTreeMap<[u8; 32], Shield>,
599    lp: &LoadedPolicy,
600    subject_exempt: &dyn Fn(&SubjectId) -> bool,
601    out: &mut RuleOutcome,
602) {
603    let tiers = rule.tiers.as_ref().expect("validated: content rules carry tiers");
604    // The needle has to live in the same space as the haystack. Message text is
605    // normalized below; a pattern that is not gets compared against text it can
606    // never equal, so "Vector" silently matched nothing while "vector" matched.
607    // Hoisted out of the corpus loop: this does not vary per message.
608    let folded_patterns: Vec<String> = match &rule.matcher {
609        Match::Keyword { patterns, normalize: n } => {
610            patterns.iter().map(|p| normalize::apply(p, *n, codes)).collect()
611        }
612        _ => Vec::new(),
613    };
614    // (subject, message) -> hits, plus the citations each produced.
615    type MessageHits = (u32, u64, Vec<Citation>);
616    let mut per_message: BTreeMap<([u8; 32], [u8; 32]), MessageHits> = BTreeMap::new();
617
618    for m in corpus {
619        // Exempt content is barred from being CITED, but stays in every corpus
620        // statistic — exemptions change who can be accused, never what the
621        // community looks like.
622        if exempt_channels.contains(&m.channel.0) || subject_exempt(&m.author) {
623            continue;
624        }
625        let (hits, citations) = match &rule.matcher {
626            Match::Keyword { normalize: n, .. } => {
627                let text = normalize::apply(&m.text, *n, codes);
628                let hits = cancel_exempt_hits(&text, keyword_hits(&text, &folded_patterns), exempts);
629                let cits = hits
630                    .iter()
631                    .map(|h| {
632                        let target = CitationTarget::Message { message_id: m.id };
633                        // Carry WHAT matched. A moderator reading "matched rule
634                        // words" learns nothing; reading the word itself can
635                        // judge in a second whether the rule is right.
636                        let matched: String = text
637                            .get(h.start..h.end)
638                            .unwrap_or_default()
639                            .chars()
640                            .take(caps::MAX_DETAIL_LEN)
641                            .collect();
642                        Citation {
643                            id: citation_id(&lp.hash, &rule.id, Scope::PerMessage, &m.author, &target, Some(h.span())),
644                            target,
645                            at: m.at_ms,
646                            span: Some(h.span()),
647                            detail: (!matched.is_empty()).then_some(matched),
648                            suppressed: false,
649                        }
650                    })
651                    .collect::<Vec<_>>();
652                (hits.len() as u32, cits)
653            }
654            Match::Link { patterns } => {
655                let domains = link_hits(&m.text, patterns, exempts);
656                let target = CitationTarget::Message { message_id: m.id };
657                // A link hit is a domain, not a text range: no span.
658                let cits = if domains.is_empty() {
659                    vec![]
660                } else {
661                    vec![Citation {
662                        id: citation_id(&lp.hash, &rule.id, Scope::PerMessage, &m.author, &target, None),
663                        target,
664                        at: m.at_ms,
665                        span: None,
666                        detail: Some(domains.join(", ")),
667                        suppressed: false,
668                    }]
669                };
670                (domains.len() as u32, cits)
671            }
672            Match::Mentions {} => {
673                let target = CitationTarget::Message { message_id: m.id };
674                let cits = if m.mentions == 0 {
675                    vec![]
676                } else {
677                    vec![Citation {
678                        id: citation_id(&lp.hash, &rule.id, Scope::PerMessage, &m.author, &target, None),
679                        target,
680                        at: m.at_ms,
681                        span: None,
682                        detail: None,
683                        suppressed: false,
684                    }]
685                };
686                (m.mentions, cits)
687            }
688            // Regex needs the pinned crate build; declared, not yet wired.
689            _ => (0, vec![]),
690        };
691        if hits > 0 {
692            per_message.insert((m.author.0, m.id.0), (hits, m.at_ms, citations));
693        }
694    }
695
696    // Per-subject: every message's own hit count, kept individually so a
697    // density rung can cite EVERY message that reached it.
698    let mut by_subject: BTreeMap<[u8; 32], Vec<(u32, Vec<Citation>)>> = BTreeMap::new();
699    for ((subject, _), (hits, _at, cits)) in per_message {
700        by_subject.entry(subject).or_default().push((hits, cits));
701    }
702
703    for (subject_bytes, messages) in by_subject {
704        let subject = SubjectId(subject_bytes);
705        // Density = the densest single message; persistence = the window sum.
706        let density: u32 = messages.iter().map(|(h, _)| *h).max().unwrap_or(0);
707        let persistence: u32 = messages.iter().map(|(h, _)| *h).sum();
708
709        for (scope, rungs, hits) in [
710            (Scope::PerMessage, &tiers.per_message, density),
711            (Scope::PerWindow, &tiers.per_window, persistence),
712        ] {
713            if rungs.is_empty() {
714                continue;
715            }
716            // The highest rung reached: rungs validate strictly ascending.
717            let Some((idx, rung)) = rungs.iter().enumerate().rfind(|(_, g)| hits >= g.hits) else {
718                continue;
719            };
720            if gated(shields, &subject, rule, usize::from(rung.pierces_trusted)) {
721                continue;
722            }
723            // A density conviction cites every message whose OWN hit count meets
724            // the rung that fired; a persistence conviction cites the whole
725            // contributing window.
726            let citations: Vec<Citation> = match scope {
727                Scope::PerMessage => {
728                    messages.iter().filter(|(h, _)| *h >= rung.hits).flat_map(|(_, c)| c.iter().cloned()).collect()
729                }
730                _ => messages.iter().flat_map(|(_, c)| c.iter().cloned()).collect(),
731            };
732            push_tiered(rule, lp, subject, scope, idx as u8, hits, rung, citations, out);
733        }
734    }
735}
736
737/// Cross-account clustering: many identities posting one shape.
738///
739/// A cluster convicts on TWO counts, never one. Size alone would hang a
740/// community catchphrase on whoever repeats it, so the cluster must also be
741/// THIN — a script gives each identity a line or two, while regulars who share
742/// a greeting have hundreds of other messages between them. A short shape is
743/// cheap coincidence on top of that, so it clears a higher size bar.
744///
745/// Statistics read the FULL corpus: exempt members and channels still count
746/// toward cluster size and thinness (exemptions change who can be accused,
747/// never what the community looks like), they simply cannot be convicted.
748#[allow(clippy::too_many_arguments)]
749fn cohort_rule(
750    rule: &Rule,
751    corpus: &[&MessageSignal],
752    codes: &EmojiCodes,
753    exempt_channels: &BTreeSet<[u8; 32]>,
754    shields: &BTreeMap<[u8; 32], Shield>,
755    lp: &LoadedPolicy,
756    subject_exempt: &dyn Fn(&SubjectId) -> bool,
757    signals: &Signals,
758    min: u32,
759    quiet_max: u32,
760    short_factor: u32,
761    thin_ratio: Ratio,
762    out: &mut RuleOutcome,
763) {
764    // skeleton -> the distinct authors who posted it, plus their messages.
765    let mut clusters: BTreeMap<String, BTreeMap<[u8; 32], Vec<&MessageSignal>>> = BTreeMap::new();
766    for m in corpus {
767        let key = normalize::skeleton(&m.text, codes);
768        if key.is_empty() {
769            continue;
770        }
771        clusters.entry(key).or_default().entry(m.author.0).or_default().push(m);
772    }
773    // Window volume per author — the thinness input.
774    let mut volume: BTreeMap<[u8; 32], u32> = BTreeMap::new();
775    for m in corpus {
776        *volume.entry(m.author.0).or_insert(0) += 1;
777    }
778    for authors in clusters.values_mut() {
779        keep_densest_burst(authors, caps::COHORT_SPAN_MS);
780    }
781
782    // Each subject is convicted once (scope Whole) on the LARGEST cluster they
783    // belong to; ties break by clustering key ascending.
784    let mut best: BTreeMap<[u8; 32], (usize, String)> = BTreeMap::new();
785    for (key, authors) in &clusters {
786        let need = if key.chars().count() < caps::COHORT_PAYLOAD_LEN {
787            min.saturating_mul(short_factor)
788        } else {
789            min
790        } as usize;
791        if authors.len() < need {
792            continue;
793        }
794        let thin = authors.keys().filter(|a| volume.get(*a).copied().unwrap_or(0) <= quiet_max).count();
795        if (thin as u64) * (thin_ratio.denom as u64) < (authors.len() as u64) * (thin_ratio.num as u64) {
796            continue;
797        }
798        for (author, said) in authors {
799            // A member who has been talking and also said this line is in the
800            // room, not in the wave: the line must be most of what they wrote.
801            if (said.len() as u64) * 2 < u64::from(volume.get(author).copied().unwrap_or(0)) {
802                continue;
803            }
804            let slot = best.entry(*author).or_insert((0, String::new()));
805            if authors.len() > slot.0 {
806                *slot = (authors.len(), key.clone());
807            }
808        }
809    }
810
811    for (author_bytes, (size, key)) in best {
812        let subject = SubjectId(author_bytes);
813        if subject_exempt(&subject) || gated(shields, &subject, rule, usize::from(rule.pierces_trusted)) {
814            continue;
815        }
816        let messages = clusters.get(&key).and_then(|a| a.get(&author_bytes)).cloned().unwrap_or_default();
817        // Exempt content is barred from being cited even though it counted
818        // toward the cluster's shape.
819        let citable: Vec<&MessageSignal> =
820            messages.iter().copied().filter(|m| !exempt_channels.contains(&m.channel.0)).collect();
821        if citable.is_empty() {
822            continue;
823        }
824        let citations: Vec<Citation> = citable
825            .iter()
826            .map(|m| {
827                let target = CitationTarget::Message { message_id: m.id };
828                Citation {
829                    id: citation_id(&lp.hash, &rule.id, Scope::Whole, &subject, &target, None),
830                    target,
831                    at: m.at_ms,
832                    span: None,
833                    detail: None,
834                    suppressed: false,
835                }
836            })
837            .collect();
838        // The sample is the lowest inner message id in the cluster, excluding
839        // exempt members and channels: `peers` already omits them, and a sample
840        // would leak the same accusation the report may not make.
841        let sample = clusters
842            .get(&key)
843            .map(|authors| {
844                let mut candidates: Vec<&MessageSignal> = authors
845                    .iter()
846                    .filter(|(a, _)| !subject_exempt(&SubjectId(**a)))
847                    .flat_map(|(_, ms)| ms.iter().copied())
848                    .filter(|m| !exempt_channels.contains(&m.channel.0))
849                    .collect();
850                candidates.sort_by_key(|a| a.id.0);
851                candidates.first().map(|m| m.text.clone()).unwrap_or_default()
852            })
853            .unwrap_or_default();
854        let mut peers: Vec<SubjectId> = clusters
855            .get(&key)
856            .map(|a| a.keys().filter(|k| **k != author_bytes).map(|k| SubjectId(*k)).collect())
857            .unwrap_or_default();
858        peers.sort_by_key(|a| a.0);
859        peers.truncate(caps::COHORT_SAMPLE_CAP);
860        use sha2::Digest;
861        let mut hasher = sha2::Sha256::default();
862        hasher.update(key.as_bytes());
863        let evidence = vec![Evidence::Cohort {
864            skeleton_hash: Hash32(hasher.finalize().into()),
865            sample: sample.chars().take(caps::MAX_SAMPLE_LEN).collect(),
866            size: size as u32,
867            peers,
868        }];
869        let before = out.convictions.len();
870        push_direct_with(rule, lp, subject, citations, out);
871        if let Some(c) = out.convictions.get_mut(before) {
872            c.evidence = evidence;
873        }
874    }
875    let _ = signals;
876}
877
878/// Narrow one cluster to its densest burst: the window of `span_ms` holding the
879/// most distinct authors (earliest such window on a tie), keeping only the
880/// messages inside it.
881fn keep_densest_burst(authors: &mut BTreeMap<[u8; 32], Vec<&MessageSignal>>, span_ms: u64) {
882    let mut said: Vec<(u64, [u8; 32])> =
883        authors.iter().flat_map(|(a, ms)| ms.iter().map(move |m| (m.at_ms, *a))).collect();
884    said.sort();
885    let mut inside: BTreeMap<[u8; 32], usize> = BTreeMap::new();
886    let (mut best, mut best_authors, mut start) = ((0usize, 0usize), 0usize, 0usize);
887    for end in 0..said.len() {
888        *inside.entry(said[end].1).or_insert(0) += 1;
889        while said[end].0.saturating_sub(said[start].0) > span_ms {
890            if let Some(n) = inside.get_mut(&said[start].1) {
891                *n -= 1;
892                if *n == 0 {
893                    inside.remove(&said[start].1);
894                }
895            }
896            start += 1;
897        }
898        if inside.len() > best_authors {
899            best_authors = inside.len();
900            best = (start, end + 1);
901        }
902    }
903    let (from, to) = match (said.get(best.0), best.1.checked_sub(1).and_then(|i| said.get(i))) {
904        (Some(a), Some(b)) => (a.0, b.0),
905        _ => return,
906    };
907    for ms in authors.values_mut() {
908        ms.retain(|m| m.at_ms >= from && m.at_ms <= to);
909    }
910    authors.retain(|_, ms| !ms.is_empty());
911}
912
913/// The densest run of joins inside one window. Deliberately weak alone: a
914/// freshly-posted invite link is SUPPOSED to bring a burst of quiet newcomers,
915/// so this is normally `armed_by` a cohort rule and convicts nobody until
916/// something else already has.
917#[allow(clippy::too_many_arguments)]
918fn join_burst_rule(
919    rule: &Rule,
920    signals: &Signals,
921    shields: &BTreeMap<[u8; 32], Shield>,
922    lp: &LoadedPolicy,
923    subject_exempt: &dyn Fn(&SubjectId) -> bool,
924    gap_secs: u64,
925    min: u32,
926    out: &mut RuleOutcome,
927) {
928    // The owner is never part of a burst, and an unknown join is not evidence
929    // of one.
930    let mut joins: Vec<(u64, SubjectId)> = signals
931        .members
932        .iter()
933        .filter(|m| m.subject != signals.owner)
934        .filter_map(|m| m.joined_at_ms.map(|at| (at, m.subject)))
935        .collect();
936    joins.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1 .0.cmp(&b.1 .0)));
937    let gap_ms = gap_secs.saturating_mul(1000);
938    let (mut best_start, mut best_len) = (0usize, 0usize);
939    let mut start = 0usize;
940    for end in 0..joins.len() {
941        while joins[end].0.saturating_sub(joins[start].0) > gap_ms {
942            start += 1;
943        }
944        // Strictly greater: on a tie the EARLIEST window wins, which is where a
945        // raid starts.
946        if end + 1 - start > best_len {
947            best_len = end + 1 - start;
948            best_start = start;
949        }
950    }
951    if best_len < min as usize {
952        return;
953    }
954    let window = &joins[best_start..best_start + best_len];
955    let evidence = vec![Evidence::Burst {
956        from: window.first().map(|(at, _)| *at).unwrap_or(0),
957        to: window.last().map(|(at, _)| *at).unwrap_or(0),
958        size: best_len as u32,
959    }];
960    for (_, subject) in window {
961        if subject_exempt(subject) || gated(shields, subject, rule, usize::from(rule.pierces_trusted)) {
962            continue;
963        }
964        let before = out.convictions.len();
965        push_direct(rule, lp, *subject, out);
966        if let Some(c) = out.convictions.get_mut(before) {
967            c.evidence = evidence.clone();
968        }
969    }
970}
971
972/// Window-level rules: one conviction per subject, scope PerWindow.
973///
974///  * `repeat` — the most-repeated normalized text by that author; ties break by
975///    the normalized key ascending, so the citation set is reproducible. This is
976///    the copy-paste counter that catches one account spamming, where `cohort`
977///    catches many accounts sharing one line.
978///  * `rate` — the densest half-open `[t, t + per_secs)` span over the author's
979///    own message timestamps; ties take the EARLIEST span.
980#[allow(clippy::too_many_arguments)]
981fn window_rule(
982    rule: &Rule,
983    corpus: &[&MessageSignal],
984    codes: &EmojiCodes,
985    exempt_channels: &BTreeSet<[u8; 32]>,
986    shields: &BTreeMap<[u8; 32], Shield>,
987    lp: &LoadedPolicy,
988    subject_exempt: &dyn Fn(&SubjectId) -> bool,
989    out: &mut RuleOutcome,
990) {
991    let tiers = rule.tiers.as_ref().expect("validated: window rules carry tiers");
992    let rungs = &tiers.per_window;
993    if rungs.is_empty() {
994        return;
995    }
996    // Citable content only: exempt content still counts toward the corpus
997    // statistics every other rule reads, but it can never be cited here.
998    let mut by_author: BTreeMap<[u8; 32], Vec<&MessageSignal>> = BTreeMap::new();
999    for m in corpus {
1000        if exempt_channels.contains(&m.channel.0) || subject_exempt(&m.author) {
1001            continue;
1002        }
1003        by_author.entry(m.author.0).or_default().push(m);
1004    }
1005
1006    for (subject_bytes, messages) in by_author {
1007        let subject = SubjectId(subject_bytes);
1008        let (hits, cited, evidence) = match &rule.matcher {
1009            Match::Repeat { normalize: n, within_secs } => {
1010                let mut groups: BTreeMap<String, Vec<&MessageSignal>> = BTreeMap::new();
1011                for m in &messages {
1012                    let key = normalize::apply(&m.text, *n, codes);
1013                    if key.is_empty() {
1014                        continue;
1015                    }
1016                    groups.entry(key).or_default().push(m);
1017                }
1018                // With a span, each group counts only its densest run inside it,
1019                // and the winner is the tightest burst rather than the biggest
1020                // pile. "gm" once a morning is seven hits across a week and one
1021                // hit in any half hour, which is the difference between a
1022                // regular and a spammer.
1023                let scored: Vec<(String, u32, Vec<&MessageSignal>)> = groups
1024                    .into_iter()
1025                    .map(|(key, mut ms)| {
1026                        let Some(secs) = within_secs else {
1027                            let n = ms.len() as u32;
1028                            return (key, n, ms);
1029                        };
1030                        ms.sort_by_key(|m| m.at_ms);
1031                        let span = secs.saturating_mul(1000);
1032                        let (mut best, mut from) = (0usize, 0u64);
1033                        for (i, m) in ms.iter().enumerate() {
1034                            // Half-open [start, start + span), starts taken from
1035                            // the author's own timestamps — same walk as `Rate`.
1036                            let start = m.at_ms;
1037                            let count =
1038                                ms[i..].iter().take_while(|x| x.at_ms < start.saturating_add(span)).count();
1039                            if count > best {
1040                                best = count;
1041                                from = start;
1042                            }
1043                        }
1044                        let cited: Vec<&MessageSignal> = ms
1045                            .into_iter()
1046                            .filter(|m| m.at_ms >= from && m.at_ms < from.saturating_add(span))
1047                            .collect();
1048                        (key, best as u32, cited)
1049                    })
1050                    .collect();
1051                // Most repeated wins; ties by the normalized key ascending.
1052                let Some((_key, n_hits, winners)) =
1053                    scored.into_iter().max_by(|a, b| a.1.cmp(&b.1).then_with(|| b.0.cmp(&a.0)))
1054                else {
1055                    continue;
1056                };
1057                (n_hits, winners, vec![])
1058            }
1059            Match::Rate { per_secs } => {
1060                let mut times: Vec<u64> = messages.iter().map(|m| m.at_ms).collect();
1061                times.sort_unstable();
1062                let span = per_secs.saturating_mul(1000);
1063                let (mut best, mut best_from) = (0usize, 0u64);
1064                for (i, &start) in times.iter().enumerate() {
1065                    // Half-open [start, start + span); candidate starts are the
1066                    // author's own timestamps, never every millisecond.
1067                    let count = times[i..].iter().take_while(|&&t| t < start.saturating_add(span)).count();
1068                    if count > best {
1069                        best = count;
1070                        best_from = start;
1071                    }
1072                }
1073                let cited: Vec<&MessageSignal> = messages
1074                    .iter()
1075                    .copied()
1076                    .filter(|m| m.at_ms >= best_from && m.at_ms < best_from.saturating_add(span))
1077                    .collect();
1078                (
1079                    best as u32,
1080                    cited,
1081                    vec![Evidence::Rate { window_secs: *per_secs, count: best as u32, from: best_from }],
1082                )
1083            }
1084            _ => continue,
1085        };
1086
1087        let Some((idx, rung)) = rungs.iter().enumerate().rfind(|(_, g)| hits >= g.hits) else {
1088            continue;
1089        };
1090        if gated(shields, &subject, rule, usize::from(rung.pierces_trusted)) {
1091            continue;
1092        }
1093        let citations: Vec<Citation> = cited
1094            .iter()
1095            .map(|m| {
1096                let target = CitationTarget::Message { message_id: m.id };
1097                Citation {
1098                    id: citation_id(&lp.hash, &rule.id, Scope::PerWindow, &subject, &target, None),
1099                    target,
1100                    at: m.at_ms,
1101                    span: None,
1102                    detail: None,
1103                    suppressed: false,
1104                }
1105            })
1106            .collect();
1107        let before = out.convictions.len();
1108        push_tiered(rule, lp, subject, Scope::PerWindow, idx as u8, hits, rung, citations, out);
1109        if let Some(c) = out.convictions.get_mut(before) {
1110            c.evidence = evidence;
1111        }
1112    }
1113}
1114
1115#[allow(clippy::too_many_arguments)]
1116fn push_tiered(
1117    rule: &Rule,
1118    lp: &LoadedPolicy,
1119    subject: SubjectId,
1120    scope: Scope,
1121    rung_idx: u8,
1122    hits: u32,
1123    rung: &Rung,
1124    mut citations: Vec<Citation>,
1125    out: &mut RuleOutcome,
1126) {
1127    citations.sort_by_key(|a| a.id.0);
1128    citations.dedup_by(|a, b| a.id == b.id);
1129    // Counts and timestamps come from the FULL set, so a truncated exhibit list
1130    // never reads as fewer offenses nor flips `retroactive`.
1131    let citation_count = citations.len() as u32;
1132    let earliest = citations.iter().map(|c| c.at).min().unwrap_or(0);
1133    let latest = citations.iter().map(|c| c.at).max().unwrap_or(0);
1134    // Pre-Phase-4 there is no signed activation, so retroactivity is Unknown —
1135    // never `No`, which a locally-set activation time would fake.
1136    let retroactive = match lp.activated_at {
1137        None => Retroactive::Unknown,
1138        Some(activated) => {
1139            if citations.is_empty() {
1140                Retroactive::Unknown
1141            } else if latest >= activated {
1142                Retroactive::No
1143            } else {
1144                Retroactive::Yes
1145            }
1146        }
1147    };
1148    citations.truncate(caps::MAX_CITATIONS_PER_CONVICTION);
1149    let ids: Vec<CitationId> = citations.iter().map(|c| c.id).collect();
1150    out.citations.extend(citations);
1151    out.convictions.push(Conviction {
1152        id: conviction_id(&lp.hash, &rule.id, scope, rung_idx, &subject),
1153        subject,
1154        rule_id: rule.id.clone(),
1155        scope,
1156        rung: rung_idx,
1157        hits,
1158        severity: rung.severity,
1159        basis: rule.matcher.basis(),
1160        tier_weight: rung.weight,
1161        retroactive,
1162        suppressed: false,
1163        folded: false,
1164        folded_into: None,
1165        combined: false,
1166        proven_combined: false,
1167        citations: ids,
1168        citation_count,
1169        earliest_citation_at: earliest,
1170        latest_citation_at: latest,
1171        family: rule.family.clone(),
1172        evidence: vec![],
1173    });
1174}
1175
1176/// Which rules a policy would refuse a send under (cooperative prevention).
1177/// Only Deterministic rules reach here — the validator already refused the rest.
1178pub fn refusing_rules(policy: &Policy) -> Vec<&Rule> {
1179    policy.rules.iter().filter(|r| r.enforcement == Enforcement::Refuse).collect()
1180}
1181
1182/// Union of a policy-level and rule-level exemption block.
1183pub fn merged_exempt<'a>(policy: &'a Exempt, rule: &'a Exempt) -> Vec<&'a ExemptPatterns> {
1184    policy.patterns.iter().chain(rule.patterns.iter()).collect()
1185}
1186
1187#[cfg(test)]
1188mod tests {
1189    use super::super::document::*;
1190    use super::*;
1191
1192    const HOUR: u64 = 3_600_000;
1193    const NOW: u64 = 1_800_000_000_000;
1194
1195    fn sid(b: u8) -> SubjectId {
1196        SubjectId([b; 32])
1197    }
1198    fn mid(b: u8) -> MessageId {
1199        MessageId([b; 32])
1200    }
1201    fn ch(b: u8) -> Hash32 {
1202        Hash32([b; 32])
1203    }
1204
1205    fn msg(id: u8, author: u8, at: u64, text: &str) -> MessageSignal {
1206        MessageSignal { id: mid(id), author: sid(author), channel: ch(0x0a), at_ms: at, text: text.into(), mentions: 0 }
1207    }
1208
1209    fn member(b: u8, joined_ago_h: Option<u64>) -> MemberSignal {
1210        MemberSignal {
1211            subject: sid(b),
1212            joined_at_ms: joined_ago_h.map(|h| NOW - h * HOUR),
1213            roles: vec![],
1214            is_staff: false,
1215            lifetime_messages: 0,
1216            first_post_ms: None,
1217        }
1218    }
1219
1220    fn signals(members: Vec<MemberSignal>, messages: Vec<MessageSignal>) -> Signals {
1221        Signals {
1222            owner: sid(0xf0),
1223            members,
1224            messages,
1225            channels: vec![ch(0x0a)],
1226            relays: vec![RelayCoverage { url: "wss://r".into(), eose: true, events: 10 }],
1227            requested_from: NOW - 24 * HOUR,
1228            requested_to: NOW,
1229            confirmed_from: 0,
1230            confirmed_to: NOW,
1231            roster_version: Hash32([0x77; 32]),
1232        }
1233    }
1234
1235    fn loaded(policy: Policy) -> LoadedPolicy {
1236        LoadedPolicy { hash: Hash32([0x11; 32]), policy, activated_at: None }
1237    }
1238
1239    fn policy_with(rules: Vec<Rule>) -> Policy {
1240        Policy {
1241            format: FORMAT,
1242            requires: vec![],
1243            name: "p".into(),
1244            emoji_codes: vec![],
1245            shields: Shields::default(),
1246            window: Window::default(),
1247            exempt: Exempt::default(),
1248            rules,
1249        }
1250    }
1251
1252    fn link_rule() -> Rule {
1253        Rule {
1254            id: "links".into(),
1255            matcher: Match::Link { patterns: vec![] },
1256            tiers: Some(Tiers {
1257                per_message: vec![Rung { hits: 1, severity: Severity::Severe, weight: 70, pierces_trusted: false }],
1258                per_window: vec![Rung { hits: 3, severity: Severity::Severe, weight: 90, pierces_trusted: false }],
1259            }),
1260            severity: None,
1261            weight: None,
1262            pierces_trusted: false,
1263            family: None,
1264            armed_by: None,
1265            exempt: Exempt {
1266                patterns: vec![ExemptPatterns {
1267                    kind: Some(ExemptKind::Domain),
1268                    values: vec!["vectorapp.io".into()],
1269                }],
1270                ..Default::default()
1271            },
1272            enforcement: Enforcement::Advisory,
1273        }
1274    }
1275
1276    fn only(report: &ModerationReport) -> &PolicyReport {
1277        &report.policies[0]
1278    }
1279
1280    fn subject<'a>(pr: &'a PolicyReport, b: u8) -> Option<&'a SubjectReport> {
1281        pr.subjects.iter().find(|s| s.subject == sid(b))
1282    }
1283
1284    /// The design's Strict Link Blocker: three links fire BOTH scopes, and the
1285    /// numbers must match the frozen reference (70 + 90 -> 970pm -> 97).
1286    #[test]
1287    fn strict_link_blocker_reproduces_the_reference_vector() {
1288        let s = signals(
1289            vec![member(1, Some(2))],
1290            vec![
1291                msg(0xb1, 1, NOW - 3 * HOUR, "grab it at bit.ly/a"),
1292                msg(0xb2, 1, NOW - 2 * HOUR, "also tr.ee/b"),
1293                msg(0xb3, 1, NOW - HOUR, "and shm.to/c"),
1294            ],
1295        );
1296        let r = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1297        let pr = only(&r);
1298        let sub = subject(pr, 1).expect("the linker is reported");
1299        assert_eq!((sub.confidence, sub.proven), (97, 97), "both scopes, both Deterministic");
1300        assert_eq!(sub.band, Band::Alert);
1301        let scopes: Vec<Scope> = sub.convictions.iter().map(|c| c.scope).collect();
1302        assert_eq!(scopes, vec![Scope::PerMessage, Scope::PerWindow], "density and persistence both convict");
1303        assert_eq!(pr.citations.len(), 3, "one citation per offending message");
1304        assert!(pr.citations.iter().all(|c| c.span.is_none()), "a link hit is a domain, not a text span");
1305    }
1306
1307    #[test]
1308    fn an_allowlisted_domain_never_produces_a_hit() {
1309        let s = signals(
1310            vec![member(1, Some(2))],
1311            vec![msg(0xb1, 1, NOW - HOUR, "read https://vectorapp.io/blog and https://vectorapp.io/x")],
1312        );
1313        let r = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1314        assert!(subject(only(&r), 1).is_none(), "no conviction, and no subject to report");
1315        assert!(only(&r).citations.is_empty());
1316    }
1317
1318    /// Exempt content is barred from being CITED but stays in every corpus
1319    /// statistic — the rung arithmetic counts citable hits only.
1320    #[test]
1321    fn an_exempt_channel_contributes_no_hits() {
1322        let mut s = signals(
1323            vec![member(1, Some(2))],
1324            vec![msg(0xb1, 1, NOW - HOUR, "bit.ly/a"), msg(0xb2, 1, NOW - HOUR, "tr.ee/b")],
1325        );
1326        s.messages[1].channel = ch(0x0b);
1327        let mut p = policy_with(vec![link_rule()]);
1328        p.exempt.channels = vec![crate::simd::hex::bytes_to_hex_32(&[0x0b; 32])];
1329        let r = evaluate(&s, &[loaded(p)], &[], NOW);
1330        let sub = subject(only(&r), 1).unwrap();
1331        assert_eq!(sub.convictions.len(), 1, "only the density rung is reached; two links would have been needed");
1332        assert_eq!(sub.convictions[0].scope, Scope::PerMessage);
1333        assert_eq!(only(&r).citations.len(), 1, "the exempt channel's message is never cited");
1334    }
1335
1336    #[test]
1337    fn the_soft_swear_ladder_lands_in_review_not_alert() {
1338        let keyword = Rule {
1339            id: "swears".into(),
1340            matcher: Match::Keyword { patterns: vec!["darn".into()], normalize: Normalize::Fold },
1341            tiers: Some(Tiers {
1342                per_message: vec![Rung { hits: 1, severity: Severity::Minor, weight: 10, pierces_trusted: false }],
1343                per_window: vec![Rung { hits: 10, severity: Severity::Severe, weight: 70, pierces_trusted: false }],
1344            }),
1345            severity: None,
1346            weight: None,
1347            pierces_trusted: false,
1348            family: None,
1349            armed_by: None,
1350            exempt: Exempt::default(),
1351            enforcement: Enforcement::Advisory,
1352        };
1353        let messages: Vec<MessageSignal> =
1354            (0..10).map(|i| msg(0xc0 + i as u8, 1, NOW - (i + 1) * HOUR, "darn it")).collect();
1355        let s = signals(vec![member(1, Some(2))], messages);
1356        let r = evaluate(&s, &[loaded(policy_with(vec![keyword]))], &[], NOW);
1357        let sub = subject(only(&r), 1).unwrap();
1358        // 10 + 70 -> 730pm -> 73: the soft policy peaks at human review.
1359        assert_eq!(sub.confidence, 73);
1360        assert_eq!(sub.band, Band::Flagged);
1361    }
1362
1363    /// Shields gate before conviction: Protected is absolute, Trusted yields
1364    /// only to a piercing rung, Indeterminate never gates.
1365    #[test]
1366    fn shields_gate_exactly_as_declared() {
1367        let mut s = signals(
1368            vec![
1369                member(1, Some(24 * 30)), // long tenure, will be Trusted
1370                member(2, None),          // no join, no posts elsewhere: Indeterminate
1371                MemberSignal { subject: sid(3), joined_at_ms: Some(NOW - HOUR), roles: vec![], is_staff: true, lifetime_messages: 0, first_post_ms: None },
1372            ],
1373            vec![],
1374        );
1375        // Give the veteran enough varied history to clear the trust bar. The
1376        // text must be genuinely varied: `skeleton` strips digits, so numbered
1377        // fixtures collapse to ONE distinct shape and clear nothing.
1378        const WORDS: [&str; 20] = [
1379            "morning all", "shipping today", "nice one", "agreed", "on it", "good catch", "thanks",
1380            "will review", "merged", "looks fine", "same here", "no idea", "try again", "fixed now",
1381            "welcome aboard", "see you", "sounds good", "my turn", "any thoughts", "done",
1382        ];
1383        for (i, w) in WORDS.iter().enumerate() {
1384            s.messages.push(msg(0x40 + i as u8, 1, NOW - (i as u64 + 1) * HOUR, w));
1385        }
1386        s.messages.push(msg(0xd1, 1, NOW - HOUR, "bit.ly/a"));
1387        s.messages.push(msg(0xd2, 2, NOW - HOUR, "bit.ly/b"));
1388        s.messages.push(msg(0xd3, 3, NOW - HOUR, "bit.ly/c"));
1389
1390        let r = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1391        let pr = only(&r);
1392        assert_eq!(subject(pr, 1).unwrap().shield, Shield::Trusted);
1393        assert!(subject(pr, 1).unwrap().convictions.is_empty(), "a non-piercing rule cannot touch Trusted");
1394        // A member with no Join but who HAS posted has a known tenure (the
1395        // oldest trace is their first post), so they are simply un-Trusted.
1396        assert_eq!(subject(pr, 2).unwrap().shield, Shield::None);
1397        assert!(!subject(pr, 2).unwrap().convictions.is_empty(), "no shield, ordinary conviction");
1398        assert_eq!(subject(pr, 3).unwrap().shield, Shield::Protected);
1399        assert!(subject(pr, 3).unwrap().convictions.is_empty(), "staff are never convicted");
1400
1401        // The same evidence WITH a piercing rung reaches the Trusted member.
1402        let mut piercing = link_rule();
1403        piercing.tiers.as_mut().unwrap().per_message[0].pierces_trusted = true;
1404        piercing.pierces_trusted = true;
1405        let r = evaluate(&s, &[loaded(policy_with(vec![piercing]))], &[], NOW);
1406        assert!(!subject(only(&r), 1).unwrap().convictions.is_empty(), "a piercing rung reaches Trusted");
1407        assert!(subject(only(&r), 3).unwrap().convictions.is_empty(), "but nothing pierces Protected");
1408    }
1409
1410    /// Standing has three doors, and none of them opens in a day.
1411    #[test]
1412    fn trust_comes_from_roles_tenure_or_sustained_activity() {
1413        let day = 24 * HOUR;
1414        // A role the community granted is a vouch: trusted, though NOT immune
1415        // (that is Protected, and it keys on moderation permissions).
1416        let with_role =
1417            MemberSignal { subject: sid(1), joined_at_ms: Some(NOW - day), roles: vec![ch(0xaa)], is_staff: false, lifetime_messages: 0, first_post_ms: None };
1418        let veteran = member(2, Some(24 * 40));
1419        let active = member(3, Some(24 * 8));
1420        let lurker = member(4, Some(24 * 8));
1421        let loud_newcomer = member(5, Some(1));
1422
1423        let mut s = signals(vec![with_role, veteran, active, lurker, loud_newcomer], vec![]);
1424        s.messages.push(msg(0x50, 2, NOW - HOUR, "still here"));
1425        const VARIED: [&str; 5] = ["morning all", "shipping today", "nice one", "agreed", "on it"];
1426        for (i, w) in VARIED.iter().enumerate() {
1427            s.messages.push(msg(0x60 + i as u8, 3, NOW - (i as u64 + 1) * HOUR, w));
1428            s.messages.push(msg(0x70 + i as u8, 5, NOW - (i as u64 + 1) * HOUR, w));
1429        }
1430
1431        let r = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1432        let pr = only(&r);
1433        let shield = |b: u8| subject(pr, b).map(|x| x.shield);
1434        assert_eq!(shield(1), Some(Shield::Trusted), "a granted role vouches");
1435        assert_eq!(shield(2), Some(Shield::Trusted), "long tenure plus any activity");
1436        assert_eq!(shield(3), Some(Shield::Trusted), "tenure with volume and variety");
1437        assert_eq!(shield(4), None, "a silent week earns nothing");
1438        assert_eq!(shield(5), None, "and chatter cannot buy standing in a day");
1439    }
1440
1441    /// A regular of months who had a quiet week keeps their standing: volume is
1442    /// lifetime, not "what have you said for me lately".
1443    #[test]
1444    fn a_quiet_week_does_not_cost_a_regular_their_standing() {
1445        let mut veteran = member(6, Some(24 * 10));
1446        veteran.lifetime_messages = 900;
1447        let mut newcomer = member(7, Some(2));
1448        newcomer.lifetime_messages = 900; // history it could not possibly have
1449        let mut s = signals(vec![veteran, newcomer], vec![]);
1450        // Three distinct shapes this week is all the variety bar asks for.
1451        for (i, w) in ["morning all", "shipping today", "nice one"].iter().enumerate() {
1452            s.messages.push(msg(0x80 + i as u8, 6, NOW - (i as u64 + 1) * HOUR, w));
1453            s.messages.push(msg(0x90 + i as u8, 7, NOW - (i as u64 + 1) * HOUR, w));
1454        }
1455        let r = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1456        let pr = only(&r);
1457        assert_eq!(subject(pr, 6).map(|x| x.shield), Some(Shield::Trusted), "ten days and a long history");
1458        assert_eq!(subject(pr, 7).map(|x| x.shield), None, "tenure still gates: two hours buys nothing");
1459    }
1460
1461    /// The fifth member to join, very active early, then quiet for months.
1462    /// Still trusted: standing is what you built, not what you said this week.
1463    #[test]
1464    fn an_early_member_who_lurks_for_months_keeps_their_standing() {
1465        let mut lurker = member(8, Some(24 * 200));
1466        lurker.lifetime_messages = 400; // all of it long ago
1467        let s = signals(vec![lurker], vec![]); // nothing at all in the window
1468        let r = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1469        assert_eq!(subject(only(&r), 8).map(|x| x.shield), Some(Shield::Trusted));
1470    }
1471
1472    /// A member's client judges word and link filters on the message in front
1473    /// of it, and nothing that needs history. It says which is which, because a
1474    /// silent skip would read as "clean".
1475    fn cohort_rule_doc() -> Rule {
1476        Rule {
1477            id: "cohort".into(),
1478            matcher: Match::Cohort { min: 3, quiet_max: 2, short_factor: 3, thin_ratio: None },
1479            tiers: None,
1480            severity: Some(Severity::Severe),
1481            weight: Some(85),
1482            pierces_trusted: false,
1483            family: None,
1484            armed_by: None,
1485            exempt: Exempt::default(),
1486            enforcement: Enforcement::Advisory,
1487        }
1488    }
1489
1490    /// The shape of the 2026-08-19 raid: a hundred fresh identities, one line
1491    /// each. This is the test the whole engine exists to pass.
1492    #[test]
1493    fn a_hundred_fresh_accounts_saying_one_thing_is_a_raid() {
1494        let mut members: Vec<MemberSignal> = (0..100).map(|i| member(i as u8 + 10, Some(1))).collect();
1495        let mut messages: Vec<MessageSignal> =
1496            (0..100).map(|i| msg(0x10 + i as u8, i as u8 + 10, NOW - HOUR, "hello world")).collect();
1497        // A regular with real history, saying the same words in passing.
1498        members.push(member(2, Some(24 * 60)));
1499        members.last_mut().unwrap().lifetime_messages = 800;
1500        messages.push(msg(0xf1, 2, NOW - 2 * HOUR, "hello world"));
1501        for (i, w) in ["morning all", "shipping today", "nice one"].iter().enumerate() {
1502            messages.push(msg(0xf2 + i as u8, 2, NOW - (i as u64 + 3) * HOUR, w));
1503        }
1504
1505        let s = signals(members, messages);
1506        let r = evaluate(&s, &[loaded(policy_with(vec![cohort_rule_doc()]))], &[], NOW);
1507        let pr = only(&r);
1508        let convicted: Vec<&SubjectReport> =
1509            pr.subjects.iter().filter(|x| x.convictions.iter().any(|c| !c.suppressed)).collect();
1510        assert_eq!(convicted.len(), 100, "every raider, and only the raiders");
1511        assert!(convicted.iter().all(|x| x.confidence == 85 && x.band == Band::Alert));
1512        // Heuristic evidence never reaches `proven`: a human still decides.
1513        assert!(convicted.iter().all(|x| x.proven == 0), "a cohort is inference, not proof");
1514        assert_eq!(subject(pr, 2).map(|x| x.shield), Some(Shield::Trusted), "the regular is shielded, not convicted");
1515        assert!(subject(pr, 2).unwrap().convictions.is_empty());
1516
1517        let ev = &convicted[0].convictions[0].evidence;
1518        assert!(
1519            matches!(ev.first(), Some(Evidence::Cohort { size: 100, .. })),
1520            "the exhibit names the burst, not the regular who said it an hour earlier: {ev:?}"
1521        );
1522    }
1523
1524    fn convicted_by_cohort(s: Signals) -> Vec<SubjectId> {
1525        let r = evaluate(&s, &[loaded(policy_with(vec![cohort_rule_doc()]))], &[], NOW);
1526        only(&r).subjects.iter().filter(|x| x.convictions.iter().any(|c| !c.suppressed)).map(|x| x.subject).collect()
1527    }
1528
1529    /// Four members thanking the room across twelve hours, one of them mid
1530    /// conversation: a room being polite, never a raid.
1531    #[test]
1532    fn the_same_thank_you_hours_apart_convicts_nobody() {
1533        let members: Vec<MemberSignal> = (0..4).map(|i| member(10 + i, Some(48))).collect();
1534        let mut messages: Vec<MessageSignal> =
1535            (0..3).map(|i| msg(0x10 + i, 10 + i, NOW - 12 * HOUR + u64::from(i) * 60_000, "thank you")).collect();
1536        messages.push(msg(0x20, 13, NOW - HOUR, "Thank you"));
1537        for i in 0..40u8 {
1538            messages.push(msg(0x30 + i, 13, NOW - 2 * HOUR + u64::from(i) * 60_000, &format!("chatting about piano {i}")));
1539        }
1540        assert!(convicted_by_cohort(signals(members, messages)).is_empty());
1541    }
1542
1543    /// A pleasantry from a handful of newcomers in the same minutes is a
1544    /// welcome. It convicts only at `short_factor` times the cohort size.
1545    #[test]
1546    fn a_burst_of_thank_yous_is_a_welcome() {
1547        let members: Vec<MemberSignal> = (0..5).map(|i| member(10 + i, Some(1))).collect();
1548        let messages: Vec<MessageSignal> =
1549            (0..5).map(|i| msg(0x10 + i, 10 + i, NOW - HOUR + u64::from(i) * 60_000, "thank you!")).collect();
1550        assert!(convicted_by_cohort(signals(members, messages)).is_empty());
1551    }
1552
1553    /// The same payload, but spread over hours, is not one wave.
1554    #[test]
1555    fn one_payload_spread_over_hours_is_not_a_wave() {
1556        let members: Vec<MemberSignal> = (0..6).map(|i| member(10 + i, Some(30))).collect();
1557        let messages: Vec<MessageSignal> = (0..6)
1558            .map(|i| msg(0x10 + i, 10 + i, NOW - 20 * HOUR + u64::from(i) * 3 * HOUR, "free airdrop claim it right now"))
1559            .collect();
1560        assert!(convicted_by_cohort(signals(members, messages)).is_empty());
1561    }
1562
1563    /// Inside a real burst, the accounts that posted only the line are the
1564    /// wave; a member who has been talking all along and echoed it is not.
1565    #[test]
1566    fn a_talker_who_echoed_a_burst_is_not_in_it() {
1567        let mut members: Vec<MemberSignal> = (0..6).map(|i| member(10 + i, Some(1))).collect();
1568        members.push(member(40, Some(30)));
1569        let mut messages: Vec<MessageSignal> = (0..6)
1570            .map(|i| msg(0x10 + i, 10 + i, NOW - HOUR + u64::from(i) * 30_000, "free airdrop claim it right now"))
1571            .collect();
1572        messages.push(msg(0x40, 40, NOW - HOUR + 200_000, "free airdrop claim it right now"));
1573        for i in 0..10u8 {
1574            messages.push(msg(0x50 + i, 40, NOW - 3 * HOUR + u64::from(i) * 60_000, &format!("ordinary chat {i}")));
1575        }
1576        let got = convicted_by_cohort(signals(members, messages));
1577        assert_eq!(got.len(), 6, "{got:?}");
1578        assert!(!got.contains(&sid(40)));
1579    }
1580
1581    /// The corpus outlives membership: a banned raider's messages sit in local
1582    /// storage long after the rotation removed them.
1583    #[test]
1584    fn someone_already_removed_is_never_convicted_again() {
1585        // Twenty identities posted one line each; only three are still members.
1586        let members: Vec<MemberSignal> = (0..3).map(|i| member(i as u8 + 10, Some(1))).collect();
1587        let messages: Vec<MessageSignal> =
1588            (0..20).map(|i| msg(0x10 + i as u8, i as u8 + 10, NOW - HOUR, "free airdrop claim now")).collect();
1589        let s = signals(members, messages);
1590        let r = evaluate(&s, &[loaded(policy_with(vec![cohort_rule_doc()]))], &[], NOW);
1591        let pr = only(&r);
1592        assert_eq!(pr.subjects.len(), 3, "the seventeen who are gone are not re-litigated");
1593        assert!(pr.subjects.iter().all(|x| !x.convictions.is_empty()), "the three still here are convicted");
1594        // The cluster's true size still counts all twenty: exemption and
1595        // absence change who can be accused, never what the community saw.
1596        let ev = &pr.subjects[0].convictions[0].evidence;
1597        assert!(matches!(ev.first(), Some(Evidence::Cohort { size: 20, .. })), "{ev:?}");
1598    }
1599
1600    /// Arming asks whether a raid is happening HERE and NOW, not whether one
1601    /// ever happened: a cohort of accounts that are all gone must not arm a
1602    /// burst rule against whoever is still present.
1603    #[test]
1604    fn a_past_raid_does_not_arm_a_rule_against_the_living() {
1605        let mut burst = Rule {
1606            id: "burst".into(),
1607            matcher: Match::JoinBurst { gap_secs: 600, min: 5 },
1608            tiers: None,
1609            severity: Some(Severity::Major),
1610            weight: Some(40),
1611            pierces_trusted: false,
1612            family: None,
1613            armed_by: Some(ArmedBy { rule: "cohort".into(), scope: ArmScope::Community, min_subjects: Some(3), also: vec![] }),
1614            exempt: Exempt::default(),
1615            enforcement: Enforcement::Advisory,
1616        };
1617        // Twenty raiders posted one line each and were removed; six ordinary
1618        // members remain, all of whom joined in one burst.
1619        let members: Vec<MemberSignal> = (0..6)
1620            .map(|i| MemberSignal {
1621                subject: sid(i as u8 + 40),
1622                joined_at_ms: Some(NOW - HOUR + i * 30_000),
1623                roles: vec![],
1624                is_staff: false,
1625                lifetime_messages: 0,
1626                first_post_ms: None,
1627            })
1628            .collect();
1629        let messages: Vec<MessageSignal> =
1630            (0..20).map(|i| msg(0x10 + i as u8, i as u8 + 10, NOW - HOUR, "free airdrop claim now")).collect();
1631        let s = signals(members, messages);
1632        let r = evaluate(&s, &[loaded(policy_with(vec![cohort_rule_doc(), burst.clone()]))], &[], NOW);
1633        assert_eq!(
1634            only(&r).subjects.iter().filter(|x| !x.convictions.is_empty()).count(),
1635            0,
1636            "the cohort is entirely gone, so it arms nothing against the living"
1637        );
1638
1639        // The same burst DOES fire when the cohort is among the current members.
1640        burst.armed_by = Some(ArmedBy { rule: "cohort".into(), scope: ArmScope::Community, min_subjects: Some(3), also: vec![] });
1641        let mut members: Vec<MemberSignal> = (0..6)
1642            .map(|i| MemberSignal {
1643                subject: sid(i as u8 + 40),
1644                joined_at_ms: Some(NOW - HOUR + i * 30_000),
1645                roles: vec![],
1646                is_staff: false,
1647                lifetime_messages: 0,
1648                first_post_ms: None,
1649            })
1650            .collect();
1651        members.extend((0..20).map(|i| member(i as u8 + 10, Some(1))));
1652        let messages: Vec<MessageSignal> =
1653            (0..20).map(|i| msg(0x10 + i as u8, i as u8 + 10, NOW - HOUR, "free airdrop claim now")).collect();
1654        let s = signals(members, messages);
1655        let r = evaluate(&s, &[loaded(policy_with(vec![cohort_rule_doc(), burst]))], &[], NOW);
1656        let convicted = only(&r).subjects.iter().filter(|x| !x.convictions.is_empty()).count();
1657        assert!(convicted >= 20, "a live cohort arms it: {convicted}");
1658    }
1659
1660    /// Size alone must never convict: a catchphrase everyone repeats is a
1661    /// community, and the thinness bar is what tells it from a script.
1662    #[test]
1663    fn a_community_catchphrase_is_not_a_cohort() {
1664        let members: Vec<MemberSignal> = (0..20)
1665            .map(|i| {
1666                let mut m = member(i as u8 + 10, Some(24 * 60));
1667                m.lifetime_messages = 500;
1668                m
1669            })
1670            .collect();
1671        let mut messages: Vec<MessageSignal> = Vec::new();
1672        for i in 0..20u8 {
1673            // Everyone says it — and everyone also says plenty else.
1674            messages.push(msg(0x20 + i, i + 10, NOW - HOUR, "good morning everyone"));
1675            for (j, w) in ["shipping today", "nice one", "agreed", "on it"].iter().enumerate() {
1676                messages.push(msg(0x60 + i * 4 + j as u8, i + 10, NOW - (j as u64 + 2) * HOUR, w));
1677            }
1678        }
1679        let s = signals(members, messages);
1680        let r = evaluate(&s, &[loaded(policy_with(vec![cohort_rule_doc()]))], &[], NOW);
1681        let convicted = only(&r).subjects.iter().filter(|x| !x.convictions.is_empty()).count();
1682        assert_eq!(convicted, 0, "twenty chatty regulars sharing a greeting are not a raid");
1683    }
1684
1685    /// A burst of quiet newcomers is what a freshly-posted invite link LOOKS
1686    /// like, so it convicts nobody until a cohort already has.
1687    #[test]
1688    fn an_invite_link_burst_convicts_nobody_on_its_own() {
1689        let mut burst = Rule {
1690            id: "burst".into(),
1691            matcher: Match::JoinBurst { gap_secs: 600, min: 5 },
1692            tiers: None,
1693            severity: Some(Severity::Major),
1694            weight: Some(40),
1695            pierces_trusted: false,
1696            family: None,
1697            armed_by: None,
1698            exempt: Exempt::default(),
1699            enforcement: Enforcement::Advisory,
1700        };
1701        // Ten people joined within a few minutes and said nothing alike.
1702        let members: Vec<MemberSignal> = (0..10)
1703            .map(|i| MemberSignal {
1704                subject: sid(i as u8 + 10),
1705                joined_at_ms: Some(NOW - HOUR + i * 30_000),
1706                roles: vec![],
1707                is_staff: false,
1708                lifetime_messages: 0,
1709                first_post_ms: None,
1710            })
1711            .collect();
1712        let s = signals(members, vec![]);
1713
1714        // Unarmed, the burst convicts them all — which is why the built-in
1715        // policy never ships it that way.
1716        let r = evaluate(&s, &[loaded(policy_with(vec![burst.clone()]))], &[], NOW);
1717        assert_eq!(only(&r).subjects.iter().filter(|x| !x.convictions.is_empty()).count(), 10);
1718
1719        // Armed by a cohort that never fired, it convicts nobody.
1720        burst.armed_by = Some(ArmedBy { rule: "cohort".into(), scope: ArmScope::Community, min_subjects: Some(3), also: vec![] });
1721        let r = evaluate(&s, &[loaded(policy_with(vec![cohort_rule_doc(), burst]))], &[], NOW);
1722        assert_eq!(
1723            only(&r).subjects.iter().filter(|x| !x.convictions.is_empty()).count(),
1724            0,
1725            "no cohort, no conviction: an invite link is not an attack"
1726        );
1727    }
1728
1729    #[test]
1730    fn a_member_evaluates_only_stateless_rules() {
1731        let stateful = Rule {
1732            id: "quiet".into(),
1733            matcher: Match::MessagesLte { n: 2 },
1734            tiers: None,
1735            severity: Some(Severity::Notice),
1736            weight: Some(10),
1737            pierces_trusted: false,
1738            family: None,
1739            armed_by: None,
1740            exempt: Exempt::default(),
1741            enforcement: Enforcement::Advisory,
1742        };
1743        let s = signals(vec![member(1, Some(2))], vec![msg(0xb1, 1, NOW - HOUR, "bit.ly/a")]);
1744        let policies = [loaded(policy_with(vec![link_rule(), stateful]))];
1745
1746        let as_member = evaluate_as(&s, &policies, &[], NOW, EvalMode::Member);
1747        let pr = &as_member.policies[0];
1748        let state = |id: &str| pr.rule_status.iter().find(|r| r.rule_id == id).map(|r| r.state);
1749        assert_eq!(state("links"), Some(RuleState::Evaluated), "a link filter needs no history");
1750        assert_eq!(state("quiet"), Some(RuleState::RequiresHistory), "counting a member's past does");
1751        let sub = subject(pr, 1).unwrap();
1752        assert_eq!(sub.convictions.len(), 1, "the link conviction stands on its own");
1753
1754        // The same evidence, evaluated by an admin, runs everything.
1755        let as_admin = evaluate_as(&s, &policies, &[], NOW, EvalMode::Admin);
1756        let pr = &as_admin.policies[0];
1757        assert!(pr.rule_status.iter().all(|r| r.state == RuleState::Evaluated));
1758        assert_eq!(subject(pr, 1).unwrap().convictions.len(), 2);
1759    }
1760
1761    #[test]
1762    fn fresh_account_aggravators_fold_to_one() {
1763        let tenure = Rule {
1764            id: "tenure".into(),
1765            matcher: Match::TenureLt { secs: 24 * 3600 },
1766            tiers: None,
1767            severity: Some(Severity::Notice),
1768            weight: Some(20),
1769            pierces_trusted: false,
1770            family: None,
1771            armed_by: None,
1772            exempt: Exempt::default(),
1773            enforcement: Enforcement::Advisory,
1774        };
1775        let quiet = Rule {
1776            id: "quiet".into(),
1777            matcher: Match::MessagesLte { n: 2 },
1778            tiers: None,
1779            severity: Some(Severity::Notice),
1780            weight: Some(10),
1781            pierces_trusted: false,
1782            family: None,
1783            armed_by: None,
1784            exempt: Exempt::default(),
1785            enforcement: Enforcement::Advisory,
1786        };
1787        let s = signals(vec![member(1, Some(2))], vec![msg(0xb1, 1, NOW - HOUR, "hello world")]);
1788        let r = evaluate(&s, &[loaded(policy_with(vec![tenure, quiet]))], &[], NOW);
1789        let sub = subject(only(&r), 1).unwrap();
1790        // Two correlated proxies for "new account" fold to the strongest: 20,
1791        // not 20-OR-10 = 28.
1792        assert_eq!(sub.confidence, 20);
1793        let folded = sub.convictions.iter().find(|c| c.rule_id == "quiet").unwrap();
1794        assert!(folded.folded && !folded.combined);
1795        assert_eq!(sub.convictions.iter().filter(|c| c.combined).count(), 1);
1796    }
1797
1798    #[test]
1799    fn unknown_tenure_is_never_a_conviction() {
1800        let tenure = Rule {
1801            id: "tenure".into(),
1802            matcher: Match::TenureLt { secs: 24 * 3600 },
1803            tiers: None,
1804            severity: Some(Severity::Notice),
1805            weight: Some(20),
1806            pierces_trusted: false,
1807            family: None,
1808            armed_by: None,
1809            exempt: Exempt::default(),
1810            enforcement: Enforcement::Advisory,
1811        };
1812        let s = signals(vec![member(9, None)], vec![]);
1813        let r = evaluate(&s, &[loaded(policy_with(vec![tenure]))], &[], NOW);
1814        let pr = only(&r);
1815        let status = pr.rule_status.iter().find(|s| s.rule_id == "tenure").unwrap();
1816        assert_eq!(status.unknown_subjects, vec![sid(9)], "per-subject unknown, not a community-wide block");
1817        assert!(subject(pr, 9).unwrap().convictions.is_empty());
1818    }
1819
1820    /// Indeterminate means "we could not establish tenure" — no join AND no
1821    /// posts — and it is informational: the subject is judged as if unshielded.
1822    #[test]
1823    fn indeterminate_tenure_never_gates_a_conviction() {
1824        let quiet = Rule {
1825            id: "quiet".into(),
1826            matcher: Match::MessagesLte { n: 2 },
1827            tiers: None,
1828            severity: Some(Severity::Notice),
1829            weight: Some(10),
1830            pierces_trusted: false,
1831            family: None,
1832            armed_by: None,
1833            exempt: Exempt::default(),
1834            enforcement: Enforcement::Advisory,
1835        };
1836        let s = signals(vec![member(7, None)], vec![]);
1837        let r = evaluate(&s, &[loaded(policy_with(vec![quiet]))], &[], NOW);
1838        let sub = subject(only(&r), 7).unwrap();
1839        assert_eq!(sub.shield, Shield::Indeterminate, "no join, no posts: unknowable");
1840        assert_eq!(sub.confidence, 10, "and judged exactly as if unshielded");
1841    }
1842
1843    fn window_rule_policy(m: Match, rungs: Vec<Rung>) -> Policy {
1844        policy_with(vec![Rule {
1845            id: "w".into(),
1846            matcher: m,
1847            tiers: Some(Tiers { per_message: vec![], per_window: rungs }),
1848            severity: None,
1849            weight: None,
1850            pierces_trusted: false,
1851            family: None,
1852            armed_by: None,
1853            exempt: Exempt::default(),
1854            enforcement: Enforcement::Advisory,
1855        }])
1856    }
1857
1858    /// One account pasting the same line over and over — the counterpart to
1859    /// `cohort`, which catches many accounts sharing one line.
1860    #[test]
1861    fn repeat_catches_one_account_pasting_the_same_thing() {
1862        let mut messages: Vec<MessageSignal> = (0..5)
1863            .map(|i| msg(0xa0 + i as u8, 1, NOW - (i + 1) * HOUR, "CLAIM YOUR FREE AIRDROP NOW"))
1864            .collect();
1865        // Variations a spammer reaches for first: case, punctuation, digits.
1866        messages.push(msg(0xb0, 1, NOW - 6 * HOUR, "claim your free airdrop now!!!"));
1867        messages.push(msg(0xb1, 1, NOW - 7 * HOUR, "hello everyone"));
1868        let s = signals(vec![member(1, Some(2))], messages);
1869        let p = window_rule_policy(
1870            Match::Repeat { normalize: Normalize::Skeleton, within_secs: None },
1871            vec![Rung { hits: 3, severity: Severity::Major, weight: 50, pierces_trusted: false }],
1872        );
1873        let r = evaluate(&s, &[loaded(p)], &[], NOW);
1874        let sub = subject(only(&r), 1).unwrap();
1875        let c = &sub.convictions[0];
1876        assert_eq!(c.scope, Scope::PerWindow);
1877        assert_eq!(c.hits, 6, "case and punctuation are one line of attacker code, so they do not vary the shape");
1878        assert_eq!(c.citation_count, 6, "every repetition is cited, not just the ones past the rung");
1879        assert_eq!(sub.confidence, 50);
1880    }
1881
1882    #[test]
1883    fn rate_finds_the_densest_span_and_cites_only_it() {
1884        // Five in a burst, then one much later: the burst is the evidence.
1885        let mut messages: Vec<MessageSignal> =
1886            (0..5).map(|i| msg(0xc0 + i as u8, 1, NOW - 60 * 60 * 1000 + i * 10_000, "spam")).collect();
1887        messages.push(msg(0xcf, 1, NOW - 10 * 60 * 1000, "unrelated"));
1888        let s = signals(vec![member(1, Some(2))], messages);
1889        let p = window_rule_policy(
1890            Match::Rate { per_secs: 60 },
1891            vec![Rung { hits: 5, severity: Severity::Major, weight: 55, pierces_trusted: false }],
1892        );
1893        let r = evaluate(&s, &[loaded(p)], &[], NOW);
1894        let sub = subject(only(&r), 1).unwrap();
1895        let c = &sub.convictions[0];
1896        assert_eq!(c.hits, 5, "five inside one minute");
1897        assert_eq!(c.citation_count, 5, "the straggler is not part of the burst");
1898        assert!(
1899            matches!(c.evidence.first(), Some(Evidence::Rate { count: 5, window_secs: 60, .. })),
1900            "the span is reported as evidence: {:?}",
1901            c.evidence
1902        );
1903    }
1904
1905    #[test]
1906    fn a_pardon_suppresses_the_conviction_and_its_citations() {
1907        let s = signals(
1908            vec![member(1, Some(2))],
1909            vec![
1910                msg(0xb1, 1, NOW - 3 * HOUR, "bit.ly/a"),
1911                msg(0xb2, 1, NOW - 2 * HOUR, "tr.ee/b"),
1912                msg(0xb3, 1, NOW - HOUR, "shm.to/c"),
1913            ],
1914        );
1915        let policy = policy_with(vec![link_rule()]);
1916        let lp = loaded(policy);
1917        let pardon = Override {
1918            target: OverrideTarget::Rule {
1919                policy_hash: lp.hash,
1920                rule_id: "links".into(),
1921                scope: Scope::PerMessage,
1922                subject: sid(1),
1923            },
1924            issuer: sid(0xf0),
1925            issued_at: NOW - HOUR,
1926            expires_at: NOW + HOUR,
1927        };
1928        let r = evaluate(&s, &[lp], &[pardon], NOW);
1929        let pr = only(&r);
1930        let sub = subject(pr, 1).unwrap();
1931        let pardoned = sub.convictions.iter().find(|c| c.scope == Scope::PerMessage).unwrap();
1932        assert!(pardoned.suppressed && !pardoned.combined, "reported, never combined");
1933        // The pardoned conviction's citations are suppressed for the content
1934        // consumer; the surviving per-window conviction keeps citing them.
1935        assert!(pr.citations.iter().any(|c| c.suppressed), "a pardon reaches the content consumer too");
1936        // The per-window conviction was NOT pardoned (scope is part of the key).
1937        assert!(!sub.convictions.iter().find(|c| c.scope == Scope::PerWindow).unwrap().suppressed);
1938    }
1939
1940    #[test]
1941    fn an_inert_policy_reports_why_and_convicts_nothing() {
1942        let mut p = policy_with(vec![link_rule()]);
1943        p.requires = vec!["quarantine".into()];
1944        let r = evaluate(&signals(vec![member(1, Some(2))], vec![]), &[loaded(p)], &[], NOW);
1945        let pr = only(&r);
1946        assert!(matches!(&pr.inert, Some(InertReason::UnknownRequiredKey { key }) if key == "quarantine"));
1947        assert!(pr.subjects.is_empty() && pr.rule_status.is_empty());
1948    }
1949
1950    #[test]
1951    fn evaluation_is_pure_and_ordering_is_canonical() {
1952        let s = signals(
1953            vec![member(3, Some(2)), member(1, Some(2)), member(2, Some(2))],
1954            vec![
1955                msg(0xb3, 3, NOW - HOUR, "bit.ly/c"),
1956                msg(0xb1, 1, NOW - 2 * HOUR, "bit.ly/a"),
1957                msg(0xb2, 2, NOW - 3 * HOUR, "bit.ly/b"),
1958            ],
1959        );
1960        let a = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1961        let b = evaluate(&s, &[loaded(policy_with(vec![link_rule()]))], &[], NOW);
1962        assert_eq!(a, b, "same inputs, same report");
1963        let ids: Vec<[u8; 32]> = only(&a).subjects.iter().map(|s| s.subject.0).collect();
1964        let mut sorted = ids.clone();
1965        sorted.sort();
1966        assert_eq!(ids, sorted, "subjects sort by canonical id");
1967        let cits: Vec<[u8; 32]> = only(&a).citations.iter().map(|c| c.id.0).collect();
1968        let mut cs = cits.clone();
1969        cs.sort();
1970        assert_eq!(cits, cs, "citations sort by canonical id");
1971    }
1972
1973    #[test]
1974    fn the_window_clamps_by_recency_and_count() {
1975        let mut p = policy_with(vec![link_rule()]);
1976        p.window = Window { hours: 2, max_messages: 2 };
1977        let s = signals(
1978            vec![member(1, Some(48))],
1979            vec![
1980                msg(0xb0, 1, NOW - 10 * HOUR, "bit.ly/old"), // outside the window
1981                msg(0xb1, 1, NOW - 90 * 60 * 1000, "bit.ly/a"),
1982                msg(0xb2, 1, NOW - 60 * 60 * 1000, "bit.ly/b"),
1983                msg(0xb3, 1, NOW - 30 * 60 * 1000, "bit.ly/c"),
1984            ],
1985        );
1986        let r = evaluate(&s, &[loaded(p)], &[], NOW);
1987        assert_eq!(only(&r).citations.len(), 2, "newest two inside the window; the older two never enter the corpus");
1988    }
1989
1990    fn word_rule(pattern: &str) -> Rule {
1991        Rule {
1992            id: "words".into(),
1993            matcher: Match::Keyword { patterns: vec![pattern.into()], normalize: Normalize::Fold },
1994            tiers: Some(Tiers {
1995                per_message: vec![Rung { hits: 1, severity: Severity::Minor, weight: 10, pierces_trusted: false }],
1996                per_window: vec![],
1997            }),
1998            severity: None,
1999            weight: None,
2000            pierces_trusted: false,
2001            family: None,
2002            armed_by: None,
2003            exempt: Exempt::default(),
2004            enforcement: Enforcement::Advisory,
2005        }
2006    }
2007
2008    fn hits_for(pattern: &str, text: &str) -> usize {
2009        let s = signals(vec![member(1, Some(2))], vec![msg(0xd1, 1, NOW - HOUR, text)]);
2010        let r = evaluate(&s, &[loaded(policy_with(vec![word_rule(pattern)]))], &[], NOW);
2011        only(&r).subjects.len()
2012    }
2013
2014    /// A capitalised word matched nothing at all: the corpus was casefolded and
2015    /// the pattern was not, so the two could never meet. Silent, and the filter
2016    /// looked like it was simply finding nothing in a clean community.
2017    #[test]
2018    fn a_pattern_matches_in_the_same_case_space_as_the_text() {
2019        for pattern in ["Vector", "VECTOR", "vector", "VeCtOr"] {
2020            assert_eq!(hits_for(pattern, "we should ship vector today"), 1, "pattern {pattern:?} caught nothing");
2021        }
2022    }
2023
2024    /// Casefolding the pattern must not quietly turn a whole-word rule into a
2025    /// substring one: token anchoring is the whole reason folding is safe.
2026    #[test]
2027    fn folding_a_pattern_keeps_its_word_anchoring() {
2028        assert_eq!(hits_for("Art", "we should start today"), 0, "\"Art\" must not match inside \"start\"");
2029        assert_eq!(hits_for("*Art*", "we should start today"), 1, "an explicit wildcard still matches inside");
2030    }
2031
2032    fn repeat_policy(within_secs: Option<u64>) -> Policy {
2033        let mut p = window_rule_policy(
2034            Match::Repeat { normalize: Normalize::Skeleton, within_secs },
2035            vec![
2036                Rung { hits: 4, severity: Severity::Major, weight: 50, pierces_trusted: false },
2037                Rung { hits: 8, severity: Severity::Severe, weight: 85, pierces_trusted: false },
2038            ],
2039        );
2040        // The shipped window: the point is that a WEEK of history is in scope
2041        // and the burst span is what narrows it.
2042        p.window = Window { hours: 168, max_messages: 4000 };
2043        p
2044    }
2045
2046    fn repeat_hits(within_secs: Option<u64>, at_hours: &[u64]) -> usize {
2047        let msgs: Vec<MessageSignal> = at_hours
2048            .iter()
2049            .enumerate()
2050            .map(|(i, h)| msg(0xe0 + i as u8, 1, NOW - h * HOUR, "gm"))
2051            .collect();
2052        // No shield: a brand-new member is exactly who this must not misjudge.
2053        let s = signals(vec![member(1, Some(1))], msgs);
2054        let r = evaluate(&s, &[loaded(repeat_policy(within_secs))], &[], NOW);
2055        only(&r).subjects.len()
2056    }
2057
2058    /// A regular saying "gm" once a morning is not a spammer, and counting
2059    /// across the whole seven-day window could not tell the two apart: eight
2060    /// mornings read exactly like eight messages in a minute.
2061    #[test]
2062    fn a_daily_greeting_is_not_a_repeat_burst() {
2063        let mornings: Vec<u64> = (0..8).map(|d| d * 24 + 1).collect();
2064        assert_eq!(repeat_hits(None, &mornings), 1, "the unbounded rule convicts a regular");
2065        assert_eq!(
2066            repeat_hits(Some(super::super::harness::REPEAT_BURST_SECS), &mornings),
2067            0,
2068            "a burst-bounded rule must leave a daily greeting alone"
2069        );
2070    }
2071
2072    /// The thing it is actually for: the same line over and over inside minutes.
2073    #[test]
2074    fn a_burst_of_the_same_line_still_convicts() {
2075        let burst: Vec<u64> = vec![1, 1, 1, 1, 1, 1, 1, 1];
2076        assert_eq!(
2077            repeat_hits(Some(super::super::harness::REPEAT_BURST_SECS), &burst),
2078            1,
2079            "eight identical messages in one span must still be caught"
2080        );
2081    }
2082
2083    /// The engine convicts on EVIDENCE, and one anomaly is not evidence.
2084    ///
2085    /// A join flood alone asks for a look; a join flood that is also one script
2086    /// across many accounts is two independent sources and convicts. The gap
2087    /// between them is what keeps a popular invite link from being staged for
2088    /// removal, so it is pinned here rather than left to the weights.
2089    #[test]
2090    fn one_anomaly_asks_for_a_look_and_two_convict() {
2091        const MIN: u64 = 60 * 1000;
2092        const VARIED: [&str; 12] = [
2093            "hey everyone", "glad to be here", "what is this place",
2094            "found you through a podcast", "nice community", "hello all",
2095            "just looking around", "someone linked me here", "good morning",
2096            "how does this work", "reading the pins now", "thanks for the invite",
2097        ];
2098        // `n` strangers arriving across `span` minutes, brand new and silent but
2099        // for one message each.
2100        let wave = |n: u64, span: u64, same_text: bool| -> (usize, u32) {
2101            let members: Vec<MemberSignal> = (1..=n)
2102                .map(|i| {
2103                    let mut m = member(i as u8, Some(1));
2104                    m.joined_at_ms = Some(NOW - (span * MIN) + (i * span * MIN / n));
2105                    m.first_post_ms = None;
2106                    m.lifetime_messages = 0;
2107                    m
2108                })
2109                .collect();
2110            let msgs: Vec<MessageSignal> = (1..=n)
2111                .map(|i| {
2112                    let text = if same_text {
2113                        "join our airdrop".to_string()
2114                    } else {
2115                        VARIED[(i as usize - 1) % VARIED.len()].to_string()
2116                    };
2117                    msg(0xa0 + i as u8, i as u8, NOW - 2 * MIN, &text)
2118                })
2119                .collect();
2120            let s = signals(members, msgs);
2121            let r = evaluate(&s, &[loaded(crate::community::policy::harness::default_policy())], &[], NOW);
2122            let p = only(&r);
2123            (p.subjects.len(), p.subjects.first().map(|x| x.confidence).unwrap_or(0))
2124        };
2125
2126        // A good afternoon on an invite link: no anomaly at all.
2127        assert_eq!(wave(5, 10, false), (0, 0), "an ordinary invite wave must convict nobody");
2128
2129        // One anomaly — they arrived fast, but they are saying different things.
2130        let (caught, conf) = wave(12, 5, false);
2131        assert_eq!(caught, 12);
2132        assert!((25..50).contains(&conf), "a lone join flood reached {conf}; it must stay a look, not a verdict");
2133
2134        // Two anomalies — arrived fast AND reading from one script.
2135        let (caught, conf) = wave(12, 5, true);
2136        assert_eq!(caught, 12);
2137        assert!(conf >= 75, "a scripted flood only reached {conf}; two sources must convict");
2138
2139        // One anomaly again, the other way round: one script, arriving slowly.
2140        let (caught, conf) = wave(20, 60, true);
2141        assert_eq!(caught, 20);
2142        assert!(conf >= 75, "a scripted wave only reached {conf}");
2143    }
2144}