Cotton code
1015 lines · 43.2 KB · RustRaw
//! Readable Email definitions over the archive's stored rows and shared state engine.//! Envelope and sender values are produced here for every generic caller.use super::{Page, Stored};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{rows, text, Valid};use crate::mcp::handlers::emails::{senders, shared};use crate::mcp::handlers::records_2::messages::media_out;use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Order, Query};use cotton_core::definitions::TableDefinition;use cotton_core::rules::email_state::{email_folder_filter, email_folder_sql, fold_thread_state, EmailFolder};use rusqlite::types::Value as SqlValue;use cotton_core::records::{Condition, WhereClause};use serde_json::{Map, Value};use std::collections::BTreeMap;pub fn handles(table: &str) -> bool {    matches!(table, "email" | "email_thread" | "email_sender")}fn stored(id: String, data: Map<String, Value>) -> Stored {    Stored {        id,        created_at: text(&data, "created_at"),        updated_at: text(&data, "updated_at"),        deleted_at: text(&data, "trashed_at"),        data,        byline: None,    }}fn array(row: &Map<String, Value>, key: &str) -> Valid<Vec<Value>> {    match row.get(key) {        None | Some(Value::Null) => Ok(Vec::new()),        Some(Value::Array(values)) => Ok(values.clone()),        Some(Value::String(raw)) => serde_json::from_str(raw)            .map_err(|e| ToolFailure::new(format!("Email {key} could not be read: {e}"))),        _ => Err(ToolFailure::new(format!("Email {key} is not an array"))),    }}fn messages(ctx: &Ctx<'_>, thread: Option<&str>) -> Valid<Vec<Map<String, Value>>> {    let mut query = email_query();    if let Some(id) = thread {        query = query.eq("thread_id", id.to_string());    }    rows(ctx, &query)}/// Every email's columns, oldest first.fn email_query() -> Query {    Query::on("cotton_emails")        .columns(&[            "id",            "thread_id",            "subject",            "from_name",            "from_email",            "recipients",            "sent_at",            "body",            "snippet",            "attachments",            "unread",            "starred",            "in_inbox",            "trashed_at",            "gmail_account",            "workspace_id",            "created_at",        ])        .order_by("sent_at", Order::Asc)        .order_by("id", Order::Asc)}/// The email list narrowed by nothing but its folder (`binned`, `in_inbox`),/// paged where it is stored: only the page's emails are shaped. Reading every/// email of the file to keep fifty was a 400 ms list at twelve thousand/// (owner, 15 Oct 2026: "everything should load instantly"). Any other/// narrowing is read the long way (`None`).fn email_page(ctx: &Ctx<'_>, definition: &TableDefinition, clauses: &[WhereClause], offset: i64, limit: i64) -> Valid<Option<Page>> {    let mut binned = false;    let mut inbox = None;    for clause in clauses {        match (clause.column.as_str(), &clause.condition) {            ("binned", Condition::Is(Value::Bool(value))) => binned = *value,            ("in_inbox", Condition::Is(Value::Bool(value))) => inbox = Some(*value),            _ => return Ok(None),        }    }    let mut query = email_query();    query = if binned { query.filter(Filter::NotNull("trashed_at".into())) } else { query.filter(Filter::IsNull("trashed_at".into())) };    if let Some(inbox) = inbox {        query = query.eq("in_inbox", SqlValue::Integer(i64::from(inbox)));    }    let total = ctx.read.count(&query).map_err(|e| ToolFailure::new(e.to_string()))?;    let found = rows(ctx, &query.limit(limit + 1).offset(offset))?;    let more = found.len() as i64 > limit;    let records = found        .iter()        .take(usize::try_from(limit).unwrap_or(0))        .map(|row| email(ctx, row).map(|record| shaped(record, definition)))        .collect::<Valid<Vec<_>>>()?;    Ok(Some(Page { records, more, total }))}/// An email's stored attachments (`{name, mime?, size?, key?}`) in the shape a/// chat message's `media` is answered in, so a conversation draws them as its/// prints. One with bytes behind it goes through `media_out`, which keeps the/// wall and adds a link; one the archive only knows by name (Gmail's, until/// its bytes are fetched) is still a fact, answered without a key.fn attachment_media(ctx: &Ctx<'_>, attachments: &[Value], row: &Map<String, Value>) -> Vec<Value> {    let row_file = text(row, "workspace_id").unwrap_or_else(|| ctx.workspace_id.to_string());    attachments        .iter()        .filter_map(|stored| {            let mut entry = Map::new();            entry.insert(                "contentType".into(),                Value::from(                    stored["mime"]                        .as_str()                        .filter(|m| !m.is_empty())                        .unwrap_or("application/octet-stream"),                ),            );            if let Some(name) = stored["name"].as_str().filter(|n| !n.is_empty()) {                entry.insert("name".into(), Value::from(name));            }            if let Some(size) = stored["size"].as_i64() {                entry.insert("sizeBytes".into(), Value::from(size));            }            match stored["key"].as_str().filter(|k| !k.is_empty()) {                Some(key) => {                    entry.insert("key".into(), Value::from(key));                    media_out(                        ctx,                        Some(&Value::Array(vec![Value::Object(entry)])),                        &row_file,                    )                    .into_iter()                    .next()                }                None => Some(Value::Object(entry)),            }        })        .collect()}fn email(ctx: &Ctx<'_>, row: &Map<String, Value>) -> Valid<Stored> {    let mut data = row.clone();    let recipients = array(row, "recipients")?;    for kind in ["to", "cc"] {        let labels = recipients            .iter()            .filter(|r| r["kind"] == kind)            .map(|r| {                let address = r["email"].as_str().unwrap_or_default();                r["name"]                    .as_str()                    .map_or_else(|| address.to_string(), |name| format!("{name} <{address}>"))            })            .collect::<Vec<_>>()            .join(", ");        data.insert(format!("{kind}_line"), Value::from(labels));    }    let attachments = array(row, "attachments")?;    let media = attachment_media(ctx, &attachments, row);    data.insert(        "media".into(),        if media.is_empty() {            Value::Null        } else {            Value::Array(media)        },    );    let thread = text(row, "thread_id").unwrap_or_default();    let own = shared::own_email_addresses(ctx, &thread)?;    let from = text(row, "from_email").unwrap_or_default().to_lowercase();    data.insert(        "direction".into(),        Value::from(if own.contains(&from) { "out" } else { "in" }),    );    data.insert(        "binned".into(),        Value::Bool(text(row, "trashed_at").is_some()),    );    for key in ["unread", "starred", "in_inbox"] {        data.insert(key.into(), Value::Bool(shared::truthy(row, key)));    }    Ok(stored(text(row, "id").unwrap_or_default(), data))}use crate::mcp::handlers::emails::kinds::{self, own_addresses};use cotton_core::rules::mail_predicate;/// Whether a read names the sender — their kind, or their address — and so/// may answer a junk sender's threads.fn asks_of_the_sender(clauses: &[WhereClause]) -> bool {    clauses        .iter()        .any(|clause| matches!(clause.column.as_str(), "sender_kind" | "sender_address"))}/// The database's lines, read once for a whole list and only when a thread on/// it has a mark to say: every thread reading them again walked the whole/// `cotton_lines` table per row (50 inbox threads, 1.85 M steps).type Lines = std::cell::OnceCell<Vec<cotton_core::rules::shell_lines::LineRow>>;fn thread(    ctx: &Ctx<'_>,    row: &Map<String, Value>,    folder: Option<EmailFolder>,    lines: &Lines,) -> Valid<Option<Stored>> {    let id = text(row, "id").unwrap_or_default();    let mut mail = messages(ctx, Some(&id))?;    if let Some(folder) = folder {        let filter = email_folder_filter(folder);        mail.retain(|row| {            text(row, "trashed_at").is_some() == filter.binned                && filter                    .in_inbox                    .is_none_or(|wanted| shared::truthy(row, "in_inbox") == wanted)        });        if mail.is_empty() {            return Ok(None);        }    }    let state = fold_thread_state(&mail.iter().map(shared::member_state).collect::<Vec<_>>());    let participants = rows(        ctx,        &Query::on("cotton_email_participants")            .columns(shared::PARTICIPANT_COLUMNS)            .eq("thread_id", id.clone()),    )?;    let from = participants        .iter()        .find(|p| p.get("role").and_then(Value::as_str) == Some("from"));    let first = mail.first();    // The sender the reader settled (v107) — who wrote to the owner, or whom    // the owner wrote to — before any guess from the participants.    let settled = text(row, "sender_address");    let address = settled        .clone()        .or_else(|| from.and_then(|p| text(p, "email")))        .or_else(|| first.and_then(|p| text(p, "from_email")));    let name = match &settled {        Some(settled) => participants            .iter()            .find(|p| text(p, "email").as_deref() == Some(settled.as_str()))            .and_then(|p| text(p, "display_name"))            .or_else(|| {                mail.iter()                    .find(|m| text(m, "from_email").is_some_and(|f| f.to_lowercase() == *settled))                    .and_then(|m| text(m, "from_name"))            }),        None => from            .and_then(|p| text(p, "display_name"))            .or_else(|| first.and_then(|p| text(p, "from_name"))),    };    let mut data = row.clone();    data.insert(        "sender".into(),        Value::from(            name.or_else(|| address.clone())                .unwrap_or_else(|| "Unknown sender".into()),        ),    );    if let Some(address) = address {        data.insert("sender_address".into(), Value::from(address));    }    // The people in the conversation: anyone one of whose addresses wrote or    // was written to. A person's page lists their mail by this.    // Never the owner's own address: the owner on their own card would make    // every conversation theirs, and the People stack every thread.    let own = own_addresses(ctx)?;    let addresses: Vec<String> = participants        .iter()        .filter_map(|p| text(p, "email"))        .map(|address| address.to_lowercase())        .filter(|address| !own.contains(address))        .collect();    let mut people: Vec<String> = shared::people_by_address(ctx, &addresses)        .into_values()        .map(|person| person.id)        .collect();    people.sort();    people.dedup();    if !people.is_empty() {        data.insert("people".into(), Value::Array(people.into_iter().map(Value::from).collect()));    }    // What its Records acts made of it: the link shows in place of the act.    {        use crate::mcp::handlers::emails::record_fields::recorded_as;        for (key, kind) in [("transaction_id", "transaction"), ("event_id", "event")] {            data.insert(key.into(), recorded_as(ctx, &id, kind).map_or(Value::Null, Value::from));        }    }    if let Some(latest) = mail.last() {        let prose = text(latest, "snippet")            .filter(|s| !s.trim().is_empty())            .or_else(|| text(latest, "body"));        if let Some(prose) = prose {            data.insert(                "preview".into(),                Value::from(                    prose                        .split_whitespace()                        .collect::<Vec<_>>()                        .join(" ")                        .chars()                        .take(160)                        .collect::<String>(),                ),            );        }    }    data.insert(        "read_state".into(),        Value::from(if state.unread { "unread" } else { "read" }),    );    data.insert("starred".into(), Value::Bool(state.starred));    data.insert("in_inbox".into(), Value::Bool(state.in_inbox));    let binned = folder.map_or_else(        || text(row, "trashed_at").is_some(),        |folder| email_folder_filter(folder).binned,    );    data.insert("binned".into(), Value::Bool(binned));    let marks = cotton_core::rules::email_state::thread_marks(state.unread, state.starred, state.in_inbox, binned);    if !marks.is_empty() {        let lines = lines.get_or_init(|| crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id));        if let Some(marks) = cotton_core::rules::email_state::say_marks(&marks, lines) {            data.insert("marks".into(), Value::from(marks));        }    }    Ok(Some(stored(id, data)))}fn all(    ctx: &Ctx<'_>,    definition: &TableDefinition,    id: Option<&str>,    folder: Option<EmailFolder>,) -> Valid<Vec<Stored>> {    match definition.id.as_str() {        "email" => {            let mail = if let Some(id) = id {                rows(                    ctx,                    &Query::on("cotton_emails")                        .columns(&[                            "id",                            "thread_id",                            "subject",                            "from_name",                            "from_email",                            "recipients",                            "sent_at",                            "body",                            "snippet",                            "attachments",                            "unread",                            "starred",                            "in_inbox",                            "trashed_at",                            "gmail_account",                            "workspace_id",                            "created_at",                        ])                        .eq("id", id.to_string()),                )?            } else {                messages(ctx, None)?            };            mail.iter().map(|r| email(ctx, r)).collect()        }        "email_thread" => {            let mut query = Query::on("cotton_email_threads")                .columns(&[                    "id",                    "subject",                    "first_at",                    "last_at",                    "email_count",                    "summary",                    "summary_by",                    "trashed_at",                    "created_at",                    "updated_at",                    "sender_address",                    "sender_kind",                    "record_kind",                    "amount_minor",                    "currency",                    "merchant",                    "record_on",                    "reference",                ])                .order_by("last_at", Order::Desc)                .order_by("id", Order::Desc);            if let Some(id) = id {                query = query.eq("id", id.to_string());            }            let lines = Lines::new();            Ok(rows(ctx, &query)?                .iter()                .map(|r| thread(ctx, r, folder, &lines))                .collect::<Valid<Vec<_>>>()?                .into_iter()                .flatten()                .collect())        }        "email_sender" => {            let answer = senders::read_email_senders(                ctx,                serde_json::json!({"folder":"all","limit":crate::mcp::handlers::common::WHOLE_SET})                    .as_object()                    .unwrap(),            )?;            let mut records = BTreeMap::new();            // Why the junk classifier decided as it did (v119) — the column the            // definition declares, answered here as the paged list answers it,            // so a sender reads the same whichever path drew it.            let reasons: BTreeMap<String, Value> = ctx                .db()                .all(                    "SELECT address, reason FROM cotton_email_senders WHERE workspace_id = ?1",                    &[SqlValue::Text(ctx.workspace_id.to_string())],                )                .map_err(|error| ToolFailure::new(error.to_string()))?                .iter()                .filter_map(|row| Some((row.text("address")?.to_string(), row.text("reason").map_or(Value::Null, Value::from))))                .collect();            let reason_of = |address: &str| reasons.get(address).cloned().unwrap_or(Value::Null);            for row in answer["senders"].as_array().into_iter().flatten() {                let address = row["address"]                    .as_str()                    .ok_or_else(|| ToolFailure::new("Email sender has no address"))?                    .to_string();                let data=serde_json::json!({"name":row["name"],"address":address,"last_at":row["lastAt"],"email_count":row["count"],"unread_count":row["unread"],"blocked":row["blocked"],"kind":row["kind"],"in_people":row.get("personId").is_some(),"reason":reason_of(&address)}).as_object().unwrap().clone();                records.insert(address.clone(), stored(address, data));            }            for address in shared::blocked_set(ctx)? {                records.entry(address.clone()).or_insert_with(||stored(address.clone(),serde_json::json!({"name":address,"address":address,"email_count":0,"unread_count":0,"blocked":true,"kind":"junk","in_people":false,"reason":reason_of(&address)}).as_object().unwrap().clone()));            }            Ok(records.into_values().collect())        }        _ => Err(ToolFailure::new("Unknown Email table")),    }}fn shaped(mut record: Stored, definition: &TableDefinition) -> Stored {    record        .data        .retain(|key, _| definition.column(key).is_some());    record}pub fn read_one(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<Option<Stored>> {    if definition.id == "email_sender" {        return Ok(sender_page(ctx, definition, &[], Some(id), 0, 1)?.and_then(|page| page.records.into_iter().next()));    }    Ok(all(ctx, definition, Some(id), None)?        .into_iter()        .find(|r| r.id == id)        .map(|r| shaped(r, definition)))}/// The unnarrowed list's visibility, without bodies, participants or per-thread/// page reads. Keep the sender fold's Rust lowercase (including Unicode) and/// blocked addresses, and count a thread only if it has a live member.fn count_live(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid<i64> {    let at = match definition.id.as_str() {        "email" => 0,        "email_thread" => 1,        "email_sender" => 2,        _ => return Err(ToolFailure::new("Unknown Email table")),    };    let totals = ctx.db().cached_counts(&format!("email-live:{}", ctx.workspace_id), || {        let read = || -> Valid<Vec<i64>> {            // Everything's three mail facets share ONE visibility pass. The            // next page reuses its totals until SQLite reports a change;            // never read every email once per facet on every page draw.            let mail = rows(ctx, &Query::on("cotton_emails")                .columns(&["thread_id", "from_email"])                .filter(Filter::IsNull("trashed_at".into())))?;            let members: std::collections::HashSet<String> = mail.iter()                .filter_map(|row| text(row, "thread_id")).collect();            let threads = rows(ctx, &Query::on("cotton_email_threads").columns(&["id"]))?                .iter().filter(|row| text(row, "id").is_some_and(|id| members.contains(&id))).count();            let mut addresses: std::collections::HashSet<String> = mail.iter()                .filter_map(|row| text(row, "from_email")).map(|address| address.to_lowercase()).collect();            addresses.extend(shared::blocked_set(ctx)?);            Ok(vec![mail.len() as i64, threads as i64, addresses.len() as i64])        };        read().map_err(|error| cotton_store::StoreError::refused(error.to_string()))    }).map_err(|error| ToolFailure::new(error.to_string()))?;    Ok(totals[at])}const THREAD_COLUMNS: &[&str] = &[    "id",    "subject",    "first_at",    "last_at",    "email_count",    "summary",    "summary_by",    "trashed_at",    "created_at",    "updated_at",    "sender_address",    "sender_kind",    "record_kind",    "amount_minor",    "currency",    "merchant",    "record_on",    "reference",];/// The emails of thread `t` that show in `folder` — the subquery each of the/// list's per-thread tests is an EXISTS over, answered by/// `idx_cotton_emails_thread_live` alone (schema 111), never the emails' rows.fn folder_members(folder: EmailFolder) -> String {    format!("SELECT 1 FROM cotton_emails e WHERE e.thread_id = t.id AND {}", email_folder_sql(folder, "e"))}/// A folder's page of threads, chosen in SQL: which threads are in the folder/// (and starred, unread, in the inbox) is a question about their emails' flags,/// asked of the index on (thread_id, sent_at); only the threads on the page/// are then assembled with their emails, participants and people. `None` when/// a clause asks about something only an assembled thread knows (a person, a/// sender) — those take the whole walk below.fn thread_page(    ctx: &Ctx<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    offset: i64,    limit: i64,    counted: super::Total,    day_span: Option<&(String, String)>,) -> Valid<Option<Page>> {    let binned = clauses        .iter()        .any(|c| c.column == "binned" && c.condition == Condition::Is(Value::Bool(true)));    let inbox = clauses.iter().find_map(|c| match &c.condition {        Condition::Is(Value::Bool(value)) if c.column == "in_inbox" => Some(*value),        _ => None,    });    let folder = match (binned, inbox) {        (true, _) => EmailFolder::Bin,        (false, Some(true)) => EmailFolder::Inbox,        (false, Some(false)) => EmailFolder::Archived,        (false, None) => EmailFolder::All,    };    // The emails a thread shows in this folder; the thread's flags are any of    // theirs (fold_thread_state), so a flag asked for is one EXISTS.    let members = folder_members(folder);    let mut wheres = vec![format!("EXISTS ({members})")];    if let Some((from, until)) = day_span {        wheres.push(format!("t.last_at >= '{}' AND t.last_at < '{}'", from, until));    }    // Junk is its own stack: the plain list (and a stack that asks nothing of    // the sender) leaves a junk sender's threads out, as it left the bin out    // when blocking binned them. The bin still shows what was binned.    if folder != EmailFolder::Bin && !asks_of_the_sender(clauses) {        wheres.push(format!("(t.sender_kind IS NULL OR t.sender_kind <> '{}')", kinds::JUNK));    }    for clause in clauses {        let flag = match (clause.column.as_str(), &clause.condition) {            ("binned", Condition::Is(Value::Bool(wanted))) => {                if *wanted != email_folder_filter(folder).binned {                    wheres.push("0".into());                }                continue;            }            ("in_inbox", Condition::Is(Value::Bool(wanted))) => ("in_inbox", *wanted),            ("starred", Condition::Is(Value::Bool(wanted))) => ("starred", *wanted),            ("read_state", Condition::Is(Value::String(state))) if state == "unread" => ("unread", true),            ("read_state", Condition::Is(Value::String(state))) if state == "read" => ("unread", false),            ("sender_kind", Condition::Is(Value::String(kind)))                if [kinds::PERSON, kinds::SERVICE, kinds::JUNK].contains(&kind.as_str()) =>            {                // A plain column, by the index on (workspace_id, sender_kind,                // last_at): a stack's page reads its own threads.                wheres.push(format!("t.sender_kind = '{kind}'"));                continue;            }            ("record_kind", Condition::Is(Value::String(kind)))                if crate::mcp::handlers::emails::record_fields::KINDS.contains(&kind.as_str()) =>            {                // A plain column, by the partial index on (workspace_id,                // record_kind, last_at): one kind of record's page.                wheres.push(format!("t.record_kind = '{kind}'"));                continue;            }            ("people", Condition::Present(wanted)) => {                // The thread's people, as `thread` finds them: a participant                // whose address is a handle of someone in People, never the                // owner's own address.                let own = own_addresses(ctx)?;                let mine = if own.is_empty() {                    String::new()                } else {                    let quoted: Vec<String> = own.iter().map(|a| format!("'{}'", a.replace('\'', "''"))).collect();                    format!(" AND p.email NOT IN ({})", quoted.join(", "))                };                wheres.push(format!(                    "{}EXISTS (SELECT 1 FROM cotton_email_participants p INDEXED BY idx_cotton_email_participants_thread \                       JOIN cotton_person_handles h ON h.workspace_id = t.workspace_id AND h.kind = 'email' AND h.normalised = p.email \                       JOIN cotton_people pp ON pp.id = h.person_id AND pp.workspace_id = t.workspace_id AND pp.trashed_at IS NULL AND h.trashed_at IS NULL \                      WHERE p.thread_id = t.id{mine})",                    if *wanted { "" } else { "NOT " }                ));                continue;            }            _ => return Ok(None),        };        let (column, wanted) = flag;        wheres.push(format!(            "{}EXISTS ({members} AND e.{column} = 1)",            if wanted { "" } else { "NOT " }        ));    }    let filter = format!("t.workspace_id = ?1 AND {}", wheres.join(" AND "));    let workspace = || SqlValue::Text(ctx.workspace_id.to_string());    let fail = |error: cotton_store::StoreError| ToolFailure::new(error.to_string());    // The count walks every thread of the mailbox (an EXISTS each), so it is    // asked only of a reader that shows it, and once per snapshot: the next    // page of the same list, or a stack's head read twice, reuses it.    let total = match counted {        super::Total::Skipped => None,        super::Total::Counted => {            let count = format!("SELECT count(*) AS n FROM cotton_email_threads t WHERE {filter}");            let counts = ctx                .db()                .cached_counts(&format!("email-thread-count:{}:{count}", ctx.workspace_id), || {                    Ok(vec![ctx.db().get(&count, &[workspace()])?.and_then(|row| row.int("n")).unwrap_or(0)])                })                .map_err(fail)?;            Some(counts.first().copied().unwrap_or(0))        }    };    // One row past the page says whether another follows, so `more` never    // waits on the count.    let mut ids = ctx        .db()        .all(            &format!(                "SELECT t.id FROM cotton_email_threads t WHERE {filter} \                 ORDER BY t.last_at DESC, t.id DESC LIMIT ?2 OFFSET ?3"            ),            &[workspace(), SqlValue::Integer(limit + 1), SqlValue::Integer(offset)],        )        .map_err(fail)?;    let more = ids.len() as i64 > limit;    ids.truncate(usize::try_from(limit).unwrap_or(0));    let mut records = Vec::new();    let lines = Lines::new();    for id in ids.iter().filter_map(|row| row.text("id")) {        let row = rows(ctx, &Query::on("cotton_email_threads").columns(THREAD_COLUMNS).eq("id", id.to_string()))?;        if let Some(record) = row.first().map(|row| thread(ctx, row, Some(folder), &lines)).transpose()?.flatten() {            records.push(shaped(record, definition));        }    }    Ok(Some(Page { records, more, total: total.unwrap_or(0) }))}/// The Senders surface's page, chosen in SQL: who writes to the owner — one/// row per address their live mail came from, never the owner's own, beside/// every blocked address — busiest first, with the kind the reader settled./// Only the page's names are then looked up among People. `None` for a/// clause it does not answer, which takes the whole walk.fn sender_page(    ctx: &Ctx<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    only: Option<&str>,    offset: i64,    limit: i64,) -> Valid<Option<Page>> {    let mut wheres: Vec<String> = Vec::new();    for clause in clauses {        match (clause.column.as_str(), &clause.condition) {            ("blocked", Condition::Is(Value::Bool(wanted))) => wheres.push(format!("blocked = {}", i64::from(*wanted))),            ("kind", Condition::Is(Value::String(kind)))                if [kinds::PERSON, kinds::SERVICE, kinds::JUNK].contains(&kind.as_str()) =>            {                wheres.push(format!("kind = '{kind}'"));            }            _ => return Ok(None),        }    }    let own = own_addresses(ctx)?;    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    let mine = if own.is_empty() {        String::new()    } else {        let holes: Vec<String> = own            .iter()            .map(|address| {                params.push(SqlValue::Text(address.clone()));                format!("?{}", params.len())            })            .collect();        format!(" AND e.from_email NOT IN ({})", holes.join(", "))    };    // One sender (their page, a command's receipt): their own mail by the    // index on (workspace_id, from_email), and their block if any.    let (mine, theirs) = match only {        Some(address) => {            params.push(SqlValue::Text(address.to_lowercase()));            let at = params.len();            (format!("{mine} AND e.from_email = ?{at}"), format!(" AND b.address = ?{at}"))        }        None => (mine, String::new()),    };    let filter = if wheres.is_empty() { String::new() } else { format!("WHERE {}", wheres.join(" AND ")) };    let senders = format!(        "WITH mail AS (SELECT e.from_email AS address, count(*) AS n, sum(CASE WHEN {unread_mail} THEN 1 ELSE 0 END) AS unread, \                              max(e.sent_at) AS last_at, max(e.from_name) AS from_name \                         FROM cotton_emails e INDEXED BY idx_cotton_emails_from \                        WHERE e.workspace_id = ?1 AND {live_mail}{mine} GROUP BY e.from_email), \              every AS (SELECT address, n, unread, last_at, from_name FROM mail \                        UNION ALL SELECT b.address, 0, 0, NULL, NULL FROM cotton_blocked_senders b \                         WHERE b.workspace_id = ?1{theirs} AND b.address NOT IN (SELECT address FROM mail)), \              senders AS (SELECT every.*, \                                 EXISTS (SELECT 1 FROM cotton_blocked_senders b WHERE b.workspace_id = ?1 AND b.address = every.address) AS blocked, \                                 (SELECT s.kind FROM cotton_email_senders s WHERE s.workspace_id = ?1 AND s.address = every.address) AS stored, \                                 (SELECT s.reason FROM cotton_email_senders s WHERE s.workspace_id = ?1 AND s.address = every.address) AS reason \                            FROM every), \              answered AS (SELECT *, CASE WHEN blocked THEN 'junk' ELSE stored END AS kind FROM senders) \         SELECT * FROM answered {filter}", live_mail = mail_predicate::live("e."), unread_mail = mail_predicate::unread("e.")    );    let fail = |error: cotton_store::StoreError| ToolFailure::new(error.to_string());    let total = ctx        .db()        .get(&format!("SELECT count(*) AS n FROM ({senders})"), &params)        .map_err(fail)?        .and_then(|row| row.int("n"))        .unwrap_or(0);    let mut paged = params.clone();    paged.push(SqlValue::Integer(limit));    paged.push(SqlValue::Integer(offset));    let rows = ctx        .db()        .all(            &format!(                "{senders} ORDER BY n DESC, last_at DESC, address LIMIT ?{} OFFSET ?{}",                paged.len() - 1,                paged.len()            ),            &paged,        )        .map_err(fail)?;    let addresses: Vec<String> = rows.iter().filter_map(|row| row.text("address").map(str::to_string)).collect();    let people = shared::people_by_address(ctx, &addresses);    let records = rows        .iter()        .filter_map(|row| {            let address = row.text("address")?.to_string();            let name = shared::name_for(&address, row.text("from_name"), &people);            let data = serde_json::json!({                "name": name,                "address": address,                "last_at": row.text("last_at"),                "email_count": row.int("n").unwrap_or(0),                "unread_count": row.int("unread").unwrap_or(0),                "blocked": row.int("blocked").unwrap_or(0) != 0,                "kind": row.text("kind"),                "in_people": people.contains_key(&address),                // Why the junk classifier decided as it did (v119); the                // owner's own act carries none.                "reason": row.text("reason"),            });            Some(shaped(stored(address, data.as_object()?.clone()), definition))        })        .collect();    Ok(Some(Page { records, more: total > offset + limit, total }))}pub fn list(    ctx: &Ctx<'_>,    definition: &TableDefinition,    project: Option<&str>,    query: Option<&str>,    clauses: &[WhereClause],    offset: i64,    limit: i64,    total: super::Total,    view: &super::day_plan::View,) -> Valid<Page> {    let span = match view.section.as_deref() {        None => None,        Some("today") if definition.id == "email_thread" => {            let zone = view.timezone.clone().unwrap_or(crate::mcp::handlers::common::workspace_timezone(ctx)?);            let today = view.today.clone().unwrap_or(crate::mcp::handlers::common::today_in(&zone, ctx.now.timestamp_millis())?);            let day = chrono::NaiveDate::parse_from_str(&today, "%Y-%m-%d").map_err(|_| ToolFailure::new("today is YYYY-MM-DD"))?;            let next = day.succ_opt().ok_or_else(|| ToolFailure::new("today has no following day"))?.to_string();            Some((cotton_store::protocol::js::to_iso_string(crate::mcp::handlers::common::start_of_day_in(&today, &zone)?).ok_or_else(|| ToolFailure::new("today is outside the supported range"))?, cotton_store::protocol::js::to_iso_string(crate::mcp::handlers::common::start_of_day_in(&next, &zone)?).ok_or_else(|| ToolFailure::new("today is outside the supported range"))?))        }        Some(_) => return Err(ToolFailure::new("Email is read as today or as its whole list")),    };    if span.is_none() && limit == 0 && project.is_none() && query.is_none() && clauses.is_empty() {        return Ok(Page { records: Vec::new(), more: false, total: count_live(ctx, definition)? });    }    if definition.id == "email_thread" && project.is_none() && query.is_none_or(str::is_empty) {        if let Some(page) = thread_page(ctx, definition, clauses, offset, limit, total, span.as_ref())? {            return Ok(page);        }    }    if definition.id == "email" && project.is_none() && query.is_none_or(str::is_empty) {        if let Some(page) = email_page(ctx, definition, clauses, offset, limit)? {            return Ok(page);        }    }    if definition.id == "email_sender" && project.is_none() && query.is_none_or(str::is_empty) {        if let Some(page) = sender_page(ctx, definition, clauses, None, offset, limit)? {            return Ok(page);        }    }    let linked = if let Some(project) = project {        Some(            rows(                ctx,                &Query::on("cotton_project_links")                    .columns(&["record_id"])                    .eq("project_id", project.to_string())                    .eq("kind", "email_thread".to_string()),            )?            .iter()            .filter_map(|r| text(r, "record_id"))            .collect::<Vec<_>>(),        )    } else {        None    };    let binned = clauses        .iter()        .any(|c| c.column == "binned" && c.condition == Condition::Is(Value::Bool(true)));    let inbox = clauses.iter().find_map(|c| {        if c.column == "in_inbox" {            if let Condition::Is(Value::Bool(value)) = &c.condition {                return Some(*value);            }        }        None    });    let folder = if binned {        EmailFolder::Bin    } else {        match inbox {            Some(true) => EmailFolder::Inbox,            Some(false) => EmailFolder::Archived,            None => EmailFolder::All,        }    };    // A thread's page asks for that thread's emails alone: read only those    // rows, never every email in the file to keep three of them.    let of_thread = clauses.iter().find_map(|c| match &c.condition {        Condition::Is(Value::String(id)) if definition.id == "email" && c.column == "thread_id" => Some(id.as_str()),        _ => None,    });    let records = match of_thread {        Some(id) => messages(ctx, Some(id))?            .iter()            .map(|row| email(ctx, row))            .collect::<Valid<Vec<_>>>()?,        None => all(ctx, definition, None, Some(folder))?,    };    // A thread in the bin is every one of its emails binned, and its page shows    // what was binned (architect 1030): asked for that thread's emails, the    // read answers them from the bin rather than the live folder.    let folder = if of_thread.is_some()        && !binned        && !records.is_empty()        && records.iter().all(|record| record.deleted_at.is_some())    {        EmailFolder::Bin    } else {        folder    };    let mut matches = Vec::new();    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    for record in records {        if let Some((from, until)) = &span {            if !text(&record.data, "last_at").is_some_and(|at| at >= *from && at < *until) { continue; }        }        if definition.id == "email"            && record.deleted_at.is_some() != email_folder_filter(folder).binned        {            continue;        }        if definition.id == "email_thread"            && folder != EmailFolder::Bin            && !asks_of_the_sender(clauses)            && record.data.get("sender_kind").and_then(Value::as_str) == Some(kinds::JUNK)        {            continue;        }        if let Some(ids) = &linked {            let thread = if definition.id == "email" {                text(&record.data, "thread_id").unwrap_or_default()            } else {                record.id.clone()            };            if !ids.contains(&thread) {                continue;            }        }        let mail = if definition.id == "email_thread" {            messages(ctx, Some(&record.id))?        } else {            Vec::new()        };        if !clauses.iter().all(|clause| {            if definition.id == "email_thread" && clause.column == "sender_address" {                return mail.iter().any(|row| {                    let value = row.get("from_email").unwrap_or(&Value::Null);                    match &clause.condition {                        Condition::Is(expected) => value == expected,                        Condition::OneOf(expected) => expected.contains(value),                        Condition::Present(present) => {                            (*present) == (!value.is_null() && value.as_str() != Some(""))                        }                        Condition::NoneOf(unwanted) => {                            !value.is_null() && value.as_str() != Some("") && !unwanted.contains(value)                        }                        Condition::Month(month) => cotton_core::records::in_month(value, *month),                        Condition::WithinDays(days) => cotton_core::records::within_days(value, *days, ctx.now),                        Condition::Bound(bound) => cotton_core::records::in_bound(value, *bound),                        Condition::On(day) => cotton_core::records::on_day(value, *day, zone.today, &zone.tz),                    }                });            }            let value = record.data.get(&clause.column).unwrap_or(&Value::Null);            // A column holding several (`people`) matches by any one of them.            if let Value::Array(held) = value {                return match &clause.condition {                    Condition::Is(expected) => held.contains(expected),                    Condition::OneOf(expected) => expected.iter().any(|one| held.contains(one)),                    Condition::Present(present) => *present != held.is_empty(),                    Condition::NoneOf(unwanted) => {                        !held.is_empty() && !held.iter().any(|one| unwanted.contains(one))                    }                    Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => false,                };            }            match &clause.condition {                Condition::Is(expected) => value == expected,                Condition::OneOf(expected) => expected.contains(value),                Condition::Present(present) => {                    (*present) == (!value.is_null() && value.as_str() != Some(""))                }                Condition::NoneOf(unwanted) => {                    !value.is_null() && value.as_str() != Some("") && !unwanted.contains(value)                }                Condition::Month(month) => cotton_core::records::in_month(value, *month),                        Condition::WithinDays(days) => cotton_core::records::within_days(value, *days, ctx.now),                        Condition::Bound(bound) => cotton_core::records::in_bound(value, *bound),                        Condition::On(day) => cotton_core::records::on_day(value, *day, zone.today, &zone.tz),            }        }) {            continue;        }        if let Some(query) = query.filter(|s| !s.is_empty()) {            let mut hay = record                .data                .iter()                .filter(|(k, _)| !matches!(k.as_str(), "read_state" | "binned" | "direction"))                .filter_map(|(_, v)| v.as_str())                .collect::<Vec<_>>()                .join(" ");            if definition.id == "email_thread" {                for mail in messages(ctx, Some(&record.id))? {                    for key in ["from_name", "from_email", "body"] {                        if let Some(words) = text(&mail, key) {                            hay.push(' ');                            hay.push_str(&words);                        }                    }                    for recipient in array(&mail, "recipients")? {                        for key in ["name", "email"] {                            if let Some(words) = recipient[key].as_str() {                                hay.push(' ');                                hay.push_str(words);                            }                        }                    }                }            }            if !hay.to_lowercase().contains(&query.to_lowercase()) {                continue;            }        }        matches.push(shaped(record, definition));    }    let total = matches.len() as i64;    let more = total > offset + limit;    Ok(Page {        records: matches            .into_iter()            .skip(offset as usize)            .take(limit as usize)            .collect(),        more,        total,    })}#[cfg(test)]#[path = "email_views_plan_tests.rs"]mod plan_tests;