//! The junk classifier's rules (the junk lane, 12 Oct 2026 — the owner's //! "figure out spam more aggressively using AI"): once an hour the serving Mac //! asks the household's Connected AI one word — person, service or junk — for //! every sender nobody has decided yet. The model call is the server's //! (`cotton_server::junk`); what it may ask about, what it may write and what //! it never touches are here, so one implementation answers them all. //! //! - **Who is asked.** A sender of kind `service` that nobody decided //! (`decided_by` NULL): new since the last run, or a service the owner never //! touched. A person, a junk sender and a sender anyone decided are never //! asked — so a decided sender costs no model call again. //! - **The hard rules first, never overridden.** Someone in People, someone //! the owner writes to, and a sender whose mail carries a record (a receipt, //! an amount, a ticket or booking, a code, a delivery) are held by the rules //! without asking the model; and a model's `junk` still goes through //! [`super::senders::block_sender`] as an assistant, which refuses all three //! again ([`super::kinds::junk_refusal`]). //! - **The owner's act is final.** Junk and Keep on the Senders surface stamp //! `decided_by = owner` ([`owner_decided`]); the classifier never picks such //! a sender and [`apply`] never writes one. //! - **No body text.** What the model is shown is the sender's name, address, //! the subjects of its last [`SUBJECTS`] threads and two counts — [`Material`] //! has no field a body could travel in. use std::collections::{BTreeSet, HashSet}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use super::kinds::{carries_a_record, junk_refusal, settle_addresses, SERVICE}; use super::shared::people_by_address; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::{maybe_row, now_iso, text, update_row}; use crate::mcp::protocol::ToolFailure; use crate::mcp::read_db::Query; use cotton_core::rules::mail_predicate; /// `decided_by` when the owner junked or kept the sender. pub const OWNER: &str = "owner"; /// `decided_by` when the classifier (or a rule it ran) decided. pub const ASSISTANT: &str = "assistant"; /// The most senders one pass asks about — one model call. pub const PER_PASS: i64 = 50; /// How many of a sender's newest threads' subjects the model sees. pub const SUBJECTS: usize = 5; /// A record's kind on a thread (v111) that holds its sender by the rules. const RECORD_KINDS: &[&str] = &["receipt", "statement", "ticket", "booking", "code", "delivery"]; /// The one word the model answers per sender. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Word { Person, Service, Junk, } impl Word { pub const ALL: [Word; 3] = [Word::Person, Word::Service, Word::Junk]; pub const fn as_str(self) -> &'static str { match self { Word::Person => "person", Word::Service => "service", Word::Junk => "junk", } } pub fn parse(word: &str) -> Option { Word::ALL.into_iter().find(|w| w.as_str() == word.trim().to_lowercase()) } } /// What the model is shown about one sender. No body, no snippet: the /// struct has no field one could travel in. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Material { pub address: String, /// The display name on its newest mail. pub name: Option, /// Its newest threads' subjects, newest first, at most [`SUBJECTS`]. pub subjects: Vec, /// Live mail from it. pub mail: i64, /// Of those, the ones the owner has read. pub opened: i64, } /// The model's word for one sender, and the few words why. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Verdict { pub address: String, pub word: Word, pub reason: String, } /// What [`due`] found. #[derive(Debug, Default)] pub struct Due { /// The senders to ask the model about. pub ask: Vec, /// Senders the hard rules settled without asking. pub held: i64, } /// What [`apply`] did. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct Applied { pub junk: i64, pub service: i64, pub person: i64, /// Junk verdicts the hard rules refused; the sender is held as a service. pub refused: i64, /// Verdicts for a sender that was no longer undecided — the owner acted, /// a rule moved it, or it was never asked. pub skipped: i64, } fn failure(error: impl std::fmt::Display) -> ToolFailure { ToolFailure::new(error.to_string()) } /// The senders nobody has decided, newest first, at most `limit`. Those the /// hard rules hold are settled here — someone in People becomes a person by /// the rule, a sender of records is stamped a service with the record named /// — and only the rest are answered for asking. pub fn due(ctx: &mut Ctx<'_>, limit: i64) -> Result { let workspace = SqlValue::Text(ctx.workspace_id.to_string()); let undecided: Vec = ctx .db() .all( "SELECT address FROM cotton_email_senders \ WHERE workspace_id = ?1 AND kind = ?2 AND decided_by IS NULL \ ORDER BY created_at DESC, address LIMIT ?3", &[workspace.clone(), SqlValue::Text(SERVICE.to_string()), SqlValue::Integer(limit)], ) .map_err(failure)? .iter() .filter_map(|row| row.text("address").map(str::to_string)) .collect(); let mut out = Due::default(); if undecided.is_empty() { return Ok(out); } let in_people: HashSet = people_by_address(ctx, &undecided).into_keys().collect(); let mut to_people = BTreeSet::new(); for address in undecided { if in_people.contains(&address) { to_people.insert(address); continue; } let subjects: Vec = ctx .db() .all( &format!("SELECT subject FROM cotton_email_threads INDEXED BY idx_cotton_email_threads_sender \ WHERE workspace_id = ?1 AND sender_address = ?2 AND {live_thread} \ ORDER BY last_at DESC, id LIMIT ?3", live_thread = mail_predicate::live_thread("")), &[workspace.clone(), SqlValue::Text(address.clone()), SqlValue::Integer(SUBJECTS as i64)], ) .map_err(failure)? .iter() .map(|row| row.text("subject").unwrap_or_default().trim().to_string()) .collect(); if let Some(record) = held_by_records(ctx, &address, &subjects)? { stamp(ctx, &address, Word::Service, &format!("service: its mail carries {record}"))?; out.held += 1; continue; } let counts = ctx .db() .get( &format!("SELECT count(*) AS mail, coalesce(sum(CASE WHEN {read_mail} THEN 1 ELSE 0 END), 0) AS opened \ FROM cotton_emails WHERE workspace_id = ?1 AND from_email = ?2 AND {live_mail}", live_mail = mail_predicate::live(""), read_mail = mail_predicate::read("")), &[workspace.clone(), SqlValue::Text(address.clone())], ) .map_err(failure)?; let name = ctx .db() .get( "SELECT from_name FROM cotton_emails \ WHERE workspace_id = ?1 AND from_email = ?2 AND from_name IS NOT NULL AND trim(from_name) <> '' \ ORDER BY sent_at DESC LIMIT 1", &[workspace.clone(), SqlValue::Text(address.clone())], ) .map_err(failure)? .and_then(|row| row.text("from_name").map(|name| name.trim().to_string())); out.ask.push(Material { address, name, subjects: subjects.into_iter().filter(|subject| !subject.is_empty()).collect(), mail: counts.as_ref().and_then(|row| row.int("mail")).unwrap_or(0), opened: counts.as_ref().and_then(|row| row.int("opened")).unwrap_or(0), }); } if !to_people.is_empty() { out.held += to_people.len() as i64; settle_addresses(ctx, &to_people, &HashSet::new())?; } ctx.commit()?; Ok(out) } /// The record a sender's mail carries, read from what the reader already /// stored — a thread typed as a record (v111) or a subject that names one — /// never from a body. fn held_by_records(ctx: &Ctx<'_>, address: &str, subjects: &[String]) -> Result, ToolFailure> { let holes: Vec = (0..RECORD_KINDS.len()).map(|i| format!("?{}", i + 3)).collect(); let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(address.to_string())]; params.extend(RECORD_KINDS.iter().map(|kind| SqlValue::Text((*kind).to_string()))); let typed = ctx .db() .get( &format!( "SELECT record_kind FROM cotton_email_threads INDEXED BY idx_cotton_email_threads_sender \ WHERE workspace_id = ?1 AND sender_address = ?2 AND record_kind IN ({}) LIMIT 1", holes.join(", ") ), ¶ms, ) .map_err(failure)?; if let Some(kind) = typed.and_then(|row| row.text("record_kind").map(str::to_string)) { return Ok(Some(format!("a {kind}"))); } Ok(subjects.iter().find_map(|subject| carries_a_record(subject)).map(str::to_string)) } /// The sender row for `address`, if mail ever came from it. fn sender_row(ctx: &Ctx<'_>, address: &str) -> Result>, ToolFailure> { maybe_row( ctx, &Query::on("cotton_email_senders") .columns(&["id", "kind", "decided_by"]) .eq("address", address.to_string()), ) } fn stamp(ctx: &mut Ctx<'_>, address: &str, word: Word, reason: &str) -> Result<(), ToolFailure> { let Some(row) = sender_row(ctx, address)? else { return Ok(()) }; let now = now_iso(ctx); let mut patch = Map::new(); patch.insert("decided_by".into(), Value::from(ASSISTANT)); patch.insert("verdict".into(), Value::from(word.as_str())); patch.insert("reason".into(), Value::from(reason)); patch.insert("decided_at".into(), Value::from(now)); update_row(ctx, "cotton_email_senders", &text(&row, "id").unwrap_or_default(), patch) } /// The owner junked (`Some("junk")`) or kept (`None`) `address` on the /// Senders surface: final. The classifier never asks about it again. pub fn owner_decided(ctx: &mut Ctx<'_>, address: &str, verdict: Option) -> Result<(), ToolFailure> { let Some(row) = sender_row(ctx, address)? else { return Ok(()) }; let now = now_iso(ctx); let mut patch = Map::new(); patch.insert("decided_by".into(), Value::from(OWNER)); patch.insert("verdict".into(), verdict.map_or(Value::Null, |word| Value::from(word.as_str()))); patch.insert("reason".into(), Value::Null); patch.insert("decided_at".into(), Value::from(now)); update_row(ctx, "cotton_email_senders", &text(&row, "id").unwrap_or_default(), patch)?; ctx.commit() } /// Write the model's verdicts. Only a sender still undecided and still a /// service is written; a junk the hard rules refuse is held as a service with /// the rule named. pub fn apply(ctx: &mut Ctx<'_>, verdicts: &[Verdict]) -> Result { let mut applied = Applied::default(); for verdict in verdicts { let address = verdict.address.trim().to_lowercase(); let open = sender_row(ctx, &address)?.is_some_and(|row| { row.get("decided_by").is_none_or(Value::is_null) && text(&row, "kind").as_deref() == Some(SERVICE) }); if !open { applied.skipped += 1; continue; } let reason = verdict.reason.trim(); match verdict.word { Word::Junk => { if let Some(refusal) = junk_refusal(ctx, &address)? { stamp(ctx, &address, Word::Service, &format!("kept: {refusal}"))?; applied.refused += 1; continue; } // The existing block path, as an assistant: its own refusal // stands behind the one above. let mut args = Map::new(); args.insert("address".into(), Value::from(address.clone())); super::senders::block_sender(ctx, &args)?; stamp(ctx, &address, Word::Junk, &format!("junk: {reason}"))?; applied.junk += 1; } Word::Person => { stamp(ctx, &address, Word::Person, &format!("person: {reason}"))?; ctx.commit()?; settle_addresses(ctx, &BTreeSet::from([address.clone()]), &HashSet::new())?; applied.person += 1; } Word::Service => { stamp(ctx, &address, Word::Service, &format!("service: {reason}"))?; applied.service += 1; } } ctx.commit()?; } Ok(applied) } // ── the question the model is asked ───────────────────────────────────────── /// The forced tool the model answers through. pub const TOOL: &str = "name_senders"; pub const SYSTEM_PROMPT: &str = "You sort the senders of one person's email. For each sender you \ are given its name, its address, the subjects of its newest threads, how many emails it has sent \ and how many of them the person opened. Answer ONE word per sender:\n\ - person: a human writing to them in their own words — a friend, a colleague, someone they deal with.\n\ - service: a company, shop, bank, school or tool they use, sending updates, receipts, alerts or \ account mail they may want.\n\ - junk: marketing, newsletters and promotions they never asked for or never open, cold outreach, \ spam.\n\ When unsure, answer service: junk files the sender's mail away. Give a reason of a few words \ (\"newsletter, never opened\"). Answer for every sender you are given and for no other."; /// The tool's schema: one entry per sender asked. pub fn tool_schema() -> Value { json!({ "type": "object", "properties": { "senders": { "type": "array", "items": { "type": "object", "properties": { "address": { "type": "string" }, "kind": { "type": "string", "enum": ["person", "service", "junk"] }, "reason": { "type": "string", "description": "A few words, e.g. \"newsletter, never opened\"." } }, "required": ["address", "kind", "reason"], "additionalProperties": false } } }, "required": ["senders"], "additionalProperties": false }) } /// The user message: one JSON line per sender. pub fn prompt(asked: &[Material]) -> String { asked .iter() .map(|material| { json!({ "address": material.address, "name": material.name, "subjects": material.subjects, "emails": material.mail, "opened": material.opened, }) .to_string() }) .collect::>() .join("\n") } /// The verdicts in the model's answer, for the senders it was asked about /// and nothing else; an unknown word is dropped, and a sender answered twice /// keeps its first answer. pub fn verdicts(input: &Value, asked: &[Material]) -> Vec { let wanted: HashSet<&str> = asked.iter().map(|material| material.address.as_str()).collect(); let mut seen = HashSet::new(); input .get("senders") .and_then(Value::as_array) .into_iter() .flatten() .filter_map(|entry| { let address = entry.get("address")?.as_str()?.trim().to_lowercase(); let word = Word::parse(entry.get("kind")?.as_str()?)?; if !wanted.contains(address.as_str()) || !seen.insert(address.clone()) { return None; } let reason: String = entry .get("reason") .and_then(Value::as_str) .unwrap_or_default() .trim() .chars() .take(120) .collect(); Some(Verdict { address, word, reason }) }) .collect() }