//! Group-event grammar for the `_chat.txt` route — the port of//! `packages/import-core/src/group.ts`//! (spec `2026-08-16-cotton-group-mirror-design.md` §3).//!//! ## Why this exists at all//!//! An iOS GROUP export attributes its system events like messages, in two//! disguises this module has to see through://!//! ```text//! [d, t] AQ <> TinFactory: Arlo Quillby added you//! — the "sender" is the GROUP NAME (as it stands at export time), and the//! parser's sender split has no way to know that string is not a person.//!//! [d, t] Arlo Quillby: Arlo Quillby turned off disappearing messages.//! — the "sender" is the ACTOR, and the body opens by repeating their name.//! ```//!//! A DM export writes the same events WITHOUT attribution, which the parser//! already classifies as system lines — so everything here runs only on the//! group route and dm behaviour stays byte-identical.//!//! **Case folding.** Every `(?i)` here is Rust's Unicode simple case folding//! where JavaScript's `i` without the `u` flag is the ECMAScript//! `Canonicalize` rule, which refuses to fold a non-ASCII code point onto an//! ASCII one. They disagree on exactly two shapes — U+212A KELVIN SIGN//! against `k`, and U+017F LATIN SMALL LETTER LONG S against `s` — neither of//! which WhatsApp writes into an event phrase or a quoted group name.use std::sync::OnceLock;use regex::Regex;use serde::{Deserialize, Serialize};usecrate::import::text::{collapse_whitespace, js_trim_start, utf16_len};/// U+201C/U+201D — iOS quotes group names with curly quotes; Android uses/// straight ones.const LEFT_QUOTE: char = '\u{201c}';const RIGHT_QUOTE: char = '\u{201d}';/// `created group "X"` / `changed the group name to "X"` //// `changed the subject … to "X"`.fn title_patterns() -> &'static [Regex; 3] {static RE: OnceLock<[Regex; 3]> = OnceLock::new(); RE.get_or_init(|| {let open = format!("[\"'{LEFT_QUOTE}]");let close = format!("[\"'{RIGHT_QUOTE}]");let inner = format!("[^\"'{LEFT_QUOTE}{RIGHT_QUOTE}]"); [Regex::new(&format!("(?i)created (?:the )?group {open}({inner}+){close}" )) .expect("created group"),Regex::new(&format!("(?i)changed the group name to {open}({inner}+){close}" )) .expect("renamed group"),Regex::new(&format!("(?i)changed the subject (?:from {open}{inner}*{close} )?to {open}({inner}+){close}" )) .expect("changed subject"), ] })}/// A group title named by a creation or rename event, in corpus order.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pubstructGroupTitleEvent {pub title: String,pub sent_at: String,}/// One line of the corpus `extract_group_titles` reads — a system line's text/// or a message's body, with the instant it carries.#[derive(Debug, Clone, PartialEq, Eq)]pubstructTitleCandidate<'a> {pub text: &'a str,pub sent_at: &'a str,}/// Pull every creation/rename title out of a chronological list of texts.////// The sort is by BYTES where the TypeScript sorts by `localeCompare`. Every/// `sent_at` here comes out of the adapter as `…Z` with millisecond precision,/// so the two orders coincide on every input this can see; and both sorts are/// STABLE, which is what keeps two renames in the same millisecond in the/// order the file wrote them.pubfn extract_group_titles(events: &[TitleCandidate<'_>]) -> Vec<GroupTitleEvent> {letmut titles: Vec<GroupTitleEvent> = Vec::new();for event in events {for pattern in title_patterns() {ifletSome(captures) = pattern.captures(event.text) { titles.push(GroupTitleEvent { title: collapse_whitespace(&captures[1]), sent_at: event.sent_at.to_string(), });break; } } } titles.sort_by(|a, b| a.sent_at.cmp(&b.sent_at)); titles}/// The latest rename wins; `None` when no event names the group.pubfn latest_title(titles: &[GroupTitleEvent]) -> Option<&str> { titles.last().map(|event| event.title.as_str())}/// The closed list of verb phrases WhatsApp writes into group events. Closed/// on purpose: matching generic verbs ("added", alone) against human sentences/// would misfile real messages, so every phrase here is anchored by the/// event-shape checks in `is_group_event_body` before it counts.fn event_phrase() -> &'staticRegex {static RE: OnceLock<Regex> = OnceLock::new(); RE.get_or_init(|| {Regex::new("(?i)created (?:the )?group|created this group|added|removed|left$|left the group\ |joined using|changed the group name|changed the subject|changed this group\ |changed the group description|changed their phone number\ |turned (?:on|off) disappearing messages|disappearing messages|now an admin\ |no longer an admin|security code|end-to-end encrypted|pinned a message\ |unpinned|blocked|unblocked", ) .expect("event phrase") })}fn boilerplate_openers() -> &'static [Regex; 2] {static RE: OnceLock<[Regex; 2]> = OnceLock::new(); RE.get_or_init(|| { [Regex::new("(?i)^(?:Disappearing messages|Messages and calls are end-to-end encrypted)", ) .expect("boilerplate"),Regex::new("(?i)^You(?:'re| are) (?:now an admin|no longer an admin)") .expect("admin boilerplate"), ] })}/// Is this attributed line really a group event?////// True when the body opens by naming its own sender (the `X: X did Y` iOS/// shape) or the export's second person (`You did Y`), followed by one of the/// closed event phrases; or when the body is unmistakable boilerplate. A body/// that merely CONTAINS an event phrase mid-sentence is a person talking.////// Known residual risk, accepted in the spec: a human message that literally/// opens `You added …` would be filed as an event. It still lands in the/// thread, just styled as a system line.pubfn is_group_event_body(sender: &str, body: &str) -> bool {let collapsed = collapse_whitespace(body);if collapsed.is_empty() {returnfalse; }if boilerplate_openers() .iter() .any(|pattern| pattern.is_match(&collapsed)) {returntrue; }let sender_collapsed = collapse_whitespace(sender);let lowered = collapsed.to_lowercase();for opener in [sender_collapsed.as_str(), "You"] {let opener_lowered = opener.to_lowercase();if !lowered.starts_with(&opener_lowered) {continue; }// `collapsed.slice(opener.length)` — UTF-16 code units of the ORIGINAL// opener, not of its lowercased form, which is what the TypeScript// does even though lowercasing can change a string's length.letSome(rest) = slice_from_utf16(&collapsed, utf16_len(opener)) else {continue; };let rest = js_trim_start(&rest);if event_phrase().is_match(rest) && utf16_len(rest) < 200 {returntrue; } }false}/// `String.prototype.slice(start)` in UTF-16 code units. `None` when the cut/// would land inside a surrogate pair — JavaScript would hand back a lone/// surrogate and a Rust `String` cannot hold one. Unreachable from an opener/// that is a prefix of the body, which is the only way this is called.fn slice_from_utf16(input: &str, start: usize) -> Option<String> {let units: Vec<u16> = input.encode_utf16().collect();if start >= units.len() {returnSome(String::new()); }String::from_utf16(&units[start..]).ok()}/// Is this "sender" actually the group itself? iOS attributes some events to/// the group's CURRENT name, so any sender equal to a known title is the group/// speaking, not a person.pubfn is_group_pseudo_sender(sender: &str, titles: &[GroupTitleEvent]) -> bool {let collapsed = collapse_whitespace(sender).to_lowercase(); titles .iter() .any(|event| event.title.to_lowercase() == collapsed)}fn encryption_boilerplate() -> &'staticRegex {static RE: OnceLock<Regex> = OnceLock::new(); RE.get_or_init(|| Regex::new("(?i)end-to-end encrypted").expect("encryption"))}/// The one event with no story value — dropped rather than imported.pubfn is_encryption_boilerplate(text: &str) -> bool { encryption_boilerplate().is_match(text)}/// `wa:group:` + slug — the thread's stable import identity (spec §8).pubconst GROUP_EXTERNAL_KEY_PREFIX: &str = "wa:group:";/// Everything that is not `[a-z0-9]` becomes a hyphen, so the result is pure/// ASCII and the 48-unit cap is 48 characters however exotic the title was.////// It does NOT normalise: `école` written with a combining acute slugs as/// `e-cole`, and `你好世界` slugs as `untitled`. That is the TypeScript's/// behaviour and it is pinned by vector rather than tidied, because the key/// is a thread's stable identity and "tidying" it silently re-homes a chat.pubfn slugify_title(title: &str) -> String {let lowered = collapse_whitespace(title).to_lowercase();letmut kebab = String::with_capacity(lowered.len());letmut pending_dash = false;for ch in lowered.chars() {if ch.is_ascii_lowercase() || ch.is_ascii_digit() {if pending_dash { kebab.push('-'); pending_dash = false; } kebab.push(ch); } else { pending_dash = true; } }// A trailing run collapses to one hyphen, which the trim below removes —// the TypeScript emits it and then strips it, and so does this.if pending_dash { kebab.push('-'); }let trimmed = kebab.trim_matches('-');let capped: String = trimmed.chars().take(48).collect();let slug = capped.trim_end_matches('-');if slug.is_empty() {"untitled".to_string() } else { slug.to_string() }}pubfn group_external_key(title: &str) -> String { format!("{GROUP_EXTERNAL_KEY_PREFIX}{}", slugify_title(title))}#[cfg(test)]#[path = "group_tests.rs"]mod tests;