//! Who writes to the owner, and the addresses they are done with.//!//! A blocked sender is a ROW, not a filter folded into the reads: it is a fact//! the owner stated, and it syncs to the phone like anything else. Blocking//! files the sender's mail into Junk — their sender kind — and never bins it://! nothing goes to Gmail's bin (architect, 11 Oct 2026). Lifting the block//! takes the mail out of Junk again, by the same rule.usecrate::mcp::writer::Retract;use std::collections::HashMap;use cotton_core::rules::email_state::email_folder_filter;use cotton_core::rules::people::handles::{normalise_handle, HandleKind};use rusqlite::types::ValueasSqlValue;usecrate::mcp::protocol::ToolFailure;use cotton_store::protocol::derived_id::blocked_sender_id;use serde_json::{Map, Value};usesuper::kinds::settle_addresses;usesuper::shared::{blocked_set, name_for, people_by_address, truthy};use std::collections::{BTreeSet, HashSet};usesuper::validate::{validate_block_sender, validate_list_email_senders};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{insert_row, maybe_row, rows as read_rows, text};usecrate::mcp::read_db::{Filter, Order, Query};/// One sender, folded across their mail.structSender { address: String, name: String, count: i64, unread: i64, last_at: String, blocked: bool, person_id: Option<String>, kind: Option<String>,}pubfn list_email_senders(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult { read_email_senders(ctx,args)}pubfn read_email_senders(ctx: &Ctx<'_>, args: &Map<String, Value>) -> ToolResult {let args = validate_list_email_senders(args)?;let filter = email_folder_filter(args.folder);letmut query = Query::on("cotton_emails").columns(&["from_email","from_name","sent_at","unread","trashed_at","in_inbox", ]); query = query.filter(if filter.binned {Filter::NotNull("trashed_at".to_string()) } else {Filter::IsNull("trashed_at".to_string()) });ifletSome(in_inbox) = filter.in_inbox { query = query.eq("in_inbox", in_inbox); }let rows = read_rows(ctx, &query)?;let blocked = blocked_set(ctx)?;// Who each one is, as the reader settled it (v107).let kinds: std::collections::HashMap<String, String> = read_rows( ctx, &Query::on("cotton_email_senders").columns(&["address", "kind"]), )? .iter() .filter_map(|row| Some((text(row, "address")?, text(row, "kind")?))) .collect();let people = people_by_address( ctx, &rows .iter() .filter_map(|row| text(row, "from_email").map(|address| address.to_lowercase())) .collect::<Vec<String>>(), );letmut order: Vec<String> = Vec::new();letmut grouped: HashMap<String, Sender> = HashMap::new();for row in &rows {letSome(address) = text(row, "from_email").map(|value| value.to_lowercase()) else {continue; };let sent_at = text(row, "sent_at").unwrap_or_default();match grouped.get_mut(&address) {Some(existing) => { existing.count += 1;if truthy(row, "unread") { existing.unread += 1; }if sent_at > existing.last_at { existing.last_at = sent_at; } }None => { order.push(address.clone()); grouped.insert( address.clone(),Sender { name: name_for(&address, text(row, "from_name").as_deref(), &people), person_id: people.get(&address).map(|person| person.id.clone()), blocked: blocked.contains(&address), kind: kinds.get(&address).cloned(), address, count: 1, unread: i64::from(truthy(row, "unread")), last_at: sent_at, }, ); } } }let total = grouped.len() as i64;letmut senders: Vec<&Sender> = order .iter() .filter_map(|address| grouped.get(address)) .collect();// `b.count - a.count || b.lastAt.localeCompare(a.lastAt)` — busiest first,// most recent as the tie-break. A stable sort, so an exact tie keeps the// order the fold saw, which the TypeScript's `Array.sort` also guarantees. senders.sort_by(|a, b| { b.count .cmp(&a.count) .then_with(|| b.last_at.cmp(&a.last_at)) });let out_senders: Vec<Value> = senders .into_iter() .take(args.limit.max(0) as usize) .map(|sender| {letmut out = Map::new(); out.insert("address".to_string(), Value::from(sender.address.clone())); out.insert("name".to_string(), Value::from(sender.name.clone())); out.insert("count".to_string(), Value::from(sender.count)); out.insert("unread".to_string(), Value::from(sender.unread)); out.insert("lastAt".to_string(), Value::from(sender.last_at.clone())); out.insert("blocked".to_string(), Value::Bool(sender.blocked));ifletSome(kind) = &sender.kind { out.insert("kind".to_string(), Value::from(kind.clone())); }ifletSome(person_id) = &sender.person_id { out.insert("personId".to_string(), Value::from(person_id.clone())); }Value::Object(out) }) .collect();letmut out = Map::new(); out.insert("senders".to_string(), Value::Array(out_senders)); out.insert("total".to_string(), Value::from(total));Ok(Value::Object(out))}pubfn block_sender(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let address = validate_block_sender(args)?;// The hard rules (mail-simplified item 5): an assistant never junks// someone in People, someone the owner writes to, or a sender of records// the owner keeps. The owner's own block is an act and is never refused.if !ctx.is_owner_app() {ifletSome(reason) = super::kinds::junk_refusal(ctx, &address)? {returnErr(crate::mcp::protocol::ToolFailure::new(format!("not blocked: {reason}"))); } }let id = blocked_sender_id(ctx.file.namespace(), &address);let existing = maybe_row( ctx, &Query::on("cotton_blocked_senders") .columns(&["id"]) .eq("id", id.to_string()), )?;if existing.is_none() {letmut patch = Map::new(); patch.insert("address".to_string(), Value::from(address.clone())); insert_row(ctx, "cotton_blocked_senders", &id, patch)?; } ctx.commit()?;// The sender is junk now, and every thread they are the sender of files// into Junk with them. Bounded by their threads, by the sender index.let (settled, _) = settle_addresses(ctx, &BTreeSet::from([address.clone()]), &HashSet::new())?;// The owner's Junk is final: the hourly classifier never decides this// sender again (the junk lane, 12 Oct 2026).if ctx.is_owner_app() {super::classify::owner_decided(ctx, &address, Some(super::classify::Word::Junk))?; } ctx.audit("block_sender", &format!("{address}, {} thread(s) into Junk", settled.threads));letmut out = Map::new(); out.insert("address".to_string(), Value::from(address)); out.insert("junk".to_string(), Value::from(settled.threads)); out.insert("binned".to_string(), Value::from(0));Ok(Value::Object(out))}pubfn unblock_sender(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let address = validate_block_sender(args)?;let id = blocked_sender_id(ctx.file.namespace(), &address); ctx.writer()?.retract("cotton_blocked_senders", &id, Retract::Relation); ctx.commit()?;// Out of Junk: the sender is a person or a service again, by the rule, and// their threads follow. Nothing was binned, so nothing is restored.let (settled, _) = settle_addresses(ctx, &BTreeSet::from([address.clone()]), &HashSet::new())?;// The owner's Keep is final, as their Junk is.if ctx.is_owner_app() {super::classify::owner_decided(ctx, &address, None)?; } ctx.audit("unblock_sender", &format!("{address}, {} thread(s) out of Junk", settled.threads));letmut out = Map::new(); out.insert("address".to_string(), Value::from(address)); out.insert("restored".to_string(), Value::from(0));Ok(Value::Object(out))}/// Add to People (the sweep lane, 12 Oct 2026): the owner's explicit act on a/// sender, never automatic. It links the sender to the one person whose email/// handle the address is — archived ones included, who come back — and makes/// a person (the sender's own name, the address as their handle) only when/// nobody holds it, so it never makes a second person for a handle already/// held. The sender is a person then, by the owner's word, and its threads/// move to the People stack.pubfn add_sender_to_people(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {let address = validate_block_sender(args)?;let handle = normalise_handle(HandleKind::Email, &address).unwrap_or_else(|| address.clone());let holder = ctx .db() .all("SELECT h.person_id, p.archived_at FROM cotton_person_handles h JOIN cotton_people p ON p.id = h.person_id WHERE h.workspace_id = ?1 AND h.kind = 'email' AND h.normalised = ?2 ORDER BY p.archived_at IS NOT NULL, h.created_at LIMIT 1", &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(handle)], ) .map_err(|error| ToolFailure::new(error.to_string()))? .first() .map(|row| (row.text("person_id").unwrap_or_default().to_string(), row.text("archived_at").is_some()));let (person_id, made) = match holder {Some((id, archived)) => {if archived {letmut back = Map::new(); back.insert("id".into(), Value::from(id.clone()));crate::mcp::handlers::records_1::people::unarchive_person(ctx, &back)?; } (id, false) }None => {letmut person = Map::new(); person.insert("fullName".into(), Value::from(sender_name(ctx, &address)?)); person.insert("emails".into(), Value::from(vec![address.clone()]));// Two people may share a name; the handle is what names one. person.insert("allowDuplicateName".into(), Value::Bool(true));let made = crate::mcp::handlers::records_1::people::create_person(ctx, &person)?; (made.get("id").and_then(Value::as_str).unwrap_or_default().to_string(), true) } };// A blocked sender added to People is not junk any more.let blocked = blocked_sender_id(ctx.file.namespace(), &address);if maybe_row(ctx, &Query::on("cotton_blocked_senders").columns(&["id"]).eq("id", blocked.to_string()))?.is_some() { ctx.writer()?.retract("cotton_blocked_senders", &blocked, Retract::Relation); ctx.commit()?; }super::classify::owner_decided(ctx, &address, Some(super::classify::Word::Person))?;let (settled, _) = settle_addresses(ctx, &BTreeSet::from([address.clone()]), &HashSet::new())?; ctx.audit("add_sender_to_people", &format!("{address} {} person {person_id}, {} thread(s) to People",if made { "made" } else { "linked to" }, settled.threads ), );let name = maybe_row(ctx, &Query::on("cotton_people").columns(&["full_name"]).eq("id", person_id.clone()))? .and_then(|row| text(&row, "full_name")) .unwrap_or_else(|| address.clone());letmut out = Map::new(); out.insert("address".into(), Value::from(address));if made {let change = crate::mcp::handlers::tables::record_added(ctx, "person", &person_id)?; out.insert("change".into(), change); } out.insert("personId".into(), Value::from(person_id)); out.insert("made".into(), Value::Bool(made));// The receipt the Senders surface shows. out.insert("receipt".into(),Value::from(if made { format!("Added {name} to People") } else { format!("Linked to {name} in People") }), );Ok(Value::Object(out))}/// The name a sender signs their newest mail with, or the address itself.fn sender_name(ctx: &Ctx<'_>, address: &str) -> Result<String, ToolFailure> {let named = ctx .db() .all("SELECT from_name FROM cotton_emails WHERE workspace_id = ?1 AND lower(from_email) = ?2 AND from_name IS NOT NULL AND trim(from_name) <> '' ORDER BY sent_at DESC LIMIT 1", &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(address.to_string())], ) .map_err(|error| ToolFailure::new(error.to_string()))? .first() .and_then(|row| row.text("from_name").map(|name| name.trim().to_string()));Ok(named.unwrap_or_else(|| address.to_string()))}pubfn list_blocked_senders(ctx: &mutCtx<'_>, _args: &Map<String, Value>) -> ToolResult {let rows = read_rows( ctx, &Query::on("cotton_blocked_senders") .columns(&["id", "address", "created_at"]) .order_by("address", Order::Asc), )?;let blocked: Vec<Value> = rows .iter() .map(|row| {letmut out = Map::new(); out.insert("address".to_string(),Value::from(text(row, "address").unwrap_or_default()), ); out.insert("blockedAt".to_string(), text(row, "created_at").map_or(Value::Null, Value::from), );Value::Object(out) }) .collect();letmut out = Map::new(); out.insert("blocked".to_string(), Value::Array(blocked));Ok(Value::Object(out))}