//! Who wrote: the mail reader files every sender as a person, a service or //! junk, and each thread carries its sender's kind — the People, Records and //! Junk stacks key on it (architect, 11 Oct 2026, the three stacks' item 3 (c)). //! //! Every value is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]). mod support; use std::sync::Arc; use cotton_tools::mcp::dispatch::{Ctx, ToolServices}; use cotton_tools::mcp::handlers::emails::junk; use cotton_tools::mcp::handlers::emails::kinds::{self, carries_a_record, is_machine_address}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::Harness; use support::mcp::{call_tool, call_tool_as_owner, call_tool_raw, mint_token}; const OWNER: &str = "owner@example.invalid"; const NOW: &str = "2026-10-05T09:00:00.000Z"; fn file() -> (Harness, String) { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); h.run( "INSERT INTO cotton_google_accounts (id, workspace_id, google_email, created_at, updated_at) VALUES ('google-1', ?1, ?2, ?3, ?3)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(OWNER.into()), SqlValue::Text(NOW.into())], ); (h, secret) } fn mail(key: &str, from: &str, to: &[&str], cc: &[&str], at: &str) -> Value { json!({ "threadKey": key, "subject": format!("An invented subject {key}"), "sentAt": at, "body": "An invented body.", "messageId": format!("<{key}-{at}@example.invalid>"), "from": { "email": from }, "to": to.iter().map(|a| json!({ "email": a })).collect::>(), "cc": cc.iter().map(|a| json!({ "email": a })).collect::>(), }) } fn ingest(h: &Harness, secret: &str, emails: Vec) { let out = call_tool(h, secret, "ingest_emails", json!({ "emails": emails })); assert!(out.get("added").is_some(), "{out}"); } fn kind_of_sender(h: &Harness, address: &str) -> Option { h.one("SELECT kind FROM cotton_email_senders WHERE address = ?1", &[SqlValue::Text(address.into())]) .and_then(|row| row.get("kind").and_then(Value::as_str).map(str::to_string)) } fn kind_of_thread(h: &Harness, key: &str) -> (Option, Option) { let row = h .one( "SELECT sender_address, sender_kind FROM cotton_email_threads WHERE external_key = ?1", &[SqlValue::Text(key.into())], ) .expect("the thread"); let text = |column: &str| row.get(column).and_then(Value::as_str).map(str::to_string); (text("sender_address"), text("sender_kind")) } fn as_reader(h: &Harness, f: impl FnOnce(&mut Ctx<'_>) -> T) -> T { let services = ToolServices::none(); let audit = |_tool: &str, _summary: &str| {}; h.with(|db| { let mut ctx = Ctx::for_worker( db, &h.file, &h.owner_id, cotton_tools::mcp::writer::job("gmail"), "job:gmail", cotton_tools::clock::Clock::now(&h.clock), Arc::clone(&h.random), &services, &audit, ); let out = f(&mut ctx); ctx.commit().expect("commits"); out }) } fn people(h: &Harness) -> i64 { h.count("SELECT count(*) AS n FROM cotton_people", &[]) } /// RULE: A mail the owner sent never makes a person: the address they wrote to (To, not cc, never a list, noreply or bounce address) becomes a sender of kind person, and People stays exactly as it was — a person is made by an act, never by a reader. #[test] fn a_sent_mails_to_never_makes_a_person() { let (h, secret) = file(); let before = people(&h); ingest( &h, &secret, vec![ mail("sent-1", OWNER, &["friend@example.invalid"], &["copied@example.invalid"], "2026-10-01T09:00:00.000Z"), mail("sent-2", OWNER, &["no-reply@shop.example.invalid", "news-bounces@lists.example.invalid"], &[], "2026-10-01T10:00:00.000Z"), mail("in-1", "friend@example.invalid", &[OWNER], &[], "2026-10-02T09:00:00.000Z"), mail("in-2", "copied@example.invalid", &[OWNER], &[], "2026-10-02T10:00:00.000Z"), mail("in-3", "no-reply@shop.example.invalid", &[OWNER], &[], "2026-10-02T11:00:00.000Z"), ], ); assert_eq!(people(&h), before, "the reader made a person"); assert_eq!(kind_of_sender(&h, "friend@example.invalid").as_deref(), Some("person")); assert_eq!(kind_of_sender(&h, "copied@example.invalid").as_deref(), Some("service"), "cc is not written to"); assert_eq!(kind_of_sender(&h, "no-reply@shop.example.invalid").as_deref(), Some("service")); assert_eq!(kind_of_sender(&h, OWNER), None, "the owner is never their own sender"); // A thread the owner started is filed by whom they wrote to. assert_eq!(kind_of_thread(&h, "sent-1"), (Some("friend@example.invalid".into()), Some("person".into()))); assert_eq!(kind_of_thread(&h, "in-1"), (Some("friend@example.invalid".into()), Some("person".into()))); assert_eq!(kind_of_thread(&h, "in-2"), (Some("copied@example.invalid".into()), Some("service".into()))); assert_eq!(kind_of_thread(&h, "in-3").1.as_deref(), Some("service")); } #[test] fn a_machine_address_is_never_written_to() { for address in [ "no-reply@example.invalid", "noreply+abc@example.invalid", "do_not_reply@example.invalid", "mailer-daemon@example.invalid", "bounces+123@example.invalid", "team-request@example.invalid", "anyone@lists.example.invalid", "club@googlegroups.com", ] { assert!(is_machine_address(address), "{address}"); } for address in ["friend@example.invalid", "support@example.invalid", "replies@example.invalid"] { assert!(!is_machine_address(address), "{address}"); } } /// RULE: Someone added to People makes their sender a person on the reader's next pass, and every thread they are the sender of follows into the People stack; the plain list never needs a person to exist. #[test] fn someone_added_to_people_moves_their_threads_into_the_people_stack() { let (h, secret) = file(); ingest(&h, &secret, vec![mail("in-1", "neighbour@example.invalid", &[OWNER], &[], "2026-10-02T09:00:00.000Z")]); assert_eq!(kind_of_thread(&h, "in-1").1.as_deref(), Some("service")); h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('person-1', ?1, 'An Invented Neighbour', ?2, ?2)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); h.run( "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) \ VALUES ('handle-1', ?1, 'person-1', 'email', 'neighbour@example.invalid', 'neighbour@example.invalid', 'manual', ?2, ?2)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); let settled = as_reader(&h, kinds::settle_all).expect("settles"); assert_eq!((settled.senders, settled.threads), (1, 1)); assert_eq!(kind_of_sender(&h, "neighbour@example.invalid").as_deref(), Some("person")); assert_eq!(kind_of_thread(&h, "in-1").1.as_deref(), Some("person")); // Settled is settled: a second pass writes nothing. assert_eq!(as_reader(&h, kinds::settle_all).expect("settles"), kinds::Settled::default()); } /// RULE: The pass after v107 settles every thread stored before it, and ONCE takes a blocked sender's binned mail out of the bin into Junk, local-only: the row is marked synced so nothing goes to Gmail (architect, 11 Oct 2026, the 6,707). #[test] fn the_first_pass_files_a_blocked_senders_binned_mail_into_junk_without_telling_gmail() { let (h, _secret) = file(); let workspace = || SqlValue::Text(h.workspace_id.clone()); h.run( "INSERT INTO cotton_blocked_senders (id, workspace_id, address, created_at) VALUES ('blocked-1', ?1, 'offers@example.invalid', ?2)", &[workspace(), SqlValue::Text(NOW.into())], ); // Stored before v107: no sender kind, the blocked sender's mail binned and // still pending for Gmail, a friend's mail binned by the owner. h.run( "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, trashed_at, created_at, updated_at) VALUES \ ('thread-offers', ?1, 'offers', 'An invented offer', ?2, ?2, 1, ?2, ?2, ?2), \ ('thread-friend', ?1, 'friend', 'An invented note', ?2, ?2, 1, ?2, ?2, ?2)", &[workspace(), SqlValue::Text(NOW.into())], ); h.run( "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, recipients, sent_at, gmail_id, gmail_account, trashed_at, sync_state, created_at) VALUES \ ('email-offers', ?1, 'thread-offers', '', 'offers@example.invalid', '[]', ?2, 'g1', ?3, ?2, 'pending', ?2), \ ('email-friend', ?1, 'thread-friend', '', 'friend@example.invalid', '[]', ?2, 'g2', ?3, ?2, 'synced', ?2)", &[workspace(), SqlValue::Text(NOW.into()), SqlValue::Text(OWNER.into())], ); let settled = as_reader(&h, kinds::settle_all).expect("settles"); assert_eq!(settled.restored, 1); let email = |id: &str| { h.one("SELECT trashed_at, sync_state FROM cotton_emails WHERE id = ?1", &[SqlValue::Text(id.into())]).expect("the email") }; assert_eq!(email("email-offers")["trashed_at"], Value::Null); assert_eq!(email("email-offers")["sync_state"], "synced", "nothing goes to Gmail"); assert!(email("email-friend")["trashed_at"].is_string(), "the owner's own binning stands"); assert_eq!(kind_of_thread(&h, "offers"), (Some("offers@example.invalid".into()), Some("junk".into()))); assert_eq!(kind_of_thread(&h, "friend").1.as_deref(), Some("service")); let thread_binned = h .one("SELECT trashed_at FROM cotton_email_threads WHERE id = 'thread-offers'", &[]) .expect("the thread"); assert_eq!(thread_binned["trashed_at"], Value::Null); // Once: a later pass leaves a junk mail the owner bins in the bin. h.run("UPDATE cotton_emails SET trashed_at = ?1 WHERE id = 'email-offers'", &[SqlValue::Text(NOW.into())]); assert_eq!(as_reader(&h, kinds::settle_all).expect("settles").restored, 0); } fn page(h: &Harness, secret: &str, filter: Value) -> Vec { let answer = call_tool(h, secret, "list_records", json!({ "table": "email_thread", "where": filter, "limit": 50 })); answer["records"] .as_array() .unwrap_or_else(|| panic!("records: {answer}")) .iter() .map(|record| record["data"]["subject"].as_str().unwrap_or_default().to_string()) .collect() } /// RULE: The three stacks are People {sender_kind: person}, Records {sender_kind: service} and Junk {sender_kind: junk}, each a column test on the thread; the plain list leaves Junk out, as it left the bin out when blocking binned. #[test] fn the_stacks_split_the_list_by_sender_kind_and_the_plain_list_leaves_junk_out() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("sent", OWNER, &["friend@example.invalid"], &[], "2026-10-01T09:00:00.000Z"), mail("friend", "friend@example.invalid", &[OWNER], &[], "2026-10-02T09:00:00.000Z"), mail("receipt", "receipts@shop.example.invalid", &[OWNER], &[], "2026-10-03T09:00:00.000Z"), mail("offer", "offers@example.invalid", &[OWNER], &[], "2026-10-04T09:00:00.000Z"), ], ); call_tool(&h, &secret, "block_sender", json!({ "address": "offers@example.invalid" })); let subject = |key: &str| format!("An invented subject {key}"); assert_eq!(page(&h, &secret, json!({ "sender_kind": "person" })), vec![subject("friend"), subject("sent")]); assert_eq!(page(&h, &secret, json!({ "sender_kind": "service" })), vec![subject("receipt")]); assert_eq!(page(&h, &secret, json!({ "sender_kind": "junk" })), vec![subject("offer")]); assert_eq!(page(&h, &secret, json!({})), vec![subject("receipt"), subject("friend"), subject("sent")]); // A sender's own conversations still answer, junk or not. assert_eq!(page(&h, &secret, json!({ "sender_address": "offers@example.invalid" })), vec![subject("offer")]); } /// RULE: A stack's page reads its own threads: asked by sender kind, the threads it builds are the same 50 among 500 threads and 50,000, by the index on (workspace_id, sender_kind, last_at). #[test] fn a_stack_page_costs_its_own_threads() { let steps = |threads: i64| { let (h, secret) = file(); h.run( "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < ?1) \ INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, sender_address, sender_kind, created_at, updated_at) \ SELECT printf('thread-%08d', i), ?2, printf('key-%08d', i), 'An invented subject', \ strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01', printf('+%d minutes', i)), \ strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01', printf('+%d minutes', i)), 1, \ printf('sender%d@example.invalid', i % 40), CASE WHEN i % 10 = 0 THEN 'person' ELSE 'service' END, ?3, ?3 FROM n", &[SqlValue::Integer(threads), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); h.run( "WITH RECURSIVE n(i) AS (SELECT 0 UNION ALL SELECT i + 1 FROM n WHERE i + 1 < ?1) \ INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, sent_at, body, created_at) \ SELECT printf('email-%08d', i), ?2, printf('thread-%08d', i), printf('<%d@example.invalid>', i), \ printf('sender%d@example.invalid', i % 40), strftime('%Y-%m-%dT%H:%M:%fZ', '2026-01-01', printf('+%d minutes', i)), \ 'An invented body.', ?3 FROM n", &[SqlValue::Integer(threads), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); h.db.watch_statements(); assert_eq!(page(&h, &secret, json!({ "sender_kind": "person" })).len(), 50); h.db.steps_by_statement() .into_iter() .filter(|(_, sql)| !sql.contains("NOT EXISTS (SELECT 1 FROM _writes")) .map(|(steps, _)| steps) .sum::() }; let small = steps(500); let large = steps(50_000); // The count walks the stack's threads by index (the phone shows it); the // page is the page's. let per_thread = (large - small) / ((50_000 - 500) / 10); assert!(per_thread <= 40, "a stack page read {large} steps among 50,000 threads and {small} among 500"); } fn senders(h: &Harness, secret: &str, filter: Value) -> Vec<(String, i64, Option, bool)> { let answer = call_tool(h, secret, "list_records", json!({ "table": "email_sender", "where": filter, "limit": 50 })); answer["records"] .as_array() .unwrap_or_else(|| panic!("records: {answer}")) .iter() .map(|record| { let data = &record["data"]; ( data["address"].as_str().unwrap_or_default().to_string(), data["email_count"].as_i64().unwrap_or(-1), data["kind"].as_str().map(str::to_string), data["blocked"].as_bool().unwrap_or(false), ) }) .collect() } /// RULE: The Senders surface is who writes to the owner — one row per address their live mail came from, busiest first, never the owner's own address, with every blocked address beside them and the kind the reader settled; Junk senders is the same list asked for the blocked. #[test] fn the_senders_surface_is_who_writes_busiest_first_and_never_the_owner() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("sent", OWNER, &["friend@example.invalid"], &[], "2026-10-01T09:00:00.000Z"), mail("friend", "friend@example.invalid", &[OWNER], &[], "2026-10-02T09:00:00.000Z"), mail("receipt-1", "receipts@shop.example.invalid", &[OWNER], &[], "2026-10-03T09:00:00.000Z"), mail("receipt-2", "receipts@shop.example.invalid", &[OWNER], &[], "2026-10-03T10:00:00.000Z"), mail("offer", "offers@example.invalid", &[OWNER], &[], "2026-10-04T09:00:00.000Z"), ], ); call_tool(&h, &secret, "block_sender", json!({ "address": "offers@example.invalid" })); call_tool(&h, &secret, "block_sender", json!({ "address": "silent@example.invalid" })); assert_eq!( senders(&h, &secret, json!({})), vec![ ("receipts@shop.example.invalid".to_string(), 2, Some("service".to_string()), false), ("offers@example.invalid".to_string(), 1, Some("junk".to_string()), true), ("friend@example.invalid".to_string(), 1, Some("person".to_string()), false), ("silent@example.invalid".to_string(), 0, Some("junk".to_string()), true), ] ); assert_eq!( senders(&h, &secret, json!({ "blocked": true })).into_iter().map(|row| row.0).collect::>(), vec!["offers@example.invalid".to_string(), "silent@example.invalid".to_string()] ); assert_eq!( senders(&h, &secret, json!({ "kind": "person" })).into_iter().map(|row| row.0).collect::>(), vec!["friend@example.invalid".to_string()] ); // One sender's own record, as a command's receipt reads it. let one = call_tool(&h, &secret, "get_record_by_table", json!({ "table": "email_sender", "id": "receipts@shop.example.invalid" })); assert_eq!(one["data"]["email_count"], 2, "{one}"); assert_eq!(one["data"]["in_people"], false, "{one}"); } /// RULE: Adding a sender to People moves their threads into the People stack at once — create_person and update_person settle the senders their addresses name — and a person is still made only by that act. #[test] fn adding_a_sender_to_people_moves_their_mail_at_once() { let (h, secret) = file(); ingest(&h, &secret, vec![mail("in-1", "neighbour@example.invalid", &[OWNER], &[], "2026-10-02T09:00:00.000Z")]); assert_eq!(kind_of_thread(&h, "in-1").1.as_deref(), Some("service")); let made = call_tool( &h, &secret, "create_person", json!({ "fullName": "An Invented Neighbour", "emails": ["Neighbour@example.invalid"] }), ); assert!(made.get("id").is_some(), "{made}"); assert_eq!(kind_of_sender(&h, "neighbour@example.invalid").as_deref(), Some("person")); assert_eq!(kind_of_thread(&h, "in-1").1.as_deref(), Some("person")); // Their address taken away again: back to Records. let id = made["id"].as_str().expect("an id").to_string(); call_tool(&h, &secret, "update_person", json!({ "id": id, "emails": [] })); assert_eq!(kind_of_thread(&h, "in-1").1.as_deref(), Some("service")); } fn mail_saying(key: &str, from: &str, subject: &str, body: &str) -> Value { json!({ "threadKey": key, "subject": subject, "sentAt": "2026-10-03T09:00:00.000Z", "body": body, "messageId": format!("<{key}@example.invalid>"), "from": { "email": from }, "to": [{ "email": OWNER }], }) } /// RULE: An assistant's block (the classifier's junking) is refused for someone in People, someone the owner has written to, or a sender whose mail carries an amount, an invoice or receipt, a ticket or booking, a one-time code or a delivery; the model's opinion applies only outside those (mail-simplified item 5). #[test] fn an_assistant_never_junks_a_person_or_a_sender_of_records() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("sent", OWNER, &["friend@example.invalid"], &[], "2026-10-01T09:00:00.000Z"), mail_saying("receipt", "orders@shop.example.invalid", "Your receipt for order 1042", "Thank you for shopping."), mail_saying("code", "auth@bank.example.invalid", "Sign in", "Your one-time password is 482913."), mail_saying("parcel", "updates@courier.example.invalid", "Good news", "Your parcel is out for delivery today."), mail_saying("fare", "trips@rail.example.invalid", "Trip summary", "Total charged INR 1,240.00 for your journey."), mail_saying("offer", "deals@letters.example.invalid", "Ten things this week", "An invented newsletter with nothing to keep."), ], ); h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('person-1', ?1, 'An Invented Neighbour', ?2, ?2)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); h.run( "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised, source, created_at, updated_at) \ VALUES ('handle-1', ?1, 'person-1', 'email', 'neighbour@example.invalid', 'neighbour@example.invalid', 'manual', ?2, ?2)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into())], ); for (address, because) in [ ("neighbour@example.invalid", "People"), ("friend@example.invalid", "written to"), ("orders@shop.example.invalid", "an invoice or receipt"), ("auth@bank.example.invalid", "a one-time code"), ("updates@courier.example.invalid", "a delivery"), ("trips@rail.example.invalid", "an amount"), ] { let answer = call_tool_raw(&h, &secret, "block_sender", json!({ "address": address })); assert!(answer.is_error, "{address} was junked by an assistant: {}", answer.text); assert!(answer.text.contains(because), "{address}: {}", answer.text); } assert_eq!(h.count("SELECT count(*) AS n FROM cotton_blocked_senders", &[]), 0); // Outside the rules, the assistant's opinion stands. let junked = call_tool(&h, &secret, "block_sender", json!({ "address": "deals@letters.example.invalid" })); assert_eq!(junked["junk"], 1, "{junked}"); } /// RULE: The owner's own block is an act, never refused by the classifier's rules: the owner may junk anyone, a receipt sender included. #[test] fn the_owner_may_junk_anyone() { let (h, secret) = file(); ingest(&h, &secret, vec![mail_saying("receipt", "orders@shop.example.invalid", "Your receipt for order 1042", "Thanks.")]); let answer = call_tool_as_owner(&h, "device:phone", "block_sender", json!({ "address": "orders@shop.example.invalid" })); assert!(!answer.is_error, "{}", answer.text); assert_eq!(kind_of_thread(&h, "receipt").1.as_deref(), Some("junk")); } #[test] fn a_record_is_named_by_what_it_carries() { for (words, record) in [ ("Payment of $12.50 received", Some("an amount")), ("₹499 debited from your account", Some("an amount")), ("Rs. 2,000 credited", Some("an amount")), ("Your e-ticket and boarding pass", Some("a ticket or booking")), ("Booking confirmed: PNR 4521", Some("a ticket or booking")), ("Use 381920 as your verification code", Some("a one-time code")), ("Your order has shipped", Some("a delivery")), ("Tax invoice for September", Some("an invoice or receipt")), ("Ten things we loved this week", None), ("Join us for the spring fair", None), ] { assert_eq!(carries_a_record(words), record, "{words}"); } } // ── the 30-day Junk clock (mail-simplified item 3, decision 4470cfe6) ───────── fn binned(h: &Harness, key: &str) -> bool { h.one("SELECT trashed_at FROM cotton_email_threads WHERE external_key = ?1", &[SqlValue::Text(key.into())]) .expect("the thread")["trashed_at"] .is_string() } fn purge(h: &Harness) -> junk::Purged { as_reader(h, |ctx| { let mut all = junk::Purged::default(); loop { let (step, more) = junk::purge_step(ctx).expect("purges"); all.threads += step.threads; all.emails += step.emails; if !more { return all; } } }) } /// A blocked sender's mail files into Junk, never the bin, and stays there for /// thirty days from the later of the block and its newest mail; then the /// serving Mac's purge puts it in the bin, where it can still be brought back. /// Nothing younger than thirty days is purged — a sender writing again keeps /// their conversation in Junk for thirty days from that mail — and nothing /// that is not Junk is touched. #[test] fn junk_waits_thirty_days_then_goes_to_the_bin_and_nothing_younger_is_purged() { let (h, secret) = file(); call_tool(&h, &secret, "block_sender", json!({ "address": "offers@example.invalid" })); ingest( &h, &secret, vec![ mail("offers", "offers@example.invalid", &[OWNER], &[], "2026-09-08T09:00:00.000Z"), mail("friend", "friend@example.invalid", &[OWNER], &[], "2026-09-08T09:00:00.000Z"), ], ); assert_eq!(kind_of_thread(&h, "offers").1.as_deref(), Some("junk")); assert!(!binned(&h, "offers"), "a blocked sender's mail goes to Junk, never the bin"); h.clock.advance(chrono::Duration::days(29)); assert_eq!(purge(&h), junk::Purged::default(), "twenty-nine days is not thirty"); // The sender writes again on day 29: the conversation's clock restarts. ingest(&h, &secret, vec![mail("offers", "offers@example.invalid", &[OWNER], &[], "2026-10-07T09:00:00.000Z")]); h.clock.advance(chrono::Duration::days(2)); assert_eq!(purge(&h), junk::Purged::default(), "thirty days from the newest mail, not the first"); assert!(!binned(&h, "offers")); h.clock.advance(chrono::Duration::days(29)); assert_eq!(purge(&h), junk::Purged { threads: 1, emails: 2 }); assert!(binned(&h, "offers"), "past thirty days Junk goes to the bin"); assert!(!binned(&h, "friend"), "only Junk is purged"); assert_eq!(purge(&h), junk::Purged::default(), "a binned conversation is not binned twice"); } /// Mail stored long before its sender was blocked waits thirty days from the /// BLOCK — the 6,707 that came out of the bin start their clock at the block, /// not at the day they arrived. #[test] fn old_mail_from_a_sender_blocked_today_waits_thirty_days_from_the_block() { let (h, secret) = file(); ingest(&h, &secret, vec![mail("offers", "offers@example.invalid", &[OWNER], &[], "2026-09-08T09:00:00.000Z")]); h.clock.advance(chrono::Duration::days(90)); call_tool(&h, &secret, "block_sender", json!({ "address": "offers@example.invalid" })); assert_eq!(kind_of_thread(&h, "offers").1.as_deref(), Some("junk")); assert_eq!(purge(&h), junk::Purged::default(), "blocked today: the mail's age does not count"); h.clock.advance(chrono::Duration::days(31)); assert_eq!(purge(&h).threads, 1); assert!(binned(&h, "offers")); } /// Threads stored unsettled (no sender kind), one mail each, written straight /// into the file as a reader older than v107 left them. fn unsettled(h: &Harness, threads: &[(&str, &str, &str)]) { for (key, from, to) in threads { let workspace = SqlValue::Text(h.workspace_id.clone()); h.run( "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) \ VALUES (?2, ?1, ?3, 'An invented subject', ?4, ?4, 1, ?4, ?4)", &[workspace.clone(), SqlValue::Text(format!("thread-{key}")), SqlValue::Text((*key).into()), SqlValue::Text(NOW.into())], ); h.run( "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, recipients, sent_at, gmail_account, sync_state, created_at) \ VALUES (?2, ?1, ?3, ?4, ?5, ?6, ?7, ?8, 'synced', ?7)", &[ workspace, SqlValue::Text(format!("email-{key}")), SqlValue::Text(format!("thread-{key}")), SqlValue::Text(format!("<{key}@example.invalid>")), SqlValue::Text((*from).into()), SqlValue::Text(json!([{ "email": to }]).to_string()), SqlValue::Text(NOW.into()), SqlValue::Text(OWNER.into()), ], ); } } /// One settle step as the gmail pass runs it — its own hold — and the /// statements' steps it read (SQLite's own count, which a machine's load /// cannot move). Straight on the driver: the archive rows a test writes in /// bulk carry no receipts, and nothing here writes them. fn one_settle_step(h: &Harness) -> (bool, u64) { let services = ToolServices::none(); let audit = |_tool: &str, _summary: &str| {}; let before = h.db.steps(); let mut ctx = Ctx::for_worker( &h.db, &h.file, &h.owner_id, cotton_tools::mcp::writer::job("gmail"), "job:gmail", cotton_tools::clock::Clock::now(&h.clock), Arc::clone(&h.random), &services, &audit, ); let (_, more) = kinds::settle_step(&mut ctx).expect("settles"); ctx.commit().expect("commits"); (more, h.db.steps() - before) } /// RULE: a settle step reads in proportion to the threads it settles, never to the archive — seven unsettled threads cost the same in a file of half a million mails as in an empty one. /// 12 Oct 2026: every step asked who the owner had ever written to by reading every mail in the file — 2,253,437 steps, 5.5 s inside the gmail pass's write hold on the owner's Mac, for seven facts — while every other writer waited. #[test] fn a_settle_step_reads_its_own_threads_never_the_whole_archive() { const ARCHIVE: i64 = 500_000; let seven: Vec<(String, String)> = (0..7).map(|i| (format!("new-{i}"), format!("sender-{i}@example.invalid"))).collect(); let threads: Vec<(&str, &str, &str)> = seven.iter().map(|(key, from)| (key.as_str(), from.as_str(), OWNER)).collect(); let (empty, _secret) = file(); unsettled(&empty, &threads); let (more, small) = one_settle_step(&empty); assert!(more, "the step settled threads"); let (large, _secret) = file(); let workspace = SqlValue::Text(large.workspace_id.clone()); large.run( "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, sender_address, sender_kind, first_at, last_at, email_count, created_at, updated_at) \ VALUES ('thread-archive', ?1, 'archive', 'An invented archive', 'friend@example.invalid', 'person', ?2, ?2, 1, ?2, ?2)", &[workspace.clone(), SqlValue::Text(NOW.into())], ); unsettled(&large, &threads); // Twelve years of mail, settled long ago: half the owner's own, sent to // someone; half sent to them. Straight on the driver and last — half a // million receipts are not what this measures, and `Harness::run` gives // every row without one its receipt. large .db .run( "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ?3) \ INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, recipients, sent_at, gmail_account, sync_state, created_at) \ SELECT 'archive-' || i, ?1, 'thread-archive', '', \ CASE i % 2 WHEN 0 THEN ?2 ELSE 'friend@example.invalid' END, \ CASE i % 2 WHEN 0 THEN '[{\"email\":\"friend@example.invalid\"}]' ELSE '[]' END, \ ?4, ?2, 'synced', ?4 FROM n", &[workspace, SqlValue::Text(OWNER.into()), SqlValue::Integer(ARCHIVE), SqlValue::Text(NOW.into())], ) .expect("the archive lands"); let (more, steps) = one_settle_step(&large); assert!(more, "the step settled threads"); assert!( steps <= small * 2, "seven threads read {steps} steps beside {ARCHIVE} mails, {small} in an empty file" ); assert!(steps < u64::try_from(ARCHIVE).unwrap_or(u64::MAX), "a step read {steps} steps: the archive, not its threads"); assert_eq!(kind_of_thread(&large, "new-0").1.as_deref(), Some("service")); } /// RULE: whom the owner wrote to is learnt from the threads a step settles, and a sender found written to in a LATER step becomes a person there, its threads settled earlier moving with it — no step reads the whole archive to know it first. #[test] fn a_sender_written_to_in_a_later_step_takes_its_earlier_threads_to_people() { let (h, _secret) = file(); // A friend's thread first, then more threads than one step settles, then // the owner's own mail to the friend — two steps apart. let filler: Vec<(String, String)> = (0..200).map(|i| (format!("filler-{i}"), format!("shop-{i}@example.invalid"))).collect(); let mut threads: Vec<(&str, &str, &str)> = vec![("from-friend", "friend@example.invalid", OWNER)]; threads.extend(filler.iter().map(|(key, from)| (key.as_str(), from.as_str(), OWNER))); threads.push(("to-friend", OWNER, "friend@example.invalid")); unsettled(&h, &threads); assert!(one_settle_step(&h).0, "more than one step's threads"); as_reader(&h, kinds::settle_all).expect("settles"); assert_eq!(kind_of_sender(&h, "friend@example.invalid").as_deref(), Some("person")); assert_eq!(kind_of_thread(&h, "from-friend").1.as_deref(), Some("person")); assert_eq!(kind_of_thread(&h, "to-friend").1.as_deref(), Some("person")); }