//! The email tools, end to end over `dispatch::call_tool` on a fake //! `ToolServices` rather than the `/v1/mcp` endpoint (spec //! `2026-08-29-cotton-email-design.md`): batches ingest idempotently, threads //! group by the caller's conversation key, participants resolve to people by //! exact address AT READ TIME, the thread joins a project, and every write //! lands in the file as a sync op the phone would fold. //! //! The "the bin" block reaches `handlers::bin` rather than this group; it //! lives in this file all the same. //! //! ONE DIVERGENCE, and it is invisible from here: `read_email_thread` does not //! reach for a signer, so it echoes an attachment WITHOUT a `url` — the //! TypeScript's own answer where `ctx.documents` is absent. See //! `emails::read::attachments_out`. mod support; use cotton_store::protocol::derived_id::{email_id, email_thread_id}; use cotton_store::protocol::fingerprint::email::message_id_external_id; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::Harness; use support::mcp::{call_tool_as_owner, call_tool, call_tool_raw, mint_token}; fn writer_harness() -> (Harness, String) { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); (h, secret) } fn run(h: &Harness, sql: &str, params: &[SqlValue]) { h.run(sql, params); } /// Every row a query answers, as `(column, value)` pairs — the shape the two /// TypeScript files' assertions were ported into, kept rather than swapped for /// the harness's map so no assertion below had to be rewritten. fn all(h: &Harness, sql: &str, params: &[SqlValue]) -> Vec> { h.with(|db| db.all(sql, params)) .expect("the read runs") .into_iter() .map(|row| { row.columns() .iter() .map(|(name, value)| { ( name.clone(), match value { SqlValue::Null => Value::Null, SqlValue::Integer(int) => Value::from(*int), SqlValue::Real(real) => Value::from(*real), SqlValue::Text(text) => Value::from(text.clone()), SqlValue::Blob(_) => Value::from(""), }, ) }) .collect() }) .collect() } /// One column of the first row a query answers. fn one(h: &Harness, sql: &str, params: &[SqlValue], name: &str) -> Value { all(h, sql, params) .first() .and_then(|row| { row.iter() .find(|(column, _)| column == name) .map(|(_, value)| value.clone()) }) .unwrap_or(Value::Null) } fn text(sql_value: &Value) -> String { sql_value.as_str().unwrap_or_default().to_string() } // ── the two conversations both files build on ─────────────────────────────── fn acme(over: Value) -> Value { let mut email = json!({ "threadKey": "gmail:acme-contract", "subject": "Re: Acme contract", "sentAt": "2026-08-20T10:00:00.000Z", "body": "Sending over the revised contract. CC'ing finance.", "messageId": "", "from": { "email": "Alice@Acme.com", "name": "Alice Kumar" }, "to": [{ "email": "owner@example.com" }], "cc": [{ "email": "finance@acme.com", "name": "Acme Finance" }] }); if let (Some(target), Some(source)) = (email.as_object_mut(), over.as_object()) { for (key, value) in source { target.insert(key.clone(), value.clone()); } } email } fn acme_reply() -> Value { json!({ "threadKey": "gmail:acme-contract", "subject": "Re: Acme contract", "sentAt": "2026-08-21T09:30:00.000Z", "body": "Looks good — signing today.", "messageId": "", "from": { "email": "owner@example.com", "name": "Asha" }, "to": [{ "email": "alice@acme.com" }] }) } /// The thread ids the answer to an ingest carries. fn thread_ids(out: &Value) -> Vec { out["threads"] .as_array() .expect("threads") .iter() .map(|thread| text(&thread["threadId"])) .collect() } // ── ingest_emails ─────────────────────────────────────────────────────────── #[test] fn lands_threads_emails_and_participants_as_sync_ops_with_derived_ids() { let (h, secret) = writer_harness(); let out = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({})), acme_reply()] }), ); assert_eq!(out["added"], 2); assert_eq!(out["skipped"], 0); let threads = out["threads"].as_array().expect("threads"); assert_eq!(threads.len(), 1); // The earliest email names the thread, reply chain stripped. assert_eq!(threads[0]["subject"], "Acme contract"); assert_eq!( text(&threads[0]["threadId"]), email_thread_id(h.file.namespace(), "gmail:acme-contract") ); let thread = &all( &h, "SELECT subject, first_at, last_at, email_count FROM cotton_email_threads", &[], )[0]; assert_eq!( thread .iter() .cloned() .collect::>(), json!({ "subject": "Acme contract", "first_at": "2026-08-20T10:00:00.000Z", "last_at": "2026-08-21T09:30:00.000Z", "email_count": 2 }) .as_object() .expect("an object") .clone() ); let external = message_id_external_id(Some("")).expect("an external id"); let email_row = all( &h, "SELECT id, from_email, recipients FROM cotton_emails WHERE external_id = ?", &[SqlValue::Text(external.clone())], ); let email_row: serde_json::Map = email_row[0].iter().cloned().collect(); // Addresses are lowercased for identity; the id is derived from the // fingerprint so two producers converge. assert_eq!(email_row["from_email"], "alice@acme.com"); assert_eq!(text(&email_row["id"]), email_id(h.file.namespace(), &external)); // CC survives as first-class data on the row. assert_eq!( serde_json::from_str::(&text(&email_row["recipients"])).expect("json"), json!([ { "email": "owner@example.com", "kind": "to" }, { "email": "finance@acme.com", "name": "Acme Finance", "kind": "cc" } ]) ); // The participant set carries the HIGHEST role each address held: // owner@ was a recipient of one email and the sender of the other. let mut roles: Vec<(String, String)> = all(&h, "SELECT email, role FROM cotton_email_participants", &[]) .iter() .map(|row| { let row: serde_json::Map = row.iter().cloned().collect(); (text(&row["email"]), text(&row["role"])) }) .collect(); roles.sort(); assert_eq!( roles, vec![ ("alice@acme.com".to_string(), "from".to_string()), ("finance@acme.com".to_string(), "cc".to_string()), ("owner@example.com".to_string(), "from".to_string()), ] ); // Every write is stamped by the FILE's author (`_meta.author_id`, slice // 2c), which is what makes it a write the phone folds. There is no log to // read it out of — the tables answer for an author, and a stamp ENDS in // that author's device id. let author = h.file_author(); for table in [ "cotton_email_threads", "cotton_emails", "cotton_email_participants", ] { let rows = all( &h, &format!("SELECT substr(_hlc, 20) AS author FROM {table}"), &[], ); assert!(!rows.is_empty(), "{table} holds no row"); for row in &rows { let row: serde_json::Map = row.iter().cloned().collect(); assert_eq!(row["author"], author.as_str(), "{table}"); } } } #[test] fn is_idempotent_the_same_batch_again_adds_nothing_and_says_so() { let (h, secret) = writer_harness(); call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({})), acme_reply()] }), ); let again = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({})), acme_reply()] }), ); assert_eq!(again["added"], 0); assert_eq!(again["skipped"], 2); assert_eq!( one(&h, "SELECT COUNT(*) AS n FROM cotton_emails", &[], "n"), 2 ); assert_eq!( one( &h, "SELECT email_count FROM cotton_email_threads", &[], "email_count" ), 2 ); } #[test] fn dedupes_mail_with_no_message_id_by_content_never_by_sender() { let (h, secret) = writer_harness(); let no_id = json!({ "threadKey": "imap:orphan", "subject": "Receipt", "sentAt": "2026-08-22T08:00:00.000Z", "body": "Payment received, thank you.", "from": { "email": "billing@shop.example" }, "to": [{ "email": "owner@example.com" }] }); let first = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [no_id.clone()] }), ); assert_eq!(first["added"], 1); // Same content re-imported with a DIFFERENT sender name/address casing — // identity was decided at import time from content alone, so this skips. let mut second = no_id.clone(); second["from"] = json!({ "email": "Billing@Shop.example", "name": "Shop Billing" }); let again = call_tool(&h, &secret, "ingest_emails", json!({ "emails": [second] })); assert_eq!(again["added"], 0); assert_eq!(again["skipped"], 1); } #[test] fn truncates_an_oversized_body_loudly_and_refuses_a_foreign_attachment_key() { let (h, secret) = writer_harness(); let big = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({ "body": "x".repeat(70_000), "messageId": "" }))] }), ); assert_eq!(big["truncated"].as_array().expect("truncated").len(), 1); assert!(text(&big["note"]).contains("truncated")); let external = message_id_external_id(Some("")).expect("an external id"); let stored = one( &h, "SELECT body FROM cotton_emails WHERE external_id = ?", &[SqlValue::Text(external)], "body", ); assert!(text(&stored).contains("[Cotton stored the first 65536 characters")); let refused = call_tool_raw( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({ "messageId": "", "attachments": [{ "name": "leak.pdf", "key": "ws/someone-else/file.pdf" }] }))] }), ); assert!(refused.is_error); assert!(refused.text.contains("not in this workspace's media store")); } // ── read_email_thread ─────────────────────────────────────────────────────── #[test] fn reads_chronologically_keeps_to_cc_as_sent_and_pages_backwards() { let (h, secret) = writer_harness(); let ingested = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({})), acme_reply()] }), ); let thread_id = thread_ids(&ingested)[0].clone(); let read = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_id }), ); let emails = read["emails"].as_array().expect("emails"); assert_eq!( emails .iter() .map(|email| text(&email["sentAt"])) .collect::>(), vec![ "2026-08-20T10:00:00.000Z".to_string(), "2026-08-21T09:30:00.000Z".to_string() ] ); assert_eq!(emails[0]["from"]["name"], "Alice Kumar"); assert_eq!( emails[0]["cc"], json!([{ "email": "finance@acme.com", "name": "Acme Finance" }]) ); assert_eq!(read["nextBefore"], Value::Null); let page = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_id, "limit": 1 }), ); assert_eq!(page["emails"][0]["sentAt"], "2026-08-21T09:30:00.000Z"); assert_eq!(page["nextBefore"], "2026-08-21T09:30:00.000Z"); let older = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_id, "limit": 1, "before": page["nextBefore"] }), ); assert_eq!(older["emails"][0]["sentAt"], "2026-08-20T10:00:00.000Z"); } #[test] fn pages_backwards_without_reading_a_page_twice_when_a_page_holds_more_than_one() { // The test above pages ONE row at a time, where the oldest and the newest // of a page are the same row — so it cannot tell a correct handle from a // handle pointing at the wrong end. This one can: three messages, two at a // time, must be read exactly once each and reach the beginning. // // Before 4g the handle was the NEWEST instant on the page, and since the // filter is `sent_at < before`, walking it returned the same page less its // newest row for ever. let (h, secret) = writer_harness(); let mut emails = vec![acme(json!({})), acme_reply()]; emails.push(acme(json!({ "messageId": "", "sentAt": "2026-08-22T08:00:00.000Z", "subject": "Re: Invoice 4471", "body": "A third synthetic message.", }))); call_tool(&h, &secret, "ingest_emails", json!({ "emails": emails })); let listed = call_tool(&h, &secret, "list_email_threads", json!({})); let thread_id = text(&listed["threads"][0]["id"]); let mut seen: Vec = Vec::new(); let mut before: Option = None; for _ in 0..6 { let mut args = json!({ "threadId": thread_id, "limit": 2 }); if let Some(cursor) = &before { args["before"] = json!(cursor); } let page = call_tool(&h, &secret, "read_email_thread", args); let mut instants: Vec = page["emails"] .as_array() .expect("emails") .iter() .map(|email| text(&email["sentAt"])) .collect(); instants.append(&mut seen); seen = instants; match page["nextBefore"].as_str() { Some(cursor) => before = Some(cursor.to_string()), None => break, } } assert_eq!( seen, vec![ "2026-08-20T10:00:00.000Z".to_string(), "2026-08-21T09:30:00.000Z".to_string(), "2026-08-22T08:00:00.000Z".to_string(), ], "every message once, oldest first, and the walk reached the beginning" ); } #[test] fn matches_participants_to_people_by_exact_address_retroactively() { let (h, secret) = writer_harness(); let ingested = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({}))] }), ); let thread_id = thread_ids(&ingested)[0].clone(); // Nobody is identified yet — the display name from the mail stands in. let before = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_id }), ); let alice = before["thread"]["participants"] .as_array() .expect("participants") .iter() .find(|one| one["email"] == "alice@acme.com") .expect("alice") .clone(); assert_eq!(alice["name"], "Alice Kumar"); assert!(alice.get("personId").is_none()); // A person row gains the address — nothing is backfilled, the next read // simply matches. let person = call_tool( &h, &secret, "create_person", json!({ "fullName": "Alice K.", "emails": ["alice@acme.com"] }), ); let after = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_id }), ); let matched = after["thread"]["participants"] .as_array() .expect("participants") .iter() .find(|one| one["email"] == "alice@acme.com") .expect("alice") .clone(); assert_eq!(matched["name"], "Alice K."); assert_eq!(matched["personId"], person["id"]); } #[test] fn carries_the_summary_who_wrote_it_and_what_has_arrived_since() { // Schema v15: an email conversation carries the owner's paragraph about // it, in the header beside the subject. Every instant is seeded // explicitly, so nothing on this path reads the clock. let (h, secret) = writer_harness(); let ingested = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({})), acme_reply()] }), ); let thread_id = thread_ids(&ingested)[0].clone(); // The two emails are 2026-08-20T10:00 and 2026-08-21T09:30; the summary // predates both, so both count as having arrived since. run( &h, "UPDATE cotton_email_threads SET summary = ?, summary_by = ?, summary_updated_at = ? \ WHERE id = ?", &[ SqlValue::Text( "Contract redlines with Acme; finance is copied throughout.".to_string(), ), SqlValue::Text("Claude Code".to_string()), SqlValue::Text("2026-08-19T08:00:00.000Z".to_string()), SqlValue::Text(thread_id.clone()), ], ); let read = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_id }), ); assert_eq!( read["thread"]["summary"], json!({ "text": "Contract redlines with Acme; finance is copied throughout.", "by": "Claude Code", "updatedAt": "2026-08-19T08:00:00.000Z", "since": { "count": 2, "noun": "email" } }) ); } #[test] fn omits_the_summary_key_entirely_when_there_is_none() { let (h, secret) = writer_harness(); let ingested = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({}))] }), ); let read = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_ids(&ingested)[0] }), ); assert!(read["thread"] .as_object() .expect("a thread") .get("summary") .is_none()); } #[test] fn omits_since_when_nothing_has_arrived() { let (h, secret) = writer_harness(); let ingested = call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({})), acme_reply()] }), ); let thread_id = thread_ids(&ingested)[0].clone(); // "Nothing has arrived since" means the summary was written after the last // email LANDED. The cue counts arrival (`created_at`), not authorship, so // an ingest IS an arrival however old the mail itself was sent — which is // the whole point: a backfill into a summarised thread must not read as // silence. let landed = one( &h, "SELECT MAX(created_at) AS at FROM cotton_emails WHERE thread_id = ?", &[SqlValue::Text(thread_id.clone())], "at", ); // Asserted, not defaulted: a null MAX would make `summary_updated_at` // falsy, the reader would skip the count entirely, and this test would pass // having exercised nothing. assert!(landed.is_string(), "nothing landed"); let written_at = cotton_tools::clock::iso( chrono::DateTime::parse_from_rfc3339(&text(&landed)) .expect("an instant") .with_timezone(&chrono::Utc) + chrono::Duration::milliseconds(1), ); run( &h, "UPDATE cotton_email_threads SET summary = ?, summary_by = ?, summary_updated_at = ? \ WHERE id = ?", &[ SqlValue::Text("Contract redlines with Acme.".to_string()), SqlValue::Text("Claude Code".to_string()), SqlValue::Text(written_at), SqlValue::Text(thread_id.clone()), ], ); let read = call_tool( &h, &secret, "read_email_thread", json!({ "threadId": thread_id }), ); let summary = read["thread"]["summary"].as_object().expect("a summary"); assert_eq!( summary.keys().cloned().collect::>(), vec![ "text".to_string(), "by".to_string(), "updatedAt".to_string() ] ); } #[test] fn answers_absent_and_foreign_threads_with_one_sentence() { let (h, secret) = writer_harness(); let refused = call_tool_raw( &h, &secret, "read_email_thread", json!({ "threadId": "00000000-0000-0000-0000-000000000000" }), ); assert!(refused.is_error); assert!(refused.text.contains("no such email thread")); } // ── list_email_threads ────────────────────────────────────────────────────── #[test] fn lists_newest_first_with_participants_and_filters_by_address() { let (h, secret) = writer_harness(); call_tool( &h, &secret, "ingest_emails", json!({ "emails": [ acme(json!({})), { "threadKey": "gmail:other", "subject": "Dinner Friday", "sentAt": "2026-08-25T18:00:00.000Z", "body": "Are you around?", "messageId": "", "from": { "email": "ravi@friends.example", "name": "Ravi" }, "to": [{ "email": "owner@example.com" }] } ] }), ); let all_threads = call_tool(&h, &secret, "list_email_threads", json!({})); assert_eq!( all_threads["threads"] .as_array() .expect("threads") .iter() .map(|thread| text(&thread["subject"])) .collect::>(), vec!["Dinner Friday".to_string(), "Acme contract".to_string()] ); let filtered = call_tool( &h, &secret, "list_email_threads", json!({ "participant": "Alice@Acme.com" }), ); assert_eq!( filtered["threads"] .as_array() .expect("threads") .iter() .map(|thread| text(&thread["subject"])) .collect::>(), vec!["Acme contract".to_string()] ); } // ── email threads in projects and search ──────────────────────────────────── #[test] fn search_records_finds_emails_by_body_and_threads_by_subject() { let (h, secret) = writer_harness(); call_tool( &h, &secret, "ingest_emails", json!({ "emails": [acme(json!({})), acme_reply()] }), ); let by_body = call_tool( &h, &secret, "search_records", json!({ "query": "revised contract", "kinds": ["email"] }), ); let hits = by_body["records"].as_array().expect("records"); assert!(!hits.is_empty()); assert_eq!(hits[0]["kind"], "email"); assert_eq!( text(&hits[0]["threadId"]), email_thread_id(h.file.namespace(), "gmail:acme-contract") ); let by_subject = call_tool( &h, &secret, "search_records", json!({ "query": "acme", "kinds": ["email_thread"] }), ); assert_eq!(by_subject["records"][0]["kind"], "email_thread"); } // ═══ the mail CLIENT (schema v33) ═══════════════════════════════════════════ // What these pin is the part a person watches happen: archiving a conversation // means archiving every message in it (Gmail's model), the thread's own bin // state is the AND over its messages while everything else is the OR, blocking // sweeps what is already here, and nothing is erased until the bin is emptied. fn mail(over: Value) -> Value { let mut email = json!({ "threadKey": "gmail:t1", "subject": "Retrofit quote", "sentAt": "2026-08-20T10:00:00.000Z", "body": "Here is the quote.", "messageId": "", "from": { "email": "ravi@example.com", "name": "Ravi" }, "to": [{ "email": "owner@example.com" }] }); if let (Some(target), Some(source)) = (email.as_object_mut(), over.as_object()) { for (key, value) in source { target.insert(key.clone(), value.clone()); } } email } fn newsletter() -> Value { json!({ "threadKey": "gmail:t2", "subject": "This week at Acme", "sentAt": "2026-08-21T10:00:00.000Z", "body": "Nine things you must know.", "messageId": "", "from": { "email": "news@acme.com", "name": "Acme" }, "to": [{ "email": "owner@example.com" }] }) } /// Two conversations: one of two messages, one newsletter. fn seed(h: &Harness, secret: &str) -> (String, String) { call_tool( h, secret, "ingest_emails", json!({ "emails": [ mail(json!({})), mail(json!({ "messageId": "", "sentAt": "2026-08-20T12:00:00.000Z", "from": { "email": "owner@example.com" }, "to": [{ "email": "ravi@example.com" }] })), newsletter() ] }), ); let list = call_tool(h, secret, "list_email_threads", json!({})); let threads = list["threads"].as_array().expect("threads").clone(); let find = |subject: &str| { threads .iter() .find(|thread| thread["subject"] == subject) .map(|thread| text(&thread["id"])) .unwrap_or_else(|| panic!("no thread called {subject}")) }; (find("Retrofit quote"), find("This week at Acme")) } fn ids_of(out: &Value) -> Vec { out["threads"] .as_array() .expect("threads") .iter() .map(|thread| text(&thread["id"])) .collect() } // ── folders ───────────────────────────────────────────────────────────────── #[test] fn puts_everything_ingested_in_the_inbox_read_with_nothing_to_push() { let (h, secret) = writer_harness(); seed(&h, &secret); let inbox = call_tool( &h, &secret, "list_email_threads", json!({ "folder": "inbox" }), ); let threads = inbox["threads"].as_array().expect("threads"); assert_eq!(threads.len(), 2); assert!(threads.iter().any(|thread| { thread["unread"] == false && thread["starred"] == false && thread["inInbox"] == true })); // Mail no mailbox filed carries no push state — `ingest_emails` from an // assistant is not a Gmail import. let states = all(&h, "SELECT sync_state FROM cotton_emails", &[]); assert_eq!(states.len(), 3); for row in &states { assert_eq!(row[0].1, Value::Null); } } #[test] fn moves_a_whole_conversation_out_of_the_inbox_every_message_of_it() { let (h, secret) = writer_harness(); let (quote, news) = seed(&h, &secret); let out = call_tool( &h, &secret, "update_email", json!({ "threadId": quote, "inbox": false }), ); assert_eq!(out["changed"], 2); let inbox = call_tool( &h, &secret, "list_email_threads", json!({ "folder": "inbox" }), ); assert_eq!(ids_of(&inbox), vec![news.clone()]); let archived = call_tool( &h, &secret, "list_email_threads", json!({ "folder": "archived" }), ); assert_eq!(ids_of(&archived), vec![quote]); } #[test] fn keeps_the_bin_out_of_every_folder_but_the_bin() { let (h, secret) = writer_harness(); let (_quote, news) = seed(&h, &secret); call_tool( &h, &secret, "update_email", json!({ "threadId": news, "bin": true }), ); for folder in ["inbox", "archived", "all"] { let out = call_tool( &h, &secret, "list_email_threads", json!({ "folder": folder }), ); assert!(!ids_of(&out).contains(&news), "{folder} still shows it"); } let bin = call_tool( &h, &secret, "list_email_threads", json!({ "folder": "bin" }), ); assert_eq!(bin["threads"][0]["id"], Value::from(news)); assert!(bin["threads"][0]["trashedAt"].is_string()); } #[test] fn narrows_to_one_sender_and_to_what_is_unread() { let (h, secret) = writer_harness(); let (quote, _news) = seed(&h, &secret); let by_sender = call_tool( &h, &secret, "list_email_threads", json!({ "sender": "ravi@example.com" }), ); assert_eq!(ids_of(&by_sender), vec![quote.clone()]); let none = call_tool( &h, &secret, "list_email_threads", json!({ "unreadOnly": true }), ); assert_eq!(none["threads"], json!([])); call_tool( &h, &secret, "update_email", json!({ "threadId": quote, "read": false }), ); let unread = call_tool( &h, &secret, "list_email_threads", json!({ "unreadOnly": true }), ); assert_eq!(ids_of(&unread), vec![quote]); } // ── update_email ──────────────────────────────────────────────────────────── #[test] fn refuses_a_call_that_names_neither_a_message_nor_a_conversation() { let (h, secret) = writer_harness(); let out = call_tool_raw(&h, &secret, "update_email", json!({ "read": true })); assert!(out.is_error); assert!(out.text.contains("exactly one of id")); } #[test] fn refuses_a_patch_with_nothing_in_it_rather_than_doing_nothing_quietly() { let (h, secret) = writer_harness(); let (quote, _news) = seed(&h, &secret); let out = call_tool_raw(&h, &secret, "update_email", json!({ "threadId": quote })); assert!(out.is_error); assert!(out.text.contains("nothing to change")); } #[test] fn answers_the_same_way_for_a_thread_in_another_workspace_as_for_one_that_never_existed() { let (h, secret) = writer_harness(); let out = call_tool_raw( &h, &secret, "update_email", json!({ "threadId": "11111111-1111-4111-8111-111111111111", "read": true }), ); assert!(out.is_error); assert!(out.text.contains("no such email or email thread")); } #[test] fn bins_the_conversations_own_row_only_when_every_message_of_it_is_binned() { let (h, secret) = writer_harness(); let (quote, _news) = seed(&h, &secret); let messages: Vec = all( &h, "SELECT id FROM cotton_emails WHERE thread_id = ? ORDER BY sent_at", &[SqlValue::Text(quote.clone())], ) .iter() .map(|row| text(&row[0].1)) .collect(); call_tool( &h, &secret, "update_email", json!({ "id": messages[0], "bin": true }), ); assert_eq!( one( &h, "SELECT trashed_at FROM cotton_email_threads WHERE id = ?", &[SqlValue::Text(quote.clone())], "trashed_at" ), Value::Null ); call_tool( &h, &secret, "update_email", json!({ "id": messages[1], "bin": true }), ); assert!(one( &h, "SELECT trashed_at FROM cotton_email_threads WHERE id = ?", &[SqlValue::Text(quote)], "trashed_at" ) .is_string()); } // ── update_emails ─────────────────────────────────────────────────────────── #[test] fn answers_per_id_so_one_bad_id_never_fails_the_batch() { let (h, secret) = writer_harness(); let (quote, news) = seed(&h, &secret); let out = call_tool( &h, &secret, "update_emails", json!({ "threadIds": [quote, "11111111-1111-4111-8111-111111111111", news], "bin": true }), ); assert_eq!(out["changed"], 2); assert_eq!(out["failed"], 1); assert_eq!( out["results"] .as_array() .expect("results") .iter() .map(|row| row["ok"].clone()) .collect::>(), vec![Value::Bool(true), Value::Bool(false), Value::Bool(true)] ); } #[test] fn refuses_ids_and_thread_ids_together_one_or_the_other_never_both() { let (h, secret) = writer_harness(); let (quote, _news) = seed(&h, &secret); let out = call_tool_raw( &h, &secret, "update_emails", json!({ "ids": [quote.clone()], "threadIds": [quote], "read": true }), ); assert!(out.is_error); } // ── senders and blocking ──────────────────────────────────────────────────── #[test] fn groups_by_the_address_as_it_was_sent_busiest_first() { let (h, secret) = writer_harness(); seed(&h, &secret); let out = call_tool( &h, &secret, "list_email_senders", json!({ "folder": "all" }), ); let senders = out["senders"].as_array().expect("senders"); // Every sender has one message here, so the tie breaks on the LATEST — // which is the newsletter. assert_eq!(senders[0]["address"], "news@acme.com"); assert_eq!(senders[0]["count"], 1); let last_ats: Vec = senders .iter() .map(|sender| text(&sender["lastAt"])) .collect(); let mut descending = last_ats.clone(); descending.sort(); descending.reverse(); assert_eq!(last_ats, descending); let mut addresses: Vec = senders .iter() .map(|sender| text(&sender["address"])) .collect(); addresses.sort(); assert_eq!( addresses, vec![ "news@acme.com".to_string(), "owner@example.com".to_string(), "ravi@example.com".to_string() ] ); assert!(senders.iter().all(|sender| sender["blocked"] == false)); } /// The kind each thread's sender is, by subject. fn sender_kinds(h: &Harness) -> Vec<(String, Option)> { all( h, "SELECT subject, sender_kind FROM cotton_email_threads ORDER BY subject", &[], ) .into_iter() .map(|row| (text(&row[0].1), row[1].1.as_str().map(str::to_string))) .collect() } /// RULE: Blocking a sender files their mail into Junk (the thread's sender_kind) and never into the bin, and nothing is marked to go to Gmail (architect, 11 Oct 2026). #[test] fn files_a_blocked_senders_mail_and_everything_they_send_afterwards_into_junk() { let (h, secret) = writer_harness(); seed(&h, &secret); let blocked = call_tool( &h, &secret, "block_sender", json!({ "address": "News@Acme.com" }), ); assert_eq!(blocked["address"], "news@acme.com"); assert_eq!(blocked["junk"], 1); assert_eq!(blocked["binned"], 0); assert!(sender_kinds(&h).contains(&("This week at Acme".to_string(), Some("junk".to_string())))); // And the next one from them files into Junk too — never the bin, and // nothing pending for Gmail. call_tool( &h, &secret, "ingest_emails", json!({ "emails": [{ "threadKey": "gmail:t3", "subject": "More this week", "sentAt": "2026-08-22T10:00:00.000Z", "body": "Ten more things.", "messageId": "", "from": { "email": "news@acme.com" }, "to": [{ "email": "owner@example.com" }] }] }), ); let bin = call_tool(&h, &secret, "list_bin", json!({ "kind": "email" })); assert!(bin["entries"].as_array().expect("entries").is_empty(), "{bin}"); assert!(sender_kinds(&h).contains(&("More this week".to_string(), Some("junk".to_string())))); assert!(all( &h, "SELECT id FROM cotton_emails WHERE trashed_at IS NOT NULL OR sync_state = 'pending'", &[] ) .is_empty()); } #[test] fn lists_a_block_and_unblocking_takes_the_mail_out_of_junk() { let (h, secret) = writer_harness(); seed(&h, &secret); call_tool( &h, &secret, "block_sender", json!({ "address": "news@acme.com" }), ); let listed = call_tool(&h, &secret, "list_blocked_senders", json!({})); let blocked = listed["blocked"].as_array().expect("blocked"); assert_eq!(blocked.len(), 1); assert_eq!(blocked[0]["address"], "news@acme.com"); assert!(blocked[0]["blockedAt"].is_string()); let lifted = call_tool( &h, &secret, "unblock_sender", json!({ "address": "news@acme.com" }), ); assert_eq!(lifted["address"], "news@acme.com"); assert_eq!(lifted["restored"], 0); assert_eq!( call_tool(&h, &secret, "list_blocked_senders", json!({})), json!({ "blocked": [] }) ); // Out of Junk, a service again; nothing was ever in the bin. assert!(sender_kinds(&h).contains(&("This week at Acme".to_string(), Some("service".to_string())))); let bin = call_tool(&h, &secret, "list_bin", json!({})); assert!(bin["entries"].as_array().expect("entries").is_empty()); } #[test] fn blocking_twice_is_one_block_and_no_second_sweep() { let (h, secret) = writer_harness(); seed(&h, &secret); call_tool( &h, &secret, "block_sender", json!({ "address": "news@acme.com" }), ); let again = call_tool( &h, &secret, "block_sender", json!({ "address": "news@acme.com" }), ); assert_eq!(again["binned"], 0); assert_eq!( call_tool(&h, &secret, "list_blocked_senders", json!({}))["blocked"] .as_array() .expect("blocked") .len(), 1 ); } /// RULE: Blocking an address again after unblocking it lands the block at the address's derived id and it is live: a Retract never blocks a later create at the same id. #[test] fn unblock_then_block_same_address_succeeds() { let (h, secret) = writer_harness(); let address = "blocked@example.invalid"; let block_id = |h: &Harness| { let rows = all( h, "SELECT id FROM cotton_blocked_senders WHERE address = ?", &[SqlValue::Text(address.to_string())], ); rows.first().map(|row| text(&row[0].1)) }; call_tool(&h, &secret, "block_sender", json!({ "address": address })); let first = block_id(&h).expect("the block landed"); call_tool(&h, &secret, "unblock_sender", json!({ "address": address })); assert_eq!(block_id(&h), None, "the unblock left the block standing"); let again = call_tool_raw(&h, &secret, "block_sender", json!({ "address": address })); assert!(!again.is_error, "blocking again after an unblock was refused: {}", again.text); assert_eq!(block_id(&h), Some(first), "the second block did not land live at the first block's id"); assert_eq!( call_tool(&h, &secret, "list_blocked_senders", json!({}))["blocked"] .as_array() .expect("blocked") .len(), 1 ); } // ── the bin (handlers::bin, exercised through the email rows) ─────────────── #[test] fn lists_what_is_waiting_across_kinds_newest_first_counted_per_kind() { let (h, secret) = writer_harness(); let (_quote, news) = seed(&h, &secret); call_tool( &h, &secret, "update_email", json!({ "threadId": news, "bin": true }), ); let out = call_tool(&h, &secret, "list_bin", json!({})); // The conversation is counted once; its own message is listed with it. // New empty Bin kinds must not change these fixture counts. assert_eq!(out["counts"]["email_thread"], 1); assert_eq!(out["counts"]["email"], 0); assert_eq!(out["counts"].as_object().expect("counts").values() .map(|n| n.as_u64().expect("a count")).sum::(), 1); let entries = out["entries"].as_array().expect("entries"); let kinds: Vec = entries.iter().map(|entry| text(&entry["kind"])).collect(); assert_eq!(kinds, vec!["email_thread".to_string()]); assert!(entries .iter() .all(|entry| entry["title"] == "This week at Acme")); } #[test] fn restores_a_row_and_says_so_when_there_was_nothing_to_restore() { let (h, secret) = writer_harness(); let (_quote, news) = seed(&h, &secret); call_tool( &h, &secret, "update_email", json!({ "threadId": news, "bin": true }), ); assert_eq!( call_tool( &h, &secret, "restore_from_bin", json!({ "kind": "email_thread", "id": news }) )["restored"], true ); assert_eq!( call_tool( &h, &secret, "restore_from_bin", json!({ "kind": "email_thread", "id": news }) )["restored"], false ); } #[test] fn empties_the_bin_says_what_it_erased_and_says_what_gmail_still_holds() { let (h, secret) = writer_harness(); let (_quote, news) = seed(&h, &secret); call_tool( &h, &secret, "update_email", json!({ "threadId": news, "bin": true }), ); let out = call_tool_as_owner(&h, "device:phone", "empty_bin", json!({})).json(); assert_eq!(out["erased"]["email"], 1); assert_eq!(out["erased"]["email_thread"], 1); assert_eq!(out["erased"].as_object().expect("erased counts").values() .map(|n| n.as_u64().expect("an erased count")).sum::(), 2); assert_eq!(out["total"], 2); assert_eq!( call_tool(&h, &secret, "list_bin", json!({}))["entries"] .as_array() .expect("entries") .len(), 0 ); // The conversation that was NOT binned is untouched. assert_eq!( call_tool( &h, &secret, "list_email_threads", json!({ "folder": "all" }) )["threads"] .as_array() .expect("threads") .len(), 1 ); } #[test] fn keeps_what_went_in_recently_when_only_the_old_ones_were_asked_for() { let (h, secret) = writer_harness(); let (_quote, news) = seed(&h, &secret); call_tool( &h, &secret, "update_email", json!({ "threadId": news, "bin": true }), ); assert_eq!( call_tool_as_owner(&h, "device:phone", "empty_bin", json!({ "olderThanDays": 30 })).json()["total"], 0 ); } /// RULE: list_bin refuses a kind with no Bin and names every kind that has /// one, read from `BinKind::ALL` — the kind asked about is a primitive whose /// registry entry says it is not binnable, so making a kind binnable (todo, /// 15 Oct 2026) never turns this guard red. #[test] fn refuses_a_kind_that_has_no_bin_naming_the_ones_that_do() { let (h, secret) = writer_harness(); let unbinnable = cotton_core::constants::PrimitiveKind::ALL .into_iter() .find(|kind| !cotton_core::primitives::primitive(*kind).binnable.is_member()) .expect("some primitive kind has no bin"); let out = call_tool_raw(&h, &secret, "list_bin", json!({ "kind": unbinnable.as_str() })); assert!(out.is_error, "{} has no bin: {}", unbinnable.as_str(), out.text); for kind in cotton_core::constants::BinKind::ALL { assert!(out.text.contains(kind.as_str()), "{} missing from: {}", kind.as_str(), out.text); } }