172 lines · 7.9 KB · RustRaw
//! Records typed by kind (architect, 11 Oct 2026: "mail from companies is//! records, not mail"): the reader types a SERVICE thread — receipt,//! statement, ticket, booking, code, delivery or notice — and lifts its//! amount, merchant, date and reference; a thread that is no service's carries//! none of it.//!//! 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::kinds;use rusqlite::types::Value as SqlValue;use serde_json::{json, 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";const SHOP: &str = "receipts@shop.example.invalid";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, 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, "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}");}/// The thread's typed columns, by its key.fn record(h: &Harness, key: &str) -> Value { let row = h .one( "SELECT sender_kind, record_kind, amount_minor, currency, merchant, record_on, reference \ FROM cotton_email_threads WHERE external_key = ?1", &[SqlValue::Text(key.into())], ) .expect("the thread"); Value::Object(row)}fn as_reader<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("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 page(h: &Harness, secret: &str, filter: Value) -> Vec<String> { 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 reader types a service thread the moment its mail lands — kind, amount, merchant, the date it is about and its reference — and a page of one kind is a column test on the thread.#[test]fn a_service_thread_is_typed_as_it_lands_and_a_kind_is_its_own_page() { let (h, secret) = file(); ingest( &h, &secret, vec![ mail("coffee", SHOP, "Synthetic Coffee", "Your receipt from Synthetic Coffee", "Order number: SC-10442\nPaid on 3 Oct 2026\nTotal: ₹300.00"), mail("rail", "tickets@rail.example.invalid", "Example Rail", "E-ticket: Bengaluru to Pune", "PNR: 4711XQ\nDate of journey: 18 Oct 2026"), mail("terms", "news@example.invalid", "Example", "Updates to our terms", "Nothing to keep."), ], ); assert_eq!( record(&h, "coffee"), json!({"sender_kind":"service","record_kind":"receipt","amount_minor":30000,"currency":"INR","merchant":"Synthetic Coffee","record_on":"2026-10-03","reference":"SC-10442"}) ); assert_eq!(record(&h, "rail")["record_on"], "2026-10-18"); assert_eq!( record(&h, "terms"), json!({"sender_kind":"service","record_kind":"notice","amount_minor":null,"currency":null,"merchant":null,"record_on":null,"reference":null}) ); assert_eq!(page(&h, &secret, json!({ "record_kind": "receipt" })), vec!["Your receipt from Synthetic Coffee"]); assert_eq!(page(&h, &secret, json!({ "record_kind": "ticket" })), vec!["E-ticket: Bengaluru to Pune"]); // Settled is settled: a second pass writes nothing. assert_eq!(as_reader(&h, kinds::settle_all).expect("settles"), kinds::Settled::default());}/// RULE: A thread whose sender is a person never carries a record kind: a friend's "receipt" is mail, and a sender who becomes someone in People takes every record field off their threads at once.#[test]fn a_person_thread_never_gets_a_record_kind() { let (h, secret) = file(); let mut to_friend = mail("sent", OWNER, "Owner", "Lunch", "See you"); to_friend["to"] = json!([{ "email": "friend@example.invalid" }]); ingest(&h, &secret, vec![to_friend]); ingest(&h, &secret, vec![mail("friend", "friend@example.invalid", "A Friend", "Your receipt for lunch", "Total: ₹450")]); assert_eq!(record(&h, "friend")["sender_kind"], "person"); assert_eq!(record(&h, "friend")["record_kind"], Value::Null); ingest(&h, &secret, vec![mail("shop", SHOP, "Synthetic Coffee", "Your receipt", "Total: ₹300")]); assert_eq!(record(&h, "shop")["record_kind"], "receipt"); h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES ('person-1', ?1, 'An Invented Barista', ?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', ?3, ?3, 'manual', ?2, ?2)", &[SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(NOW.into()), SqlValue::Text(SHOP.into())], ); as_reader(&h, kinds::settle_all).expect("settles"); assert_eq!( record(&h, "shop"), json!({"sender_kind":"person","record_kind":null,"amount_minor":null,"currency":null,"merchant":null,"record_on":null,"reference":null}) );}/// RULE: A one-time code is never stored: a code mail's thread is typed code with its merchant, and its digits are nowhere on the thread.#[test]fn a_one_time_code_is_typed_and_its_digits_are_never_stored_on_the_thread() { let (h, secret) = file(); ingest(&h, &secret, vec![mail("otp", "noreply@bank.example.invalid", "Example Bank", "Your OTP", "482913 is your one-time password. Ref TXN99123.")]); let row = record(&h, "otp"); assert_eq!(row["record_kind"], "code"); assert_eq!(row["merchant"], "Example Bank"); assert!(!row.to_string().contains("482913") && !row.to_string().contains("TXN99123"), "{row}");}/// RULE: The pass after v111 types every service thread settled before it, a step at a time, and then has nothing left to type.#[test]fn the_pass_types_service_threads_settled_before_records_had_kinds() { let (h, secret) = file(); ingest(&h, &secret, vec![mail("coffee", SHOP, "Synthetic Coffee", "Your receipt", "Total: ₹300")]); h.run( "UPDATE cotton_email_threads SET record_kind = NULL, amount_minor = NULL, currency = NULL, merchant = NULL", &[], ); let settled = as_reader(&h, kinds::settle_all).expect("settles"); assert_eq!(settled.threads, 1); assert_eq!(record(&h, "coffee")["record_kind"], "receipt"); assert_eq!(record(&h, "coffee")["amount_minor"], 30000); assert_eq!(as_reader(&h, kinds::settle_all).expect("settles"), kinds::Settled::default());}