Cotton code
693 lines · 29.3 KB · RustRaw
//! Who wrote: every address mail comes from is a PERSON, a SERVICE or JUNK//! (architect, 11 Oct 2026, the three stacks' item 3 (c)).//!//! The kind lives on `cotton_email_senders` and is copied onto each thread as//! its `sender_kind`, which is what the People, Records and Junk stacks key on.//! The mail reader writes it, by one rule ([`WANT`])://!//! - **junk** when the address is blocked;//! - **person** when it is a handle of someone in People, or the owner has//!   sent a mail with it in To — not cc, never a list, noreply or bounce//!   address ([`is_machine_address`]), never one of the owner's own;//! - **person** too when the junk classifier (or the owner) said so — the//!   sender row's `verdict` (v119), below the rules above and never over a//!   block;//! - **service** otherwise.//!//! A reader never MAKES a person: the People card stays an act of the owner's//! (Cotton is the address book). Written-to is a stored fact on the sender row//! (`written_to`), so the rule is a few index probes per address, never a walk//! over the owner's sent mail.use std::collections::{BTreeSet, HashMap, HashSet};use cotton_store::protocol::derived_id::email_sender_id;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use super::shared::{refold_threads, ThreadIds};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{flag, in_chunks, insert_row, now_iso, rows as read_rows, text, update_row};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};pub const PERSON: &str = "person";pub const SERVICE: &str = "service";pub const JUNK: &str = "junk";/// The one rule, over a relation `a(address, written_to, verdict)`; `?1` is the/// workspace. Both the reader's settle and the whole-table check ask it, so/// there is one implementation of who a sender is.const WANT: &str = "CASE \    WHEN EXISTS (SELECT 1 FROM cotton_blocked_senders b \                  WHERE b.workspace_id = ?1 AND b.address = a.address) THEN 'junk' \    WHEN a.written_to = 1 OR EXISTS (SELECT 1 FROM cotton_person_handles h \                  CROSS JOIN cotton_people p ON p.id = h.person_id \                  WHERE h.workspace_id = ?1 AND h.kind = 'email' AND h.normalised = a.address \                    AND p.workspace_id = ?1 AND p.trashed_at IS NULL AND h.trashed_at IS NULL) THEN 'person' \    WHEN a.verdict = 'person' THEN 'person' \    ELSE 'service' END";/// How many unsettled threads one backfill step takes — one hold of the file.const BACKFILL_STEP: i64 = 200;/// How many steps one sweep runs before leaving the rest to the next — a/// hundred thousand threads in one sweep, the file released between steps.pub const SETTLE_STEPS: usize = 500;/// An address no person answers at: a noreply or bounce address, a mailer/// daemon, a list. Writing to one never makes its sender a person.pub fn is_machine_address(address: &str) -> bool {    let Some((local, domain)) = address.rsplit_once('@') else {        return true;    };    let local = local.split('+').next().unwrap_or(local);    let squashed: String = local.chars().filter(char::is_ascii_alphanumeric).collect();    squashed.contains("noreply")        || squashed.contains("donotreply")        || squashed.contains("dontreply")        || squashed == "mailerdaemon"        || squashed == "postmaster"        || local.contains("bounce")        || local.ends_with("-request")        || local.ends_with("-owner")        || domain.starts_with("lists.")        || domain.starts_with("list.")        || domain == "googlegroups.com"        || domain.ends_with(".googlegroups.com")        || domain == "groups.io"}// ── the hard rules an assistant's junking obeys (mail-simplified item 5) ──/// What a message says that makes it a record the owner keeps: an amount, an/// invoice or receipt, a ticket or booking, a one-time code, a delivery. The/// first thing it finds, in words, or `None`.pub fn carries_a_record(words: &str) -> Option<&'static str> {    use std::sync::OnceLock;    static RULES: OnceLock<Vec<(regex::Regex, &'static str)>> = OnceLock::new();    let rules = RULES.get_or_init(|| {        [            (r"(?i)(₹|\$|€|£|¥|\b(rs|inr|usd|eur|gbp|aed|sgd|jpy)\.?)\s?\d[\d,]*(\.\d+)?", "an amount"),            (r"(?i)\d[\d,]*(\.\d{1,2})?\s?(inr|usd|eur|gbp|aed|sgd|jpy)\b", "an amount"),            (r"(?i)\b(invoice|receipt|payment (received|confirmation|successful)|bill (generated|payment)|tax invoice)\b", "an invoice or receipt"),            (r"(?i)\b(e-?ticket|ticket|boarding pass|pnr|booking (confirmed|confirmation|id|reference)|itinerary|reservation)\b", "a ticket or booking"),            (r"(?i)\b(otp|one[- ]time (password|code|passcode)|verification code|security code|login code|passcode)\b", "a one-time code"),            (r"(?i)\b(out for delivery|delivered|has shipped|shipped|dispatched|tracking (number|id)|your (order|parcel|package))\b", "a delivery"),        ]        .into_iter()        .filter_map(|(pattern, said)| regex::Regex::new(pattern).ok().map(|rule| (rule, said)))        .collect()    });    rules.iter().find(|(rule, _)| rule.is_match(words)).map(|(_, said)| *said)}/// Why `address` is never an assistant's to junk, or `None`: someone in/// People, someone the owner has written to, or a sender whose mail carries a/// record the owner keeps. The owner's own block is an act and asks none of/// this; an assistant's (the classifier's) is refused by it.pub fn junk_refusal(ctx: &Ctx<'_>, address: &str) -> Result<Option<String>, ToolFailure> {    let address = address.trim().to_lowercase();    let in_people = !super::shared::people_by_address(ctx, std::slice::from_ref(&address)).is_empty();    if in_people {        return Ok(Some(format!("{address} is someone in People; only the owner junks a person")));    }    let written = read_rows(        ctx,        &Query::on("cotton_email_senders").columns(&["written_to"]).eq("address", address.clone()),    )?    .first()    .is_some_and(|row| flag(row, "written_to"));    if written {        return Ok(Some(format!("the owner has written to {address}; only the owner junks someone they write to")));    }    let mail = read_rows(        ctx,        &Query::on("cotton_emails").columns(&["subject", "snippet"]).eq("from_email", address.clone()),    )?;    for row in &mail {        let words = format!("{} {}", text(row, "subject").unwrap_or_default(), text(row, "snippet").unwrap_or_default());        if let Some(record) = carries_a_record(&words) {            return Ok(Some(format!(                "mail from {address} carries {record} (\"{}\"); a sender of records the owner keeps is never junked by an assistant",                text(row, "subject").unwrap_or_default()            )));        }    }    Ok(None)}/// The addresses mail is read FOR — a connected Google account, a mailbox/// connected by app password — lower-cased.pub fn own_addresses(ctx: &Ctx<'_>) -> Result<Vec<String>, ToolFailure> {    let found = ctx        .db()        .all(            "SELECT google_email AS address FROM cotton_google_accounts WHERE workspace_id = ?1 \             UNION SELECT reaches AS address FROM cotton_connections \              WHERE workspace_id = ?1 AND kind IN ('google', 'mail')",            &[SqlValue::Text(ctx.workspace_id.to_string())],        )        .map_err(|error| ToolFailure::new(error.to_string()))?;    Ok(found        .iter()        .filter_map(|row| row.text("address"))        .map(|address| address.trim().to_lowercase())        .filter(|address| !address.is_empty())        .collect())}fn lower(row: &Map<String, Value>, column: &str) -> Option<String> {    text(row, column)        .map(|value| value.trim().to_lowercase())        .filter(|value| !value.is_empty())}/// Whether `address` is the owner's on this message: one of the accounts mail/// is read for, or the mailbox this very message was read from.fn is_own(address: &str, row: &Map<String, Value>, own: &HashSet<String>) -> bool {    own.contains(address)        || lower(row, "gmail_account").as_deref() == Some(address)        || lower(row, "account").as_deref() == Some(address)}/// What a thread's typed record columns should hold once its kind is `kind`:/// a service thread is typed from its newest mail from the sender/// ([`super::record_fields::read_record`]); any other kind carries no record./// Only the columns that differ from `row`'s are answered, so an unchanged/// thread writes nothing.fn record_patch(    ctx: &Ctx<'_>,    thread_id: &str,    kind: &str,    row: &Map<String, Value>,    own: &HashSet<String>,) -> Result<Map<String, Value>, ToolFailure> {    let want = if kind == SERVICE {        let mail = read_rows(            ctx,            &Query::on("cotton_emails")                .columns(&["subject", "body", "from_name", "from_email", "gmail_account", "account"])                .eq("thread_id", thread_id.to_string())                .order_by("sent_at", Order::Desc)                .order_by("id", Order::Desc)                // A record's newest mail is near the end; the owner's own                // replies are few. Never the whole thread's bodies.                .limit(8),        )?;        let newest = mail            .iter()            .find(|row| lower(row, "from_email").is_some_and(|from| !is_own(&from, row, own)))            .or_else(|| mail.first());        match newest {            Some(row) => super::record_fields::read_record(                &text(row, "subject").unwrap_or_default(),                &text(row, "body").unwrap_or_default(),                text(row, "from_name").as_deref(),            )            .columns(),            None => super::record_fields::RecordFields::notice().columns(),        }    } else {        super::record_fields::cleared()    };    // A field a person wrote is theirs: the rules never write over it (the    // junk lane, brief 2).    let edited = super::extract::edited_fields(ctx, thread_id)?;    let mut patch: Map<String, Value> = want        .into_iter()        .filter(|(column, _)| !edited.contains(column))        .filter(|(column, value)| row.get(column).unwrap_or(&Value::Null) != value)        .collect();    // The rules typed the thread afresh: the model's line no longer speaks for    // it, and it may be asked once more (v121).    if !patch.is_empty() {        patch.insert("record_reason".into(), Value::Null);    }    Ok(patch)}fn recipients(row: &Map<String, Value>) -> Vec<(String, String)> {    let parsed = match row.get("recipients") {        Some(Value::String(raw)) => serde_json::from_str::<Value>(raw).unwrap_or(Value::Null),        Some(value) => value.clone(),        None => Value::Null,    };    parsed        .as_array()        .into_iter()        .flatten()        .filter_map(|entry| {            let address = entry["email"].as_str()?.trim().to_lowercase();            let kind = entry["kind"].as_str().unwrap_or("to").to_string();            (!address.is_empty()).then_some((address, kind))        })        .collect()}/// The columns [`thread_sender`] and [`written_to`] read of a message.pub const SENDER_COLUMNS: &[&str] = &["from_email", "recipients", "sent_at", "gmail_account", "account"];/// A thread's sender, from its messages oldest first: who first wrote to the/// owner in it; when the owner wrote every message, the first person they/// wrote to. `None` for a thread with no mail.pub fn thread_sender(mail: &[Map<String, Value>], own: &HashSet<String>) -> Option<String> {    if let Some(from) = mail        .iter()        .find_map(|row| lower(row, "from_email").filter(|from| !is_own(from, row, own)))    {        return Some(from);    }    for wanted in [Some("to"), None] {        for row in mail {            if let Some((address, _)) = recipients(row).into_iter().find(|(address, kind)| {                wanted.is_none_or(|wanted| kind == wanted) && !is_own(address, row, own)            }) {                return Some(address);            }        }    }    mail.first().and_then(|row| lower(row, "from_email"))}/// The addresses the owner wrote to in these messages: To only, never a list,/// noreply or bounce address, never their own.pub fn written_to(mail: &[Map<String, Value>], own: &HashSet<String>) -> HashSet<String> {    let mut out = HashSet::new();    for row in mail {        let Some(from) = lower(row, "from_email") else { continue };        if !is_own(&from, row, own) {            continue;        }        for (address, kind) in recipients(row) {            if kind == "to" && !is_own(&address, row, own) && !is_machine_address(&address) {                out.insert(address);            }        }    }    out}/// What [`WANT`] says each address is.fn wanted(ctx: &Ctx<'_>, addresses: &[(String, bool, Option<String>)]) -> Result<HashMap<String, String>, ToolFailure> {    let mut out = HashMap::new();    for batch in addresses.chunks(200) {        let values: Vec<String> = (0..batch.len())            .map(|i| format!("(?{}, ?{}, ?{})", 2 + 3 * i, 3 + 3 * i, 4 + 3 * i))            .collect();        let sql = format!(            "WITH a(address, written_to, verdict) AS (VALUES {}) SELECT a.address AS address, {WANT} AS kind FROM a",            values.join(", ")        );        let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];        for (address, written, verdict) in batch {            params.push(SqlValue::Text(address.clone()));            params.push(SqlValue::Integer(i64::from(*written)));            params.push(verdict.clone().map_or(SqlValue::Null, SqlValue::Text));        }        for row in ctx.db().all(&sql, &params).map_err(|error| ToolFailure::new(error.to_string()))? {            if let (Some(address), Some(kind)) = (row.text("address"), row.text("kind")) {                out.insert(address.to_string(), kind.to_string());            }        }    }    Ok(out)}/// What one settle did.#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]pub struct Settled {    /// Sender rows written (made or changed).    pub senders: i64,    /// Threads whose sender or kind was written.    pub threads: i64,    /// Messages a blocked sender sent that came out of the bin into Junk.    pub restored: i64,}impl Settled {    fn add(&mut self, other: Settled) {        self.senders += other.senders;        self.threads += other.threads;        self.restored += other.restored;    }}/// Write each address's sender row by the rule, and carry a changed kind onto/// every thread that address is the sender of. `written` marks addresses the/// owner has just been seen writing to.pub fn settle_addresses(    ctx: &mut Ctx<'_>,    addresses: &BTreeSet<String>,    written: &HashSet<String>,) -> Result<(Settled, HashMap<String, String>), ToolFailure> {    let mut settled = Settled::default();    if addresses.is_empty() {        return Ok((settled, HashMap::new()));    }    let list: Vec<String> = addresses.iter().cloned().collect();    let existing: HashMap<String, Map<String, Value>> = in_chunks(&list, |batch| {        read_rows(            ctx,            &Query::on("cotton_email_senders")                .columns(&["id", "address", "kind", "written_to", "verdict"])                .filter(Filter::In(                    "address".to_string(),                    batch.iter().map(|address| SqlValue::Text(address.clone())).collect(),                )),        )    })?    .into_iter()    .filter_map(|row| text(&row, "address").map(|address| (address, row)))    .collect();    let asked: Vec<(String, bool, Option<String>)> = list        .iter()        .map(|address| {            let row = existing.get(address);            let was = row.is_some_and(|row| flag(row, "written_to"));            (address.clone(), was || written.contains(address), row.and_then(|row| text(row, "verdict")))        })        .collect();    let kinds = wanted(ctx, &asked)?;    let mut changed: Vec<(String, String)> = Vec::new();    for (address, written_to, _) in &asked {        let kind = kinds.get(address).cloned().unwrap_or_else(|| SERVICE.to_string());        match existing.get(address) {            None => {                let mut patch = Map::new();                patch.insert("address".into(), Value::from(address.clone()));                patch.insert("kind".into(), Value::from(kind.clone()));                patch.insert("written_to".into(), Value::Bool(*written_to));                insert_row(ctx, "cotton_email_senders", &email_sender_id(ctx.file.namespace(), address), patch)?;                settled.senders += 1;                changed.push((address.clone(), kind.clone()));            }            Some(row) => {                let mut patch = Map::new();                if text(row, "kind").as_deref() != Some(kind.as_str()) {                    patch.insert("kind".into(), Value::from(kind.clone()));                    changed.push((address.clone(), kind.clone()));                }                if flag(row, "written_to") != *written_to {                    patch.insert("written_to".into(), Value::Bool(*written_to));                }                if !patch.is_empty() {                    patch.insert("updated_at".into(), Value::from(now_iso(ctx)));                    update_row(ctx, "cotton_email_senders", &text(row, "id").unwrap_or_default(), patch)?;                    settled.senders += 1;                }            }        }    }    for (address, kind) in &changed {        settled.threads += carry_kind(ctx, address, kind)?;    }    ctx.commit()?;    Ok((settled, kinds))}/// The senders among `addresses` the reader already knows, settled again —/// for a write that may change who someone is (a person made or given an/// address, or one taken away): their threads move stacks at once rather/// than at the next sweep. An address no mail came from is left alone.pub fn resettle(ctx: &mut Ctx<'_>, addresses: &BTreeSet<String>) -> Result<Settled, ToolFailure> {    let list: Vec<String> = addresses.iter().map(|address| address.trim().to_lowercase()).collect();    let known: BTreeSet<String> = in_chunks(&list, |batch| {        read_rows(            ctx,            &Query::on("cotton_email_senders")                .columns(&["address"])                .filter(Filter::In(                    "address".to_string(),                    batch.iter().map(|address| SqlValue::Text(address.clone())).collect(),                )),        )    })?    .iter()    .filter_map(|row| text(row, "address"))    .collect();    Ok(settle_addresses(ctx, &known, &HashSet::new())?.0)}/// Every thread `address` is the sender of takes `kind`, by the index on/// (workspace_id, sender_address) — asked for a new sender row too, since a/// thread may name its sender before the row exists.fn carry_kind(ctx: &mut Ctx<'_>, address: &str, kind: &str) -> Result<i64, ToolFailure> {    let threads = ctx        .db()        .all(            "SELECT id, record_kind, amount_minor, currency, merchant, record_on, reference \               FROM cotton_email_threads INDEXED BY idx_cotton_email_threads_sender \              WHERE workspace_id = ?1 AND sender_address = ?2 \                AND (sender_kind IS NULL OR sender_kind <> ?3)",            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(address.to_string()),                SqlValue::Text(kind.to_string()),            ],        )        .map_err(|error| ToolFailure::new(error.to_string()))?;    let now = now_iso(ctx);    let own: HashSet<String> = own_addresses(ctx)?.into_iter().collect();    let mut written = 0;    for found in &threads {        let Some(id) = found.text("id") else { continue };        let current: Map<String, Value> = super::record_fields::COLUMNS            .iter()            .map(|column| {                let value = match column {                    &"amount_minor" => found.int(column).map_or(Value::Null, Value::from),                    _ => found.text(column).map_or(Value::Null, Value::from),                };                (column.to_string(), value)            })            .collect();        let mut patch = record_patch(ctx, id, kind, &current, &own)?;        patch.insert("sender_kind".into(), Value::from(kind));        patch.insert("updated_at".into(), Value::from(now.clone()));        update_row(ctx, "cotton_email_threads", id, patch)?;        written += 1;    }    Ok(written)}/// Settle the named threads: each one's sender, that sender's row, and the/// thread's own `sender_address` and `sender_kind`. The reader calls this for/// every thread a batch of mail touched, so a new thread is in its stack the/// moment it lands. The caller has COMMITTED the messages this reads.pub fn settle_threads(    ctx: &mut Ctx<'_>,    thread_ids: &[String],    written: &HashSet<String>,) -> Result<Settled, ToolFailure> {    if thread_ids.is_empty() && written.is_empty() {        return Ok(Settled::default());    }    let own: HashSet<String> = own_addresses(ctx)?.into_iter().collect();    let mut written = written.clone();    let mut senders: Vec<(String, Option<String>)> = Vec::with_capacity(thread_ids.len());    for id in thread_ids {        let mail = read_rows(            ctx,            &Query::on("cotton_emails")                .columns(SENDER_COLUMNS)                .eq("thread_id", id.clone())                .order_by("sent_at", Order::Asc)                .order_by("id", Order::Asc),        )?;        written.extend(written_to(&mail, &own));        senders.push((id.clone(), thread_sender(&mail, &own)));    }    let addresses: BTreeSet<String> = senders        .iter()        .filter_map(|(_, sender)| sender.clone())        .chain(written.iter().cloned())        .collect();    let (mut settled, kinds) = settle_addresses(ctx, &addresses, &written)?;    let threads: HashMap<String, Map<String, Value>> = in_chunks(thread_ids, |batch| {        read_rows(            ctx,            &Query::on("cotton_email_threads")                .columns(&["id", "sender_address", "sender_kind", "record_kind", "amount_minor", "currency", "merchant", "record_on", "reference"])                .filter(Filter::In(                    "id".to_string(),                    batch.iter().map(|id| SqlValue::Text(id.clone())).collect(),                )),        )    })?    .into_iter()    .filter_map(|row| text(&row, "id").map(|id| (id, row)))    .collect();    let now = now_iso(ctx);    for (id, sender) in senders {        let Some(row) = threads.get(&id) else { continue };        // A thread with no mail has nobody to key on; it is filed as a        // service so it is never asked again.        let kind = sender            .as_ref()            .and_then(|address| kinds.get(address).cloned())            .unwrap_or_else(|| SERVICE.to_string());        // The thread gained mail (or was never typed): its record is read        // again from the newest mail, or cleared when it is no service's.        let mut patch = record_patch(ctx, &id, &kind, row, &own)?;        if text(row, "sender_address") != sender {            patch.insert("sender_address".into(), sender.clone().map_or(Value::Null, Value::from));        }        if text(row, "sender_kind").as_deref() != Some(kind.as_str()) {            patch.insert("sender_kind".into(), Value::from(kind));        }        if !patch.is_empty() {            patch.insert("updated_at".into(), Value::from(now.clone()));            update_row(ctx, "cotton_email_threads", &id, patch)?;            settled.threads += 1;        }    }    ctx.commit()?;    Ok(settled)}/// One step of the mail reader's settle, run a pass at a time until it says/// it is done — each step one short hold of the file:////// 1. while threads no reader has settled yet remain (every thread stored///    before v107), a step settles [`BACKFILL_STEP`] of them — and, ONCE, a///    blocked sender's mail in them comes out of the bin into Junk,///    local-only: the row is marked synced so nothing goes to Gmail, and///    Gmail's trash copy is left as it is (architect, 11 Oct 2026, the 6,707///    binned mails);/// 2. then every sender whose kind the rule now answers differently — someone///    added to People, a block made or lifted elsewhere — is rewritten, and///    its threads follow, and the settle is done.pub fn settle_step(ctx: &mut Ctx<'_>) -> Result<(Settled, bool), ToolFailure> {    let unsettled: Vec<String> = ctx        .db()        .all(            "SELECT id FROM cotton_email_threads WHERE workspace_id = ?1 AND sender_kind IS NULL LIMIT ?2",            &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Integer(BACKFILL_STEP)],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .iter()        .filter_map(|row| row.text("id").map(str::to_string))        .collect();    if unsettled.is_empty() {        let typed = type_untyped(ctx)?;        if typed > 0 {            return Ok((Settled { threads: typed, ..Settled::default() }, true));        }        return Ok((settle_stale(ctx)?, false));    }    let mut settled = Settled::default();    settled.restored += out_of_the_bin(ctx, &unsettled)?;    // Only these threads' own mail says whom the owner wrote to. A sender a    // later step finds written to changes kind there, and `carry_kind` moves    // the threads already settled. This step read the whole archive once —    // every mail, twelve years of it, 5.5 s inside the gmail pass's write    // hold on the owner's Mac (12 Oct 2026), for seven facts.    settled.add(settle_threads(ctx, &unsettled, &HashSet::new())?);    Ok((settled, true))}/// One backfill step of records typed by kind: service threads settled before/// v111 carry no `record_kind` yet, and [`BACKFILL_STEP`] of them are typed.fn type_untyped(ctx: &mut Ctx<'_>) -> Result<i64, ToolFailure> {    let untyped = ctx        .db()        .all(            "SELECT id, record_kind, amount_minor, currency, merchant, record_on, reference FROM cotton_email_threads \              WHERE workspace_id = ?1 AND sender_kind = 'service' AND record_kind IS NULL LIMIT ?2",            &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Integer(BACKFILL_STEP)],        )        .map_err(|error| ToolFailure::new(error.to_string()))?;    if untyped.is_empty() {        return Ok(0);    }    let own: HashSet<String> = own_addresses(ctx)?.into_iter().collect();    let now = now_iso(ctx);    let mut typed = 0;    for found in &untyped {        let Some(id) = found.text("id") else { continue };        let mut patch = record_patch(ctx, id, SERVICE, &Map::new(), &own)?;        patch.insert("updated_at".into(), Value::from(now.clone()));        update_row(ctx, "cotton_email_threads", id, patch)?;        typed += 1;    }    ctx.commit()?;    Ok(typed)}/// Every step of the settle in one call — for a caller that holds the file/// anyway (a test, a small file).pub fn settle_all(ctx: &mut Ctx<'_>) -> Result<Settled, ToolFailure> {    let mut settled = Settled::default();    loop {        let (step, more) = settle_step(ctx)?;        settled.add(step);        if !more {            return Ok(settled);        }    }}/// The one-time restore: a blocked sender's binned mail in these (unsettled)/// threads comes out of the bin, local-only.fn out_of_the_bin(ctx: &mut Ctx<'_>, thread_ids: &[String]) -> Result<i64, ToolFailure> {    let binned = in_chunks(thread_ids, |batch| {        read_rows(            ctx,            &Query::on("cotton_emails")                .columns(&["id", "thread_id", "from_email", "gmail_id"])                .filter(Filter::In(                    "thread_id".to_string(),                    batch.iter().map(|id| SqlValue::Text(id.clone())).collect(),                ))                .filter(Filter::NotNull("trashed_at".to_string())),        )    })?;    if binned.is_empty() {        return Ok(0);    }    let blocked = super::shared::blocked_set(ctx)?;    let now = now_iso(ctx);    let mut threads = ThreadIds::new();    let mut restored = 0;    for row in &binned {        let Some(from) = lower(row, "from_email") else { continue };        if !blocked.contains(&from) {            continue;        }        let mut patch = Map::new();        patch.insert("trashed_at".into(), Value::Null);        if row.get("gmail_id").is_some_and(|id| !id.is_null()) {            patch.insert("sync_state".into(), Value::from("synced"));        }        update_row(ctx, "cotton_emails", &text(row, "id").unwrap_or_default(), patch)?;        if let Some(thread) = text(row, "thread_id") {            threads.insert(thread);        }        restored += 1;    }    if restored > 0 {        ctx.commit()?;        refold_threads(ctx, &threads, &now)?;        ctx.commit()?;    }    Ok(restored)}/// Senders whose kind the rule now answers differently, rewritten.fn settle_stale(ctx: &mut Ctx<'_>) -> Result<Settled, ToolFailure> {    let stale: BTreeSet<String> = ctx        .db()        .all(            &format!(                "SELECT address FROM (SELECT a.address AS address, a.kind AS kind, {WANT} AS want \                   FROM cotton_email_senders a WHERE a.workspace_id = ?1) WHERE want <> kind"            ),            &[SqlValue::Text(ctx.workspace_id.to_string())],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .iter()        .filter_map(|row| row.text("address").map(str::to_string))        .collect();    Ok(settle_addresses(ctx, &stale, &HashSet::new())?.0)}