Cotton code
833 lines · 33.5 KB · RustRaw
//! `ingest_emails` — batches land idempotently, the THREAD carries the//! conversation, and identity is the Message-ID first with a CONTENT//! fingerprint as the fallback. Never sender identity: naming someone later//! must change nothing a re-import skips.use std::collections::{HashMap, HashSet};use cotton_core::rules::email_state::email_state_from_labels;use cotton_core::media::keys::is_key_in_row_file;use cotton_store::protocol::derived_id::email_participant_id;use cotton_store::protocol::fingerprint::email::{    email_content_fingerprint, message_id_external_id, strip_reply_prefixes,    EmailContentFingerprintInput, EmailOccurrenceCounter,};use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use super::engine_shim::strip_quoted_reply;use super::photos::{record_email_photos, EmailPhotosOutcome};use super::shared::{    blocked_set, derive_snippet, refold_threads, role_rank, trashed_after_restate, ThreadIds, EMAIL_BODY_MAX,    PARTICIPANT_COLUMNS, STATE_COLUMNS, TRUNCATION_MARK,};use super::validate::{    validate_ingest_emails, EmailAddressArg, IngestEmailArg, IngestEmailGmailArg,};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{    in_chunks, insert_row, now_iso, quoted, rows as read_rows, text, update_row, utf16_clip,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Query};fn lowered(address: &EmailAddressArg) -> String {    address.email.to_lowercase()}/// Identity plus the body as it will be STORED.struct PreparedEmail {    arg: IngestEmailArg,    external_id: String,    body: String,    truncated: bool,}/// Identity per email, computed ONCE for the whole batch: Message-ID when the/// source has one, the content fingerprint otherwise — with the occurrence/// counter scoped per threadKey, the scope one pass walks.fn prepare(emails: Vec<IngestEmailArg>) -> Result<Vec<PreparedEmail>, ToolFailure> {    let mut counters: HashMap<String, EmailOccurrenceCounter> = HashMap::new();    let mut out = Vec::with_capacity(emails.len());    for arg in emails {        // Strip the quoted-reply tail BEFORE anything reads the body: a reply's        // pasted thread is pure duplication (every email is its own row), and        // both the content fingerprint and the truncation ceiling must see the        // one new message, not the whole conversation.        let body = strip_quoted_reply(&arg.body);        let external_id = match message_id_external_id(arg.message_id.as_deref()) {            Some(id) => id,            None => {                let counter = counters.entry(arg.thread_key.clone()).or_default();                let occurrence = counter                    .next(&arg.sent_at, Some(&arg.subject), &body)                    .map_err(|error| ToolFailure::new(error.to_string()))?;                email_content_fingerprint(&EmailContentFingerprintInput {                    sent_at: &arg.sent_at,                    subject: Some(&arg.subject),                    body: &body,                    occurrence,                })                .map_err(|error| ToolFailure::new(error.to_string()))?            }        };        // `String.prototype.length` is UTF-16 units, and the ceiling was        // written against it — a body of emoji must not be cut at half the        // characters here and none there.        let truncated = body.encode_utf16().count() > EMAIL_BODY_MAX;        let body = if truncated {            format!("{}{TRUNCATION_MARK}", utf16_clip(&body, EMAIL_BODY_MAX))        } else {            body        };        out.push(PreparedEmail {            arg,            external_id,            body,            truncated,        });    }    Ok(out)}/// One recipient, as the row's `recipients` json holds it.fn recipient_entry(address: &EmailAddressArg, kind: &str) -> Value {    let mut entry = Map::new();    entry.insert("email".to_string(), Value::from(lowered(address)));    if let Some(name) = address.name.as_ref().filter(|name| !name.is_empty()) {        entry.insert("name".to_string(), Value::from(name.clone()));    }    entry.insert("kind".to_string(), Value::from(kind));    Value::Object(entry)}fn attachment_value(attachment: &super::validate::IngestEmailAttachmentArg) -> Value {    let mut out = Map::new();    out.insert("name".to_string(), Value::from(attachment.name.clone()));    if let Some(mime) = &attachment.mime {        out.insert("mime".to_string(), Value::from(mime.clone()));    }    if let Some(size) = attachment.size {        out.insert("size".to_string(), Value::from(size));    }    if let Some(key) = &attachment.key {        out.insert("key".to_string(), Value::from(key.clone()));    }    Value::Object(out)}/// Whether a stored mail date is one a message can carry: a year from 1900/// to 2100, as the readers bound every date they read/// (`cotton_server::mailbox::mail_date`).fn believable(at: &str) -> bool {    at.get(..4)        .filter(|_| at.as_bytes().get(4) == Some(&b'-'))        .and_then(|year| year.parse::<i32>().ok())        .is_some_and(|year| (1900..=2100).contains(&year))}pub fn ingest_emails(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let emails = validate_ingest_emails(args)?;    ingest_prepared_emails(ctx, emails)}/// The INTERNAL entry point: emails already built as typed args, `gmail`/// block and all.////// The MCP tool is this plus validation, which is the same split the TypeScript/// has between `validateIngestEmails` and `ingestEmails` — and the reason/// `validate_ingest_emails` can go on refusing a `gmail` block from an assistant/// (`ingest_emails_carries_no_gmail_block_from_the_mcp_surface` guards that)/// while the Gmail import still carries one. Collapsing the two, as this file/// first did, left the import with no way to hand its own block through: the/// state leg of the sync — `gmail_id`, `gmail_account`, `labels`, `unread`,/// `starred`, `in_inbox` — was silently never written.pub fn ingest_prepared_emails(    ctx: &mut Ctx<'_>,    emails: Vec<super::validate::IngestEmailArg>,) -> ToolResult {    // Attachment keys are validated BEFORE anything writes: a key outside this    // workspace's media prefix is refused whole, the wall every media surface    // stands behind.    for email in &emails {        for attachment in &email.attachments {            if let Some(key) = &attachment.key {                // Against the file the rows are written into — the                // `workspace_id` the writer stamps on every row — not the                // reader's open file, which is the same thing today and                // stays so when it is not.                if !is_key_in_row_file(Some(key), ctx.workspace_id) {                    return Err(ToolFailure::new(format!(                        "attachment key {} is not in this workspace's media store — mint an \                         upload for this workspace and use the key it returns; nothing was \                         ingested",                        quoted(key)                    )));                }            }        }    }    let prepared = prepare(emails)?;    // A message its SOURCE erased is not brought back: the mailbox's own    // deletion was mirrored here as a source-erase, and a later pass that    // meets the message again (a re-read, a second label event) skips it.    let offered = prepared.len();    let mut kept = Vec::with_capacity(offered);    for email in prepared {        if !source_erased(ctx, "cotton_emails", &email.external_id)? {            kept.push(email);        }    }    let prepared = kept;    let source_erased_count = (offered - prepared.len()) as i64;    // What the archive already holds, one chunked read over the batch's ids.    // The ROW is read, not just the id: a message Cotton already has may have    // MOVED in the mailbox since, and a re-ingest is how the backfill learns    // that. State is not append-only; the body is.    let mut unique_ids: Vec<String> = Vec::new();    let mut seen_ids: HashSet<&str> = HashSet::new();    for email in &prepared {        if seen_ids.insert(email.external_id.as_str()) {            unique_ids.push(email.external_id.clone());        }    }    let mut state_columns: Vec<&str> = STATE_COLUMNS.to_vec();    state_columns.push("external_id");    state_columns.push("from_email");    state_columns.push("labels");    state_columns.push("sent_at");    let existing = in_chunks(&unique_ids, |batch| {        read_rows(            ctx,            &Query::on("cotton_emails")                .columns(&state_columns)                .filter(Filter::In(                    "external_id".to_string(),                    batch.iter().map(|id| SqlValue::Text(id.clone())).collect(),                )),        )    })?;    let existing_rows: HashMap<String, Map<String, Value>> = existing        .into_iter()        .filter_map(|row| text(&row, "external_id").map(|key| (key, row)))        .collect();    // Who the owner is done with. Mail from a blocked address files into Junk    // (its thread's sender_kind), never into the bin, and nothing goes to    // Gmail (architect, 11 Oct 2026). Gmail restating TRASH on one of theirs    // does not bin it here either: Junk is where it lives.    let blocked = blocked_set(ctx)?;    // Group by conversation, in call order.    let mut thread_order: Vec<String> = Vec::new();    let mut by_thread_key: HashMap<String, Vec<PreparedEmail>> = HashMap::new();    for email in prepared {        let key = email.arg.thread_key.clone();        by_thread_key            .entry(key.clone())            .or_insert_with(|| {                thread_order.push(key.clone());                Vec::new()            })            .push(email);    }    let existing_threads = in_chunks(&thread_order, |batch| {        read_rows(            ctx,            &Query::on("cotton_email_threads")                .columns(&[                    "id",                    "external_key",                    "subject",                    "first_at",                    "last_at",                    "email_count",                ])                .filter(Filter::In(                    "external_key".to_string(),                    batch                        .iter()                        .map(|key| SqlValue::Text(key.clone()))                        .collect(),                )),        )    })?;    let mut thread_by_key: HashMap<String, ThreadState> = existing_threads        .iter()        .filter_map(|row| {            text(row, "external_key").map(|key| {                (                    key,                    ThreadState {                        id: text(row, "id").unwrap_or_default(),                        subject: text(row, "subject"),                        first_at: text(row, "first_at"),                        last_at: text(row, "last_at"),                        email_count: row.get("email_count").and_then(Value::as_i64).unwrap_or(0),                    },                )            })        })        .collect();    let now = now_iso(ctx);    let mut threads_out: Vec<Value> = Vec::new();    let mut truncated_ids: Vec<String> = Vec::new();    // Known messages whose labels arrived again — their state is re-read from    // Gmail's answer after the loop, in one pass.    let mut restated: Vec<(Map<String, Value>, IngestEmailGmailArg)> = Vec::new();    // A message stored with a date no mail can carry (a header read at its    // word before the readers bounded it), which the re-read dates believably.    let mut redated: Vec<(String, String, String)> = Vec::new();    // Conversations that gained a message which landed straight in the bin —    // one Gmail already had in its own bin.    let mut born_binned = ThreadIds::new();    let mut added = 0_i64;    let mut skipped = source_erased_count;    // The pictures attached to the emails this call landed (schema v41).    let mut photos = EmailPhotosOutcome::default();    for thread_key in &thread_order {        let mut group = by_thread_key.remove(thread_key).unwrap_or_default();        // Oldest first, so "the earliest email names the thread" is one pass.        group.sort_by(|a, b| a.arg.sent_at.cmp(&b.arg.sent_at));        let mut thread = match thread_by_key.remove(thread_key) {            Some(thread) => thread,            None => {                let subject = strip_reply_prefixes(&group[0].arg.subject);                let born = ThreadState {                    id: live_id(ctx, "cotton_email_threads", thread_key)?,                    subject: (!subject.is_empty()).then_some(subject),                    first_at: None,                    last_at: None,                    email_count: 0,                };                let mut patch = Map::new();                patch.insert("external_key".to_string(), Value::from(thread_key.as_str()));                patch.insert(                    "subject".to_string(),                    born.subject.clone().map_or(Value::Null, Value::from),                );                patch.insert("email_count".to_string(), Value::from(0));                insert_row(ctx, "cotton_email_threads", &born.id, patch)?;                born            }        };        // The batch's own dedupe: two copies of one email in one call land once.        let mut seen_in_call: HashSet<String> = HashSet::new();        let mut thread_added = 0_i64;        let mut thread_skipped = 0_i64;        let mut earliest = thread.first_at.clone();        let mut latest = thread.last_at.clone();        for email in &group {            if existing_rows.contains_key(&email.external_id)                || seen_in_call.contains(&email.external_id)            {                thread_skipped += 1;                if let Some(known) = existing_rows.get(&email.external_id) {                    let stored = text(known, "sent_at");                    if stored.as_deref().is_some_and(|at| !believable(at))                        && believable(&email.arg.sent_at)                        && stored.as_deref() != Some(email.arg.sent_at.as_str())                    {                        if let (Some(id), Some(thread_id)) = (text(known, "id"), text(known, "thread_id")) {                            redated.push((id, thread_id, email.arg.sent_at.clone()));                        }                    }                }                if let (Some(known), Some(gmail)) = (                    existing_rows.get(&email.external_id),                    email.arg.gmail.as_ref(),                ) {                    restated.push((known.clone(), gmail.clone()));                }                continue;            }            seen_in_call.insert(email.external_id.clone());            let recipients: Vec<Value> = email                .arg                .to                .iter()                .map(|address| recipient_entry(address, "to"))                .chain(                    email                        .arg                        .cc                        .iter()                        .map(|address| recipient_entry(address, "cc")),                )                .chain(                    email                        .arg                        .bcc                        .iter()                        .map(|address| recipient_entry(address, "bcc")),                )                .collect();            let id = live_id(ctx, "cotton_emails", &email.external_id)?;            // The mailbox's state, derived from the labels the importer            // carried. A caller with no `gmail` block (an assistant filing mail            // from anywhere else) gets the columns' own defaults: read, in the            // inbox, nothing to push — the honest answer for mail no mailbox            // filed.            let state = email                .arg                .gmail                .as_ref()                .map(|gmail| email_state_from_labels(&gmail.labels));            let is_blocked = blocked.contains(&lowered(&email.arg.from));            let trashed_at =                (!is_blocked && state.is_some_and(|state| state.trashed)).then(|| now.clone());            let mut patch = Map::new();            patch.insert("thread_id".to_string(), Value::from(thread.id.clone()));            if let Some(account) = &email.arg.account {                patch.insert("account".to_string(), Value::from(account.clone()));            }            patch.insert(                "external_id".to_string(),                Value::from(email.external_id.clone()),            );            patch.insert(                "subject".to_string(),                if email.arg.subject.is_empty() {                    Value::Null                } else {                    Value::from(email.arg.subject.clone())                },            );            patch.insert(                "from_email".to_string(),                Value::from(lowered(&email.arg.from)),            );            patch.insert(                "from_name".to_string(),                email.arg.from.name.clone().map_or(Value::Null, Value::from),            );            if let (Some(gmail), Some(state)) = (email.arg.gmail.as_ref(), state) {                patch.insert("gmail_id".to_string(), Value::from(gmail.id.clone()));                patch.insert(                    "gmail_account".to_string(),                    Value::from(gmail.account.clone()),                );                patch.insert(                    "labels".to_string(),                    Value::from(                        gmail                            .labels                            .iter()                            .map(|label| Value::from(label.clone()))                            .collect::<Vec<Value>>(),                    ),                );                patch.insert("unread".to_string(), Value::from(state.unread));                patch.insert("starred".to_string(), Value::from(state.starred));                patch.insert("in_inbox".to_string(), Value::from(state.in_inbox));                patch.insert(                    "trashed_at".to_string(),                    trashed_at.clone().map_or(Value::Null, Value::from),                );                patch.insert("sync_state".to_string(), Value::from("synced"));            } else {                patch.insert(                    "trashed_at".to_string(),                    trashed_at.clone().map_or(Value::Null, Value::from),                );                if let Some(flags) = email.arg.flags {                    patch.insert("unread".to_string(), Value::from(flags.unread));                    patch.insert("starred".to_string(), Value::from(flags.starred));                }            }            // Arrays, never pre-stringified: the op writer encodes json columns            // itself, and a double-encoded '"[]"' fails the file's json_type            // CHECK (the relay lesson, 2026-08-26).            patch.insert("recipients".to_string(), Value::Array(recipients));            patch.insert(                "sent_at".to_string(),                Value::from(email.arg.sent_at.clone()),            );            patch.insert(                "body".to_string(),                if email.body.is_empty() {                    Value::Null                } else {                    Value::from(email.body.clone())                },            );            patch.insert(                "snippet".to_string(),                email                    .arg                    .snippet                    .clone()                    .or_else(|| derive_snippet(&email.body))                    .map_or(Value::Null, Value::from),            );            patch.insert(                "attachments".to_string(),                Value::Array(email.arg.attachments.iter().map(attachment_value).collect()),            );            insert_row(ctx, "cotton_emails", &id, patch)?;            // An image attached to this email is a photo the person now has.            // Never throws — one attachment's trouble is counted, and the email            // is already a fact.            photos.add(record_email_photos(ctx, &email.arg.attachments));            if email.truncated {                truncated_ids.push(id);            }            if trashed_at.is_some() {                born_binned.insert(thread.id.clone());            }            thread_added += 1;            if earliest                .as_deref()                .is_none_or(|current| email.arg.sent_at.as_str() < current)            {                earliest = Some(email.arg.sent_at.clone());            }            if latest                .as_deref()                .is_none_or(|current| email.arg.sent_at.as_str() > current)            {                latest = Some(email.arg.sent_at.clone());            }        }        if thread_added > 0 {            let inserted: Vec<&PreparedEmail> = group                .iter()                .filter(|email| seen_in_call.contains(&email.external_id))                .collect();            upsert_participants(ctx, &thread.id, &inserted, &now)?;            let mut patch = Map::new();            patch.insert(                "first_at".to_string(),                earliest.clone().map_or(Value::Null, Value::from),            );            patch.insert(                "last_at".to_string(),                latest.clone().map_or(Value::Null, Value::from),            );            patch.insert(                "email_count".to_string(),                Value::from(thread.email_count + thread_added),            );            patch.insert("updated_at".to_string(), Value::from(now.clone()));            // The earliest email names the thread — set once, never rewritten.            if thread.subject.is_none() {                let subject = strip_reply_prefixes(&group[0].arg.subject);                if !subject.is_empty() {                    patch.insert("subject".to_string(), Value::from(subject));                }            }            update_row(ctx, "cotton_email_threads", &thread.id, patch)?;            thread.email_count += thread_added;            thread.first_at = earliest;            thread.last_at = latest;        }        added += thread_added;        skipped += thread_skipped;        let mut out = Map::new();        out.insert("threadId".to_string(), Value::from(thread.id.clone()));        out.insert(            "subject".to_string(),            thread.subject.clone().map_or(Value::Null, Value::from),        );        out.insert("added".to_string(), Value::from(thread_added));        out.insert("skipped".to_string(), Value::from(thread_skipped));        threads_out.push(Value::Object(out));    }    if !born_binned.is_empty() {        // The refold reads the messages this call just inserted.        ctx.commit()?;        refold_threads(ctx, &born_binned, &now)?;    }    // A message Cotton already had, whose labels Gmail restated: bring the    // columns up to date and mark it `synced`, because this IS what the mailbox    // says. Not `pending` — nothing local changed, so there is nothing to push.    let mut restated_count = 0_i64;    let mut restated_threads = ThreadIds::new();    for (row, gmail) in &restated {        let state = email_state_from_labels(&gmail.labels);        let mut patch = Map::new();        patch.insert("gmail_id".to_string(), Value::from(gmail.id.clone()));        patch.insert(            "gmail_account".to_string(),            Value::from(gmail.account.clone()),        );        patch.insert("account".to_string(), Value::from(gmail.account.clone()));        patch.insert(            "labels".to_string(),            Value::from(                gmail                    .labels                    .iter()                    .map(|label| Value::from(label.clone()))                    .collect::<Vec<Value>>(),            ),        );        patch.insert("unread".to_string(), Value::from(state.unread));        patch.insert("starred".to_string(), Value::from(state.starred));        patch.insert("in_inbox".to_string(), Value::from(state.in_inbox));        let junk = text(row, "from_email").is_some_and(|from| blocked.contains(&from.to_lowercase()));        patch.insert("trashed_at".to_string(), trashed_after_restate(row, state.trashed, junk, &now));        patch.insert("sync_state".to_string(), Value::from("synced"));        let Some(id) = text(row, "id") else { continue };        update_row(ctx, "cotton_emails", &id, patch)?;        if let Some(thread_id) = text(row, "thread_id") {            restated_threads.insert(thread_id);        }        restated_count += 1;    }    if restated_count > 0 {        ctx.commit()?;        refold_threads(ctx, &restated_threads, &now)?;    }    // The re-read's date stands for one no mail can carry, and each thread    // it was in spans its messages' dates again.    let mut redated_threads = ThreadIds::new();    for (id, thread_id, sent_at) in &redated {        let mut patch = Map::new();        patch.insert("sent_at".to_string(), Value::from(sent_at.clone()));        update_row(ctx, "cotton_emails", id, patch)?;        redated_threads.insert(thread_id.clone());    }    if !redated.is_empty() {        // The span reads the dates just written.        ctx.commit()?;    }    for thread_id in redated_threads.iter() {        let dates: Vec<String> = read_rows(ctx, &Query::on("cotton_emails").columns(&["sent_at"]).eq("thread_id", thread_id.to_string()))?            .iter()            .filter_map(|row| text(row, "sent_at"))            .collect();        let mut patch = Map::new();        patch.insert("first_at".to_string(), dates.iter().min().map_or(Value::Null, |at| Value::from(at.clone())));        patch.insert("last_at".to_string(), dates.iter().max().map_or(Value::Null, |at| Value::from(at.clone())));        patch.insert("updated_at".to_string(), Value::from(now.clone()));        update_row(ctx, "cotton_email_threads", thread_id, patch)?;    }    if !redated.is_empty() {        ctx.commit()?;    }    ctx.commit()?;    // Who wrote: each thread that gained mail is settled with its sender's    // kind, so it is in its stack the moment it lands.    let gained: Vec<String> = threads_out        .iter()        .filter(|thread| thread["added"].as_i64().unwrap_or(0) > 0)        .filter_map(|thread| thread["threadId"].as_str().map(str::to_string))        .collect();    super::kinds::settle_threads(ctx, &gained, &HashSet::new())?;    let photos_seen = photos.photos + photos.merged + photos.failed;    ctx.audit(        "ingest_emails",        &format!(            "{added} added, {skipped} skipped, {} thread(s){}",            threads_out.len(),            if photos_seen > 0 {                format!(                    ", {} photo(s) + {} sighting(s) on known photos, {} failed",                    photos.photos, photos.merged, photos.failed                )            } else {                String::new()            }        ),    );    let mut out = Map::new();    out.insert("threads".to_string(), Value::Array(threads_out));    out.insert("added".to_string(), Value::from(added));    out.insert("skipped".to_string(), Value::from(skipped));    // Only when a picture was in play: an assistant filing plain mail should    // not read a photos block that says nothing happened.    if photos_seen > 0 {        let mut block = Map::new();        block.insert("added".to_string(), Value::from(photos.photos));        block.insert("merged".to_string(), Value::from(photos.merged));        block.insert("failed".to_string(), Value::from(photos.failed));        out.insert("photos".to_string(), Value::Object(block));    }    if restated_count > 0 {        out.insert("restated".to_string(), Value::from(restated_count));    }    if !truncated_ids.is_empty() {        let note = format!(            "{} bod{} over {EMAIL_BODY_MAX} characters and stored truncated, with a visible marker",            truncated_ids.len(),            if truncated_ids.len() == 1 {                "y was"            } else {                "ies were"            }        );        out.insert(            "truncated".to_string(),            Value::from(                truncated_ids                    .iter()                    .map(|id| Value::from(id.clone()))                    .collect::<Vec<Value>>(),            ),        );        out.insert("note".to_string(), Value::from(note));    }    Ok(Value::Object(out))}/// What one conversation's row says, carried through the loop.struct ThreadState {    id: String,    subject: Option<String>,    first_at: Option<String>,    last_at: Option<String>,    email_count: i64,}/// The thread's address set after these emails: new addresses join, a known/// address may climb ('from' > 'to' > 'cc') and gain its first display name —/// it never falls or goes nameless again.fn upsert_participants(    ctx: &mut Ctx<'_>,    thread_id: &str,    inserted: &[&PreparedEmail],    now: &str,) -> Result<(), ToolFailure> {    // The batch's view of each address, folded across every inserted email.    let mut order: Vec<String> = Vec::new();    let mut wanted: HashMap<String, (String, Option<String>)> = HashMap::new();    let mut fold = |address: &EmailAddressArg, role: &str| {        let key = lowered(address);        match wanted.get_mut(&key) {            Some(entry) => {                if role_rank(&entry.0) < role_rank(role) {                    entry.0 = role.to_string();                }                if entry.1.is_none() {                    entry.1.clone_from(&address.name);                }            }            None => {                order.push(key.clone());                wanted.insert(key, (role.to_string(), address.name.clone()));            }        }    };    for email in inserted {        fold(&email.arg.from, "from");        for address in &email.arg.to {            fold(address, "to");        }        for address in &email.arg.cc {            fold(address, "cc");        }        // bcc is folded as `cc`, the TypeScript's own choice: the thread's        // participant list has three ranks, not four.        for address in &email.arg.bcc {            fold(address, "cc");        }    }    if order.is_empty() {        return Ok(());    }    let existing = read_rows(        ctx,        &Query::on("cotton_email_participants")            .columns(PARTICIPANT_COLUMNS)            .eq("thread_id", thread_id.to_string()),    )?;    let existing_by_email: HashMap<String, Map<String, Value>> = existing        .into_iter()        .filter_map(|row| text(&row, "email").map(|email| (email, row)))        .collect();    for address in &order {        let (role, name) = wanted.get(address).cloned().unwrap_or_default();        let Some(existing) = existing_by_email.get(address) else {            let mut patch = Map::new();            patch.insert("thread_id".to_string(), Value::from(thread_id));            patch.insert("email".to_string(), Value::from(address.as_str()));            patch.insert(                "display_name".to_string(),                name.clone().map_or(Value::Null, Value::from),            );            patch.insert("role".to_string(), Value::from(role.clone()));            insert_row(                ctx,                "cotton_email_participants",                &email_participant_id(thread_id, address),                patch,            )?;            continue;        };        let mut patch = Map::new();        let current = text(existing, "role").unwrap_or_default();        if role_rank(&role) > role_rank(&current) {            patch.insert("role".to_string(), Value::from(role.clone()));        }        if text(existing, "display_name").is_none() {            if let Some(name) = name.filter(|name| !name.is_empty()) {                patch.insert("display_name".to_string(), Value::from(name));            }        }        if !patch.is_empty() {            patch.insert("updated_at".to_string(), Value::from(now));            let Some(id) = text(existing, "id") else {                continue;            };            update_row(ctx, "cotton_email_participants", &id, patch)?;        }    }    Ok(())}/// The id a thread or a message is born at: the one derived from its key, or/// the next generation of it when the owner erased that one from the bin — an/// erased row is never written again, and mail that arrives anew is new.fn live_id(ctx: &Ctx<'_>, table: &str, key: &str) -> Result<String, ToolFailure> {    cotton_store::erase::generation_id(ctx.db(), table, &[ctx.file.namespace().as_str(), key])        .map_err(|error| ToolFailure::new(error.to_string()))}/// Whether a job mirroring the source's own deletion erased the row born from/// `key` — at its derived id or any generation of it that has been erased.fn source_erased(ctx: &Ctx<'_>, table: &str, key: &str) -> Result<bool, ToolFailure> {    use cotton_store::protocol::derived_id::derived_id;    let namespace = ctx.file.namespace();    let mut id = derived_id(table, &[namespace.as_str(), key]);    let mut generation: u64 = 0;    loop {        let row = ctx            .db()            .get(                "SELECT reason FROM _gone WHERE tbl = ? AND row_id = ?",                &[SqlValue::Text(table.to_string()), SqlValue::Text(id.clone())],            )            .map_err(|error| ToolFailure::new(error.to_string()))?;        let Some(row) = row else { return Ok(false) };        if row.text("reason").is_some_and(|reason| reason.starts_with("source:")) {            return Ok(true);        }        generation += 1;        id = derived_id(table, &[namespace.as_str(), key, "gen", &generation.to_string()]);    }}