647 lines · 42.5 KB · RustRaw
//! Contacts over a phone copy: the answers CONTACTS-ANSWERS.md fixes. Every name and number is invented.use serde_json::{json, Value};use super::{tier, Facts, Tier};use crate::handle::CottonHandle;use crate::phone::passwords::tests::phone;fn over(client: &crate::shell::client::ClientController, method: &str, request: &Value) -> Result<Value, crate::methods::MethodError> { if super::METHODS.contains(&method) { super::call(client, method, request) } else { crate::phone::contacts_same::call(client, method, request) }}fn answer(handle: &CottonHandle, method: &str, request: Value) -> Value { over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}/// Lay Contacts' kit tables on this copy, as every open does (`lay_kit_tables_at_open`).pub(crate) fn hold_contacts(handle: &CottonHandle) { let ids: Vec<String> = ["shared_handle", "person_source", "person_state", "person_fact", "group_origin", "person_pair", "handle_label"].iter().map(|s| s.to_string()).collect(); handle .client() .with_writer(|replica| { cotton_tools::kit::lay_kit_tables(&replica.driver, chrono::Utc::now(), std::sync::Arc::new(cotton_tools::random::SystemRandom), None, &ids) .map(|_| ()) .map_err(|failure| failure.0) }) .unwrap();}fn names(section: &Value) -> Vec<String> { section["rows"].as_array().unwrap().iter().map(|r| r["words"].as_str().unwrap().to_string()).collect()}fn section<'a>(home: &'a Value, id: &str) -> Option<&'a Value> { home["sections"].as_array().unwrap().iter().find(|s| s["id"] == id)}fn add(handle: &CottonHandle, name: &str, phones: &[&str], emails: &[&str]) -> String { let made = answer(handle, "contacts.add", json!({ "name": name, "phones": phones, "emails": emails })); made["id"].as_str().unwrap_or_else(|| panic!("made: {made}")).to_string()}fn run(handle: &CottonHandle, sql: &str, args: &[&str]) { let args: Vec<rusqlite::types::Value> = args.iter().map(|a| rusqlite::types::Value::Text(a.to_string())).collect(); handle.client().with_writer(|replica| replica.driver.run(sql, &args).map(|_| ()).map_err(|e| e.to_string())).unwrap();}/// RULE (PEOPLE-DESIGN f.1): the tiers are written rules over both directions; someone he never answers never rises.#[test]fn the_tiers_follow_the_written_rules() { let took = |weeks_8, count_90d, count_year| Facts { count_90d, count_year, weeks_8, took_part: true, last_ms: None }; assert_eq!(tier(&took(3, 4, 4), false), Tier::Close); assert_eq!(tier(&took(2, 10, 10), false), Tier::Often); assert_eq!(tier(&took(1, 2, 2), false), Tier::Now); assert_eq!(tier(&took(0, 0, 0), false), Tier::Rest); let unanswered = Facts { count_90d: 50, count_year: 50, weeks_8: 8, took_part: false, last_ms: None }; assert_eq!(tier(&unanswered, false), Tier::Rest, "a sender he never answers never rises"); assert_eq!(tier(&Facts::default(), true), Tier::Close, "a pin keeps someone in Close");}/// RULE (CONTACTS-ANSWERS 1-3): a contact added is on the home and its page; a number two contacts hold is kept by both/// and said on each page; their facts lift them into a tier; the home's search finds a number.#[test]fn home_and_page_answer_with_a_shared_landline() { let (_dir, handle) = phone(); hold_contacts(&handle); let empty = answer(&handle, "contacts.home", json!({})); assert_eq!(empty["empty"]["title"], "No contacts yet"); assert!(empty["import"].is_object(), "the address book is offered until it was read"); let dad = add(&handle, "Dev Example", &["+91 22 2345 6789"], &[]); let mom = add(&handle, "Mira Example", &["+91 22 2345 6789", "+91 98765 00001"], &["mira@example.test"]); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(names(section(&home, "rest").unwrap()), ["Dev Example", "Mira Example"]); assert_eq!(home["kinds"][0]["on"], true); let page = answer(&handle, "contacts.person", json!({ "id": mom })); assert_eq!(page["title"], "Mira Example"); let landline = page["reach"].as_array().unwrap().iter().find(|h| h["words"] == "+91 22 2345 6789").unwrap_or_else(|| panic!("{page}")); assert_eq!(landline["detail"], "Also Dev Example's"); assert_eq!(page["subtitle"], "Everyone else"); assert!(page["acts"].as_array().unwrap().iter().any(|a| a["id"] == "pin")); // Comms' line for Dad: they wrote each other in 4 of the last 8 weeks. let at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); run( &handle, "INSERT INTO cotton_person_fact (id, workspace_id, person, app, kind, count, count_90d, count_year, weeks_8, took_part, last, created_at, updated_at) \ SELECT 'f-1', workspace_id, ?1, 'comms', 'messages', 40, 30, 40, 4, 1, ?2, ?2, ?2 FROM _meta", &[&dad, &at], ); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(names(section(&home, "close").unwrap()), ["Dev Example"]); assert_eq!(section(&home, "close").unwrap()["rows"][0]["detail"], "Talked today"); let dad_page = answer(&handle, "contacts.person", json!({ "id": dad })); assert_eq!(dad_page["between"][0]["app"], "comms"); assert_eq!(dad_page["between"][0]["detail"], "40 messages · Talked today"); let found = answer(&handle, "contacts.home", json!({ "query": "98765 00001" })); assert_eq!(names(&found["sections"][0]), ["Mira Example"]); let found = answer(&handle, "contacts.home", json!({ "query": "dev" })); assert_eq!(names(&found["sections"][0]), ["Dev Example"]); // A pin (contacts.pin writes it) keeps her in Close. run(&handle, "INSERT INTO cotton_person_state (id, workspace_id, person, pinned, created_at, updated_at) SELECT 'st-1', workspace_id, ?1, 1, ?2, ?2 FROM _meta", &[&mom, &at]); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(names(section(&home, "close").unwrap()), ["Dev Example", "Mira Example"]); // An organisation is its own kind. add(&handle, "Acme Example", &[], &[]); let org = answer(&handle, "contacts.add", json!({ "name": "Globex Example", "kind": "organisation" })); let orgs = answer(&handle, "contacts.home", json!({ "kind": "organisation" })); assert_eq!(names(&orgs["sections"][0]), ["Globex Example"]); assert!(over(&handle.client(), "contacts.add", &json!({ "name": "Bot", "kind": "assistant" })).is_err(), "an assistant is not made here"); let _ = org;}/// CONTACT KINDS: a number or an address keeps his label; the page shows it in place of the/// kind's word, the edit form gives it beside each value, and edit changes it. A value with no label reads as before.#[test]fn a_handle_keeps_its_label_through_add_page_and_edit() { let (_dir, handle) = phone(); hold_contacts(&handle); let made = answer(&handle, "contacts.add", json!({ "name": "Asha Example", "phones": [{ "value": "+91 98765 00011", "label": "cell" }, "+91 98765 00012"], "emails": [{ "value": "asha@example.test", "label": "Studio" }] })); let id = made["id"].as_str().unwrap().to_string(); let page = answer(&handle, "contacts.person", json!({ "id": id })); let reach = page["reach"].as_array().unwrap(); let detail = |value: &str| reach.iter().find(|h| h["words"] == value).unwrap_or_else(|| panic!("{page}"))["detail"].clone(); assert_eq!(detail("+91 98765 00011"), "Mobile"); assert_eq!(detail("asha@example.test"), "Studio"); // Unlabelled: the kind's word, as before; every reach row keeps its shape (id, kind, words, detail, shared, acts). let plain = reach.iter().find(|h| h["words"] == "+91 98765 00012").unwrap(); assert_eq!(plain["label"], Value::Null); for row in reach { for key in ["id", "kind", "words", "detail", "shared", "acts"] { assert!(row.get(key).is_some(), "{key} in {row}"); } } let form = answer(&handle, "contacts.edit.form", json!({ "id": id })); let phones = &form["fields"][1]; let at = phones["values"].as_array().unwrap().iter().position(|v| v == "+91 98765 00011").unwrap(); assert_eq!(phones["labels"][at], "Mobile"); answer(&handle, "contacts.edit", json!({ "id": id, "phones": [{ "value": "+91 98765 00011", "label": "Work" }, "+91 98765 00012"] })); let page = answer(&handle, "contacts.person", json!({ "id": id })); let row = page["reach"].as_array().unwrap().iter().find(|h| h["words"] == "+91 98765 00011").unwrap().clone(); assert_eq!(row["detail"], "Work");}/// RULE (PEOPLE-DESIGN f.3, b.3; BUILD 2 items 2 and 4): Same person? is asked from the evidence and never merged by/// itself; yes merges, and Unmerge within 30 days puts the other back with its own email; no is never asked again.#[test]fn same_person_merges_on_yes_and_unmerge_puts_everything_back() { let (_dir, handle) = phone(); hold_contacts(&handle); // Asha is the fuller card (two numbers, kept in Close); the twin a short one sharing a number. let asha = add(&handle, "Asha Example", &["+91 98765 43210", "+91 98765 00001"], &[]); let twin = add(&handle, "Asha", &["+91 98765 00001"], &["asha@example.test"]); let ravi = add(&handle, "Ravi Example", &[], &[]); run(&handle, "INSERT INTO cotton_person_state (id, workspace_id, person, pinned, created_at, updated_at) SELECT 'st-a', workspace_id, ?1, 1, '2026-01-01', '2026-01-01' FROM _meta", &[&asha]); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(home["same"]["words"], "1 looks like the same person twice"); let list = answer(&handle, "contacts.same.list", json!({})); assert_eq!(list["count"], 1); assert_eq!(list["pairs"][0]["why"], "the same number"); let yes = list["pairs"][0]["acts"][0]["call"]["request"].clone(); let joined = answer(&handle, "contacts.same", yes); assert_eq!(joined["id"], asha, "the fuller, pinned card is kept, whichever side it was"); let (keep, drop) = (asha.clone(), twin.clone()); let home = answer(&handle, "contacts.home", json!({})); assert!(home["same"].is_null()); assert_eq!(names(section(&home, "close").unwrap()), ["Asha Example"], "{home}"); let kept = answer(&handle, "contacts.person", json!({ "id": keep })); let reach: Vec<&str> = kept["reach"].as_array().unwrap().iter().map(|h| h["words"].as_str().unwrap()).collect(); assert_eq!(reach.iter().filter(|r| **r == "+91 98765 00001").count(), 1, "a shared number is said once: {reach:?}"); assert!(reach.contains(&"asha@example.test") && reach.contains(&"+91 98765 43210"), "{reach:?}"); assert!(kept["acts"].as_array().unwrap().iter().any(|a| a["id"] == "unmerge")); assert_eq!(answer(&handle, "contacts.person", json!({ "id": drop }))["mergedInto"], keep); let back = answer(&handle, "contacts.unmerge", json!({ "id": keep })); assert_eq!(back["ids"], json!([keep, drop])); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(names(section(&home, "rest").unwrap()).len(), 2); let twin_page = answer(&handle, "contacts.person", json!({ "id": twin })); assert!(twin_page["reach"].as_array().unwrap().iter().any(|h| h["words"] == "asha@example.test"), "the twin keeps its own email"); assert_eq!(answer(&handle, "contacts.same.list", json!({}))["count"], 0, "an undone join is not asked again"); let _ = ravi;}/// RULE (PEOPLE-DESIGN b.6; BUILD 1b): reading the address book makes each card a contact once; reading it again/// changes nothing; a landline two cards share makes two contacts, never one.#[test]fn reading_the_address_book_twice_makes_nothing_twice() { let (_dir, handle) = phone(); hold_contacts(&handle); let cards = json!([ { "deviceContactId": "card-1", "fullName": "Dev Example", "phones": ["+91 22 2345 6789"] }, { "deviceContactId": "card-2", "fullName": "Mira Example", "phones": ["+91 22 2345 6789"] }, { "deviceContactId": "card-3", "fullName": "Ravi Example", "emails": ["ravi@example.test"] }, ]); let first = answer(&handle, "contacts.read", json!({ "cards": cards })); assert_eq!(first["read"], 3); assert_eq!(first["made"], 3, "{first}"); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(names(section(&home, "rest").unwrap()), ["Dev Example", "Mira Example", "Ravi Example"]); assert!(home["import"].is_null(), "read once, not offered again"); let again = answer(&handle, "contacts.read", json!({ "cards": cards })); assert_eq!(again["made"], 0, "{again}"); assert_eq!(names(section(&answer(&handle, "contacts.home", json!({})), "rest").unwrap()).len(), 3); // The landline pair: each side shows the number, and yes joins them (seen hanging on the emulator, 28 Nov). let list = answer(&handle, "contacts.same.list", json!({})); assert_eq!(list["pairs"][0]["why"], "the same number"); assert_eq!(list["pairs"][0]["a"]["reach"], json!(["+91 22 2345 6789"]), "{list}"); assert_eq!(list["pairs"][0]["b"]["reach"], json!(["+91 22 2345 6789"]), "{list}"); let yes = list["pairs"][0]["acts"][0]["call"]["request"].clone(); let joined = answer(&handle, "contacts.same", yes); assert!(joined["said"].as_str().is_some_and(|said| said.starts_with("Joined")), "{joined}"); assert_eq!(names(section(&answer(&handle, "contacts.home", json!({})), "rest").unwrap()).len(), 2); assert_eq!(answer(&handle, "contacts.read", json!({ "cards": cards }))["made"], 0, "a merged card is found again, never made twice");}/// RULE (PEOPLE-DESIGN f.6, f.1): Comms counts each person's line on the phone (`person_fact`); someone he writes with/// week after week is Close, and someone who only writes to him, never answered, stays in Everyone else.#[test]fn comms_lines_lift_a_person_he_talks_with_into_close() { let (_dir, handle) = phone(); hold_contacts(&handle); let asha = add(&handle, "Asha Example", &["+15550100001"], &[]); let _ravi = add(&handle, "Ravi Example", &["+15550100002"], &[]); let day = 86_400_000_i64; let now = chrono::Utc::now().timestamp_millis(); let iso = |ms: i64| chrono::DateTime::from_timestamp_millis(ms).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); run(&handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, created_at, updated_at) SELECT 'c-asha', workspace_id, '15550100001', '2026-01-01', '2026-01-01' FROM _meta", &[]); run(&handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, created_at, updated_at) SELECT 'c-ravi', workspace_id, '15550100002', '2026-01-01', '2026-01-01' FROM _meta", &[]); for (thread, contact) in [("t-asha", "c-asha"), ("t-ravi", "c-ravi")] { run(&handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, contact_id, read_seq, created_at, updated_at) SELECT ?1, workspace_id, 'dm', ?1, ?2, 0, '2026-01-01', '2026-01-01' FROM _meta", &[thread, contact]); } let mut n = 0; for week in 0..4 { for (thread, direction) in [("t-asha", "in"), ("t-asha", "out"), ("t-ravi", "in")] { n += 1; let (id, at) = (format!("m-{n}"), iso(now - (week * 7 + 1) * day)); run(&handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) \ SELECT ?1, ?2, workspace_id, ?3, 'cotton', 'live', 'hello', ?4, 1, ?4, ?1 FROM _meta", &[&id, thread, direction, &at]); } } let counted = answer(&handle, "contacts.facts", json!({})); assert_eq!(counted["changed"], 2, "{counted}"); assert_eq!(answer(&handle, "contacts.facts", json!({}))["changed"], 0, "a recount with nothing new writes nothing"); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(names(section(&home, "close").unwrap()), ["Asha Example"]); assert_eq!(names(section(&home, "rest").unwrap()), ["Ravi Example"], "never answered, never rises"); let page = answer(&handle, "contacts.person", json!({ "id": asha })); assert_eq!(page["between"][0]["detail"], "8 messages · Talked yesterday"); // A group chat he writes in becomes a group Contacts made, once (f.2). run(&handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, read_seq, created_at, updated_at) SELECT 't-fam', workspace_id, 'group', 't-fam', 'Family', 0, '2026-01-01', '2026-01-01' FROM _meta", &[]); for (id, contact) in [("tp-1", "c-asha"), ("tp-2", "c-ravi")] { run(&handle, "INSERT INTO cotton_msg_thread_participants (id, thread_id, workspace_id, contact_id, is_self, created_at) SELECT ?1, 't-fam', workspace_id, ?2, 0, '2026-01-01' FROM _meta", &[id, contact]); } run(&handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) \ SELECT 'm-fam', 't-fam', workspace_id, 'out', 'whatsapp', 'live', 'dinner?', ?1, 1, ?1, 'm-fam' FROM _meta", &[&iso(now - day)]); let counted = answer(&handle, "contacts.facts", json!({})); assert_eq!(counted["groups"], 1, "{counted}"); assert_eq!(answer(&handle, "contacts.facts", json!({}))["groups"], 0, "made once"); let page = answer(&handle, "contacts.person", json!({ "id": asha })); assert_eq!(page["groups"][0]["words"], "Family"); let why = handle.client().with_writer(|replica| Ok(replica.driver.get("SELECT made_by, reason FROM cotton_group_origin", &[]).map_err(|e| e.to_string())?.map(|r| crate::phone::passwords::json_row(&r)))).unwrap().unwrap(); assert_eq!(why["made_by"], "app"); assert_eq!(why["reason"], "from your \"Family\" chat on WhatsApp");}/// Every live line, as (person, app, kind, count, count_90d, count_year, weeks_8, took_part, last), in order.fn lines(handle: &CottonHandle) -> Vec<String> { handle .client() .with_writer(|replica| { replica .driver .all( "SELECT person || '|' || app || '|' || kind || '|' || coalesce(count, 0) || '|' || coalesce(count_90d, 0) || '|' || coalesce(count_year, 0) || '|' || coalesce(weeks_8, 0) || '|' || coalesce(took_part, 0) || '|' || coalesce(last, '') AS line \ FROM cotton_person_fact WHERE deleted_at IS NULL ORDER BY person, app, kind", &[], ) .map(|rows| rows.into_iter().filter_map(|r| r.text("line").map(str::to_string)).collect::<Vec<_>>()) .map_err(|e| e.to_string()) }) .unwrap()}/// RULE (PEOPLE-DESIGN f.1, f.6; NEXT-PERSON-FACTS): Post, Days and Albums each count their line on the phone. Mail/// both ways week after week is Close; events together are "Now and then"; a face in photos is said on the page but/// lifts nobody; a list's mail and a declined or future event count for nobody. A full rebuild equals the running/// result.#[test]fn post_days_and_albums_count_their_lines_and_a_rebuild_equals_the_running_result() { let (_dir, handle) = phone(); hold_contacts(&handle); let mira = add(&handle, "Mira Example", &[], &["mira@invented.example"]); let kabir = add(&handle, "Kabir Example", &["+15550100011"], &["kabir@invented.example"]); let lena = add(&handle, "Lena Example", &[], &[]); let _zoe = add(&handle, "Zoe Example", &[], &["zoe@invented.example"]); let day = 86_400_000_i64; let now = chrono::Utc::now().timestamp_millis(); let iso = |ms: i64| chrono::DateTime::from_timestamp_millis(ms).unwrap().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let mail = |id: &str, direction: &str, from: &str, to: &str, ago: i64, list: Option<&str>| { let recipients = json!([{ "email": to, "kind": "to" }]).to_string(); run(&handle, "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) SELECT 'th-' || ?1, workspace_id, 'key-' || ?1, 'Hello', ?2, ?2, 1, ?2, ?2 FROM _meta", &[id, &iso(now - ago * day)]); run( &handle, "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, recipients, sent_at, body, snippet, attachments, unread, account, in_inbox, direction, list_id, created_at) \ SELECT ?1, workspace_id, 'th-' || ?1, 'x-' || ?1, 'Hello', ?2, ?3, ?4, 'Hello', 'Hello', '[]', 0, 'me@invented.example', 1, ?5, ?6, ?4 FROM _meta", &[id, from, &recipients, &iso(now - ago * day), direction, list.unwrap_or("")], ); }; // Mira: written both ways in 4 weeks; one list mail too, which counts for nobody. Zoe: writes, never answered. for week in 0..4 { mail(&format!("in-{week}"), "in", "mira@invented.example", "me@invented.example", week * 7 + 1, None); mail(&format!("out-{week}"), "out", "me@invented.example", "Mira@Invented.example", week * 7 + 2, None); mail(&format!("zoe-{week}"), "in", "zoe@invented.example", "me@invented.example", week * 7 + 1, None); } mail("list-1", "in", "mira@invented.example", "me@invented.example", 3, Some("news.invented.example")); // Kabir: an event naming him, one with him as a guest by address, one declined, one ahead. // The Days kit's later columns, as a Days copy holds them. for column in ["people", "my_response", "trashed_at"] { let has = handle.client().with_writer(|r| r.driver.get(&format!("SELECT 1 AS one FROM pragma_table_info('cotton_events') WHERE name = '{column}'"), &[]).map_err(|e| e.to_string())).unwrap(); if has.is_none() { run(&handle, &format!("ALTER TABLE cotton_events ADD COLUMN {column} TEXT"), &[]); } } let event = |id: &str, ago: i64, people: &str, response: &str| { run( &handle, "INSERT INTO cotton_events (id, title, starts_at, people, my_response, created_at, updated_at) VALUES (?1, 'Walk', ?2, ?3, ?4, ?2, ?2)", &[id, &iso(now - ago * day), people, response], ); }; event("ev-named", 10, &json!([kabir]).to_string(), "accepted"); event("ev-guest", 20, "[]", "accepted"); run(&handle, "INSERT INTO cotton_event_attendees (id, event_id, email, created_at, updated_at) VALUES ('g-1', 'ev-guest', 'KABIR@invented.example', '2026-01-01', '2026-01-01')", &[]); event("ev-declined", 5, &json!([kabir]).to_string(), "declined"); event("ev-ahead", -5, &json!([kabir]).to_string(), "accepted"); // Lena: her named face in two photos (twice in one of them). let (ph1, ph2) = (format!("photo:{}", "a".repeat(64)), format!("photo:{}", "b".repeat(64))); for (photo, ago) in [(ph1.as_str(), 30), (ph2.as_str(), 40)] { run(&handle, "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, created_at, updated_at) SELECT ?1, workspace_id, 'k/' || substr(?1, 7) || '.jpg', substr(?1, 7), 'image/jpeg', 2048, ?2, ?2, ?2 FROM _meta", &[photo, &iso(now - ago * day)]); } for (face, photo) in [("f-1", ph1.as_str()), ("f-2", ph1.as_str()), ("f-3", ph2.as_str())] { run(&handle, "INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, source_id, x, y, w, h, person_id, created_at, updated_at) SELECT ?1, workspace_id, 'photo', ?2, 'cotton', ?1, 0.1, 0.1, 0.2, 0.2, ?3, '2026-01-01', '2026-01-01' FROM _meta", &[face, photo, &lena]); } let page = |id: &str| answer(&handle, "contacts.person", json!({ "id": id })); // Omar: Comms, written both ways each week (the fourth source on the same copy). let omar = add(&handle, "Omar Example", &["+15550100021"], &[]); run(&handle, "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, created_at, updated_at) SELECT 'c-omar', workspace_id, '15550100021', '2026-01-01', '2026-01-01' FROM _meta", &[]); run(&handle, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, contact_id, read_seq, created_at, updated_at) SELECT 't-omar', workspace_id, 'dm', 't-omar', 'c-omar', 0, '2026-01-01', '2026-01-01' FROM _meta", &[]); for week in 0..4_i64 { for direction in ["in", "out"] { let (id, at) = (format!("m-omar-{week}-{direction}"), iso(now - (week * 7 + 1) * day)); run(&handle, "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, seq, created_at, external_id) \ SELECT ?1, 't-omar', workspace_id, ?2, 'cotton', 'live', 'hello', ?3, 1, ?3, ?1 FROM _meta", &[&id, direction, &at]); } } answer(&handle, "contacts.facts", json!({})); assert_eq!(answer(&handle, "contacts.facts", json!({}))["changed"], 0, "a recount with nothing new writes nothing"); let home = answer(&handle, "contacts.home", json!({})); assert_eq!(names(section(&home, "close").unwrap()).len(), 2, "{home}"); for name in ["Mira Example", "Omar Example"] { assert!(names(section(&home, "close").unwrap()).contains(&name.to_string()), "{home}"); } assert!(page(&omar)["between"][0]["detail"].as_str().unwrap().starts_with("8 messages"), "{}", page(&omar)); assert_eq!(names(section(&home, "now").unwrap()), ["Kabir Example"], "{home}"); assert_eq!(names(section(&home, "rest").unwrap()), ["Lena Example", "Zoe Example"], "photos lift nobody; never answered, never rises"); assert!(page(&mira)["between"][0]["detail"].as_str().unwrap().starts_with("8 mails"), "{}", page(&mira)); assert_eq!(page(&kabir)["between"][0]["detail"], "2 events together"); assert_eq!(page(&lena)["between"][0]["detail"], "In 2 of your photos"); // Something new arrives and is counted: then a rebuild from nothing gives the very same lines. mail("out-late", "out", "me@invented.example", "kabir@invented.example", 0, None); answer(&handle, "contacts.facts", json!({})); let running = lines(&handle); assert!(running.iter().any(|l| l.starts_with(&format!("{kabir}|post|mail|1|"))), "{running:?}"); run(&handle, "DELETE FROM cotton_person_fact", &[]); run(&handle, "DELETE FROM _contacts_counted", &[]); answer(&handle, "contacts.facts", json!({})); assert_eq!(lines(&handle), running, "a full rebuild equals the running result"); // A source gone: its line is set aside, as a rebuild would leave it out. run(&handle, "UPDATE cotton_photos SET trashed_at = '2026-01-02'", &[]); answer(&handle, "contacts.facts", json!({})); assert!(!lines(&handle).iter().any(|l| l.contains("|albums|")), "{:?}", lines(&handle));}/// RULE (Android, 28 Nov 2026): a copy made before a kit column on person (`birthday`, `merged_into`) still merges:/// what the union would fill there waits for the column, and nothing is refused.#[test]fn an_older_copy_without_the_newer_person_columns_still_merges() { let (_dir, handle) = phone(); hold_contacts(&handle); let older = handle .client() .with_writer(|replica| { let held: Vec<String> = replica.driver.all("SELECT name FROM pragma_table_info('cotton_people')", &[]).map_err(|e| e.to_string())?.iter().filter_map(|r| r.text("name").map(str::to_string)).collect(); for column in ["birthday", "merged_into", "phones", "emails"] { if held.iter().any(|h| h == column) { replica.driver.run(&format!("ALTER TABLE cotton_people DROP COLUMN {column}"), &[]).map_err(|e| e.to_string())?; } } Ok(held) }) .unwrap(); let keep = add(&handle, "Asha Example", &["+91 98765 43210"], &[]); let drop = add(&handle, "Asha Example", &[], &["asha@example.test"]); run(&handle, "UPDATE cotton_people SET birth_month = 4, birth_day = 17 WHERE id = ?1", &[&drop]); let joined = answer(&handle, "contacts.merge", json!({ "keep": keep, "drop": drop })); assert!(joined["said"].as_str().is_some_and(|s| s.starts_with("Joined")), "{joined} (copy held {older:?})"); let page = answer(&handle, "contacts.person", json!({ "id": keep })); assert_eq!(page["reach"].as_array().unwrap().len(), 2, "{page}"); answer(&handle, "contacts.unmerge", json!({ "id": keep })); assert_eq!(answer(&handle, "contacts.person", json!({ "id": drop }))["reach"][0]["words"], "asha@example.test");}/// RULE (CONTACTS-ANSWERS 5.1): signed in, a merge on the phone also sends the object's half (`merge_people`), which/// moves the links of apps this phone does not hold; Unmerge sends `unmerge_people`.#[test]fn a_merge_signed_in_sends_the_objects_half() { use cotton_client::transport::scripted::{Reply, ScriptedExchange}; let (_dir, handle) = phone(); hold_contacts(&handle); let keep = add(&handle, "Asha Example", &["+91 98765 43210"], &[]); let drop = add(&handle, "Asha Example", &[], &["asha@example.test"]); let exchange = ScriptedExchange::new([Reply::ok(r#"{"id":"k","moved":{},"left":[]}"#), Reply::ok(r#"{"ids":[]}"#)]); let door = crate::phone::personal_object::ObjectDoor { address: cotton_client::transport::object::ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: exchange.clone(), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into(), }; handle.client().set_object_door(Some(std::sync::Arc::new(door))); answer(&handle, "contacts.merge", json!({ "keep": keep, "drop": drop })); answer(&handle, "contacts.unmerge", json!({ "id": keep })); let sent: Vec<Value> = exchange.seen().iter().map(|seen| serde_json::from_slice(&seen.body).unwrap()).collect(); assert_eq!(sent[0], json!({ "act": "merge_people", "args": { "keep": keep, "drop": drop } })); assert_eq!(sent[1], json!({ "act": "unmerge_people", "args": { "id": keep } }));}/// RULE (Android, 28 Nov 2026): a copy that holds the whole `birthday` the object keeps (a kit column the build's/// compiled spec does not name) merges, and the survivor takes the duplicate's birthday.#[test]fn a_copy_holding_the_whole_birthday_merges() { let (_dir, handle) = phone(); hold_contacts(&handle); handle .client() .with_writer(|replica| { let held = replica.driver.all("SELECT name FROM pragma_table_info('cotton_people')", &[]).map_err(|e| e.to_string())?.iter().any(|r| r.text("name") == Some("birthday")); if !held { replica.driver.run("ALTER TABLE cotton_people ADD COLUMN birthday TEXT", &[]).map_err(|e| e.to_string())?; } Ok(()) }) .unwrap(); let keep = add(&handle, "Asha Example", &["+91 98765 43210"], &[]); let drop = add(&handle, "Asha Example", &[], &["asha@example.test"]); run(&handle, "UPDATE cotton_people SET birth_month = 4, birth_day = 17, birthday = '--04-17' WHERE id = ?1", &[&drop]); let joined = answer(&handle, "contacts.merge", json!({ "keep": keep, "drop": drop })); assert!(joined["said"].as_str().is_some_and(|s| s.starts_with("Joined")), "{joined}"); let kept = handle.client().with_writer(|replica| Ok(replica.driver.get("SELECT birth_month, birthday FROM cotton_people WHERE id = ?", &[rusqlite::types::Value::Text(keep.clone())]).map_err(|e| e.to_string())?.map(|r| crate::phone::passwords::json_row(&r)))).unwrap().unwrap(); assert_eq!(kept["birth_month"], 4, "{kept:?}");}/// RULE (PEOPLE-DESIGN f.2 "Events"): the same people at three events or more become a group Contacts made, under/// the name the events carry, "at the same N events in Days"; made once, and a group he deleted is not made again.#[test]fn the_same_people_at_three_events_become_a_group_contacts_made() { let (_dir, client) = crate::shell::client::phone_tests::attached(); let ids: Vec<String> = ["shared_handle", "person_source", "person_state", "person_fact", "group_origin", "person_pair"].iter().map(|s| s.to_string()).collect(); client .with_writer(|replica| { cotton_tools::kit::lay_kit_tables(&replica.driver, chrono::Utc::now(), std::sync::Arc::new(cotton_tools::random::SystemRandom), None, &ids).map(|_| ()).map_err(|failure| failure.0) }) .unwrap(); let person = |name: &str, phone: &str| { let made = client.write("create_person", json!({ "fullName": name, "phones": [phone] }).as_object().unwrap()).expect("create_person"); made.pointer("/answer/id").and_then(Value::as_str).expect("an id").to_string() }; let (kabir, omar) = (person("Kabir Example", "+15550100031"), person("Omar Example", "+15550100032")); let sql = |text: &str, args: &[&str]| { let args: Vec<rusqlite::types::Value> = args.iter().map(|a| rusqlite::types::Value::Text(a.to_string())).collect(); client.with_writer(|replica| replica.driver.run(text, &args).map(|_| ()).map_err(|e| e.to_string())).unwrap(); }; for column in ["people", "my_response", "trashed_at"] { let has = client.with_writer(|r| r.driver.get(&format!("SELECT 1 AS one FROM pragma_table_info('cotton_events') WHERE name = '{column}'"), &[]).map_err(|e| e.to_string())).unwrap(); if has.is_none() { sql(&format!("ALTER TABLE cotton_events ADD COLUMN {column} TEXT"), &[]); } } // Early in the year: this copy's clock is fixed, and an event counts once it has begun. let both = json!([kabir, omar]).to_string(); let alone = json!([kabir]).to_string(); for (id, title, people, at) in [("e1", "Badminton", &both, "2026-01-05"), ("e2", "Badminton", &both, "2026-01-12"), ("e3", "Badminton ", &both, "2026-01-19"), ("e4", "Walk", &alone, "2026-01-20")] { sql("INSERT INTO cotton_events (id, title, starts_at, people, created_at, updated_at) VALUES (?1, ?2, ?3 || 'T18:00:00.000Z', ?4, ?3, ?3)", &[id, title, at, people]); } let groups = || crate::phone::contacts_groups::call(&client, "contacts.groups", &json!({})).unwrap(); let facts = || crate::phone::contacts_facts::count(&client).unwrap(); let counted = facts(); assert_eq!(counted["groups"], 1, "{counted}"); let listed = groups(); assert_eq!(listed["sections"][0]["id"], "app", "{listed}"); assert_eq!(names(&listed["sections"][0]), ["Badminton"]); assert_eq!(listed["sections"][0]["rows"][0]["detail"], "2 · at the same 3 events in Days"); assert_eq!(facts()["groups"], 0, "made once"); let id = listed["sections"][0]["rows"][0]["id"].as_str().unwrap().to_string(); crate::phone::contacts_groups::call(&client, "contacts.group.delete", &json!({ "id": id })).unwrap(); assert_eq!(facts()["groups"], 0, "a group he deleted is not made again"); assert_eq!(groups()["sections"], json!([]));}/// RULE (PEOPLE-DESIGN f.2 "Work"): the domain of his own address (no webmail) makes Work, "people at <domain>";/// another domain he wrote to someone at becomes an organisation (kind organisation) that the person's page names;/// each made once, and webmail makes nothing.#[test]fn his_work_domain_makes_work_and_a_domain_he_wrote_to_becomes_an_organisation() { let (_dir, client) = crate::shell::client::phone_tests::attached(); let ids: Vec<String> = ["shared_handle", "person_source", "person_state", "person_fact", "group_origin", "person_pair"].iter().map(|s| s.to_string()).collect(); client .with_writer(|replica| { cotton_tools::kit::lay_kit_tables(&replica.driver, chrono::Utc::now(), std::sync::Arc::new(cotton_tools::random::SystemRandom), None, &ids).map(|_| ()).map_err(|failure| failure.0) }) .unwrap(); let person = |name: &str, email: &str| { let made = client.write("create_person", json!({ "fullName": name, "emails": [email] }).as_object().unwrap()).expect("create_person"); made.pointer("/answer/id").and_then(Value::as_str).expect("an id").to_string() }; person("Asha Example", "asha@tinwork.example"); person("Ravi Example", "ravi@tinwork.example"); let dev = person("Dev Example", "dev@acme.example"); person("Gita Example", "gita@gmail.com"); let sql = |text: &str, args: &[&str]| { let args: Vec<rusqlite::types::Value> = args.iter().map(|a| rusqlite::types::Value::Text(a.to_string())).collect(); client.with_writer(|replica| replica.driver.run(text, &args).map(|_| ()).map_err(|e| e.to_string())).unwrap(); }; for (id, to) in [("m1", "dev@acme.example"), ("m2", "gita@gmail.com"), ("m3", "asha@tinwork.example")] { sql("INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) SELECT 'th-' || ?1, workspace_id, 'key-' || ?1, 'Hello', '2026-01-05', '2026-01-05', 1, '2026-01-05', '2026-01-05' FROM _meta", &[id]); let recipients = json!([{ "email": to, "kind": "to" }]).to_string(); sql( "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, recipients, sent_at, body, snippet, attachments, unread, account, in_inbox, direction, created_at) \ SELECT ?1, workspace_id, 'th-' || ?1, 'x-' || ?1, 'Hello', 'me@tinwork.example', ?2, '2026-01-05', 'Hello', 'Hello', '[]', 0, 'me@tinwork.example', 0, 'out', '2026-01-05' FROM _meta", &[id, &recipients], ); } let counted = crate::phone::contacts_facts::count(&client).unwrap(); assert_eq!(counted["groups"], 2, "Work and Acme: {counted}"); assert_eq!(crate::phone::contacts_facts::count(&client).unwrap()["groups"], 0, "made once"); let groups = crate::phone::contacts_groups::call(&client, "contacts.groups", &json!({})).unwrap(); assert_eq!(names(&groups["sections"][0]), ["Work"], "{groups}"); assert_eq!(groups["sections"][0]["rows"][0]["detail"], "2 · people at tinwork.example"); let organisations = crate::phone::contacts_app::call(&client, "contacts.home", &json!({ "kind": "organisation" })).unwrap(); let listed: Vec<String> = organisations["sections"].as_array().unwrap().iter().flat_map(|s| names(s)).collect(); assert_eq!(listed, ["Acme"], "{organisations}"); let page = crate::phone::contacts_app::call(&client, "contacts.person", &json!({ "id": dev })).unwrap(); assert_eq!(page["organisation"]["words"], "Acme", "{}", page["organisation"]); assert_eq!(super::super::contacts_facts::organisation_name("mail.acme.co.uk"), "Acme");}fn scalar_text(handle: &CottonHandle, sql: &str) -> Vec<String> { handle .client() .with_writer(|replica| Ok(replica.driver.all(sql, &[]).map_err(|e| e.to_string())?.iter().map(|r| crate::phone::passwords::json_row(r).values().next().map(|v| v.to_string()).unwrap_or_default()).collect())) .unwrap()}fn signed_in(handle: &CottonHandle, replies: Vec<cotton_client::transport::scripted::Reply>) -> std::sync::Arc<cotton_client::transport::scripted::ScriptedExchange> { let exchange = cotton_client::transport::scripted::ScriptedExchange::new(replies); let door = crate::phone::personal_object::ObjectDoor { address: cotton_client::transport::object::ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: exchange.clone(), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into(), }; handle.client().set_object_door(Some(std::sync::Arc::new(door))); exchange}/// RULE (coordinator, 28 Nov 2026): the object owns a merge (`person_merge`). A merge made offline waits in the/// phone's queue, reads as made meanwhile, goes to the object exactly once when signed in, and once the object's/// answer has synced the phone keeps no record of its own: one record. Unmerge then goes to the object once.#[test]fn an_offline_merge_then_sync_leaves_one_record_and_unmerge_undoes_it() { use cotton_client::transport::scripted::Reply; let (_dir, handle) = phone(); hold_contacts(&handle); let keep = add(&handle, "Asha Example", &["+91 98765 43210"], &[]); let drop = add(&handle, "asha example", &[], &["asha@example.test"]); answer(&handle, "contacts.merge", json!({ "keep": keep, "drop": drop })); // Offline: the merge reads as made, and nothing moved yet. assert_eq!(names(section(&answer(&handle, "contacts.home", json!({})), "rest").unwrap()), ["Asha Example"]); let page = answer(&handle, "contacts.person", json!({ "id": keep })); assert_eq!(page["reach"].as_array().unwrap().len(), 2, "{page}"); assert!(page["acts"].as_array().unwrap().iter().any(|a| a["id"] == "unmerge")); assert_eq!(scalar_text(&handle, "SELECT COUNT(*) FROM _contacts_pending"), ["1"]); assert_eq!(scalar_text(&handle, "SELECT COUNT(*) FROM cotton_person_state WHERE merged_into IS NOT NULL OR moved IS NOT NULL"), ["0"], "the phone keeps no record of its own"); // Signed in: the act goes once, never twice. let exchange = signed_in(&handle, vec![Reply::ok(r#"{"id":"k","moved":{"person_handle.person_id":1},"left":[]}"#), Reply::ok(r#"{"ids":[]}"#)]); answer(&handle, "contacts.facts", json!({})); answer(&handle, "contacts.facts", json!({})); let sent: Vec<Value> = exchange.seen().iter().map(|seen| serde_json::from_slice(&seen.body).unwrap()).collect(); assert_eq!(sent, vec![json!({ "act": "merge_people", "args": { "keep": keep, "drop": drop } })]); // The object's answer syncs: the duplicate archived with merged_into, its email moved. run(&handle, "ALTER TABLE cotton_people ADD COLUMN merged_into TEXT", &[]); run(&handle, "UPDATE cotton_people SET archived_at = '2026-11-28T00:00:00.000Z', merged_into = ?1 WHERE id = ?2", &[&keep, &drop]); run(&handle, "UPDATE cotton_person_handles SET person_id = ?1 WHERE person_id = ?2", &[&keep, &drop]); answer(&handle, "contacts.facts", json!({})); assert_eq!(scalar_text(&handle, "SELECT COUNT(*) FROM _contacts_pending"), ["0"], "the object's record is the one record"); let page = answer(&handle, "contacts.person", json!({ "id": keep })); assert_eq!(page["reach"].as_array().unwrap().len(), 2); assert_eq!(answer(&handle, "contacts.person", json!({ "id": drop }))["mergedInto"], keep); // Unmerge goes to the object, once. let back = answer(&handle, "contacts.unmerge", json!({ "id": keep })); assert_eq!(back["ids"], json!([keep, drop])); answer(&handle, "contacts.facts", json!({})); let sent: Vec<Value> = exchange.seen().iter().map(|seen| serde_json::from_slice(&seen.body).unwrap()).collect(); assert_eq!(sent.len(), 2); assert_eq!(sent[1], json!({ "act": "unmerge_people", "args": { "id": keep } })); assert_eq!(scalar_text(&handle, "SELECT COUNT(*) FROM _contacts_pending"), ["0"]);}/// RULE (Cotton works before sign-in): a merge made signed out and let go before sign-in never reaches the object.#[test]fn a_merge_let_go_before_sign_in_never_reaches_the_object() { let (_dir, handle) = phone(); hold_contacts(&handle); let keep = add(&handle, "Asha Example", &["+91 98765 43210"], &[]); let drop = add(&handle, "asha example", &[], &["asha@example.test"]); answer(&handle, "contacts.merge", json!({ "keep": keep, "drop": drop })); answer(&handle, "contacts.unmerge", json!({ "id": keep })); assert_eq!(names(section(&answer(&handle, "contacts.home", json!({})), "rest").unwrap()).len(), 2); let exchange = signed_in(&handle, vec![]); answer(&handle, "contacts.facts", json!({})); assert_eq!(exchange.calls(), 0);}