Cotton code
432 lines · 15.7 KB · RustRaw
//! What every email verb needs: the stored-body ceiling, the snippet, the//! address→person match, and the two writers thread state is maintained by.//!//! Everything that decides what a state change MEANS lives in//! `cotton_core::rules::email_state` — the same functions the app's own//! service calls. Two writers deciding separately what "archive" means is how//! a phone and a server end up disagreeing about where a message is, and the//! person watching is the one who finds out.use std::collections::{HashMap, HashSet};use cotton_core::rules::email_state::{    email_row_patch, fold_thread_state, EmailStatePatch, EmailThreadMemberState,};use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{flag, in_chunks, now_iso, rows as read_rows, text, update_row};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Query};/// The stored-body ceiling. Real mail bodies are a few KB; past this is a/// quoted-history avalanche or an inline blob, and the archive keeps the head/// with a VISIBLE marker — truncation is reported per email, never silent.pub const EMAIL_BODY_MAX: usize = 65_536;pub const TRUNCATION_MARK: &str =    "\n\n[Cotton stored the first 65536 characters; the rest was cut at ingest]";/// How long an attachment link an assistant was handed stays alive.pub const EMAIL_MEDIA_TTL_SECONDS: i64 = 300;/// The columns every state read selects — `EmailStateRow`.pub const STATE_COLUMNS: &[&str] = &[    "id",    "thread_id",    "gmail_id",    "unread",    "starred",    "in_inbox",    "trashed_at",];/// The columns a participant read selects.pub const PARTICIPANT_COLUMNS: &[&str] = &["id", "thread_id", "email", "display_name", "role"];/// `value === true || value === 1` — SQLite hands a bool column back either/// way depending on who wrote the row.pub fn truthy(row: &Map<String, Value>, column: &str) -> bool {    flag(row, column)}/// The one-line preview when the caller did not send one.////// `body.replace(/\s+/g, " ").trim()`, then 140 UTF-16 units — the ceiling is/// written for JavaScript's `length`, so it is counted in the units that/// `length` counts.pub fn derive_snippet(body: &str) -> Option<String> {    let mut flat = String::with_capacity(body.len());    let mut in_space = false;    for character in body.chars() {        if cotton_store::protocol::js::is_js_whitespace(character) {            in_space = true;            continue;        }        if in_space && !flat.is_empty() {            flat.push(' ');        }        in_space = false;        flat.push(character);    }    if flat.is_empty() {        return None;    }    let units: Vec<u16> = flat.encode_utf16().collect();    if units.len() <= 140 {        return Some(flat);    }    Some(format!("{}…", String::from_utf16_lossy(&units[..139])))}/// `ROLE_RANK` — `from` outranks `to` outranks `cc`. An unknown role ranks 0,/// the TypeScript's `?? 0`.pub fn role_rank(role: &str) -> i64 {    match role {        "from" => 3,        "to" => 2,        "cc" => 1,        _ => 0,    }}/// The per-message facts a thread's row is folded from.pub fn member_state(row: &Map<String, Value>) -> EmailThreadMemberState {    EmailThreadMemberState {        unread: truthy(row, "unread"),        starred: truthy(row, "starred"),        in_inbox: truthy(row, "in_inbox"),        trashed_at: text(row, "trashed_at"),    }}// ── person matching, at read time ───────────────────────────────────────────#[derive(Debug, Clone)]pub struct MatchedPerson {    pub id: String,    pub name: String,}/// address → person, by exact match against `cotton_people.emails` — the JSON/// array the People tool keeps. Resolved at READ time so a person who gains an/// address tomorrow claims their whole mail history with no backfill.////// Raw SQL on purpose: `json_each` is not a `Query` verb, and growing one for/// a single reader would be a facade shaped by its first caller. A failure/// reads UNMATCHED — names still shown — which is the TypeScript's own/// behaviour where no driver is at hand.pub fn people_by_address(ctx: &Ctx<'_>, addresses: &[String]) -> HashMap<String, MatchedPerson> {    let mut out: HashMap<String, MatchedPerson> = HashMap::new();    let mut seen: HashSet<&str> = HashSet::new();    let mut unique: Vec<&str> = Vec::new();    for address in addresses {        if !address.is_empty() && seen.insert(address.as_str()) {            unique.push(address.as_str());        }    }    if unique.is_empty() {        return out;    }    const CHUNK: usize = 200;    for batch in unique.chunks(CHUNK) {        let holes = vec!["?"; batch.len()].join(", ");        // From the handles, by the index on (workspace_id, kind, normalised):        // the addresses asked for, then their people. Led by the people, the        // read walked every person in the file for each thread on a Mail page        // (11 Oct 2026, 248,914,242 steps in one read).        let sql = format!(            "SELECT p.id, p.full_name, h.normalised AS addr \               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 IN ({holes}) \                AND p.workspace_id = ?1 AND p.trashed_at IS NULL AND h.trashed_at IS NULL"        );        let mut params: Vec<SqlValue> = vec![SqlValue::Text(ctx.workspace_id.to_string())];        params.extend(batch.iter().map(|a| SqlValue::Text((*a).to_string())));        let Ok(found) = ctx.db().all(&sql, &params) else {            return out;        };        for row in found {            let (Some(addr), Some(id), Some(name)) =                (row.text("addr"), row.text("id"), row.text("full_name"))            else {                continue;            };            out.entry(addr.to_string()).or_insert(MatchedPerson {                id: id.to_string(),                name: name.to_string(),            });        }    }    out}/// The name a reader should see for an address, best first: the matched/// person's, the mail's own display name, the bare address.////// `displayName || address` in the TypeScript — an EMPTY display name falls/// through to the address, which `Option::filter` reproduces.pub fn name_for(    address: &str,    display_name: Option<&str>,    people: &HashMap<String, MatchedPerson>,) -> String {    if let Some(person) = people.get(address) {        return person.name.clone();    }    display_name        .filter(|name| !name.is_empty())        .unwrap_or(address)        .to_string()}/// One participant, as every read answers it.pub fn participant_out(row: &Map<String, Value>, people: &HashMap<String, MatchedPerson>) -> Value {    let email = text(row, "email").unwrap_or_default();    let mut out = Map::new();    out.insert("email".to_string(), Value::from(email.clone()));    out.insert(        "name".to_string(),        Value::from(name_for(            &email,            text(row, "display_name").as_deref(),            people,        )),    );    out.insert(        "role".to_string(),        Value::from(text(row, "role").unwrap_or_default()),    );    if let Some(person) = people.get(&email) {        out.insert("personId".to_string(), Value::from(person.id.clone()));    }    Value::Object(out)}// ── the addresses the owner is done with ────────────────────────────────────/// A blocked sender is a ROW, never a filter folded into a query: the block is/// a fact the owner stated, it syncs to the phone, and what it binned stays/// binned when it is lifted.pub fn blocked_set(ctx: &Ctx<'_>) -> Result<HashSet<String>, ToolFailure> {    let found = read_rows(        ctx,        &Query::on("cotton_blocked_senders").columns(&["address"]),    )?;    Ok(found        .iter()        .filter_map(|row| text(row, "address"))        .collect())}/// Where a mail's bin stands once its mailbox restated its labels — Gmail's/// pull and IMAP's flags both ask this, so the two cannot disagree.////// Gmail's TRASH bins it (keeping the instant Cotton FIRST saw it binned: a/// restated label is not the mail thrown away a second time). Two bins are/// Cotton's own and a mailbox without TRASH does not undo them: a blocked/// sender's mail, which lives in Junk (architect, 11 Oct 2026), and a bin the/// owner made here that never reached the mailbox — "Deleting here also/// deletes in Gmail" off — which the stored labels say by holding no TRASH./// A mail the mailbox HAD binned and no longer does was taken out of its bin/// there, and comes out here.pub fn trashed_after_restate(row: &Map<String, Value>, mailbox_trashed: bool, junk: bool, now: &str) -> Value {    let binned_at = text(row, "trashed_at");    if mailbox_trashed {        return Value::from(binned_at.unwrap_or_else(|| now.to_string()));    }    if junk || !stored_labels_hold_trash(row) {        return binned_at.map_or(Value::Null, Value::from);    }    Value::Null}/// Whether the stored `labels` — what the mailbox last held — carry TRASH./// The column's codec is JSON, but a row written before it can hold the array/// as text; both are read.fn stored_labels_hold_trash(row: &Map<String, Value>) -> bool {    let parsed = match row.get("labels") {        Some(Value::String(raw)) => serde_json::from_str::<Value>(raw).unwrap_or(Value::Null),        Some(value) => value.clone(),        None => Value::Null,    };    parsed.as_array().is_some_and(|labels| labels.iter().any(|label| label.as_str() == Some("TRASH")))}// ── thread state, the one piece that is stored rather than folded ───────────/// An insertion-ordered set of thread ids — a JavaScript `Set`, whose/// iteration order the write order follows.#[derive(Debug, Default)]pub struct ThreadIds {    order: Vec<String>,    seen: HashSet<String>,}impl ThreadIds {    pub fn new() -> ThreadIds {        ThreadIds::default()    }    pub fn insert(&mut self, id: impl Into<String>) {        let id = id.into();        if self.seen.insert(id.clone()) {            self.order.push(id);        }    }    pub fn is_empty(&self) -> bool {        self.order.is_empty()    }    pub fn iter(&self) -> impl Iterator<Item = &String> {        self.order.iter()    }}/// Re-derive each named conversation's `trashed_at` from its messages.////// The ONE piece of thread-level state that is stored rather than folded at/// read time, and therefore the one thing every message write has to maintain./// It is derived from the whole conversation, never from the patch that caused/// the write: "was that the last one still out of the bin" is a question only/// the whole conversation can answer.////// The caller COMMITS before calling this — the messages whose state it reads/// back may have been written by this same call, and the writer is deferred.pub fn refold_threads(    ctx: &mut Ctx<'_>,    thread_ids: &ThreadIds,    now: &str,) -> Result<(), ToolFailure> {    for thread_id in thread_ids.iter() {        let members = read_rows(            ctx,            &Query::on("cotton_emails")                .columns(&["unread", "starred", "in_inbox", "trashed_at"])                .eq("thread_id", thread_id.to_string()),        )?;        let folded = fold_thread_state(            &members                .iter()                .map(member_state)                .collect::<Vec<EmailThreadMemberState>>(),        );        let mut patch = Map::new();        patch.insert(            "trashed_at".to_string(),            folded.trashed_at.map_or(Value::Null, Value::from),        );        patch.insert("updated_at".to_string(), Value::from(now));        update_row(ctx, "cotton_email_threads", thread_id, patch)?;    }    Ok(())}/// Every message of the named threads, plus the messages named directly.pub fn target_rows(    ctx: &Ctx<'_>,    ids: &[String],    thread_ids: &[String],) -> Result<Vec<Map<String, Value>>, ToolFailure> {    let mut found: Vec<Map<String, Value>> = Vec::new();    if !ids.is_empty() {        found.extend(in_chunks(ids, |batch| {            read_rows(                ctx,                &Query::on("cotton_emails")                    .columns(STATE_COLUMNS)                    .filter(Filter::In(                        "id".to_string(),                        batch.iter().map(|id| SqlValue::Text(id.clone())).collect(),                    )),            )        })?);    }    if !thread_ids.is_empty() {        found.extend(in_chunks(thread_ids, |batch| {            read_rows(                ctx,                &Query::on("cotton_emails")                    .columns(STATE_COLUMNS)                    .filter(Filter::In(                        "thread_id".to_string(),                        batch.iter().map(|id| SqlValue::Text(id.clone())).collect(),                    )),            )        })?);    }    let mut seen: HashSet<String> = HashSet::new();    found.retain(|row| text(row, "id").is_some_and(|id| seen.insert(id)));    Ok(found)}/// Write one patch onto a set of messages and re-fold every thread they belong/// to.////// The thread's `trashed_at` is the one piece of thread-level state STORED/// rather than folded at read time, so it is the one thing a message write has/// to maintain — and it is maintained from the whole conversation, never from/// the patch, because "was that the last one" is a question only the whole/// conversation can answer.pub fn apply_email_state(    ctx: &mut Ctx<'_>,    rows: &[Map<String, Value>],    patch: EmailStatePatch,) -> Result<i64, ToolFailure> {    let now = now_iso(ctx);    let mut threads = ThreadIds::new();    let mut changed = 0_i64;    for row in rows {        let Some(id) = text(row, "id") else { continue };        let row_patch = email_row_patch(            patch,            &now,            row.get("gmail_id").is_some_and(|v| !v.is_null()),        );        if row_patch.is_empty() {            continue;        }        update_row(ctx, "cotton_emails", &id, row_patch)?;        if let Some(thread_id) = text(row, "thread_id") {            threads.insert(thread_id);        }        changed += 1;    }    // The refold READS the rows this loop just wrote. The TypeScript's driver    // applies each update as it is made; this writer is deferred, so the batch    // is minted here — a second commit later in the same call is legal and    // mints its own ops.    ctx.commit()?;    refold_threads(ctx, &threads, &now)?;    Ok(changed)}pub fn own_email_addresses(ctx: &Ctx<'_>, thread_id: &str) -> Result<Vec<String>, ToolFailure> {    let workspace = SqlValue::Text(ctx.workspace_id.to_string());    let mut own: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();    let accounts = ctx        .db()        .all(            "SELECT google_email AS address FROM cotton_google_accounts WHERE workspace_id = ?             UNION             SELECT gmail_account AS address FROM cotton_emails INDEXED BY idx_cotton_emails_thread_sent              WHERE workspace_id = ? AND thread_id = ? AND gmail_account IS NOT NULL",            &[                workspace.clone(),                workspace,                SqlValue::Text(thread_id.to_string()),            ],        )        .map_err(|error| ToolFailure::new(error.to_string()))?;    for row in &accounts {        if let Some(address) = row.text("address") {            let lowered = address.trim().to_lowercase();            if !lowered.is_empty() {                own.insert(lowered);            }        }    }    Ok(own.into_iter().collect())}