Cotton code
2332 lines · 87.1 KB · RustRaw
//! THE MESSAGE IMPORT ENGINE — the port of//! `packages/core/src/services/messagesImport.service.ts`.//!//! One implementation of "who this message is from, which thread it belongs to,//! which contact it resolves to, and what a re-import skips". The TypeScript is//! shared by the phone, the server and the Mac for exactly that reason, and a//! second copy of it would be a second answer to the only question an importer//! is ever asked.//!//! ## Why it lives in `cotton-rules`//!//! It runs on the phone (re-exported at `cotton_core::import::messages_engine`)//! and in the Worker as WASM, over a JS driver (`cotton-rules-wasm`), and it//! earns that the same way [`crate::messages::resolve_contact`] does: it is//! DRIVER-IN. It//! opens nothing, holds no connection and mints no id — every read is a method//! on [`ImportDriver`], every write is returned as a [`Change`], and the//! clock and the id source arrive as arguments. What is left is the DECISION//! layer, which is what this crate is for, and which the phone, the server and//! the Mac all have to agree about.//!//! ## The two-phase write, and why it is two//!//! `runBatch` writes twice on purpose. The first batch carries the thread, its//! contacts, its participants, its messages and its reactions — one act, so a//! conversation never lands half-built. The reply pass runs AFTER those rows//! exist, because an archive arrives in batches and a reply routinely lands//! before the line it quotes; it is idempotent, so it runs after every import//! and links whatever the previous run could not.//!//! So the surface here is [`plan_import`] → write → [`plan_reply_links`] →//! write, with [`run_import`] composing the four for a caller that just wants//! the batch applied. A probe ([`probe_import`]) resolves the same threads and//! reports the same difference and writes NOTHING — it takes `&D` and returns no//! changes at all, so "a probe must never write" is a property of the type//! rather than a rule somebody has to remember.//!//! ## What the port could not keep//!//! * **`previewForMessage`'s `try`/`catch`.** The TypeScript casts the//!   envelope's `media`/`meta` JSON to the typed shapes and catches whatever the//!   preview throws on a malformed entry, because the preview is cosmetic and//!   must not sink the batch that carries the messages. Rust has no cast: the//!   same JSON is DESERIALISED here, and a deserialisation that fails takes the//!   same fallback line the `catch` writes. Same two branches, reached the same//!   way.//! * **`storeNewId` / `storeNow` / `storeDb`.** Three process-wide singletons//!   in the TypeScript, three arguments here.//! * **The `ApiResponse` envelope.** A `Result` says the same thing, and the//!   `NOT_AUTHENTICATED` arm belongs to whatever calls this — there is no//!   session in this crate to check.use std::collections::{BTreeMap, BTreeSet};use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use crate::change::Change;use crate::ids::{dm_thread_id, group_thread_id};use crate::fingerprint::message::{    content_fingerprint, minute_bucket, normalize_body_for_id, ContentFingerprintInput,    CONTENT_EXTERNAL_ID_PREFIX,};use crate::js::collapse_whitespace_and_trim;use crate::ids::REACTION_ACTOR_SELF;use crate::import::envelope::{    EnvelopeMessage, EnvelopeThread, EnvelopeThreadParticipant, ImportBatch,};use crate::import::group::{group_external_key, slugify_title, GROUP_EXTERNAL_KEY_PREFIX};use crate::phone::normalize_phone_in;use crate::chat_ids::reaction_row_id;use crate::messages::media_only::{body_is_wordless, media_only_kind};use crate::messages::preview::{preview_for_message, should_advance_thread, PreviewSource, MESSAGE_PREVIEW_MAX};use crate::messages::resolve_contact::{    contact_handle_changes, find_contact_by_handle, handle_key, handles_from,    normalize_contact_handle_in, people_by_handle, require_handle, resolve_contact, ContactDriver,    ContactError, ContactHandle, Region,    ContactHandleKind, ContactSource, MatchedPerson, ResolveContactArgs,};use crate::messages::{js_trim, slice_utf16, MessageMedia, MessageMeta, MessagePoll, MessagePollVoter};const THREADS: &str = "cotton_msg_threads";const MESSAGES: &str = "cotton_msg_messages";const PARTICIPANTS: &str = "cotton_msg_thread_participants";const REACTIONS: &str = "cotton_msg_reactions";const WORKSPACES: &str = "cotton_workspaces";/// How many messages the overlap probe fingerprints against.pub const OVERLAP_PROBE_IDS: usize = 300;/* ---------------------------------------------------------------- helpers -- *//// The comparison key for a label: layout and case are not identity.////// `label.replace(/\s+/g, " ").trim().toLowerCase()` — ECMAScript's whitespace/// class on both the collapse and the trim, and the Unicode default case fold,/// which is what Rust's `to_lowercase` performs.pub fn import_label_key(label: &str) -> String {    collapse_whitespace_and_trim(label).to_lowercase()}/// A label that is a number is not a name worth storing as one.////// `/^\+?[\d\s().-]{8,}$/` over the trimmed label. `\d` is the ASCII digits (no/// `u` flag), `\s` is ECMAScript's class, and every character the class admits/// is one UTF-16 unit wide — so counting `chars` counts what `{8,}` counts.pub fn label_looks_like_phone(label: &str) -> bool {    let trimmed = js_trim(label);    let rest = trimmed.strip_prefix('+').unwrap_or(trimmed);    rest.chars().count() >= 8        && rest.chars().all(|ch| {            ch.is_ascii_digit()                || crate::js::is_js_whitespace(ch)                || matches!(ch, '(' | ')' | '.' | '-')        })}/// The `{ phone?, email? }` an envelope names its counterpart by.fn source_of(message: &EnvelopeMessage) -> ContactSource<'_> {    ContactSource {        phone: message.phone.as_deref(),        email: message.email.as_deref(),    }}/// The same, for a participant block.fn participant_source(participant: &EnvelopeThreadParticipant) -> ContactSource<'_> {    ContactSource {        phone: participant.phone.as_deref(),        email: participant.email.as_deref(),    }}/// All identities the source supplied for a participant, with the same/// normalisation the contact and People stores use: a phone without a code is/// read in `region`, the owner's own number's country.pub fn participant_handles(participant: &EnvelopeThreadParticipant, region: Option<Region>) -> Vec<ContactHandle> {    let mut handles=handles_from(&participant_source(participant),region);    if let Some(handle)=participant.handle.as_ref().and_then(|h|normalize_contact_handle_in(h.kind,&h.value,region)) {        if !handles.contains(&handle){handles.push(handle);}    }    handles}fn sender_handles(message: &EnvelopeMessage, region: Option<Region>) -> Vec<ContactHandle> {    let mut handles=handles_from(&source_of(message),region);    if let Some(raw)=message.meta.as_ref().and_then(|m|m.get("source")).and_then(|source|source.get("senderHandle")) {        if let Ok(raw)=serde_json::from_value::<crate::import::envelope::EnvelopeHandle>(raw.clone()) {            if let Some(handle)=normalize_contact_handle_in(raw.kind,&raw.value,region) {                if !handles.contains(&handle){handles.push(handle);}            }        }    }    handles}#[derive(Default)]struct ParticipantSeats {    labels:BTreeMap<String,Option<String>>,    handles:BTreeMap<String,Option<String>>,    /// The region a sender's code-less number is read in, as the seats' were.    region:Option<Region>,}impl ParticipantSeats {    fn in_region(region:Option<Region>)->Self{ParticipantSeats{region,..Default::default()}}    fn insert(&mut self,label:&str,handles:&[ContactHandle],seat:&str) {        fn add(map:&mut BTreeMap<String,Option<String>>,key:String,seat:&str){            match map.get(&key){                Some(Some(old)) if old!=seat=>{map.insert(key,None);},                None=>{map.insert(key,Some(seat.into()));},                _=>{},            }        }        add(&mut self.labels,import_label_key(label),seat);        for handle in handles {add(&mut self.handles,handle_key(handle),seat);}    }    fn sender(&self,message:&EnvelopeMessage)->Option<&str>{        let handles=if message.direction==crate::import::envelope::Direction::In{sender_handles(message,self.region)}else{vec![]};        if !handles.is_empty(){            let mut found=None;            for handle in handles {                let Some(Some(seat))=self.handles.get(&handle_key(&handle)) else{continue;};                if found.is_some_and(|old|old!=seat.as_str()){return None;}                found=Some(seat.as_str());            }            return found;        }        message.sender_label.as_deref().and_then(|label|self.labels.get(&import_label_key(label))).and_then(|seat|seat.as_deref())    }    fn len(&self)->usize {        self.labels.values().chain(self.handles.values()).filter_map(Option::as_deref).collect::<BTreeSet<_>>().len()    }}/* ------------------------------------------------------------ the seam ---- *//// One participant row, as the engine reads it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ParticipantRow {    pub id: String,    pub contact_id: Option<String>,    pub display_name: Option<String>,}/// A thread the engine found, and the one column it decides with.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ThreadHit {    pub id: String,    pub contact_id: Option<String>,}/// What a probe says about a thread that already holds part of this chat.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ThreadStats {    pub count: i64,    pub oldest_sent_at: Option<String>,    pub newest_sent_at: Option<String>,}/// The winner of the overlap probe: a thread and how many of the probed ids it/// holds. The MAJORITY test is the engine's, not the driver's — a driver that/// applied it would be a second place the rule lives.#[derive(Debug, Clone, PartialEq, Eq)]pub struct OverlapHit {    pub thread_id: String,    pub contact_id: Option<String>,    pub matched: i64,}/// Which kind of thread a question is about. The column holds the string.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum ThreadKind {    Dm,    Group,}impl ThreadKind {    pub const fn as_str(self) -> &'static str {        match self {            ThreadKind::Dm => "dm",            ThreadKind::Group => "group",        }    }}/// The reads this engine asks a file for.////// One method per QUESTION rather than a general `all(sql, params)`, for the/// reason [`ContactDriver`] gives: the statements are fixed and declared above,/// so an implementation runs them rather than composing a paraphrase in which a/// workspace filter can go missing.pub trait ImportDriver: ContactDriver {    /// `DM_THREAD_BY_CONTACT_SQL`.    fn dm_thread_for_contact(        &self,        workspace_id: &str,        contact_id: &str,    ) -> Result<Option<String>, ContactError>;    /// `THREAD_BY_ID_SQL`.    fn thread_by_id(        &self,        workspace_id: &str,        id: &str,        kind: ThreadKind,    ) -> Result<Option<ThreadHit>, ContactError>;    /// `known_external_ids_sql`. An empty `ids` is never asked.    fn known_external_ids(        &self,        thread_id: &str,        channel: &str,        ids: &[&str],    ) -> Result<BTreeSet<String>, ContactError>;    /// `THREAD_STATS_SQL`.    fn thread_stats(&self, thread_id: &str, channel: &str) -> Result<ThreadStats, ContactError>;    /// `GROUP_THREAD_BY_KEY_SQL` — the id and the stored title.    fn group_thread_by_key(        &self,        workspace_id: &str,        external_key: &str,    ) -> Result<Option<(String, Option<String>)>, ContactError>;    /// `JID_GROUP_THREADS_SQL` — each thread's id and stored title.    fn jid_group_threads(        &self,        workspace_id: &str,    ) -> Result<Vec<(String, Option<String>)>, ContactError>;    /// `overlap_sql` — the top thread and its count, NOT the majority test.    fn thread_by_overlap(        &self,        workspace_id: &str,        channel: &str,        kind: ThreadKind,        ids: &[&str],    ) -> Result<Option<OverlapHit>, ContactError>;    /// `PARTICIPANTS_SQL`.    fn participants_of(&self, thread_id: &str) -> Result<Vec<ParticipantRow>, ContactError>;    /// `THREAD_LAST_MESSAGE_AT_SQL`. The OUTER option is "is there a row at    /// all" — a thread this batch is creating has none, which is exactly    /// "advance from nothing".    fn thread_last_message_at(        &self,        thread_id: &str,    ) -> Result<Option<Option<String>>, ContactError>;    /// `THREAD_EXTERNAL_KEY_SQL`, with the same two-level option.    fn thread_external_key(&self, thread_id: &str) -> Result<Option<Option<String>>, ContactError>;    /// `UNLINKED_REPLIES_SQL` — `(message id, quoted external id)`.    fn unlinked_replies(&self, thread_id: &str) -> Result<Vec<(String, String)>, ContactError>;    /// `reply_targets_sql` — `(message id, external id)`.    fn messages_by_external_ids(        &self,        thread_id: &str,        channel: &str,        ids: &[&str],    ) -> Result<Vec<(String, String)>, ContactError>;    /// `held_without_media_sql`. An empty `ids` is never asked.    fn held_without_media(        &self,        thread_id: &str,        channel: &str,        ids: &[&str],    ) -> Result<Vec<BareRow>, ContactError>;    /// `REAL_ID_BODIES_IN_MINUTE_SQL` — bodies, oldest first.    fn real_id_bodies_in_minute(        &self,        thread_id: &str,        channel: &str,        minute: &str,    ) -> Result<Vec<String>, ContactError>;    /// `ROWS_IN_MINUTE_SQL` — a thread's rows in one UTC minute, oldest first.    fn rows_in_minute(        &self,        thread_id: &str,        channel: &str,        minute: &str,    ) -> Result<Vec<MinuteRow>, ContactError>;    /// `MESSAGE_BY_EXTERNAL_ID_SQL` — the message a later change names.    fn message_by_external_id(        &self,        workspace_id: &str,        channel: &str,        external_id: &str,    ) -> Result<Option<ChangeTarget>, ContactError>;    /// `SELF_NAMES_SQL`. The outer option is "is there a workspace row" —    /// the TypeScript throws `NOT_FOUND` when there is not.    fn self_names_json(&self, workspace_id: &str) -> Result<Option<Option<String>>, ContactError>;    /// The country a code-less number in a batch is read in:    /// `cotton_store::phone_fold::region_hint` — the owner's first valid phone.    /// `None` when the owner has no number.    fn owner_region(&self, workspace_id: &str) -> Result<Option<Region>, ContactError>;}/* ---------------------------------------------------------------- errors -- *//// Why an import could not run.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum ImportError {    /// Whatever the file said.    #[error("{0}")]    Driver(String),    /// `requireHandle`'s refusal, verbatim.    #[error("An imported message arrived with no usable phone or email and the batch names no counterpart")]    NoUsableHandle,    /// `readSelfNames`' `AppError("Workspace not found", "NOT_FOUND")`.    #[error("Workspace not found")]    WorkspaceNotFound,    /// `setSelfName`'s `AppError(…, "VALIDATION")`.    #[error("A self name cannot be blank")]    BlankSelfName,}impl ImportError {    /// The `AppError` code the TypeScript answers with, for a caller that has to    /// put one on the wire.    pub const fn code(&self) -> &'static str {        match self {            ImportError::Driver(_) => "UNKNOWN",            ImportError::NoUsableHandle => "IMPORT_SHAPE",            ImportError::WorkspaceNotFound => "NOT_FOUND",            ImportError::BlankSelfName => "VALIDATION",        }    }}impl From<ContactError> for ImportError {    fn from(error: ContactError) -> ImportError {        ImportError::Driver(error.0)    }}/* --------------------------------------------------------------- reports -- *//// One chat's outcome — the TypeScript's `results` row.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ChatResult {    /// The counterpart's number where there is one. An email-keyed chat reports    /// `null` rather than an address in a field every caller reads as a number;    /// a group reports its external key, which is what the TypeScript puts here.    pub phone: Option<String>,    pub contact_id: Option<String>,    pub thread_id: String,    pub inserted: i64,    pub skipped: i64,    /// Always `0` per chat: the reply pass is per RUN, and its count lands in    /// the totals. Kept because the TypeScript's callers read the key.    pub unresolved_replies: i64,}/// What the group leg resolved.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct GroupResult {    pub thread_id: String,    pub title: String,    pub external_key: String,    pub participant_count: i64,    pub thread_created: bool,}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ImportTotals {    pub chats: i64,    pub inserted: i64,    pub skipped: i64,    pub unresolved_replies: i64,}/// What one applied batch did.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ImportReport {    pub chats: Vec<ChatResult>,    #[serde(skip_serializing_if = "Option::is_none")]    pub group: Option<GroupResult>,    pub totals: ImportTotals,}/// The rows a batch owes the file, and what it resolved — everything except the/// reply links, which cannot be planned until these have landed.#[derive(Debug, Clone, PartialEq)]pub struct ImportPlan {    pub changes: Vec<Change>,    pub chats: Vec<ChatResult>,    pub group: Option<GroupResult>,}/// The reply pass's answer.#[derive(Debug, Clone, PartialEq)]pub struct ReplyLinks {    pub changes: Vec<Change>,    /// Still unlinked — a non-zero count on a full-history import means the    /// export was silently truncated.    pub unresolved: i64,}/* ----------------------------------------------------------------- probe -- *//// How a probe found a group.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pub enum MatchedBy {    Key,    Overlap,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ProbeChat {    /// The external key for a group, the handle's value for a dm, and    /// `label:<label>` for a counterpart who named no handle.    pub key: String,    pub thread_id: Option<String>,    pub existing: Option<ThreadStats>,    pub would_insert: i64,    pub would_skip: i64,    pub new_external_ids: Vec<String>,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ProbeGroup {    pub thread_id: Option<String>,    pub matched_by: Option<MatchedBy>,    pub stored_title: Option<String>,}/// The preview card's "N to identify".#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ParticipantsSummary {    pub total: i64,    pub identified: i64,    pub unidentified: i64,    pub unidentified_labels: Vec<String>,}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ProbeTotals {    pub chats: i64,    pub would_insert: i64,    pub would_skip: i64,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ProbeReport {    pub chats: Vec<ProbeChat>,    #[serde(skip_serializing_if = "Option::is_none")]    pub group: Option<ProbeGroup>,    pub participants: ParticipantsSummary,    pub totals: ProbeTotals,}/* ------------------------------------------------------------------ reads -- *//// The dm thread a handle's counterpart already has, or none.fn dm_thread_id_by_handle<D: ImportDriver + ?Sized>(    db: &D,    workspace_id: &str,    handle: &ContactHandle,) -> Result<Option<String>, ImportError> {    let Some(contact) = find_contact_by_handle(db, workspace_id, handle)? else {        return Ok(None);    };    Ok(db.dm_thread_for_contact(workspace_id, &contact.id)?)}/// Which of these external ids already live in the thread?fn known_external_ids<D: ImportDriver + ?Sized>(    db: &D,    thread_id: &str,    channel: &str,    messages: &[&EnvelopeMessage],) -> Result<BTreeSet<String>, ImportError> {    if messages.is_empty() {        return Ok(BTreeSet::new());    }    let ids: Vec<&str> = messages        .iter()        .map(|message| message.external_id.as_str())        .collect();    Ok(db.known_external_ids(thread_id, channel, &ids)?)}/// Dedupe WITHIN the batch too: an export can repeat a line, and two rows with/// the same key in one write would trip the unique index rather than being/// skipped like the re-run case.fn fresh_messages<'a>(    messages: &[&'a EnvelopeMessage],    known: &BTreeSet<String>,) -> Vec<&'a EnvelopeMessage> {    let mut seen: BTreeSet<&str> = BTreeSet::new();    let mut fresh = Vec::new();    for message in messages.iter().copied() {        if known.contains(&message.external_id) || seen.contains(message.external_id.as_str()) {            continue;        }        seen.insert(message.external_id.as_str());        fresh.push(message);    }    fresh}/// The overlap leg: what survives a renamed group, a changed key — or, for a/// dm, a counterpart whose name the export writes differently from last time.////// The thread holding AT LEAST HALF of the probed ids is the conversation. A/// bare "any shared id" would fold strangers together: a fingerprint is minute/// plus body, so a greeting forwarded to two people is ONE id living in two/// conversations. A re-export overlaps on nearly every probed id; a coincidence/// overlaps on one.fn find_thread_by_overlap<D: ImportDriver + ?Sized>(    db: &D,    workspace_id: &str,    channel: &str,    kind: ThreadKind,    messages: &[&EnvelopeMessage],) -> Result<Option<ThreadHit>, ImportError> {    let mut seen: BTreeSet<&str> = BTreeSet::new();    let mut probe: Vec<&str> = Vec::new();    for message in messages.iter().copied() {        if seen.insert(message.external_id.as_str()) {            probe.push(message.external_id.as_str());        }        if probe.len() == OVERLAP_PROBE_IDS {            break;        }    }    if probe.is_empty() {        return Ok(None);    }    let Some(hit) = db.thread_by_overlap(workspace_id, channel, kind, &probe)? else {        return Ok(None);    };    if hit.matched * 2 < probe.len() as i64 {        return Ok(None);    }    Ok(Some(ThreadHit {        id: hit.thread_id,        contact_id: hit.contact_id,    }))}fn participant_for_label<'a>(    seats: &'a [ParticipantRow],    label: &str,) -> Option<&'a ParticipantRow> {    let key = import_label_key(label);    seats.iter().find(|seat| {        seat.display_name            .as_deref()            .is_some_and(|name| import_label_key(name) == key)    })}/// Who among these labels is identified — a phone given now, or a participant/// row that already has a contact.fn participants_summary(    participants: &[EnvelopeThreadParticipant],    seats: &[ParticipantRow],    extra_identified: &dyn Fn(&EnvelopeThreadParticipant) -> bool,    region: Option<Region>,) -> ParticipantsSummary {    let mut unidentified_labels = Vec::new();    let mut identified = 0i64;    for participant in participants {        let seated = participant_for_label(seats, &participant.label);        // `participant.phone` is a TRUTHINESS test in the TypeScript, so an        // empty string identifies nobody.        let has_phone = !participant_handles(participant, region).is_empty();        if has_phone            || seated.is_some_and(|seat| seat.contact_id.is_some())            || extra_identified(participant)        {            identified += 1;        } else {            unidentified_labels.push(participant.label.clone());        }    }    ParticipantsSummary {        total: participants.len() as i64,        identified,        unidentified: unidentified_labels.len() as i64,        unidentified_labels,    }}/* ----------------------------------------------------------------- writes -- */fn upsert(table: &str, row_id: &str, patch: Map<String, Value>) -> Change {    Change::upsert(table, row_id, patch)}/// Find or create ONE contact from a handle, onto the batch's pending changes.////// The rule itself lives in [`resolve_contact`] — one implementation, because a/// second would eventually disagree and here a disagreement is two contact rows/// for one human, which is a conversation split down the middle in front of the/// person whose conversation it is.#[allow(clippy::too_many_arguments)]fn ensure_contact<D: ImportDriver + ?Sized>(    db: &D,    pending: &mut Vec<Change>,    workspace_id: &str,    namespace: &str,    handle: &ContactHandle,    display_name: Option<&str>,    person_id: Option<&str>,    now: &str,    new_id: &mut dyn FnMut() -> String,    people: &BTreeMap<String, MatchedPerson>,) -> Result<String, ImportError> {    let resolved = resolve_contact(ResolveContactArgs {        db,        workspace_id,        namespace,        handle,        display_name,        person_id,        now,        new_id,        people: Some(people),    })?;    pending.extend(resolved.changes);    Ok(resolved.contact_id)}/// Every OTHER handle a counterpart named, recorded against the contact we/// settled on.////// A source that hands us both a number and an Apple ID has told us two true/// things about one person; keeping only the one we keyed on would mean the next/// batch — carrying only the other — mints a second contact beside them. The/// FIRST handle is already written by [`resolve_contact`].////// A handle another contact already owns is left alone rather than stolen: one/// number belongs to one contact in a file, and re-pointing it here would move/// somebody's conversation without anyone asking.fn record_extra_handles<D: ImportDriver + ?Sized>(    db: &D,    pending: &mut Vec<Change>,    workspace_id: &str,    namespace: &str,    contact_id: &str,    handles: &[ContactHandle],    now: &str,) -> Result<(), ImportError> {    for handle in handles.iter().skip(1) {        let owner = find_contact_by_handle(db, workspace_id, handle)?;        if owner.is_some_and(|row| row.id != contact_id) {            continue;        }        pending.extend(contact_handle_changes(            namespace,            workspace_id,            contact_id,            handle,            now,        ));    }    Ok(())}fn ensure_dm_thread<D: ImportDriver + ?Sized>(    db: &D,    pending: &mut Vec<Change>,    workspace_id: &str,    namespace: &str,    contact_id: &str,    now: &str,    reserved: Option<&str>,) -> Result<String, ImportError> {    if let Some(existing) = db.dm_thread_for_contact(workspace_id, contact_id)? {        return Ok(existing);    }    // DERIVED from (workspace, contact) — `uq_cotton_msg_threads_dm`. The    // caller's reserved id still wins where there is one: it is derived from    // the backup's own identity (`whatsapp_thread_id`), so it converges too,    // and it is what the caller keyed this batch's attachments on.    let id = reserved        .map(str::to_string)        .unwrap_or_else(|| dm_thread_id(namespace, contact_id));    let mut patch = Map::new();    patch.insert("id".to_string(), Value::from(id.as_str()));    patch.insert("workspace_id".to_string(), Value::from(workspace_id));    patch.insert("contact_id".to_string(), Value::from(contact_id));    patch.insert("kind".to_string(), Value::from("dm"));    patch.insert("archived".to_string(), Value::Bool(false));    patch.insert("created_at".to_string(), Value::from(now));    patch.insert("updated_at".to_string(), Value::from(now));    pending.push(upsert(THREADS, &id, patch));    Ok(id)}/// A dm thread for a person we know only by name: titled, no contact, until/// identified.fn create_unidentified_dm_thread(    pending: &mut Vec<Change>,    workspace_id: &str,    label: &str,    now: &str,    new_id: &mut dyn FnMut() -> String,    reserved: Option<&str>,) -> String {    let id = reserved.map(str::to_string).unwrap_or_else(new_id);    let mut patch = Map::new();    patch.insert("id".to_string(), Value::from(id.as_str()));    patch.insert("workspace_id".to_string(), Value::from(workspace_id));    patch.insert("contact_id".to_string(), Value::Null);    patch.insert("kind".to_string(), Value::from("dm"));    patch.insert("title".to_string(), Value::from(label));    patch.insert("archived".to_string(), Value::Bool(false));    patch.insert("created_at".to_string(), Value::from(now));    patch.insert("updated_at".to_string(), Value::from(now));    pending.push(upsert(THREADS, &id, patch));    id}/// Find-or-create the PARTICIPANT ROW for a label in a thread, and link it to a/// contact when the label now has one.////// A resolved contact identifies its existing seat first. Without a contact,/// an unambiguous label keeps the unidentified seat an earlier export wrote.#[allow(clippy::too_many_arguments)]fn ensure_participant(    pending: &mut Vec<Change>,    workspace_id: &str,    thread_id: &str,    seats: &mut Vec<ParticipantRow>,    participant: &EnvelopeThreadParticipant,    contact_id: Option<&str>,    now: &str,    new_id: &mut dyn FnMut() -> String,) -> String {    // A source identity wins over a display label, including on replay when    // another participant has the same label.    let index = contact_id        .and_then(|contact| seats.iter().position(|seat| seat.contact_id.as_deref() == Some(contact)))        .or_else(|| {            participant_for_label(seats, &participant.label)                .filter(|seat| contact_id.is_none() || seat.contact_id.is_none())                .and_then(|seat| seats.iter().position(|candidate| candidate.id == seat.id))        });    if let Some(index) = index {        let seat = &mut seats[index];        let mut patch = Map::new();        if seat.contact_id.is_none() {            if let Some(contact_id) = contact_id {                patch.insert("contact_id".to_string(), Value::from(contact_id));                seat.contact_id = Some(contact_id.to_string());            }        }        if seat.display_name.is_none() {            patch.insert(                "display_name".to_string(),                Value::from(participant.label.as_str()),            );            seat.display_name = Some(participant.label.clone());        }        if !patch.is_empty() {            pending.push(upsert(PARTICIPANTS, &seat.id, patch));        }        return seat.id.clone();    }    let id = new_id();    let mut patch = Map::new();    patch.insert("id".to_string(), Value::from(id.as_str()));    patch.insert("thread_id".to_string(), Value::from(thread_id));    patch.insert("workspace_id".to_string(), Value::from(workspace_id));    patch.insert(        "contact_id".to_string(),        match contact_id {            Some(contact_id) => Value::from(contact_id),            None => Value::Null,        },    );    patch.insert(        "display_name".to_string(),        Value::from(participant.label.as_str()),    );    patch.insert("created_at".to_string(), Value::from(now));    pending.push(upsert(PARTICIPANTS, &id, patch));    seats.push(ParticipantRow {        id: id.clone(),        contact_id: contact_id.map(str::to_string),        display_name: Some(participant.label.clone()),    });    id}/// One chat on the no-block path — the batch grouped by the counterpart's/// HANDLE, one dm thread per person.struct HandleChat<'a> {    handle: ContactHandle,    handles: Vec<ContactHandle>,    display_name: Option<&'a str>,    messages: Vec<&'a EnvelopeMessage>,}/// Keyed on the handle rather than the phone since schema v36: the same/// grouping question, asked of a batch whose counterparts may be Apple ID/// emails. A batch with no `dm` block must name its counterpart on every/// message, and [`require_handle`] keeps that invariant loud rather than letting/// a nameless row fall into somebody else's conversation.fn group_by_handle(messages: &[EnvelopeMessage], region: Option<Region>) -> Result<Vec<HandleChat<'_>>, ImportError> {    // Insertion order, which is what a JavaScript `Map` iterates in and what the    // per-chat results are reported in.    let mut order: Vec<HandleChat<'_>> = Vec::new();    let mut index: BTreeMap<String, usize> = BTreeMap::new();    for message in messages {        let handle =            require_handle(&source_of(message), region).map_err(|_| ImportError::NoUsableHandle)?;        let key = handle_key(&handle);        if let Some(at) = index.get(&key) {            let chat = &mut order[*at];            // First non-null name in the batch wins — an export names the same            // person on every line, and re-deciding per row would just flap.            if chat.display_name.is_none() {                chat.display_name = message.display_name.as_deref();            }            chat.messages.push(message);            continue;        }        index.insert(key, order.len());        order.push(HandleChat {            handle,            handles: handles_from(&source_of(message), region),            display_name: message.display_name.as_deref(),            messages: vec![message],        });    }    Ok(order)}/// A legacy envelope reaction, as a row.////// `owner` becomes `self`; everything else must normalise to digits — a mirror/// arriving from another file knows only phones, so the actor vocabulary is/// phone-or-self and there is no third case. An actor that is neither (an export/// that wrote a NAME) is DROPPED rather than keyed into an id nobody can parse/// back: losing an emoji is survivable, losing the message it was on is not.////// The id is derived from (message, actor), so a re-import upserts the row it/// wrote last time instead of adding a second one.fn reaction_changes(    message_id: &str,    thread_id: &str,    workspace_id: &str,    message: &EnvelopeMessage,    fallback_at: &str,    region: Option<Region>,) -> Vec<Change> {    let mut changes = Vec::new();    for reaction in message.reactions.iter().flatten() {        if js_trim(&reaction.emoji).is_empty() {            continue;        }        if js_trim(&reaction.actor).is_empty() {            continue;        }        let resolved = if reaction.actor == "owner" {            Some(REACTION_ACTOR_SELF.to_string())        } else {            normalize_phone_in(&reaction.actor, region)        };        let Some(resolved) = resolved else {            continue;        };        // `reaction_row_id` can refuse; `normalize_phone` already answered the        // only shape it refuses, so this arm is unreachable — and dropping the        // reaction is what the TypeScript's own guard does one line up.        let Ok(id) = reaction_row_id(message_id, &resolved) else {            continue;        };        let mut patch = Map::new();        patch.insert("id".to_string(), Value::from(id.as_str()));        patch.insert("workspace_id".to_string(), Value::from(workspace_id));        patch.insert("thread_id".to_string(), Value::from(thread_id));        patch.insert("message_id".to_string(), Value::from(message_id));        patch.insert("actor".to_string(), Value::from(resolved.as_str()));        patch.insert(            "emoji".to_string(),            Value::from(js_trim(&reaction.emoji).to_string()),        );        patch.insert(            "created_at".to_string(),            Value::from(match reaction.at.as_deref() {                Some(at) if !at.is_empty() => at,                _ => fallback_at,            }),        );        changes.push(upsert(REACTIONS, &id, patch));    }    changes}struct IntoThread<'a> {    thread_id: &'a str,    workspace_id: &'a str,    channel: &'a str,    messages: &'a [&'a EnvelopeMessage],    seat_id_by_label: &'a ParticipantSeats,    now: &'a str,    /// The owner's own number's country, for a reaction's code-less actor.    region: Option<Region>,}/// The write half every mode shares: skip what is here, insert the difference.fn import_into_thread<D: ImportDriver + ?Sized>(    db: &D,    pending: &mut Vec<Change>,    args: &IntoThread<'_>,    new_id: &mut dyn FnMut() -> String,) -> Result<(i64, i64), ImportError> {    let known = known_external_ids(db, args.thread_id, args.channel, args.messages)?;    let filled = pictures_filled(db, args.thread_id, args.channel, args.messages, &known)?;    let filled_count = filled.len();    for (row_id, patch) in filled {        pending.push(upsert(MESSAGES, &row_id, patch));    }    let fresh = fresh_messages(args.messages, &known);    let mut taken = export_rows_taken_over(db, args.thread_id, args.channel, &fresh)?;    let pictures = export_pictures_taken_over(db, args.thread_id, args.channel, &fresh, &taken)?;    taken.extend(pictures.iter().map(|(at, row)| (*at, row.clone())));    let mut held = export_lines_already_held(db, args.thread_id, args.channel, &fresh)?;    held.extend(export_pictures_already_held(db, args.thread_id, args.channel, &fresh, &held)?);    let mut newest: Option<&EnvelopeMessage> = None;    for (at, message) in fresh.iter().copied().enumerate() {        if held.contains(&at) {            continue;        }        if newest.is_none_or(|seen| message.sent_at > seen.sent_at) {            newest = Some(message);        }        if let Some(row_id) = taken.get(&at) {            // The export's row becomes this message: its id, its provenance and            // its quote move to the source that knows them; the row, and every            // link to it, stays.            let mut patch = Map::new();            patch.insert(                "external_id".to_string(),                Value::from(message.external_id.as_str()),            );            patch.insert("body".to_string(), Value::from(message.body.as_str()));            patch.insert("sent_at".to_string(), Value::from(message.sent_at.as_str()));            patch.insert("meta".to_string(), meta_value(message));            if let Some(external) = message.reply_to_external_id.as_deref() {                patch.insert("reply_to_external_id".to_string(), Value::from(external));            }            if pictures.contains_key(&at) {                // A picture matched by minute and kind alone: the row becomes                // the linked message whole — its bytes, and who sent it, so two                // people's pictures in one minute can never keep a crossed name.                patch.insert("media".to_string(), media_value(message));                if let Some(seat) = args.seat_id_by_label.sender(message)                {                    patch.insert("sender_participant_id".to_string(), Value::from(seat));                }            }            pending.push(upsert(MESSAGES, row_id, patch));            continue;        }        let id = new_id();        let mut patch = Map::new();        patch.insert("id".to_string(), Value::from(id.as_str()));        patch.insert("thread_id".to_string(), Value::from(args.thread_id));        patch.insert("workspace_id".to_string(), Value::from(args.workspace_id));        patch.insert(            "direction".to_string(),            Value::from(message.direction.as_str()),        );        patch.insert("channel".to_string(), Value::from(args.channel));        patch.insert("origin".to_string(), Value::from("imported"));        patch.insert("body".to_string(), Value::from(message.body.as_str()));        patch.insert("media".to_string(), media_value(message));        patch.insert(            "external_id".to_string(),            Value::from(message.external_id.as_str()),        );        patch.insert("sent_at".to_string(), Value::from(message.sent_at.as_str()));        patch.insert("created_at".to_string(), Value::from(args.now));        // Resolved from the participant rows this same run just ensured, so a        // sender can never point across threads.        patch.insert(            "sender_participant_id".to_string(),            args.seat_id_by_label.sender(message).map_or(Value::Null,Value::from),        );        // `reply_to_id` is deliberately NOT set here — the quoted line may not        // exist yet. The resolution pass links what it can.        patch.insert(            "reply_to_external_id".to_string(),            match message.reply_to_external_id.as_deref() {                Some(external) => Value::from(external),                None => Value::Null,            },        );        // Reactions are ROWS from schema v9 — two people reacting at once must        // both land, and last-write-wins over a whole JSON column keeps one of        // them. The column stays and stays empty so an old build's op folds.        patch.insert("reactions".to_string(), Value::Array(Vec::new()));        patch.insert("meta".to_string(), meta_value(message));        pending.push(upsert(MESSAGES, &id, patch));        pending.extend(reaction_changes(            &id,            args.thread_id,            args.workspace_id,            message,            &message.sent_at,            args.region,        ));    }    advance_thread_denorm(db, pending, args.thread_id, newest, args.now)?;    let written = fresh.len() - held.len() + filled_count;    Ok((        written as i64,        args.messages.len() as i64 - written as i64,    ))}/// Export lines the thread ALREADY holds under a real id: `fresh` indexes.////// The mirror of [`export_rows_taken_over`], for an export that arrives AFTER/// the linked device or the iPhone backup brought the same messages. An export/// line has no id, only its UTC minute and its text; the k-th line with a text/// in a minute is the k-th row with that text in that minute that came with a/// real id. Such a line is the same message, so it is skipped, never written/// a second time.fn export_lines_already_held<D: ImportDriver + ?Sized>(    db: &D,    thread_id: &str,    channel: &str,    fresh: &[&EnvelopeMessage],) -> Result<BTreeSet<usize>, ImportError> {    let mut by_minute: BTreeMap<String, Vec<(String, bool)>> = BTreeMap::new();    let mut held = BTreeSet::new();    for (at, message) in fresh.iter().enumerate() {        if !message.external_id.starts_with(CONTENT_EXTERNAL_ID_PREFIX) || js_trim(&message.body).is_empty() {            continue;        }        let Ok(minute) = minute_bucket(&message.sent_at) else {            continue;        };        if !by_minute.contains_key(&minute) {            let rows = db                .real_id_bodies_in_minute(thread_id, channel, &minute)?                .into_iter()                .map(|body| (normalize_body_for_id(&body), false))                .collect();            by_minute.insert(minute.clone(), rows);        }        let text = normalize_body_for_id(&message.body);        let rows = by_minute.get_mut(&minute).expect("just filled");        if let Some(row) = rows.iter_mut().find(|(body, claimed)| !claimed && *body == text) {            row.1 = true;            held.insert(at);        }    }    Ok(held)}/// How many same-minute repeats of one text an export row is looked for under.pub const TAKEOVER_OCCURRENCES: u64 = 4;/// Export rows a message with WhatsApp's own id takes over: `fresh` index → row id.////// A `_chat.txt` export has no ids, so its rows are keyed by the content/// fingerprint — UTC minute, collapsed text, occurrence among same-minute/// repeats. When the same message arrives from a source that carries the real/// id (the linked device, the iPhone backup), the fingerprint it WOULD have had/// finds the export's row exactly, and that row is taken over instead of a/// second copy being written. Occurrences are claimed lowest first, each once.fn export_rows_taken_over<D: ImportDriver + ?Sized>(    db: &D,    thread_id: &str,    channel: &str,    fresh: &[&EnvelopeMessage],) -> Result<BTreeMap<usize, String>, ImportError> {    let mut wanted: Vec<(usize, String)> = Vec::new();    for (at, message) in fresh.iter().enumerate() {        if message.external_id.starts_with(CONTENT_EXTERNAL_ID_PREFIX)            || js_trim(&message.body).is_empty()        {            continue;        }        for occurrence in 0..TAKEOVER_OCCURRENCES {            let Ok(id) = content_fingerprint(&ContentFingerprintInput {                sent_at: &message.sent_at,                body: &message.body,                occurrence,            }) else {                break;            };            wanted.push((at, id));        }    }    if wanted.is_empty() {        return Ok(BTreeMap::new());    }    let ids: Vec<&str> = wanted.iter().map(|(_, id)| id.as_str()).collect();    let rows: BTreeMap<String, String> = db        .messages_by_external_ids(thread_id, channel, &ids)?        .into_iter()        .map(|(row_id, external_id)| (external_id, row_id))        .collect();    let mut claimed: BTreeSet<&str> = BTreeSet::new();    let mut taken = BTreeMap::new();    for (at, id) in &wanted {        if taken.contains_key(at) {            continue;        }        if let Some(row_id) = rows.get(id) {            if claimed.insert(row_id.as_str()) {                taken.insert(*at, row_id.clone());            }        }    }    Ok(taken)}/// One row of `ROWS_IN_MINUTE_SQL`.#[derive(Debug, Clone, PartialEq, Eq)]pub struct MinuteRow {    pub id: String,    pub external_id: Option<String>,    pub direction: String,    pub body: Option<String>,    pub meta: Option<String>,}/// One row of `held_without_media_sql`: a message the thread holds with/// no picture.#[derive(Debug, Clone, PartialEq, Eq)]pub struct BareRow {    pub id: String,    pub external_id: String,    pub body: Option<String>,    pub meta: Option<String>,}/// `meta.mediaOnly`: what a media-only message carried; its body stays empty/// and readers say it through [`crate::messages::media_only::media_only_words`].pub use crate::messages::media_only::MEDIA_ONLY_META;/// The kinds a picture is compared by: a voice note and an audio file are one/// thing in an export (`audio omitted`), a GIF is a video on the wire.fn media_class(kind: &str) -> &'static str {    match kind {        "image" | "photo" => "image",        "video" | "gif" => "video",        "voice" | "audio" | "ptt" => "audio",        "sticker" => "sticker",        "document" => "document",        "contact" | "contacts" => "contact",        _ => "other",    }}/// A live message that is media and nothing else: its kind's class.fn live_media_only(message: &EnvelopeMessage) -> Option<&'static str> {    if message.external_id.starts_with(CONTENT_EXTERNAL_ID_PREFIX) {        return None;    }    let kind = message.meta.as_ref()?.get(MEDIA_ONLY_META)?.as_str()?;    Some(media_class(kind))}/// What an export's caption-less media line was, as far as the line says:/// `Some(None)` for a media line that names no kind (`<Media omitted>`),/// `Some(Some(class))` when its label or file name does, `None` when the line/// is not a caption-less media line at all.fn export_media_line(body: &str, meta: Option<&Map<String, Value>>) -> Option<Option<&'static str>> {    let attachment = meta?.get("attachment")?.as_object()?;    let body = js_trim(body);    // A caption is kept as the body; only the placeholder the importer wrote    // for a line with no words is a picture and nothing else.    if !(body.starts_with('[') && body.ends_with(']')) {        return None;    }    let lower = body.to_lowercase();    for (word, class) in [        ("image omitted", "image"),        ("video omitted", "video"),        ("gif omitted", "video"),        ("audio omitted", "audio"),        ("sticker omitted", "sticker"),        ("document omitted", "document"),        ("contact card omitted", "contact"),    ] {        if lower.contains(word) {            return Some(Some(class));        }    }    let name = attachment        .get("name")        .and_then(Value::as_str)        .map(str::to_uppercase)        .unwrap_or_default();    let ext = name.rsplit_once('.').map(|(_, ext)| ext).unwrap_or("");    let class = if name.contains("PHOTO-") {        Some("image")    } else if name.contains("VIDEO-") || name.contains("GIF-") {        Some("video")    } else if name.contains("AUDIO-") || name.contains("PTT-") {        Some("audio")    } else if name.contains("STICKER-") {        Some("sticker")    } else {        match ext {            "JPG" | "JPEG" | "PNG" | "HEIC" => Some("image"),            "MP4" | "MOV" | "3GP" => Some("video"),            "OPUS" | "M4A" | "MP3" | "AAC" | "OGG" => Some("audio"),            "WEBP" => Some("sticker"),            "VCF" => Some("contact"),            "" => None,            _ => Some("document"),        }    };    Some(class)}fn parsed_meta(meta: Option<&str>) -> Option<Map<String, Value>> {    serde_json::from_str::<Value>(meta?).ok()?.as_object().cloned()}fn same_media(live: &str, export: Option<&str>) -> bool {    export.is_none_or(|class| class == live)}/// A content row of one minute an export media line may take over: the row,/// the media kind its body names (None for a bare `<Media omitted>`), and/// whether a line claimed it already.type MinuteCandidate = (MinuteRow, Option<&'static str>, bool);/// Export media lines a picture-only message with WhatsApp's own id takes/// over: `fresh` index → row id.////// An export writes a picture with no words as a placeholder (`[image/// omitted]`, `[attachment: PHOTO-….jpg]`) under the fingerprint of an EMPTY/// text, so the text take-over never finds it and the picture arrived twice./// Here it is matched as the person sees it: the same minute, the same side of/// the chat, a kind the line allows (a bare `<Media omitted>` allows any);/// rows are claimed oldest first, each once.fn export_pictures_taken_over<D: ImportDriver + ?Sized>(    db: &D,    thread_id: &str,    channel: &str,    fresh: &[&EnvelopeMessage],    taken: &BTreeMap<usize, String>,) -> Result<BTreeMap<usize, String>, ImportError> {    let mut by_minute: BTreeMap<String, Vec<MinuteCandidate>> = BTreeMap::new();    let claimed_elsewhere: BTreeSet<&str> = taken.values().map(String::as_str).collect();    let mut out = BTreeMap::new();    for (at, message) in fresh.iter().enumerate() {        if taken.contains_key(&at) {            continue;        }        let Some(class) = live_media_only(message) else {            continue;        };        let Ok(minute) = minute_bucket(&message.sent_at) else {            continue;        };        if !by_minute.contains_key(&minute) {            let rows = db                .rows_in_minute(thread_id, channel, &minute)?                .into_iter()                .filter(|row| {                    row.external_id                        .as_deref()                        .is_some_and(|id| id.starts_with(CONTENT_EXTERNAL_ID_PREFIX))                })                .filter_map(|row| {                    let meta = parsed_meta(row.meta.as_deref());                    let kind = export_media_line(row.body.as_deref().unwrap_or(""), meta.as_ref())?;                    Some((row, kind, false))                })                .collect();            by_minute.insert(minute.clone(), rows);        }        let rows = by_minute.get_mut(&minute).expect("just filled");        let direction = message.direction.as_str();        if let Some(row) = rows.iter_mut().find(|(row, kind, claimed)| {            !claimed                && row.direction == direction                && same_media(class, *kind)                && !claimed_elsewhere.contains(row.id.as_str())        }) {            row.2 = true;            out.insert(at, row.0.id.clone());        }    }    Ok(out)}/// Export media lines the thread ALREADY holds as a picture-only message with/// a real id — the mirror of [`export_pictures_taken_over`] for an export that/// arrives after the linked device: `fresh` indexes, never written twice.fn export_pictures_already_held<D: ImportDriver + ?Sized>(    db: &D,    thread_id: &str,    channel: &str,    fresh: &[&EnvelopeMessage],    held: &BTreeSet<usize>,) -> Result<BTreeSet<usize>, ImportError> {    let mut by_minute: BTreeMap<String, Vec<(String, &'static str, bool)>> = BTreeMap::new();    let mut out = BTreeSet::new();    for (at, message) in fresh.iter().enumerate() {        if held.contains(&at) || !message.external_id.starts_with(CONTENT_EXTERNAL_ID_PREFIX) {            continue;        }        let Some(kind) = export_media_line(&message.body, message.meta.as_ref()) else {            continue;        };        let Ok(minute) = minute_bucket(&message.sent_at) else {            continue;        };        if !by_minute.contains_key(&minute) {            let rows = db                .rows_in_minute(thread_id, channel, &minute)?                .into_iter()                .filter(|row| {                    row.external_id                        .as_deref()                        .is_some_and(|id| !id.starts_with(CONTENT_EXTERNAL_ID_PREFIX))                })                .filter_map(|row| {                    let meta = parsed_meta(row.meta.as_deref())?;                    let class = media_class(meta.get(MEDIA_ONLY_META)?.as_str()?);                    Some((row.direction, class, false))                })                .collect();            by_minute.insert(minute.clone(), rows);        }        let rows = by_minute.get_mut(&minute).expect("just filled");        let direction = message.direction.as_str();        if let Some(row) = rows            .iter_mut()            .find(|(side, class, claimed)| !claimed && side == direction && same_media(class, kind))        {            row.2 = true;            out.insert(at);        }    }    Ok(out)}/// Rows to patch: each row's id and the fields it gains.type RowPatches = Vec<(String, Map<String, Value>)>;/// Messages the thread ALREADY holds by their real id but WITHOUT a picture,/// for which this batch brings one: `(row id, patch)`.////// The linked device's history carries a picture only for its last 30 days,/// so an older photo arrives as a row that says "Photo" and holds nothing./// The iPhone backup has the bytes. The row stays the one row it is — its/// id, its replies, its reactions — and takes the media; a body that was only/// a body that says nothing (empty, or an old row's left-behind label:/// [`body_is_wordless`]) becomes the backup's caption./// A row that already holds media is never touched, so a re-read writes/// nothing.fn pictures_filled<D: ImportDriver + ?Sized>(    db: &D,    thread_id: &str,    channel: &str,    messages: &[&EnvelopeMessage],    known: &BTreeSet<String>,) -> Result<RowPatches, ImportError> {    let carrying: Vec<&EnvelopeMessage> = messages        .iter()        .copied()        .filter(|message| known.contains(&message.external_id))        .filter(|message| message.media.as_ref().is_some_and(|media| !media.is_empty()))        .collect();    if carrying.is_empty() {        return Ok(Vec::new());    }    let ids: Vec<&str> = carrying.iter().map(|message| message.external_id.as_str()).collect();    let bare = db.held_without_media(thread_id, channel, &ids)?;    let mut filled = Vec::new();    for row in bare {        let Some(message) = carrying.iter().find(|message| message.external_id == row.external_id) else {            continue;        };        let mut patch = Map::new();        patch.insert("media".to_string(), media_value(message));        let marked = parsed_meta(row.meta.as_deref()).is_some_and(|meta| media_only_kind(&meta).is_some());        let body = row.body.as_deref().unwrap_or("");        if marked && body_is_wordless(body, true) && body != message.body {            patch.insert("body".to_string(), Value::from(message.body.as_str()));        }        filled.push((row.id, patch));    }    Ok(filled)}fn media_value(message: &EnvelopeMessage) -> Value {    match &message.media {        Some(media) => serde_json::to_value(media).unwrap_or_else(|_| Value::Array(Vec::new())),        None => Value::Array(Vec::new()),    }}fn meta_value(message: &EnvelopeMessage) -> Value {    match &message.meta {        Some(meta) => Value::Object(meta.clone()),        None => Value::Object(Map::new()),    }}/// Move the thread's list-facing stamp forward to the newest row this batch/// inserted — and only FORWARD ([`should_advance_thread`]): a five-year archive/// landing behind a live conversation must not drag its preview into the past.fn advance_thread_denorm<D: ImportDriver + ?Sized>(    db: &D,    pending: &mut Vec<Change>,    thread_id: &str,    newest: Option<&EnvelopeMessage>,    now: &str,) -> Result<(), ImportError> {    let Some(newest) = newest else {        return Ok(());    };    // A thread created earlier in this same batch is not in the file yet —    // the read finds no row, which is exactly "advance from nothing".    if let Some(current) = db.thread_last_message_at(thread_id)? {        if !should_advance_thread(current.as_deref(), &newest.sent_at) {            return Ok(());        }    }    let mut patch = Map::new();    patch.insert(        "last_message_at".to_string(),        Value::from(newest.sent_at.as_str()),    );    patch.insert(        "last_message_preview".to_string(),        Value::from(preview_of(newest)),    );    patch.insert("updated_at".to_string(), Value::from(now));    pending.push(upsert(THREADS, thread_id, patch));    Ok(())}/// The preview line for the newest row, with the TypeScript's own fallback.////// The TypeScript CASTS the envelope's `media`/`meta` JSON to the typed shapes/// and wraps the call in a `try`: the preview is cosmetic, and a malformed media/// entry must not sink the batch that carries the messages themselves. Rust has/// no cast, so the same JSON is deserialised — and a deserialisation that fails/// takes the same fallback the `catch` writes,/// `body.replace(/\s+/g, " ").trim().slice(0, 140)`.fn preview_of(message: &EnvelopeMessage) -> String {    let media: Option<Vec<MessageMedia>> = serde_json::from_value(media_value(message)).ok();    let meta: Option<MessageMeta> = serde_json::from_value(meta_value(message)).ok();    match (media, meta) {        (Some(media), Some(meta)) => preview_for_message(&PreviewSource {            body: Some(&message.body),            media: &media,            deleted_at: None,            meta: Some(&meta),        }),        _ => slice_utf16(            &collapse_whitespace_and_trim(&message.body),            MESSAGE_PREVIEW_MAX,        ),    }}/* ------------------------------------------------------------ the passes -- *//// What a caller hands the engine.pub struct ImportArgs<'a> {    pub batch: &'a ImportBatch,    /// The OPEN file's namespace, which every derived contact, handle and    /// thread id is made under. Never the batch's `workspace_id`: that is a    /// wire string naming the file, and a database made at the stop derives    /// under the old file's id rather than its own.    pub namespace: &'a str,    /// ISO stamp for every row this run creates — the batch's, never a fresh    /// clock per row.    pub now: &'a str,    /// Mints an id for a row that has no derived one.    pub new_id: &'a mut dyn FnMut() -> String,}/// Resolve the same threads an import would and report the same difference,/// writing NOTHING.////// Takes `&D` and returns no changes, so "a probe must never write" is a fact/// about the signature.pub fn probe_import<D: ImportDriver + ?Sized>(    db: &D,    batch: &ImportBatch,) -> Result<ProbeReport, ImportError> {    let workspace_id = batch.workspace_id.as_str();    let channel = batch.channel.as_str();    let reserved = batch.new_thread_id.as_deref();    let region = db.owner_region(workspace_id)?;    let all: Vec<&EnvelopeMessage> = batch.messages.iter().collect();    let mut chats: Vec<ProbeChat> = Vec::new();    let mut group: Option<ProbeGroup> = None;    let participants: ParticipantsSummary;    if let Some(thread) = &batch.thread {        let by_key = db.group_thread_by_key(workspace_id, &thread.external_key)?;        let mut thread_id = by_key.as_ref().map(|(id, _)| id.clone());        let mut matched_by = by_key.as_ref().map(|_| MatchedBy::Key);        if thread_id.is_none() {            thread_id = find_thread_by_overlap(db, workspace_id, channel, ThreadKind::Group, &all)?                .map(|hit| hit.id);            if thread_id.is_some() {                matched_by = Some(MatchedBy::Overlap);            }        }        if thread_id.is_none() {            if let Some(reserved) = reserved {                thread_id = db                    .thread_by_id(workspace_id, reserved, ThreadKind::Group)?                    .map(|hit| hit.id);            }        }        group = Some(ProbeGroup {            thread_id: thread_id.clone(),            matched_by,            stored_title: by_key.and_then(|(_, title)| title),        });        chats.push(probe_chat(            db,            &thread.external_key,            thread_id.as_deref(),            channel,            &all,        )?);        let seats = match thread_id.as_deref() {            Some(id) => db.participants_of(id)?,            None => Vec::new(),        };        participants = participants_summary(&thread.participants, &seats, &|_| false, region);    } else if let Some(dm) = &batch.dm {        let thread_id: Option<String>;        let mut identified_by_thread = false;        let probe_handle = participant_handles(dm, region).into_iter().next();        if let Some(handle) = &probe_handle {            thread_id = dm_thread_id_by_handle(db, workspace_id, handle)?;        } else {            let mut hit = find_thread_by_overlap(db, workspace_id, channel, ThreadKind::Dm, &all)?;            if hit.is_none() {                if let Some(reserved) = reserved {                    hit = db.thread_by_id(workspace_id, reserved, ThreadKind::Dm)?;                }            }            identified_by_thread = hit.as_ref().is_some_and(|found| found.contact_id.is_some());            thread_id = hit.map(|found| found.id);        }        let key = match &probe_handle {            Some(handle) => handle.value.clone(),            None => format!("label:{}", dm.label),        };        chats.push(probe_chat(db, &key, thread_id.as_deref(), channel, &all)?);        participants =            participants_summary(std::slice::from_ref(dm), &[], &|_| identified_by_thread, region);    } else {        let by_handle = group_by_handle(&batch.messages, region)?;        for chat in &by_handle {            let thread_id = dm_thread_id_by_handle(db, workspace_id, &chat.handle)?;            chats.push(probe_chat(                db,                &chat.handle.value,                thread_id.as_deref(),                channel,                &chat.messages,            )?);        }        participants = ParticipantsSummary {            total: by_handle.len() as i64,            identified: by_handle.len() as i64,            unidentified: 0,            unidentified_labels: Vec::new(),        };    }    let totals = ProbeTotals {        chats: chats.len() as i64,        would_insert: chats.iter().map(|chat| chat.would_insert).sum(),        would_skip: chats.iter().map(|chat| chat.would_skip).sum(),    };    Ok(ProbeReport {        chats,        group,        participants,        totals,    })}fn probe_chat<D: ImportDriver + ?Sized>(    db: &D,    key: &str,    thread_id: Option<&str>,    channel: &str,    messages: &[&EnvelopeMessage],) -> Result<ProbeChat, ImportError> {    let known = match thread_id {        Some(thread_id) => known_external_ids(db, thread_id, channel, messages)?,        None => BTreeSet::new(),    };    let fresh = fresh_messages(messages, &known);    Ok(ProbeChat {        key: key.to_string(),        thread_id: thread_id.map(str::to_string),        existing: match thread_id {            Some(thread_id) => Some(db.thread_stats(thread_id, channel)?),            None => None,        },        would_insert: fresh.len() as i64,        would_skip: messages.len() as i64 - fresh.len() as i64,        new_external_ids: fresh            .iter()            .map(|message| message.external_id.clone())            .collect(),    })}/// Everything one batch owes the file, in the order it must land — the thread,/// its contacts, its participant rows, its messages and its reactions, as ONE/// act.pub fn plan_import<D: ImportDriver + ?Sized>(    db: &D,    args: ImportArgs<'_>,) -> Result<ImportPlan, ImportError> {    let ImportArgs {        batch,        namespace,        now,        new_id,    } = args;    let workspace_id = batch.workspace_id.as_str();    let channel = batch.channel.as_str();    let reserved = batch.new_thread_id.as_deref();    let all: Vec<&EnvelopeMessage> = batch.messages.iter().collect();    let mut pending: Vec<Change> = Vec::new();    // ONE people fold per run, handed to every `ensure_contact` below: a batch    // resolves hundreds of counterparts, and re-reading the address book for    // each of them would walk `cotton_people` once a message.    let people = people_by_handle(db, workspace_id)?;    // A code-less number in the batch is read in the owner's own number's    // country, as the tools' handle writes read one; no owner number, no region.    let region = db.owner_region(workspace_id)?;    let mut results: Vec<ChatResult> = Vec::new();    let mut group: Option<GroupResult> = None;    if let Some(thread) = &batch.thread {        let (thread_id, seat_id_by_label, created) = plan_group_thread(            db,            &mut pending,            batch,            namespace,            thread,            &all,            now,            new_id,            &people,            reserved,            region,        )?;        let (inserted, skipped) = import_into_thread(            db,            &mut pending,            &IntoThread {                thread_id: &thread_id,                workspace_id,                channel,                messages: &all,                seat_id_by_label: &seat_id_by_label,                now,                region,            },            new_id,        )?;        group = Some(GroupResult {            thread_id: thread_id.clone(),            title: thread.title.clone(),            external_key: thread.external_key.clone(),            participant_count: seat_id_by_label.len() as i64,            thread_created: created,        });        results.push(ChatResult {            phone: Some(thread.external_key.clone()),            contact_id: None,            thread_id,            inserted,            skipped,            unresolved_replies: 0,        });    } else if let Some(dm) = &batch.dm {        let mut contact_id: Option<String> = None;        let thread_id: String;        // An EMAIL is an identity, not an unknown (schema v36). Before handles a        // counterpart without a number fell through to the titled, contactless        // thread below, which meant every iMessage conversation with an Apple ID        // landed as somebody nobody could name — so the test is "did they name a        // handle at all", and the label-only path is left for the case it was        // actually written for.        let dm_handles = participant_handles(dm, region);        if let Some(first) = dm_handles.first() {            let resolved = ensure_contact(                db,                &mut pending,                workspace_id,                namespace,                first,                if label_looks_like_phone(&dm.label) {                    None                } else {                    Some(dm.label.as_str())                },                dm.person_id.as_deref(),                now,                new_id,                &people,            )?;            record_extra_handles(db, &mut pending, workspace_id, namespace, &resolved, &dm_handles, now)?;            thread_id = ensure_dm_thread(                db,                &mut pending,                workspace_id,                namespace,                &resolved,                now,                reserved,            )?;            contact_id = Some(resolved);        } else {            let mut hit = find_thread_by_overlap(db, workspace_id, channel, ThreadKind::Dm, &all)?;            if hit.is_none() {                if let Some(reserved) = reserved {                    hit = db.thread_by_id(workspace_id, reserved, ThreadKind::Dm)?;                }            }            match hit {                Some(found) => {                    thread_id = found.id;                    contact_id = found.contact_id;                }                None => {                    thread_id = create_unidentified_dm_thread(                        &mut pending,                        workspace_id,                        &dm.label,                        now,                        new_id,                        reserved,                    );                }            }        }        let (inserted, skipped) = import_into_thread(            db,            &mut pending,            &IntoThread {                thread_id: &thread_id,                workspace_id,                channel,                messages: &all,                seat_id_by_label: &ParticipantSeats::default(),                now,                region,            },            new_id,        )?;        results.push(ChatResult {            phone: dm.phone.clone(),            contact_id,            thread_id,            inserted,            skipped,            unresolved_replies: 0,        });    } else {        for chat in group_by_handle(&batch.messages, region)? {            let contact_id = ensure_contact(                db,                &mut pending,                workspace_id,                namespace,                &chat.handle,                chat.display_name,                None,                now,                new_id,                &people,            )?;            record_extra_handles(                db,                &mut pending,                workspace_id,                namespace,                &contact_id,                &chat.handles,                now,            )?;            let thread_id = ensure_dm_thread(                db,                &mut pending,                workspace_id,                namespace,                &contact_id,                now,                // The multi-chat path derives its own: one reserved id cannot                // serve N threads.                None,            )?;            let (inserted, skipped) = import_into_thread(                db,                &mut pending,                &IntoThread {                    thread_id: &thread_id,                    workspace_id,                    channel,                    messages: &chat.messages,                    seat_id_by_label: &ParticipantSeats::default(),                    now,                    region,                },                new_id,            )?;            results.push(ChatResult {                // The RESULT's `phone` is the counterpart's number where there                // is one; an email-keyed chat reports null rather than an                // address in a field every caller reads as a number.                phone: match chat.handle.kind {                    ContactHandleKind::Phone => Some(chat.handle.value.clone()),                    _ => None,                },                contact_id: Some(contact_id),                thread_id,                inserted,                skipped,                unresolved_replies: 0,            });        }    }    Ok(ImportPlan {        changes: pending,        chats: results,        group,    })}/// One WhatsApp group, one thread, whichever door it came through first.////// The linked device and the iPhone backup key a group by its JID/// (`wa:group:<jid>@g.us`); a `_chat.txt` export has no JID and keys it by its/// title's slug. So when a JID-keyed batch finds nothing under its key it takes/// over the export's thread (and re-keys it to the JID, the identity that/// survives a rename); when an export finds nothing under its slug it joins the/// one JID-keyed group whose title slugs the same — never one of several.fn agree_group_key<D: ImportDriver + ?Sized>(    db: &D,    pending: &mut Vec<Change>,    workspace_id: &str,    thread: &EnvelopeThread,    now: &str,) -> Result<Option<(String, Option<String>)>, ImportError> {    let Some(identity) = thread.external_key.strip_prefix(GROUP_EXTERNAL_KEY_PREFIX) else {        return Ok(None);    };    if identity.ends_with("@g.us") {        if js_trim(&thread.title).is_empty() {            return Ok(None);        }        let Some(found) = db.group_thread_by_key(workspace_id, &group_external_key(&thread.title))?        else {            return Ok(None);        };        let mut patch = Map::new();        patch.insert(            "external_key".to_string(),            Value::from(thread.external_key.as_str()),        );        patch.insert("updated_at".to_string(), Value::from(now));        pending.push(upsert(THREADS, &found.0, patch));        return Ok(Some(found));    }    let mut matches = db        .jid_group_threads(workspace_id)?        .into_iter()        .filter(|(_, title)| title.as_deref().is_some_and(|title| slugify_title(title) == identity));    match (matches.next(), matches.next()) {        (Some(only), None) => Ok(Some(only)),        _ => Ok(None),    }}/// The group leg: find the thread by key, then by overlap, then by the id the/// caller reserved — and only create one when none of the three answered.#[allow(clippy::too_many_arguments)]fn plan_group_thread<D: ImportDriver + ?Sized>(    db: &D,    pending: &mut Vec<Change>,    batch: &ImportBatch,    namespace: &str,    thread: &EnvelopeThread,    messages: &[&EnvelopeMessage],    now: &str,    new_id: &mut dyn FnMut() -> String,    people: &BTreeMap<String, MatchedPerson>,    reserved: Option<&str>,    region: Option<Region>,) -> Result<(String, ParticipantSeats, bool), ImportError> {    let workspace_id = batch.workspace_id.as_str();    let mut by_key = db.group_thread_by_key(workspace_id, &thread.external_key)?;    if by_key.is_none() && batch.channel == "whatsapp" {        by_key = agree_group_key(db, pending, workspace_id, thread, now)?;    }    let mut thread_id: Option<String> = by_key.as_ref().map(|(id, _)| id.clone());    let mut thread_created = false;    if let Some(found) = thread_id.clone() {        // A blank title heals; a present one is the owner's (or a previous        // import's) and a re-import must not clobber an owner's rename.        let stored = by_key.as_ref().and_then(|(_, title)| title.as_deref());        if stored.is_none_or(|title| js_trim(title).is_empty()) && !thread.title.is_empty() {            let mut patch = Map::new();            patch.insert("title".to_string(), Value::from(thread.title.as_str()));            patch.insert("updated_at".to_string(), Value::from(now));            pending.push(upsert(THREADS, &found, patch));        }    } else if let Some(overlap) = find_thread_by_overlap(        db,        workspace_id,        &batch.channel,        ThreadKind::Group,        messages,    )? {        // Inherit the key so the next import resolves on the fast leg. Only fill        // a NULL key — two groups must never trade identities.        let current = db.thread_external_key(&overlap.id)?.flatten();        if current.is_none_or(|key| key.is_empty()) {            let mut patch = Map::new();            patch.insert(                "external_key".to_string(),                Value::from(thread.external_key.as_str()),            );            patch.insert("updated_at".to_string(), Value::from(now));            pending.push(upsert(THREADS, &overlap.id, patch));        }        thread_id = Some(overlap.id);    } else {        let handed = match reserved {            Some(reserved) => db.thread_by_id(workspace_id, reserved, ThreadKind::Group)?,            None => None,        };        match handed {            // The caller resolved this chat already; this part just overlaps            // nothing the file holds yet.            Some(found) => thread_id = Some(found.id),            None => {                // DERIVED from (workspace, external key) —                // `uq_cotton_msg_threads_group_key`, under its own prefix so a                // group key and a contact id can never hash to one id.                let id = reserved                    .map(str::to_string)                    .unwrap_or_else(|| group_thread_id(namespace, &thread.external_key));                thread_created = true;                let mut patch = Map::new();                patch.insert("id".to_string(), Value::from(id.as_str()));                patch.insert("workspace_id".to_string(), Value::from(workspace_id));                patch.insert("contact_id".to_string(), Value::Null);                patch.insert("kind".to_string(), Value::from("group"));                patch.insert("title".to_string(), Value::from(thread.title.as_str()));                patch.insert(                    "external_key".to_string(),                    Value::from(thread.external_key.as_str()),                );                patch.insert("archived".to_string(), Value::Bool(false));                patch.insert("created_at".to_string(), Value::from(now));                patch.insert("updated_at".to_string(), Value::from(now));                pending.push(upsert(THREADS, &id, patch));                thread_id = Some(id);            }        }    }    let thread_id = thread_id.expect("every branch above settles a thread id");    // Participant rows — one per label, insert-or-link, nobody removed. A member    // who LEFT the group still said what they said, and removing their row would    // orphan their attribution.    let mut seats = if thread_created {        Vec::new()    } else {        db.participants_of(&thread_id)?    };    let mut seat_id_by_label = ParticipantSeats::in_region(region);    for participant in &thread.participants {        // A group member with NO handle at all is still a participant row — an        // export that printed a name and nothing else has told us who spoke, and        // dropping the row would orphan their attribution. An email is an        // IDENTITY, so a member who has one gets a contact like anyone else.        let handles = participant_handles(participant, region);        let contact_id = match handles.first() {            Some(first) => {                let resolved = ensure_contact(                    db,                    pending,                    workspace_id,                    namespace,                    first,                    if label_looks_like_phone(&participant.label) {                        None                    } else {                        Some(participant.label.as_str())                    },                    participant.person_id.as_deref(),                    now,                    new_id,                    people,                )?;                record_extra_handles(db, pending, workspace_id, namespace, &resolved, &handles, now)?;                Some(resolved)            }            None => None,        };        let seat = ensure_participant(            pending,            workspace_id,            &thread_id,            &mut seats,            participant,            contact_id.as_deref(),            now,            new_id,        );        seat_id_by_label.insert(&participant.label,&handles,&seat);    }    Ok((thread_id, seat_id_by_label, thread_created))}/// Link every reply in this thread whose quoted message is now present.////// A second pass rather than resolution at insert time, because an archive/// arrives in batches and a reply routinely lands before the line it quotes. It/// is idempotent, so it runs after every import and picks up whatever the/// previous run could not link.pub fn plan_reply_links<D: ImportDriver + ?Sized>(    db: &D,    thread_id: &str,    channel: &str,) -> Result<ReplyLinks, ImportError> {    let rows = db.unlinked_replies(thread_id)?;    if rows.is_empty() {        return Ok(ReplyLinks {            changes: Vec::new(),            unresolved: 0,        });    }    let mut seen: BTreeSet<&str> = BTreeSet::new();    let mut wanted: Vec<&str> = Vec::new();    for (_, external) in &rows {        if seen.insert(external.as_str()) {            wanted.push(external.as_str());        }    }    let targets = db.messages_by_external_ids(thread_id, channel, &wanted)?;    let id_by_external: BTreeMap<&str, &str> = targets        .iter()        .map(|(id, external)| (external.as_str(), id.as_str()))        .collect();    let mut changes = Vec::new();    let mut unresolved = 0i64;    for (id, external) in &rows {        let target = id_by_external.get(external.as_str()).copied();        // A message quoting itself is a corrupt export, not a fact worth        // storing.        let Some(target) = target.filter(|target| *target != id.as_str()) else {            unresolved += 1;            continue;        };        let mut patch = Map::new();        patch.insert("reply_to_id".to_string(), Value::from(target));        changes.push(upsert(MESSAGES, id, patch));    }    Ok(ReplyLinks {        changes,        unresolved,    })}/// How a caller applies what the engine planned. Called at most twice per run —/// once for the batch, once for the reply links.pub type ApplyChanges<'a> = &'a mut dyn FnMut(&[Change]) -> Result<(), String>;/// Run one batch: plan, write, link the replies, write again.////// The two writes are the TypeScript's two, in its order and for its reasons —/// the first so a conversation never lands half-built, the second because the/// reply pass has to be able to SEE the rows it links.pub fn run_import<D: ImportDriver + ?Sized>(    db: &D,    args: ImportArgs<'_>,    apply: ApplyChanges<'_>,) -> Result<ImportReport, ImportError> {    let channel = args.batch.channel.clone();    let plan = plan_import(db, args)?;    if !plan.changes.is_empty() {        apply(&plan.changes).map_err(ImportError::Driver)?;    }    // The reply pass runs AFTER the rows exist, so it can see them.    let mut link_changes: Vec<Change> = Vec::new();    let mut unresolved = 0i64;    for chat in &plan.chats {        let links = plan_reply_links(db, &chat.thread_id, &channel)?;        unresolved += links.unresolved;        link_changes.extend(links.changes);    }    if !link_changes.is_empty() {        apply(&link_changes).map_err(ImportError::Driver)?;    }    let totals = ImportTotals {        chats: plan.chats.len() as i64,        inserted: plan.chats.iter().map(|chat| chat.inserted).sum(),        skipped: plan.chats.iter().map(|chat| chat.skipped).sum(),        unresolved_replies: unresolved,    };    Ok(ImportReport {        chats: plan.chats,        group: plan.group,        totals,    })}/* -------------------------------------------------- the owner's own name -- *//// **EVERY name the owner has been seen under on a channel, most recent/// first** — not the latest one.////// The owner is ONE person with several spellings: the phone's own contact/// name in one export, a number in another, a nickname a group gave them in a/// third. Keeping only the latest meant every export with a different set of/// senders asked "which one is you?" again, and re-importing the FIRST file/// asked a third time — the walk of 15 Sep 2026, finding d. A list answers all/// three, and it only ever grows by an answer the person actually gave.////// A channel whose stored value is a bare string reads as a one-name list: the/// column is JSON either way and this is a parse, not a fallback.fn read_self_names<D: ImportDriver + ?Sized>(    db: &D,    workspace_id: &str,) -> Result<BTreeMap<String, Vec<String>>, ImportError> {    let Some(stored) = db.self_names_json(workspace_id)? else {        return Err(ImportError::WorkspaceNotFound);    };    // A column that will not parse is not a reason to fail an import — the    // TypeScript's `catch` answers `{}`, and so does this.    let parsed: Value = stored        .filter(|json| !json.is_empty())        .and_then(|json| serde_json::from_str(&json).ok())        .unwrap_or(Value::Object(Map::new()));    let mut names: BTreeMap<String, Vec<String>> = BTreeMap::new();    if let Some(object) = parsed.as_object() {        for (channel, value) in object {            let held = match value {                Value::String(one) => vec![one.clone()],                Value::Array(many) => many                    .iter()                    .filter_map(Value::as_str)                    .map(str::to_string)                    .collect(),                _ => Vec::new(),            };            let mut kept: Vec<String> = Vec::new();            for name in held {                if js_trim(&name).is_empty() {                    continue;                }                // A name is remembered ONCE however many exports carried it.                if kept.iter().any(|seen| same_self_name(seen, &name)) {                    continue;                }                kept.push(name);            }            if !kept.is_empty() {                names.insert(channel.clone(), kept);            }        }    }    Ok(names)}/// Layout and case are not identity, here as everywhere else a sender label is/// compared (`identity::name_key`, which this module may not reach upwards to).fn same_self_name(a: &str, b: &str) -> bool {    js_trim(a).to_lowercase() == js_trim(b).to_lowercase()}/// Every name the owner has been seen under in an export of this channel, most/// recent first — the memory that lets an import skip "which one is you".pub fn self_names<D: ImportDriver + ?Sized>(    db: &D,    workspace_id: &str,    channel: &str,) -> Result<Vec<String>, ImportError> {    Ok(read_self_names(db, workspace_id)?        .get(channel)        .cloned()        .unwrap_or_default())}/// Remember the owner's export name for a channel. A blank name is refused, not/// stored; a name already remembered moves to the front only if it was not/// already there, so an unchanged answer writes nothing.pub fn set_self_name_change<D: ImportDriver + ?Sized>(    db: &D,    workspace_id: &str,    channel: &str,    name: &str,) -> Result<Option<Change>, ImportError> {    let trimmed = js_trim(name);    if trimmed.is_empty() {        return Err(ImportError::BlankSelfName);    }    let mut current = read_self_names(db, workspace_id)?;    let held = current.entry(channel.to_string()).or_default();    // Already the most recent answer: nothing to write, which keeps a re-import    // of the same export out of the outbox.    if held.first().map(String::as_str) == Some(trimmed) {        return Ok(None);    }    held.retain(|seen| !same_self_name(seen, trimmed));    held.insert(0, trimmed.to_string());    let mut names = Map::new();    for (channel, held) in current {        names.insert(channel, Value::Array(held.into_iter().map(Value::from).collect()));    }    let mut patch = Map::new();    patch.insert("msg_import_self_names".to_string(), Value::Object(names));    Ok(Some(upsert(WORKSPACES, workspace_id, patch)))}#[path = "message_changes.rs"]mod message_changes;pub use message_changes::*;