//! The hourly junk classifier's rules (the junk lane, 12 Oct 2026): what it //! asks the Connected AI about, what it may write, and what it never touches. //! The model itself is the server's; here its answers are handed in as //! verdicts, so each rule is held on the real reads and the real writes. //! //! 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::classify::{self, Material, Verdict, Word}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use support::harness::Harness; use support::mcp::{call_tool, call_tool_as_owner, mint_token}; const OWNER: &str = "owner@example.invalid"; const NOW: &str = "2026-10-05T09:00:00.000Z"; const BODY: &str = "BODY-SENTINEL-7f3a never leaves the file"; 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, subject: &str, at: &str) -> Value { json!({ "threadKey": key, "subject": subject, "sentAt": at, "body": BODY, "messageId": format!("<{key}-{at}@example.invalid>"), "from": { "email": from, "name": "An Invented Sender" }, "to": [{ "email": to }], }) } 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}"); } /// The classifier's own context: a job of the serving Mac, never the owner. fn as_classifier(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("junk"), "job:junk", cotton_tools::clock::Clock::now(&h.clock), Arc::clone(&h.random), &services, &audit, ); let out = f(&mut ctx); ctx.commit().expect("commits"); out }) } fn due(h: &Harness) -> Vec { as_classifier(h, |ctx| classify::due(ctx, classify::PER_PASS).expect("due reads")).ask } fn apply(h: &Harness, verdicts: &[Verdict]) -> classify::Applied { as_classifier(h, |ctx| classify::apply(ctx, verdicts).expect("verdicts apply")) } fn says(address: &str, word: Word, reason: &str) -> Verdict { Verdict { address: address.into(), word, reason: reason.into() } } fn addresses(materials: &[Material]) -> Vec { let mut out: Vec = materials.iter().map(|m| m.address.clone()).collect(); out.sort(); out } fn sender(h: &Harness, address: &str) -> serde_json::Map { h.one( "SELECT kind, decided_by, verdict, reason FROM cotton_email_senders WHERE address = ?1", &[SqlValue::Text(address.into())], ) .unwrap_or_else(|| panic!("no sender row for {address}")) } fn blocked(h: &Harness, address: &str) -> bool { h.count( "SELECT count(*) AS n FROM cotton_blocked_senders WHERE address = ?1", &[SqlValue::Text(address.into())], ) > 0 } /// RULE: A sender the owner touched — junked or kept on the Senders surface — is never decided again by the classifier: it is never asked about, and a verdict handed in for it changes nothing; the owner's act is final. #[test] fn a_sender_the_owner_touched_is_never_decided_again() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("kept", "letters@kept.example.invalid", OWNER, "This week's letter", "2026-10-01T09:00:00.000Z"), mail("junked", "offers@junked.example.invalid", OWNER, "A deal for you", "2026-10-01T10:00:00.000Z"), mail("model", "digest@model.example.invalid", OWNER, "Your digest", "2026-10-01T11:00:00.000Z"), ], ); // The owner junks one and keeps it again; junks another and leaves it. for (verb, address) in [ ("block_sender", "letters@kept.example.invalid"), ("unblock_sender", "letters@kept.example.invalid"), ("block_sender", "offers@junked.example.invalid"), ] { let answer = call_tool_as_owner(&h, "device:phone", verb, json!({ "address": address })); assert!(!answer.is_error, "{verb} {address}: {}", answer.text); } // The classifier junks the third; the owner keeps it. let applied = apply(&h, &[says("digest@model.example.invalid", Word::Junk, "newsletter, never opened")]); assert_eq!(applied.junk, 1); assert!(blocked(&h, "digest@model.example.invalid")); let answer = call_tool_as_owner(&h, "device:phone", "unblock_sender", json!({ "address": "digest@model.example.invalid" })); assert!(!answer.is_error, "{}", answer.text); assert!(due(&h).is_empty(), "the classifier asked about a sender the owner touched"); let applied = apply( &h, &[ says("letters@kept.example.invalid", Word::Junk, "newsletter"), says("offers@junked.example.invalid", Word::Service, "a shop"), says("digest@model.example.invalid", Word::Junk, "newsletter, never opened"), ], ); assert_eq!((applied.junk, applied.service, applied.person), (0, 0, 0), "{applied:?}"); assert!(!blocked(&h, "letters@kept.example.invalid"), "the owner's Keep was overridden"); assert!(blocked(&h, "offers@junked.example.invalid"), "the owner's Junk was overridden"); assert!(!blocked(&h, "digest@model.example.invalid"), "the owner's Keep after the classifier was overridden"); for address in ["letters@kept.example.invalid", "offers@junked.example.invalid", "digest@model.example.invalid"] { assert_eq!(sender(&h, address)["decided_by"], "owner", "{address}"); } assert_eq!(sender(&h, "offers@junked.example.invalid")["kind"], "junk"); assert_eq!(sender(&h, "digest@model.example.invalid")["kind"], "service"); } /// RULE: The hard rules run first and win over the model: a model that says junk to every sender junks none in People, none the owner writes to, and none whose mail carries a receipt, an amount, a ticket, a code or a delivery — those are held without asking the model. #[test] fn the_hard_rules_win_over_a_model_that_says_junk_to_everyone() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("sent", OWNER, "friend@example.invalid", "Dinner on Friday?", "2026-10-01T08:00:00.000Z"), mail("friend", "friend@example.invalid", OWNER, "Re: Dinner on Friday?", "2026-10-01T09:00:00.000Z"), mail("neighbour", "neighbour@example.invalid", OWNER, "The parcel by the door", "2026-10-01T09:30:00.000Z"), mail("receipt", "orders@shop.example.invalid", OWNER, "Your receipt for order 1042", "2026-10-01T10:00:00.000Z"), mail("ticket", "trips@rail.example.invalid", OWNER, "Your e-ticket", "2026-10-01T11:00:00.000Z"), mail("news", "letters@news.example.invalid", OWNER, "Ten things this week", "2026-10-01T12:00:00.000Z"), ], ); 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())], ); // Asked: only the sender no rule holds. let asked = as_classifier(&h, |ctx| classify::due(ctx, classify::PER_PASS).expect("due reads")); assert_eq!(addresses(&asked.ask), vec!["letters@news.example.invalid".to_string()]); assert!(asked.held >= 2, "the record senders were not held by the rules: {}", asked.held); let everyone = [ "friend@example.invalid", "neighbour@example.invalid", "orders@shop.example.invalid", "trips@rail.example.invalid", "letters@news.example.invalid", ]; let verdicts: Vec = everyone.iter().map(|a| says(a, Word::Junk, "looks like junk")).collect(); apply(&h, &verdicts); for address in &everyone[..4] { assert!(!blocked(&h, address), "{address} was junked over the hard rules"); } assert!(blocked(&h, "letters@news.example.invalid")); assert_eq!(sender(&h, "letters@news.example.invalid")["reason"], "junk: looks like junk"); let receipt = sender(&h, "orders@shop.example.invalid"); assert_eq!(receipt["kind"], "service"); assert!(receipt["reason"].as_str().is_some_and(|r| r.contains("receipt")), "{receipt:?}"); } /// RULE: A sender already decided — by the classifier or by a rule — costs no model call again: it is never in the next pass's asking, however much new mail it sends, while a new sender is. #[test] fn a_decided_sender_is_never_asked_again() { let (h, secret) = file(); ingest(&h, &secret, vec![mail("a", "digest@one.example.invalid", OWNER, "Your digest", "2026-10-01T09:00:00.000Z")]); assert_eq!(addresses(&due(&h)), vec!["digest@one.example.invalid".to_string()]); let applied = apply(&h, &[says("digest@one.example.invalid", Word::Service, "a service's updates")]); assert_eq!(applied.service, 1); assert!(due(&h).is_empty()); ingest( &h, &secret, vec![ mail("b", "digest@one.example.invalid", OWNER, "Your digest again", "2026-10-02T09:00:00.000Z"), mail("c", "hello@two.example.invalid", OWNER, "Welcome aboard", "2026-10-02T10:00:00.000Z"), ], ); assert_eq!(addresses(&due(&h)), vec!["hello@two.example.invalid".to_string()]); // A person verdict files their threads with People's, below the hard rules. apply(&h, &[says("hello@two.example.invalid", Word::Person, "writes in their own words")]); assert_eq!(sender(&h, "hello@two.example.invalid")["kind"], "person"); assert!(due(&h).is_empty()); } /// RULE: The classifier reads no body text: what it hands the model is a sender's name, address, the subjects of its last five threads and its counts — never a body or a snippet. #[test] fn the_material_is_subjects_and_counts_never_a_body() { let (h, secret) = file(); let mails: Vec = (0..7) .map(|n| { mail( &format!("t{n}"), "letters@news.example.invalid", OWNER, &format!("Letter number {n}"), &format!("2026-10-0{}T09:00:00.000Z", n + 1), ) }) .collect(); ingest(&h, &secret, mails); h.run("UPDATE cotton_emails SET unread = 1", &[]); h.run( "UPDATE cotton_emails SET unread = 0 WHERE subject IN ('Letter number 0', 'Letter number 1')", &[], ); let asked = due(&h); assert_eq!(asked.len(), 1); let material = &asked[0]; assert_eq!(material.mail, 7); assert_eq!(material.opened, 2); assert_eq!(material.subjects.len(), classify::SUBJECTS); assert_eq!(material.subjects[0], "Letter number 6", "newest thread first"); let said = classify::prompt(&asked); assert!(said.contains("Letter number 6") && said.contains("letters@news.example.invalid"), "{said}"); assert!(!said.contains("BODY-SENTINEL"), "a body reached the model's material: {said}"); assert!(!said.contains("Letter number 1"), "more than five subjects: {said}"); } /// RULE: The model's answer is read for the senders it was asked about and nothing else: an address it invents, or a word that is not person, service or junk, is dropped. #[test] fn an_answer_is_read_only_for_the_senders_asked() { let asked = vec![Material { address: "letters@news.example.invalid".into(), name: None, subjects: vec!["Ten things".into()], mail: 3, opened: 0, }]; let answer = json!({ "senders": [ { "address": "letters@news.example.invalid", "kind": "junk", "reason": "newsletter, never opened" }, { "address": "someone@else.example.invalid", "kind": "junk", "reason": "invented" }, { "address": "letters@news.example.invalid", "kind": "spam", "reason": "not a word" }, ]}); let read = classify::verdicts(&answer, &asked); assert_eq!(read.len(), 1); assert_eq!(read[0].address, "letters@news.example.invalid"); assert_eq!(read[0].word, Word::Junk); assert_eq!(read[0].reason, "newsletter, never opened"); }