Cotton code
255 lines · 12.0 KB · RustRaw
//! The Junk sweep (the sweep lane, 12 Oct 2026 — the last piece of the Mail//! design): Add to People on a sender, Not junk and Empty Junk now on the Junk//! stack, and the line on the stack's head.//!//! 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, Verdict, Word};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, 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 PHONE: &str = "device:phone";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, name: &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, "name": name }, "to": [{ "email": OWNER }],    })}fn ingest(h: &Harness, secret: &str, emails: Vec<Value>) {    let out = call_tool(h, secret, "ingest_emails", json!({ "emails": emails }));    assert!(out.get("added").is_some(), "{out}");}fn owner(h: &Harness, verb: &str, args: Value) -> Value {    let answer = call_tool_as_owner(h, PHONE, verb, args);    assert!(!answer.is_error, "{verb}: {}", answer.text);    serde_json::from_str(&answer.text).unwrap_or(Value::Null)}fn thread(h: &Harness, key: &str) -> Map<String, Value> {    h.one(        "SELECT id, sender_address, sender_kind, trashed_at FROM cotton_email_threads WHERE external_key = ?1",        &[SqlValue::Text(key.into())],    )    .expect("the thread")}fn kind(h: &Harness, key: &str) -> Option<String> {    thread(h, key).get("sender_kind").and_then(Value::as_str).map(str::to_string)}fn binned(h: &Harness, key: &str) -> bool {    thread(h, key)["trashed_at"].is_string()}fn sender(h: &Harness, address: &str) -> Map<String, Value> {    h.one(        "SELECT kind, decided_by, verdict FROM cotton_email_senders WHERE address = ?1",        &[SqlValue::Text(address.into())],    )    .expect("the sender")}fn blocked(h: &Harness, address: &str) -> bool {    h.one("SELECT 1 AS n FROM cotton_blocked_senders WHERE address = ?1", &[SqlValue::Text(address.into())]).is_some()}/// Every person (live or archived) holding `address` as an email handle.fn holders(h: &Harness, address: &str) -> Vec<String> {    h.all(        "SELECT DISTINCT person_id FROM cotton_person_handles WHERE kind = 'email' AND normalised = ?1",        &[SqlValue::Text(address.into())],    )    .iter()    .filter_map(|row| row.get("person_id").and_then(Value::as_str).map(str::to_string))    .collect()}fn people(h: &Harness) -> i64 {    h.one("SELECT count(*) AS n FROM cotton_people", &[]).expect("a count")["n"].as_i64().unwrap_or_default()}fn as_classifier<T>(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    })}/// RULE: Add to People never makes a second person for a handle already held: it links to the one person (live or archived — an archived one comes back) whose email handle the sender is, makes a person only when nobody holds it, and asked twice makes nothing new. The sender becomes a person, stamped by the owner, and its threads move to the People stack.#[test]fn add_to_people_never_makes_a_second_person_for_a_handle_already_held() {    let (h, secret) = file();    ingest(        &h,        &secret,        vec![            mail("held", "held@letters.example.invalid", "Invented Held", "2026-10-01T09:00:00.000Z"),            mail("gone", "gone@letters.example.invalid", "Invented Gone", "2026-10-01T09:00:00.000Z"),            mail("new", "new@letters.example.invalid", "Invented Newcomer", "2026-10-01T09:00:00.000Z"),        ],    );    let held = owner(&h, "create_person", json!({ "fullName": "Invented Held", "emails": ["held@letters.example.invalid"] }))["id"]        .as_str()        .expect("an id")        .to_string();    let gone = owner(&h, "create_person", json!({ "fullName": "Invented Gone", "emails": ["gone@letters.example.invalid"] }))["id"]        .as_str()        .expect("an id")        .to_string();    owner(&h, "archive_person", json!({ "id": gone }));    let before = people(&h);    let linked = owner(&h, "add_sender_to_people", json!({ "address": "held@letters.example.invalid" }));    assert_eq!(linked["personId"], held.as_str(), "{linked}");    let back = owner(&h, "add_sender_to_people", json!({ "address": "gone@letters.example.invalid" }));    assert_eq!(back["personId"], gone.as_str(), "{back}");    assert_eq!(people(&h), before, "a handle already held made a second person");    assert!(        h.one("SELECT archived_at FROM cotton_people WHERE id = ?1", &[SqlValue::Text(gone.clone())]).expect("the person")["archived_at"]            .is_null(),        "the archived holder did not come back"    );    assert_eq!(kind(&h, "gone").as_deref(), Some("person"));    let made = owner(&h, "add_sender_to_people", json!({ "address": "New@Letters.example.invalid" }));    // RULE: adding a sender answers the new person's create change so its receipt offers Undo; linking an existing person must never pretend to create them.    assert_eq!(made["change"]["verb"], "create", "{made}");    assert_eq!(made["change"]["table"], "person", "{made}");    assert_eq!(made["change"]["record_id"], made["personId"], "{made}");    assert_eq!(made["change"]["undoable"], true, "{made}");    assert_eq!(made["change"]["receipt"]["kind"], "added", "{made}");    assert!(linked.get("change").is_none(), "{linked}");    assert!(back.get("change").is_none(), "{back}");    let again = owner(&h, "add_sender_to_people", json!({ "address": "new@letters.example.invalid" }));    assert!(again.get("change").is_none(), "a retry must not offer Undo of an existing person: {again}");    assert_eq!(made["personId"], again["personId"], "asked twice, two people");    assert_eq!(people(&h), before + 1);    for address in ["held@letters.example.invalid", "gone@letters.example.invalid", "new@letters.example.invalid"] {        assert_eq!(holders(&h, address).len(), 1, "{address} is held by more than one person");        let row = sender(&h, address);        assert_eq!(row["kind"], "person", "{address}");        assert_eq!(row["decided_by"], "owner", "{address}");    }    assert_eq!(kind(&h, "new").as_deref(), Some("person"), "the threads did not move to People");    // Never automatic: an assistant cannot make the act.    let refused = support::mcp::call_tool_raw(&h, &secret, "add_sender_to_people", json!({ "address": "new@letters.example.invalid" }));    assert!(refused.is_error, "an assistant added a sender to People");}/// The command a definition offers on a record, resolved the way the app's/// `records.command` resolves it — its verb, `data`, and each binding read/// from the record's column (or `$id`).fn command_call(table: &str, command: &str, record: &Map<String, Value>) -> (String, Value) {    let definition = cotton_core::definitions::builtin_table_definition(table).expect("a built-in table");    let command = definition        .commands        .as_ref()        .and_then(|commands| commands.iter().find(|candidate| candidate.id == command))        .unwrap_or_else(|| panic!("{table} offers no {command}"));    let mut args = Map::new();    for (key, value) in command.data.iter().flat_map(|data| data.iter()) {        args.insert(key.clone(), value.clone());    }    for (argument, from) in command.bindings.iter().flat_map(|bindings| bindings.iter()) {        let value = if from == "$id" { record["id"].clone() } else { record[from.as_str()].clone() };        args.insert(argument.clone(), value);    }    (command.verb.clone().expect("a verb"), Value::Object(args))}/// RULE: Not junk on a Junk thread whitelists its sender: the thread leaves Junk (service or person by the hard rules), the sender is stamped decided by the owner, the classifier never asks about it again, and a junk verdict handed in for it changes nothing.#[test]fn not_junk_whitelists_so_the_classifier_never_refiles_the_sender() {    let (h, secret) = file();    ingest(&h, &secret, vec![mail("digest", "digest@offers.example.invalid", "An Invented Digest", "2026-10-01T09:00:00.000Z")]);    // The classifier junked it.    let filed = as_classifier(&h, |ctx| {        classify::apply(ctx, &[Verdict { address: "digest@offers.example.invalid".into(), word: Word::Junk, reason: "offers".into() }])            .expect("applies")    });    assert_eq!(filed.junk, 1);    assert_eq!(kind(&h, "digest").as_deref(), Some("junk"));    let (verb, args) = command_call("email_thread", "not_junk", &thread(&h, "digest"));    owner(&h, &verb, args);    assert_eq!(kind(&h, "digest").as_deref(), Some("service"), "Not junk left the thread in Junk");    assert!(!blocked(&h, "digest@offers.example.invalid"));    assert_eq!(sender(&h, "digest@offers.example.invalid")["decided_by"], "owner", "Not junk did not whitelist");    let due = as_classifier(&h, |ctx| classify::due(ctx, classify::PER_PASS).expect("due reads")).ask;    assert!(due.iter().all(|m| m.address != "digest@offers.example.invalid"), "the classifier asks about a whitelisted sender");    let again = as_classifier(&h, |ctx| {        classify::apply(ctx, &[Verdict { address: "digest@offers.example.invalid".into(), word: Word::Junk, reason: "offers".into() }])            .expect("applies")    });    assert_eq!(again.junk, 0, "the classifier re-filed a whitelisted sender");    assert_eq!(kind(&h, "digest").as_deref(), Some("service"));}/// RULE: Empty Junk now bins every Junk conversation at once — the app's own recoverable delete, never an erase — and nothing outside Junk; it is the owner's act only.#[test]fn empty_junk_bins_every_junk_conversation_and_nothing_else() {    let (h, secret) = file();    ingest(        &h,        &secret,        vec![            mail("offers", "offers@shop.example.invalid", "Invented Shop", "2026-10-01T09:00:00.000Z"),            mail("deals", "deals@shop.example.invalid", "Invented Deals", "2026-10-02T09:00:00.000Z"),            mail("friend", "friend@example.invalid", "Invented Friend", "2026-10-02T09:00:00.000Z"),        ],    );    owner(&h, "block_sender", json!({ "address": "offers@shop.example.invalid" }));    owner(&h, "block_sender", json!({ "address": "deals@shop.example.invalid" }));    let refused = support::mcp::call_tool_raw(&h, &secret, "empty_junk", json!({}));    assert!(refused.is_error, "an assistant emptied Junk");    assert!(!binned(&h, "offers"));    let emptied = owner(&h, "empty_junk", json!({}));    assert_eq!(emptied["threads"], 2, "{emptied}");    assert_eq!(emptied["emails"], 2, "{emptied}");    assert!(binned(&h, "offers") && binned(&h, "deals"));    assert!(!binned(&h, "friend"), "Empty Junk binned a conversation outside Junk");    let erased = h.one("SELECT count(*) AS n FROM cotton_emails WHERE trashed_at IS NOT NULL", &[]).expect("a count");    assert_eq!(erased["n"], 2, "Empty Junk bins — it never erases");    assert_eq!(owner(&h, "empty_junk", json!({}))["threads"], 0, "a second empty found more");}