//! Records filled in by the model (the junk lane, brief 2, 12 Oct 2026): a //! service thread the rules left a `notice`, or with a field empty, is asked //! about once — what it may send, what it may write, and what it never //! touches. The model's answers are handed in as its forced tool's input, so //! each rule is held on the real reads, the real validation 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_store::actor::Actor; use cotton_tools::mcp::dispatch::{Ctx, ToolServices}; use cotton_tools::mcp::handlers::emails::extract::{self, Material}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use support::harness::Harness; use support::mcp::{call_tool, 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, subject: &str, body: &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 Shop" }, "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}"); } fn as_actor(h: &Harness, actor: Actor, label: &'static str, 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, actor, label, cotton_tools::clock::Clock::now(&h.clock), Arc::clone(&h.random), &services, &audit, ); let out = f(&mut ctx); ctx.commit().expect("commits"); out }) } fn as_extractor(h: &Harness, f: impl FnOnce(&mut Ctx<'_>) -> T) -> T { as_actor(h, cotton_tools::mcp::writer::job("junk"), "job:junk", f) } fn due(h: &Harness) -> Vec { as_extractor(h, |ctx| extract::due(ctx, extract::PER_HOUR).expect("due reads")) } /// Hand the model's answer in, as the worker does. fn answer(h: &Harness, asked: &[Material], said: Value) -> extract::Extracted { let answers = extract::answers(&said, asked); as_extractor(h, |ctx| extract::apply(ctx, asked, &answers).expect("answers apply")) } fn thread_id(h: &Harness, key: &str) -> String { h.one("SELECT id FROM cotton_email_threads WHERE external_key = ?1", &[SqlValue::Text(key.into())]) .and_then(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) .unwrap_or_else(|| panic!("no thread {key}")) } fn record(h: &Harness, key: &str) -> Map { h.one( "SELECT record_kind, amount_minor, currency, merchant, record_on, reference, record_reason \ FROM cotton_email_threads WHERE external_key = ?1", &[SqlValue::Text(key.into())], ) .unwrap_or_else(|| panic!("no thread {key}")) } fn keys(h: &Harness, asked: &[Material]) -> Vec { let mut out: Vec = asked .iter() .map(|material| { h.one("SELECT external_key FROM cotton_email_threads WHERE id = ?1", &[SqlValue::Text(material.thread_id.clone())]) .and_then(|row| row.get("external_key").and_then(Value::as_str).map(str::to_string)) .unwrap_or_default() }) .collect(); out.sort(); out } /// RULE: A person's thread is never sent to the model, however notice-like its subject: only a service's thread is asked about, and an answer naming a person's thread writes nothing. #[test] fn a_person_thread_is_never_sent_to_the_model() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("sent", OWNER, "friend@example.invalid", "About Saturday", "Are we on?", "2026-10-01T08:00:00.000Z"), mail("friend", "friend@example.invalid", OWNER, "A quick update", "PRIVATE-WORDS-91 between friends.", "2026-10-01T09:00:00.000Z"), mail("shop", "hello@shop.example.invalid", OWNER, "A quick update", "Your account changed.", "2026-10-01T10:00:00.000Z"), ], ); let asked = due(&h); assert_eq!(keys(&h, &asked), vec!["shop".to_string()], "only the service's thread is asked about"); let said = extract::prompt(&asked); assert!(!said.contains("PRIVATE-WORDS-91"), "a person's words reached the model: {said}"); // An answer that names the person's thread anyway is not written. let friend = thread_id(&h, "friend"); let mut forged = asked.clone(); forged.push(Material { thread_id: friend.clone(), subject: "A quick update".into(), body_head: String::new(), sender: None }); answer( &h, &forged, json!({ "threads": [{ "thread": friend, "kind": "receipt", "merchant": "An Invented Shop" }] }), ); let row = record(&h, "friend"); assert!(row["record_kind"].is_null() && row["merchant"].is_null() && row["record_reason"].is_null(), "{row:?}"); } /// RULE: A record field the owner edited is never overwritten, and a thread the owner edited is never asked about again; the model only fills fields that are still empty. #[test] fn an_owner_edited_field_is_never_overwritten() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("edited", "hello@one.example.invalid", OWNER, "Your account", "Thanks for being with us.", "2026-10-01T09:00:00.000Z"), mail("partial", "orders@two.example.invalid", OWNER, "Your receipt", "Thanks for shopping at Two.", "2026-10-01T10:00:00.000Z"), ], ); // The owner names the first thread's merchant at their own screen. let edited = thread_id(&h, "edited"); let owner = h.with(|db| support::mcp::owner_at(db, &h.workspace_id, "phone-invented-1")); as_actor(&h, owner, "owner", |ctx| { let mut patch = Map::new(); patch.insert("merchant".into(), Value::from("The Owner's Name For It")); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_email_threads", &edited, patch).expect("the owner edits"); }); // The second already carries a merchant the rules lifted. h.run("UPDATE cotton_email_threads SET merchant = 'Two' WHERE external_key = 'partial'", &[]); let asked = due(&h); assert_eq!(keys(&h, &asked), vec!["partial".to_string()], "the owner's thread was asked about"); let mut every = asked.clone(); every.push(Material { thread_id: edited.clone(), subject: "Your account".into(), body_head: String::new(), sender: None }); let partial = thread_id(&h, "partial"); answer( &h, &every, json!({ "threads": [ { "thread": edited, "kind": "receipt", "merchant": "A Model's Guess", "amount": "12.00", "currency": "EUR" }, { "thread": partial, "kind": "receipt", "merchant": "A Model's Other Guess", "amount": "40.50", "currency": "EUR" }, ]}), ); let owners = record(&h, "edited"); assert_eq!(owners["merchant"], "The Owner's Name For It"); assert!(owners["amount_minor"].is_null() && owners["record_reason"].is_null(), "{owners:?}"); let filled = record(&h, "partial"); assert_eq!(filled["merchant"], "Two", "a field already filled was overwritten"); assert_eq!(filled["amount_minor"], 4050); assert_eq!(filled["currency"], "EUR"); assert!(filled["record_reason"].as_str().is_some_and(|line| line.contains("took") && line.contains("amount")), "{filled:?}"); assert!(due(&h).is_empty(), "a thread asked once was asked again"); // New mail makes the rules type both threads afresh: the owner's field // stands; the model's line is cleared on the thread whose record changed. ingest( &h, &secret, vec![ mail("edited", "hello@one.example.invalid", OWNER, "Your receipt", "Paid EUR 9.00 at One.", "2026-10-02T09:00:00.000Z"), mail("partial", "orders@two.example.invalid", OWNER, "Your receipt", "Paid EUR 41.00 at Two.", "2026-10-02T10:00:00.000Z"), ], ); assert_eq!(record(&h, "edited")["merchant"], "The Owner's Name For It", "the rules wrote over the owner"); let retyped = record(&h, "partial"); assert!(retyped["record_reason"].is_null(), "{retyped:?}"); } /// RULE: A one-time code is never stored: a code thread is never asked about, a model that calls a thread a code keeps only its kind and merchant, a reference that is the code the mail carries is dropped, and the reason line names fields, never values. #[test] fn a_one_time_code_is_never_stored() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("typed", "auth@bank.example.invalid", OWNER, "Your one-time password", "Use 482913 to sign in.", "2026-10-01T09:00:00.000Z"), mail("hidden", "hello@app.example.invalid", OWNER, "Sign in to App", "Welcome back. Enter 731846 in the app to continue.", "2026-10-01T10:00:00.000Z"), mail("quoted", "hello@store.example.invalid", OWNER, "Your order", "Order placed. Your pickup code: 559201.", "2026-10-01T11:00:00.000Z"), ], ); let asked = due(&h); assert!(!keys(&h, &asked).contains(&"typed".to_string()), "a code thread was asked about"); let hidden = thread_id(&h, "hidden"); let quoted = thread_id(&h, "quoted"); answer( &h, &asked, json!({ "threads": [ { "thread": hidden, "kind": "code", "merchant": "App", "reference": "731846", "amount": "7318.46", "currency": "USD", "on": "2026-10-01" }, { "thread": quoted, "kind": "receipt", "merchant": "Store", "reference": "559201" }, ]}), ); let code = record(&h, "hidden"); assert_eq!(code["record_kind"], "code"); assert_eq!(code["merchant"], "App"); assert!(code["reference"].is_null() && code["amount_minor"].is_null() && code["record_on"].is_null(), "{code:?}"); let receipt = record(&h, "quoted"); assert!(receipt["reference"].is_null(), "a code was kept as a reference: {receipt:?}"); for key in ["hidden", "quoted", "typed"] { let line = record(&h, key)["record_reason"].as_str().unwrap_or_default().to_string(); for digits in ["482913", "731846", "559201"] { assert!(!line.contains(digits), "{key}'s reason line carries a code: {line}"); } } let stored = h.count( "SELECT count(*) AS n FROM cotton_email_threads WHERE reference IN ('482913', '731846', '559201') \ OR merchant IN ('482913', '731846', '559201')", &[], ); assert_eq!(stored, 0); } /// RULE: The model's answer is validated against the columns before anything is written: a kind outside the list, a currency that is not three letters, an amount that is not a positive figure in that currency's digits, a date that is not a real calendar day, an overlong or multi-line merchant and a reference with characters no reference has are each dropped — never coerced — and what is valid beside them is kept. #[test] fn the_answer_is_validated_against_the_columns_before_it_is_written() { let asked = vec![ Material { thread_id: "t-bad".into(), subject: "Your account".into(), body_head: String::new(), sender: None }, Material { thread_id: "t-good".into(), subject: "Your receipt".into(), body_head: String::new(), sender: None }, ]; let said = json!({ "threads": [ { "thread": "t-bad", "kind": "invoice", "amount": "-5", "currency": "rupees", "on": "2026-02-30", "merchant": "x".repeat(300), "reference": "1; DROP TABLE cotton_email_threads" }, { "thread": "t-good", "kind": "receipt", "amount": "1,240.5", "currency": "inr", "on": "2026-10-03", "merchant": "An Invented Shop", "reference": "ORD-1042/A" }, { "thread": "t-elsewhere", "kind": "receipt", "merchant": "Not asked" }, ]}); let read = extract::answers(&said, &asked); assert_eq!(read.len(), 2, "{read:?}"); let bad = read.iter().find(|a| a.thread_id == "t-bad").expect("the bad answer is read"); assert_eq!((bad.kind, &bad.amount, &bad.merchant, &bad.on, &bad.reference), (None, &None, &None, &None, &None), "{bad:?}"); let good = read.iter().find(|a| a.thread_id == "t-good").expect("the good answer is read"); assert_eq!(good.kind, Some("receipt")); assert_eq!(good.amount, Some(("INR".to_string(), 124_050))); assert_eq!(good.on.as_deref(), Some("2026-10-03")); assert_eq!(good.merchant.as_deref(), Some("An Invented Shop")); assert_eq!(good.reference.as_deref(), Some("ORD-1042/A")); // A currency with no figure, or a figure with no currency, is neither. let lone = extract::answers( &json!({ "threads": [{ "thread": "t-good", "currency": "EUR" }, { "thread": "t-bad", "amount": "3.00" }] }), &asked, ); assert!(lone.iter().all(|a| a.amount.is_none()), "{lone:?}"); // A figure finer than its currency's digits is unsure, so dropped. let fine = extract::answers(&json!({ "threads": [{ "thread": "t-good", "amount": "3.005", "currency": "EUR" }] }), &asked); assert!(fine[0].amount.is_none(), "{fine:?}"); } /// RULE: The model sees a thread's subject and at most the first 2 KB of its newest service mail's body, and nothing past that. #[test] fn the_material_is_the_subject_and_the_first_two_kilobytes() { let (h, secret) = file(); let body = format!("{}TAIL-SENTINEL-55", "é".repeat(1500)); ingest(&h, &secret, vec![mail("long", "hello@long.example.invalid", OWNER, "Your account", &body, "2026-10-01T09:00:00.000Z")]); let asked = due(&h); assert_eq!(asked.len(), 1); assert!(asked[0].body_head.len() <= extract::BODY_BYTES, "{}", asked[0].body_head.len()); assert!(!extract::prompt(&asked).contains("TAIL-SENTINEL")); assert!(extract::prompt(&asked).contains("Your account")); }