Cotton code
2291 lines · 93.1 KB · RustRaw
//! What the traffic and money reads answer — sub-step 4g.//!//! EVERY FIXTURE HERE IS SYNTHETIC: an account nobody banks with, a contact//! with no number, a photo whose sha is sixty-four zeroes//! ([nothing-real-ever-goes-in-cotton-s-public-tree]). The controller is//! `shell::client::phone_tests::attached`, so these cases and the write cases//! are looking at the same device and the same v45 file.//!//! Each test is named for the BEHAVIOUR it holds, not the function it calls://! what a person would notice if it broke.use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::shell::client::phone_tests::{args, attached};use crate::shell::client::ClientController;// ── the harness ─────────────────────────────────────────────────────────────fn read(client: &ClientController, name: &str, args: &Map<String, Value>) -> Value {    let entry = super::reads::read_for(&format!("read.{name}"))        .unwrap_or_else(|| panic!("read.{name} is declared"));    // The dispatch itself, never a copy of it.    super::answer_read(client, entry, args)        .unwrap_or_else(|reason| panic!("read.{name} answered: {reason}"))}/// Run one statement against the replica, for seeding only.fn run(client: &ClientController, sql: &str, values: &[&str]) {    client        .with_writer(|replica| {            let bound: Vec<SqlValue> = values                .iter()                .map(|value| {                    if *value == "\0NULL" {                        SqlValue::Null                    } else {                        SqlValue::Text((*value).to_string())                    }                })                .collect();            replica                .driver                .run(sql, &bound)                .map_err(|error| format!("{sql}: {error}"))        })        .expect("the seed statement");}const WS: &str = crate::fixture::WORKSPACE;/// The `NULL` marker [`run`] understands. A literal `NULL` in the SQL would do/// for a constant, but half these columns are the thing under test.const NIL: &str = "\0NULL";fn sha(seed: char) -> String {    std::iter::repeat_n(seed, 64).collect()}/// A filed paper, with every column the store insists on.fn seed_document(    client: &ClientController,    id: &str,    title: &str,    mime: &str,    path: &str,    seed: char,) {    let stamp = "2026-09-01T00:00:00.000Z";    run(        client,        "INSERT INTO cotton_documents (id, workspace_id, title, original_name, mime, byte_size, \         sha256, storage_path, status_changed_at, created_at, updated_at) \         VALUES (?,?,?,'a-synthetic-file',?,'1024',?,?,?,?,?)",        &[id, WS, title, mime, &sha(seed), path, stamp, stamp, stamp],    );}// ── money ───────────────────────────────────────────────────────────────────#[test]fn the_phone_s_call_log_asks_for_the_whole_page_the_screen_shows() {    // The tool's own default is fifty and the screen asks for two hundred, so a    // read that forwarded the screen's arguments untouched would drop three    // quarters of a person's history and look like a short log rather than a    // truncated one. SIXTY ROWS is the cheapest fixture that can tell those two    // apart — on the tool's default, ten of them would be missing — where an    // empty log cannot tell them apart at all.    //    // Lane O is changing the rule so a screen reads the whole set; when    // `CALL_LOG_PAGE` moves, the ceiling below moves with it, and the floor    // (every seeded call comes back) is the half that must not.    let (_dir, client) = attached();    let stamp = "2026-09-04T09:00:00.000Z";    // More than the tool's maximum page (two hundred): the log asks for the    // whole set, and a call history is longer than any page.    let seeded = 260;    // ONE statement for all sixty. `run` takes the file per call — an open, a    // transaction and an fsync each — so sixty calls cost about four minutes on    // a busy machine, and a fixture is not worth four minutes of the `rust`    // job. `cotton_call_log` is the PHONE's log — and since schema 5 retired    // `cotton_calls`, it is the only call table left.    let rows: Vec<String> = (0..seeded)        .map(|index| {            format!(                "('call-log-{index:03}','{WS}','ios_call_history','ext-{index:03}',\                 'com.apple.telephony','in','answered','2026-09-04T09:{index:02}:00.000Z',60,\                 '{stamp}','{stamp}')"            )        })        .collect();    run(        &client,        &format!(            "INSERT INTO cotton_call_log (id, workspace_id, source, external_id, provider, \             direction, outcome, started_at, duration_s, created_at, updated_at) VALUES {}",            rows.join(",")        ),        &[],    );    let answer = read(&client, "callLog", &Map::new());    let calls = answer["calls"]        .as_array()        .unwrap_or_else(|| panic!("the log answers a calls array: {answer}"));    assert_eq!(        calls.len(),        seeded,        "every seeded call comes back — the read asks for the screen's page, not the tool's \         default fifty: {answer}"    );}// ── calls ───────────────────────────────────────────────────────────────────// ── email ───────────────────────────────────────────────────────────────────#[test]fn the_mailbox_answers_the_threads_and_the_same_folder_by_sender_in_one_read() {    // The screen's segment control is a local flip between two lists over the    // same rows. Two reads would read the mailbox twice for one tap.    let (_dir, client) = attached();    let answer = read(&client, "email", &args(&[("folder", json!("inbox"))]));    assert_eq!(answer["folder"], json!("inbox"));    assert!(answer["threads"].is_array(), "{answer}");    assert!(answer["senders"].is_array(), "{answer}");}// RULE: A blocked address is still listed after all its mail has gone, so the owner can unblock it without importing another message first.#[test]fn blocked_addresses_with_no_mail_remain_visible() {    let (_dir, client) = attached();    // The shared v45 fixture contains mail; this guard deliberately tests a blocked address with none.    run(&client, "DELETE FROM cotton_emails", &[]);    run(&client, "INSERT INTO cotton_blocked_senders (id, workspace_id, address, created_at) VALUES (?1, ?2, ?3, ?4)",        &["example-block", WS, "example@example.invalid", "2026-09-30T09:00:00Z"]);    let answer = read(&client, "email", &args(&[("folder", json!("all"))]));    assert_eq!(answer["senders"], json!([]));    assert_eq!(        answer["blockedSenders"][0]["address"],        json!("example@example.invalid")    );}#[test]fn a_mailbox_asked_for_without_a_folder_reads_the_inbox() {    let (_dir, client) = attached();    let answer = read(&client, "email", &Map::new());    assert_eq!(answer["folder"], json!("inbox"));}/// One synthetic conversation for the paper mailbox: a message from somebody/// else, then the owner's reply — imported from the owner's own mailbox, so/// the reply's `gmail_account` is the owner's address.fn seed_letters(client: &ClientController) {    let stamp = "2026-09-01T00:00:00.000Z";    run(        client,        "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \         updated_at, last_at) VALUES (?,?,'synthetic-letters','Dinner at the burrow',?,?,?)",        &[EMAIL_THREAD, WS, stamp, stamp, "2026-09-01T10:00:00.000Z"],    );    run(        client,        "INSERT INTO cotton_email_participants (id, workspace_id, thread_id, email, role, \         created_at, updated_at) VALUES ('letters-p1',?,?,'otter@example.invalid','from',?,?)",        &[WS, EMAIL_THREAD, stamp, stamp],    );    run(        client,        "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \         from_name, sent_at, body, snippet, created_at, gmail_account) \         VALUES ('letters-1',?,?,'letters-1','otter@example.invalid','Otter', \         '2026-09-01T09:00:00.000Z',?,NULL,?,'Badger@Example.invalid')",        &[WS, EMAIL_THREAD, "Are you free on Saturday?\n\nThe river is high.", stamp],    );    run(        client,        "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \         from_name, sent_at, body, snippet, created_at, gmail_account) \         VALUES ('letters-2',?,?,'letters-2','badger@example.invalid','Badger', \         '2026-09-01T10:00:00.000Z',?,?,?,'badger@example.invalid')",        &[WS, EMAIL_THREAD, "Saturday works.\n\nBring the  map.", NIL, stamp],    );}#[test]fn a_mailbox_row_carries_the_first_words_of_its_newest_message() {    // The paper strip prints one faint line under the subject. It is the    // NEWEST message's, with its whitespace folded, because that is the line a    // person scanning a mailbox is looking for.    let (_dir, client) = attached();    seed_letters(&client);    let answer = read(&client, "email", &args(&[("folder", json!("inbox"))]));    let thread = answer["threads"]        .as_array()        .and_then(|rows| rows.iter().find(|row| row["id"] == json!(EMAIL_THREAD)))        .unwrap_or_else(|| panic!("the seeded thread is listed: {answer}"));    assert_eq!(thread["preview"], json!("Saturday works. Bring the map."));}#[test]fn a_preview_prefers_the_snippet_folds_whitespace_and_cuts_with_an_ellipsis() {    use super::traffic::email_preview;    assert_eq!(email_preview(Some("  "), Some("a\n\nb")), Some("a b".to_string()));    assert_eq!(email_preview(Some("the snippet"), Some("the body")), Some("the snippet".to_string()));    assert_eq!(email_preview(None, Some(" \n ")), None);    assert_eq!(email_preview(None, None), None);    let long = "word ".repeat(80);    let cut = email_preview(None, Some(&long)).expect("a long body still previews");    assert!(cut.ends_with('\u{2026}'), "{cut}");    assert!(cut.chars().count() <= 161, "{}", cut.chars().count());}#[test]fn a_thread_names_the_owner_s_own_addresses_so_the_reader_can_tell_their_letters_apart() {    // Mine versus theirs is decided by ADDRESS, never by a display name: the    // connected Google account and every mailbox a message of this thread was    // imported from, lowercased and said once.    let (_dir, client) = attached();    seed_letters(&client);    let stamp = "2026-09-01T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_google_accounts (id, workspace_id, google_email, created_at, updated_at) \         VALUES ('letters-google',?,'hedgehog@example.invalid',?,?)",        &[WS, stamp, stamp],    );    let answer = read(        &client,        "emailThread",        &args(&[("threadId", json!(EMAIL_THREAD))]),    );    assert_eq!(        answer["ownAddresses"],        json!(["badger@example.invalid", "hedgehog@example.invalid"])    );}#[test]fn a_thread_in_a_file_with_no_mailbox_of_the_owner_s_names_no_address_as_theirs() {    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \         updated_at) VALUES (?,?,'synthetic-filed','Filed by an assistant',?,?)",        &[EMAIL_THREAD, WS, stamp, stamp],    );    run(        &client,        "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \         sent_at, body, created_at) VALUES ('filed-1',?,?,'filed-1','mole@example.invalid',?,?,?)",        &[WS, EMAIL_THREAD, stamp, "A synthetic filed message", stamp],    );    let answer = read(        &client,        "emailThread",        &args(&[("threadId", json!(EMAIL_THREAD))]),    );    assert_eq!(answer["ownAddresses"], json!([]));}// ── this phone's own disk ───────────────────────────────────────────────────/// A photo, its bytes, and a chat that saw it — plus bytes nothing points at.fn seed_storage(client: &ClientController) {    let stamp = "2026-09-05T00:00:00.000Z";    let photo_sha = sha('a');    let photo_key = format!("{WS}/messages/thread-a/{photo_sha}.jpg");    let orphan_key = format!("{WS}/photos/{}.jpg", sha('b'));    run(        client,        "INSERT INTO cotton_msg_contacts (id, workspace_id, display_name, created_at, updated_at) \         VALUES ('contact-s',?,'Alpaca Friend',?,?)",        &[WS, stamp, stamp],    );    run(        client,        "INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, created_at, \         updated_at) VALUES ('thread-a',?,'contact-s','dm',?,?)",        &[WS, stamp, stamp],    );    run(        client,        "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, \         taken_at, caption, created_at, updated_at) VALUES (?,?,?,?,'image/jpeg','2048',?,?,?,?)",        &[            &format!("photo:{photo_sha}"),            WS,            &photo_key,            &photo_sha,            stamp,            "A synthetic caption",            stamp,            stamp,        ],    );    run(        client,        "INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, \         source_id, thread_id, key, seen_at, created_at, updated_at) VALUES \         ('sight-1',?,'photo',?,'message','msg-1','thread-a',?,?,?,?)",        &[            WS,            &format!("photo:{photo_sha}"),            &photo_key,            stamp,            stamp,            stamp,        ],    );    for (key, sha_value, size) in [        (photo_key.as_str(), photo_sha.as_str(), "2048"),        (orphan_key.as_str(), sha('b').leak(), "512"),    ] {        run(            client,            "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \             state, created_at, updated_at) VALUES (?,?,?,'image/jpeg',?,?,'synced',?,?)",            &[                key,                WS,                sha_value,                size,                &format!("/tmp/{sha_value}.jpg"),                stamp,                stamp,            ],        );    }}#[test]fn the_disk_screen_counts_one_object_once_even_when_a_record_and_a_chat_share_its_key() {    // A chat photo's `cotton_photos.key` IS the message's key — nothing is    // copied — so a reader that counted the record and the attachment apart    // would tell a person their phone holds double what it does.    let (_dir, client) = attached();    seed_storage(&client);    let answer = read(&client, "storage", &Map::new());    let entries = answer["entries"].as_array().expect("entries");    let photo_sha = sha('a');    let mine: Vec<&Value> = entries        .iter()        .filter(|entry| {            entry["key"]                .as_str()                .is_some_and(|key| key.contains(&photo_sha))        })        .collect();    assert_eq!(mine.len(), 1, "one object, one row: {entries:?}");    assert_eq!(mine[0]["kind"], json!("photos"));    assert_eq!(mine[0]["sizeBytes"], json!(2048));    assert_eq!(mine[0]["recordId"], json!(format!("photo:{photo_sha}")));    assert_eq!(mine[0]["threadName"], json!("Alpaca Friend"));    assert_eq!(mine[0]["title"], json!("A synthetic caption"));}#[test]fn bytes_nothing_points_at_are_listed_rather_than_left_out_of_the_total() {    // The whole reason this screen reads the ledger instead of walking the    // record tables: an orphan a delete left behind is exactly what a person    // opening it wants to find.    let (_dir, client) = attached();    seed_storage(&client);    let answer = read(&client, "storage", &Map::new());    let orphan = answer["entries"]        .as_array()        .expect("entries")        .iter()        .find(|entry| {            entry["key"]                .as_str()                .is_some_and(|key| key.contains(&sha('b')))        })        .expect("the orphan is listed");    assert_eq!(orphan["recordId"], Value::Null);    assert_eq!(orphan["threadId"], Value::Null);    // Nothing dates an orphan but the ledger's own stamp.    assert_eq!(orphan["at"], json!("2026-09-05T00:00:00.000Z"));}#[test]fn a_chat_attachment_with_no_sighting_is_still_charged_to_its_chat() {    // The sighting table is written for photo and video RECORDS. A chat's    // other bytes — a film nobody filed, a paper somebody sent — have no    // sighting row at all, so the KEY's own folder is the only thing that says    // which conversation they belong to. `{ws}/messages/{threadId}/{sha}.{ext}`    // is that folder, and reading it one character too wide meant every such    // object fell out of the by-chat list and under-reported the chat.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_msg_contacts (id, workspace_id, display_name, created_at, updated_at) \         VALUES ('contact-t',?,'Alpaca Friend',?,?)",        &[WS, stamp, stamp],    );    run(        &client,        "INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, created_at, \         updated_at) VALUES ('thread-t',?,'contact-t','dm',?,?)",        &[WS, stamp, stamp],    );    let key = format!("{WS}/messages/thread-t/{}.mp4", sha('f'));    run(        &client,        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \         state, created_at, updated_at) VALUES (?,?,?,'video/mp4','41943040','/tmp/f.mp4', \         'synced',?,?)",        &[&key, WS, &sha('f'), stamp, stamp],    );    let answer = read(&client, "storage", &Map::new());    let entry = answer["entries"]        .as_array()        .expect("entries")        .iter()        .find(|entry| entry["key"] == json!(key))        .expect("the attachment is listed");    assert_eq!(entry["recordId"], Value::Null, "no record points at it");    assert_eq!(entry["threadId"], json!("thread-t"));    assert_eq!(entry["threadName"], json!("Alpaca Friend"));}#[test]fn a_meeting_recording_carries_the_meeting_it_belongs_to() {    // `{ws}/meetings/{id}/audio.m4a` is the whole join: there is no sighting    // for a recording, so a tail read one character too wide left the row    // untitled with no record to open, and tapping it in Largest files did    // nothing.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_meetings (id, workspace_id, title, status, source, started_at, \         status_changed_at, created_at, updated_at) \         VALUES ('meeting-m',?,'A synthetic standup','ready','recorded',?,?,?,?)",        &[WS, stamp, stamp, stamp, stamp],    );    let key = format!("{WS}/meetings/meeting-m/audio.m4a");    run(        &client,        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \         state, created_at, updated_at) VALUES (?,?,?,'audio/mp4','8192','/tmp/m.m4a','synced', \         ?,?)",        &[&key, WS, &sha('g'), stamp, stamp],    );    let answer = read(&client, "storage", &Map::new());    let entry = answer["entries"]        .as_array()        .expect("entries")        .iter()        .find(|entry| entry["key"] == json!(key))        .expect("the recording is listed");    assert_eq!(entry["recordId"], json!("meeting-m"));    assert_eq!(entry["title"], json!("A synthetic standup"));    // `kind` survived the defect on the MIME fallback alone; it is asserted so    // a later reader sees which half of the row the join actually decides.    assert_eq!(entry["kind"], json!("audio"));}#[test]fn a_photographed_paper_is_counted_as_a_document_not_as_a_picture() {    // The RECORD outranks the MIME type. A bank statement someone photographed    // is `image/jpeg` and belongs in a person's papers, not in their picture    // total.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    let key = format!("{WS}/documents/{}.jpg", sha('c'));    seed_document(        &client,        "doc-photo",        "A photographed paper",        "image/jpeg",        &key,        'c',    );    run(        &client,        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \         state, created_at, updated_at) VALUES (?,?,?,'image/jpeg','4096','/tmp/c.jpg','synced', \         ?,?)",        &[&key, WS, &sha('c'), stamp, stamp],    );    let answer = read(&client, "storage", &Map::new());    let entry = answer["entries"]        .as_array()        .expect("entries")        .iter()        .find(|entry| entry["key"] == json!(key))        .expect("the paper is listed");    assert_eq!(entry["kind"], json!("documents"));    assert_eq!(entry["title"], json!("A photographed paper"));}#[test]fn bytes_this_phone_no_longer_holds_are_not_on_the_disk_screen() {    // The screen answers "what is on THIS phone". A row queued for deletion, or    // one whose file has gone, is not something a person can free.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \         state, created_at, updated_at) VALUES (?,?,?,'image/jpeg','64',NULL,'pending',?,?)",        &[            &format!("{WS}/photos/{}.jpg", sha('d')),            WS,            &sha('d'),            stamp,            stamp,        ],    );    run(        &client,        "INSERT INTO _media (key, workspace_id, sha256, content_type, size_bytes, local_path, \         state, created_at, updated_at) VALUES (?,?,?,'image/jpeg','64','/tmp/e.jpg', \         'delete_pending',?,?)",        &[            &format!("{WS}/photos/{}.jpg", sha('e')),            WS,            &sha('e'),            stamp,            stamp,        ],    );    let answer = read(&client, "storage", &Map::new());    let keys: Vec<&str> = answer["entries"]        .as_array()        .expect("entries")        .iter()        .filter_map(|entry| entry["key"].as_str())        .collect();    assert!(        keys.iter()            .all(|key| !key.contains(&sha('d')) && !key.contains(&sha('e'))),        "{keys:?}"    );}// ── the composed-read contract ──────────────────────────────────────────────#[test]fn a_composed_read_that_wrote_is_refused_and_rolled_back() {    // The whole safety of `ReadSource::Composed` is this: a screen that wrote    // something by being LOOKED AT is a defect, and the rollback is what stops    // it leaving a row behind that nothing will ever push.    let (_dir, client) = attached();    let before = todos(&client);    let error = client        .read_rows("pretendScreen", &mut |ctx| {            let handler = cotton_tools::mcp::dispatch::handler_for("create_todo")                .expect("create_todo is in the catalogue");            handler(ctx, &args(&[("title", json!("A synthetic errand"))]))                .map_err(|failure| failure.to_string())        })        .expect_err("a read that wrote is refused");    assert!(        error.contains("read.pretendScreen wrote"),        "the refusal names the read: {error}"    );    assert_eq!(        todos(&client),        before,        "the refused write was rolled back, not merely unreported"    );}fn todos(client: &ClientController) -> i64 {    client        .with_writer(|replica| {            replica                .driver                .get("SELECT COUNT(*) AS n FROM cotton_todos", &[])                .map_err(|error| error.to_string())?                .and_then(|row| row.int("n"))                .ok_or_else(|| "no count came back".to_string())        })        .expect("the count")}// ── the pictures ────────────────────────────────────────────────────────────/// One picture, with everything the store insists on and nothing real in it.fn seed_photo(client: &ClientController, seed: char, taken: &str, subtypes: &str, utility: &str) {    let stamp = "2026-09-05T00:00:00.000Z";    let digest = sha(seed);    run(        client,        "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, \         taken_at, preview, subtypes, is_utility, created_at, updated_at) \         VALUES (?,?,?,?,'image/jpeg','1024',?,'BLUR',?,?,?,?)",        &[            &format!("photo:{digest}"),            WS,            &format!("{WS}/photos/{digest}.jpg"),            &digest,            taken,            subtypes,            utility,            stamp,            stamp,        ],    );}fn photo_id(seed: char) -> String {    format!("photo:{}", sha(seed))}#[test]fn the_grid_is_the_whole_library_and_every_tile_carries_what_it_needs_to_draw() {    // The tool's own list caps at two hundred and hands back no object key —    // an assistant asks for bytes another way. A tile has nothing else to draw    // with, so the key and the inline blur ride beside the tool's own row.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    seed_photo(&client, 'b', "2026-09-02T00:00:00.000Z", "[]", NIL);    let answer = read(&client, "photos", &Map::new());    let photos = answer["photos"].as_array().expect("photos");    assert_eq!(photos.len(), 2);    // Newest first, as the grid's month bands read it.    assert_eq!(photos[0]["id"], json!(photo_id('b')));    assert!(photos[0]["key"]        .as_str()        .expect("a key")        .ends_with(&format!("{}.jpg", sha('b'))));    assert_eq!(photos[0]["preview"], json!("BLUR"));    // The grid is the LIBRARY, not a page — asserted against the filter itself,    // because two seeded photos would read as two under any ceiling.    assert!(        super::traffic::library_filters(Some(false)).limit.is_none(),        "the grid asked for a page rather than the whole library"    );}#[test]fn a_picture_the_person_agreed_is_a_copy_leaves_the_grid_and_keeps_its_row() {    // A filter, never a delete: the row and its bytes stay until the person    // removes them from the picture's own page.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    seed_photo(&client, 'b', "2026-09-02T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_duplicates (id, workspace_id, record_kind, keep_id, copy_id, \         distance, method, state, decided_at, created_at, updated_at) \         VALUES ('dup-1',?,'photo',?,?,'2','phash','confirmed',?,?,?)",        &[WS, &photo_id('a'), &photo_id('b'), stamp, stamp, stamp],    );    let answer = read(&client, "photos", &Map::new());    let ids: Vec<&str> = answer["photos"]        .as_array()        .expect("photos")        .iter()        .filter_map(|photo| photo["id"].as_str())        .collect();    assert_eq!(ids, vec![photo_id('a').as_str()]);    // The row is still there — it left the grid, it was not deleted.    let still_there = client        .with_writer(|replica| {            replica                .driver                .get("SELECT COUNT(*) AS n FROM cotton_photos", &[])                .map_err(|error| error.to_string())?                .and_then(|row| row.int("n"))                .ok_or_else(|| "no count".to_string())        })        .expect("the count");    assert_eq!(still_there, 2);}#[test]fn the_duplicates_page_hands_back_both_pictures_of_every_pair() {    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    seed_photo(&client, 'b', "2026-09-02T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_duplicates (id, workspace_id, record_kind, keep_id, copy_id, \         distance, method, state, created_at, updated_at) \         VALUES ('dup-open',?,'photo',?,?,'2','phash','open',?,?)",        &[WS, &photo_id('a'), &photo_id('b'), stamp, stamp],    );    let answer = read(&client, "duplicates", &Map::new());    assert_eq!(answer["groups"].as_array().expect("groups").len(), 1);    let ids: Vec<&str> = answer["photos"]        .as_array()        .expect("photos")        .iter()        .filter_map(|photo| photo["id"].as_str())        .collect();    assert!(ids.contains(&photo_id('a').as_str()) && ids.contains(&photo_id('b').as_str()));}#[test]fn a_pair_whose_picture_is_gone_still_draws_its_page() {    // The screen has a sentence for a picture that is no longer there. Refusing    // the whole page because one row of a pair went would lose the person the    // decision they came to make.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_duplicates (id, workspace_id, record_kind, keep_id, copy_id, \         distance, method, state, created_at, updated_at) \         VALUES ('dup-gone',?,'photo',?,?,'2','phash','open',?,?)",        &[WS, &photo_id('a'), &photo_id('f'), stamp, stamp],    );    let answer = read(&client, "duplicates", &Map::new());    assert_eq!(answer["groups"].as_array().expect("groups").len(), 1);    assert_eq!(answer["photos"].as_array().expect("photos").len(), 1);}#[test]fn a_face_the_mac_recognises_is_asked_about_nearest_first_and_by_name() {    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    for (id, distance) in [("face-far", "0.40"), ("face-near", "0.10")] {        run(            &client,            "INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, \             source_id, x, y, w, h, suggested_person_id, suggested_distance, created_at, \             updated_at) VALUES (?,?,'photo',?,'cotton',?, '0.1','0.1','0.2','0.2','person-a',?, \             ?,?)",            &[id, WS, &photo_id('a'), id, distance, stamp, stamp],        );    }    let answer = read(&client, "faceSuggestions", &Map::new());    let faces = answer["faces"].as_array().expect("faces");    assert_eq!(faces.len(), 2);    assert_eq!(faces[0]["id"], json!("face-near"), "nearest is asked first");    assert_eq!(faces[0]["suggestedName"], json!("Alpaca Tester"));    // The face's rectangle travels with it, so the slip draws the face and not the    // whole picture.    assert_eq!(faces[0]["x"], json!(0.1));    assert_eq!(faces[0]["w"], json!(0.2));    // The picture is attached once for the whole list, never once per row.    assert_eq!(answer["photos"].as_array().expect("photos").len(), 1);}#[test]fn a_face_somebody_has_already_named_is_not_asked_about_again() {    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_faces (id, workspace_id, record_kind, record_id, source, \         source_id, x, y, w, h, person_id, suggested_person_id, suggested_distance, created_at, \         updated_at) VALUES ('face-known',?,'photo',?,'cotton','face-known', \         '0.1','0.1','0.2','0.2','person-a','person-a','0.05',?,?)",        &[WS, &photo_id('a'), stamp, stamp],    );    let answer = read(&client, "faceSuggestions", &Map::new());    assert!(answer["faces"].as_array().expect("faces").is_empty());}#[test]fn what_can_still_go_in_an_album_leaves_out_what_is_in_it_and_what_is_not_a_picture_of_anything() {    // Three exclusions, all the album service's: what the album already holds,    // a screenshot, and a utility image — the same rule the nightly pass    // applies when it builds an album by itself.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    seed_photo(        &client,        'b',        "2026-09-02T00:00:00.000Z",        "[\"screenshot\"]",        NIL,    );    seed_photo(&client, 'c', "2026-09-03T00:00:00.000Z", "[]", "1");    seed_photo(&client, 'd', "2026-09-04T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, title, starts_at, ends_at, \         created_at, updated_at) VALUES \         ('album:1',?,'trip','A synthetic trip','2026-09-01','2026-09-04',?,?)",        &[WS, stamp, stamp],    );    run(        &client,        "INSERT INTO cotton_media_album_items (id, workspace_id, album_id, record_kind, \         record_id, added_by, sort_at, created_at, updated_at) \         VALUES ('item-1',?,'album:1','photo',?,'user',?,?,?)",        &[WS, &photo_id('d'), stamp, stamp, stamp],    );    let answer = read(        &client,        "addablePhotos",        &args(&[("albumId", json!("album:1"))]),    );    let ids: Vec<&str> = answer["photos"]        .as_array()        .expect("photos")        .iter()        .filter_map(|photo| photo["id"].as_str())        .collect();    assert_eq!(ids, vec![photo_id('a').as_str()], "{ids:?}");}#[test]fn a_picture_s_page_names_the_albums_it_is_in_and_not_the_one_the_person_dismissed() {    // The open photo wears each album as a tag. A dismissed album is not one    // the person has, so the page does not wear it.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, state, decided_at, title, \         starts_at, ends_at, created_at, updated_at) VALUES \         ('album:kept',?,'trip','kept',?,'A synthetic trip','2026-09-01','2026-09-04',?,?), \         ('album:gone',?,'event','dismissed',?,'A dismissed evening','2026-09-01','2026-09-01',?,?)",        &[WS, stamp, stamp, stamp, WS, stamp, stamp, stamp],    );    for (item, album) in [("item-kept", "album:kept"), ("item-gone", "album:gone")] {        run(            &client,            "INSERT INTO cotton_media_album_items (id, workspace_id, album_id, record_kind, \             record_id, added_by, sort_at, created_at, updated_at) \             VALUES (?,?,?,'photo',?,'user',?,?,?)",            &[item, WS, album, &photo_id('a'), stamp, stamp, stamp],        );    }    let answer = read(&client, "photo", &args(&[("id", json!(photo_id('a')))]));    assert_eq!(        answer["albums"],        json!([{ "id": "album:kept", "title": "A synthetic trip", "state": "kept" }])    );}#[test]fn a_picture_s_page_says_where_it_has_been_seen_oldest_first_and_names_the_chat() {    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_msg_contacts (id, workspace_id, display_name, created_at, updated_at) \         VALUES ('contact-p',?,'Alpaca Friend',?,?)",        &[WS, stamp, stamp],    );    run(        &client,        "INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, created_at, \         updated_at) VALUES ('thread-p',?,'contact-p','dm',?,?)",        &[WS, stamp, stamp],    );    run(        &client,        "INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, \         source_id, key, seen_at, created_at, updated_at) VALUES \         ('sight-lib',?,'photo',?,'library','asset-1',?,'2026-09-02T00:00:00.000Z',?,?)",        &[            WS,            &photo_id('a'),            &format!("{WS}/photos/{}.jpg", sha('a')),            stamp,            stamp,        ],    );    run(        &client,        "INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, \         source_id, thread_id, key, seen_at, created_at, updated_at) VALUES \         ('sight-chat',?,'photo',?,'message','msg-9','thread-p',?, \         '2026-09-01T00:00:00.000Z',?,?)",        &[            WS,            &photo_id('a'),            &format!("{WS}/photos/{}.jpg", sha('a')),            stamp,            stamp,        ],    );    // A DANGLING thread id, which is the case the read's `LEFT JOIN` exists for    // and the one a null `thread_id` cannot stand in for: this sighting names a    // conversation that is not in the file, and both joins have to miss for the    // screen to fall back to "A chat". It has to be a `message` sighting to    // carry a thread id at all — the table's own    // `CHECK ((source = 'message') = (thread_id IS NOT NULL))` forbids any other    // source from naming one, so a library row could never be the dangling case.    run(        &client,        "INSERT INTO cotton_media_sightings (id, workspace_id, record_kind, record_id, source, \         source_id, thread_id, key, seen_at, created_at, updated_at) VALUES \         ('sight-gone',?,'photo',?,'message','msg-7','thread-gone',?, \         '2026-09-03T00:00:00.000Z',?,?)",        &[            WS,            &photo_id('a'),            &format!("{WS}/photos/{}.jpg", sha('a')),            stamp,            stamp,        ],    );    let answer = read(&client, "photo", &args(&[("id", json!(photo_id('a')))]));    let seen = answer["sightings"].as_array().expect("sightings");    assert_eq!(seen.len(), 3);    assert_eq!(seen[0]["id"], json!("sight-chat"), "oldest first");    assert_eq!(seen[0]["threadName"], json!("Alpaca Friend"));    // The library sighting is in no conversation at all …    assert_eq!(seen[1]["id"], json!("sight-lib"));    assert_eq!(seen[1]["threadName"], Value::Null);    // … and this one is in a conversation the file has lost. Two different    // reasons for one answer, and only the second is the join's own job.    assert_eq!(seen[2]["id"], json!("sight-gone"));    assert_eq!(seen[2]["threadId"], json!("thread-gone"));    assert_eq!(seen[2]["threadName"], Value::Null);    assert_eq!(answer["photo"]["id"], json!(photo_id('a')));}#[test]fn a_video_tile_is_handed_its_poster_never_the_film() {    // A grid pointed at the film would pull down half a gigabyte to draw twelve    // squares. A video with no poster yet answers null and the tile draws a    // play glyph on quiet ground — the honest state, not a failure.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    for (seed, poster) in [('a', "yes"), ('b', "no")] {        let digest = sha(seed);        let poster_key = format!("{WS}/videos/{digest}.poster.jpg");        run(            &client,            "INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, \             taken_at, poster_key, created_at, updated_at) \             VALUES (?,?,?,?,'video/quicktime','4096',?,?,?,?)",            &[                &format!("video:{digest}"),                WS,                &format!("{WS}/videos/{digest}.mov"),                &digest,                stamp,                if poster == "yes" { &poster_key } else { NIL },                stamp,                stamp,            ],        );    }    // The films ride in the library's own read — `/photos` is one library.    let answer = read(&client, "photos", &Map::new());    let videos = answer["videos"].as_array().expect("videos");    assert_eq!(videos.len(), 2);    let with_poster = videos        .iter()        .find(|video| video["id"] == json!(format!("video:{}", sha('a'))))        .expect("the video with a poster");    assert!(with_poster["posterKey"]        .as_str()        .expect("a poster key")        .ends_with(".poster.jpg"));    let without = videos        .iter()        .find(|video| video["id"] == json!(format!("video:{}", sha('b'))))        .expect("the video without one");    assert_eq!(without["posterKey"], Value::Null);    assert!(without["key"]        .as_str()        .expect("the film's key")        .ends_with(".mov"));}#[test]fn an_albums_members_arrive_ready_to_draw_and_so_does_its_cover() {    // `get_album` says WHICH pictures are in an album and nothing a tile can    // paint with — right for an assistant, and the reason every tile on the    // album page drew empty. The cover is asked for beside the members, so it    // still resolves when it is a picture the album no longer holds, which is    // exactly when hunting for it in the member list fails.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    seed_photo(&client, 'b', "2026-09-02T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, title, starts_at, ends_at, \         cover_id, created_at, updated_at) VALUES \         ('album:trip:2026-09-01',?,'trip','A synthetic trip','2026-09-01','2026-09-02',?,?,?)",        &[WS, &photo_id('b'), stamp, stamp],    );    run(        &client,        "INSERT INTO cotton_media_album_items (id, workspace_id, album_id, record_kind, \         record_id, added_by, sort_at, created_at, updated_at) \         VALUES ('item-2',?,'album:trip:2026-09-01','photo',?,'user',?,?,?)",        &[WS, &photo_id('a'), stamp, stamp, stamp],    );    let answer = read(&client, "album", &args(&[("id", json!("album:trip:2026-09-01"))]));    let items = answer["items"].as_array().expect("items");    assert_eq!(items.len(), 1);    assert!(        items[0]["key"]            .as_str()            .expect("the member's own key")            .ends_with(".jpg"),        "a tile has nothing to draw with without it"    );    assert_eq!(items[0]["preview"], json!("BLUR"));    assert!(answer["cover"]["key"]        .as_str()        .expect("the cover's key")        .ends_with(".jpg"));}#[test]fn an_album_with_no_cover_says_so_rather_than_answering_a_half_object() {    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, title, starts_at, ends_at, \         created_at, updated_at) VALUES \         ('album:trip:2026-09-02',?,'trip','A synthetic trip','2026-09-01','2026-09-02',?,?)",        &[WS, stamp, stamp],    );    let answer = read(&client, "album", &args(&[("id", json!("album:trip:2026-09-02"))]));    assert_eq!(answer["cover"], Value::Null);    assert_eq!(answer["items"].as_array().expect("items").len(), 0);}#[test]fn an_album_card_carries_its_cover_on_both_screens_that_draw_one() {    // The same gap one level up: `list_albums` answers a `coverId` and nothing    // a renderer can use, so a CARD named an album and drew an empty square —    // which a person reads as "those pictures are not on this phone" about    // bytes on the disk. Both the albums page and the strip on `/photos` draw    // that card, so both are asserted here.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, title, starts_at, ends_at, \         cover_id, state, created_at, updated_at) VALUES \         ('album:trip:2026-09-03',?,'trip','A synthetic trip','2026-09-01','2026-09-02',?,\         'open',?,?)",        &[WS, &photo_id('a'), stamp, stamp],    );    for (name, at) in [("albums", "albums"), ("photos", "albums")] {        let answer = read(&client, name, &args(&[]));        let cards = answer[at].as_array().expect("the album cards");        assert_eq!(cards.len(), 1, "read.{name} lost the album itself");        assert!(            cards[0]["cover"]["key"]                .as_str()                .unwrap_or_default()                .ends_with(".jpg"),            "read.{name} answers a card with no cover to draw"        );        assert_eq!(cards[0]["cover"]["preview"], json!("BLUR"));    }}#[test]fn an_album_card_with_no_cover_says_null_rather_than_a_half_object() {    // One Swift type reads a card's cover and the album page's, so the SHAPE    // of "there isn't one" has to be the same in both.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_media_albums (id, workspace_id, kind, title, starts_at, ends_at, \         state, created_at, updated_at) VALUES \         ('album:trip:2026-09-04',?,'trip','A synthetic trip','2026-09-01','2026-09-02',\         'open',?,?)",        &[WS, stamp, stamp],    );    let answer = read(&client, "albums", &args(&[]));    let cards = answer["albums"].as_array().expect("the album cards");    assert_eq!(cards.len(), 1);    assert_eq!(cards[0]["cover"], Value::Null);}#[test]fn a_pictures_own_page_is_handed_the_key_its_renderer_needs() {    // The grid's rows carry the object key; the DETAIL read did not, and those    // were the two screens in this lane that could name a picture and then not    // draw it. `media_out` says what a picture IS and never where its bytes    // are — right for an assistant, useless to a renderer — so the key is    // merged on here exactly as `media_rows` merges it for the grid.    let (_dir, client) = attached();    seed_photo(&client, 'a', "2026-09-01T00:00:00.000Z", "[]", NIL);    let answer = read(&client, "photo", &args(&[("id", json!(photo_id('a')))]));    assert!(        answer["photo"]["key"]            .as_str()            .expect("the picture's own key")            .ends_with(".jpg"),        "the page has nothing to resolve bytes with without it"    );    assert_eq!(answer["photo"]["preview"], json!("BLUR"));}#[test]fn a_films_own_page_is_handed_both_keys_because_it_draws_both() {    // A film's page plays the FILM and shows the POSTER behind the play glyph    // until it does — two objects, two keys, and the grid's rule (a tile    // resolves the poster and never the film) does not apply to a page whose    // whole purpose is the film.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    let digest = sha('a');    run(        &client,        "INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, \         taken_at, poster_key, preview, created_at, updated_at) \         VALUES (?,?,?,?,'video/quicktime','4096',?,?,'BLUR',?,?)",        &[            &format!("video:{digest}"),            WS,            &format!("{WS}/videos/{digest}.mov"),            &digest,            stamp,            &format!("{WS}/videos/{digest}.poster.jpg"),            stamp,            stamp,        ],    );    let answer = read(        &client,        "video",        &args(&[("id", json!(format!("video:{digest}")))]),    );    assert!(answer["video"]["key"]        .as_str()        .expect("the film's key")        .ends_with(".mov"));    assert!(answer["video"]["posterKey"]        .as_str()        .expect("the poster's key")        .ends_with(".poster.jpg"));}// ── the chats ───────────────────────────────────────────────────────────────const THREAD_A: &str = "44444444-4444-4444-8444-444444444401";const THREAD_B: &str = "44444444-4444-4444-8444-444444444402";/// Two contacts and their conversations — one live, one put away.fn seed_chats(client: &ClientController) {    let stamp = "2026-09-05T00:00:00.000Z";    for (contact, thread, name, archived, last) in [        (            "contact-1",            THREAD_A,            "Alpaca One",            "0",            "2026-09-05T10:00:00.000Z",        ),        (            "contact-2",            THREAD_B,            "Alpaca Two",            "1",            "2026-09-04T10:00:00.000Z",        ),    ] {        run(            client,            "INSERT INTO cotton_msg_contacts (id, workspace_id, display_name, created_at, \             updated_at) VALUES (?,?,?,?,?)",            &[contact, WS, name, stamp, stamp],        );        run(            client,            "INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, archived, \             last_message_at, created_at, updated_at) VALUES (?,?,?,'dm',?,?,?,?)",            &[thread, WS, contact, archived, last, stamp, stamp],        );    }}/// One message in a conversation, at a stated instant.fn seed_message(client: &ClientController, id: &str, thread: &str, sent_at: &str, body: &str) {    run(        client,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, \         origin, body, sent_at, created_at) VALUES (?,?,?,'in','whatsapp','live',?,?,?)",        &[id, thread, WS, body, sent_at, sent_at],    );}#[test]fn the_inbox_hides_what_the_person_put_away_and_says_how_much_that_is() {    let (_dir, client) = attached();    seed_chats(&client);    let inbox = read(&client, "threads", &Map::new());    let ids: Vec<&str> = inbox["threads"]        .as_array()        .expect("threads")        .iter()        .filter_map(|thread| thread["id"].as_str())        .collect();    assert_eq!(ids, vec![THREAD_A], "{ids:?}");    assert_eq!(inbox["archivedCount"], json!(1));    // And the count opens the other half.    let put_away = read(&client, "threads", &args(&[("archived", json!(true))]));    let ids: Vec<&str> = put_away["threads"]        .as_array()        .expect("threads")        .iter()        .filter_map(|thread| thread["id"].as_str())        .collect();    assert_eq!(ids, vec![THREAD_B], "{ids:?}");}#[test]fn one_person_on_two_numbers_is_one_row_on_the_inbox() {    // The whole reason the inbox groups by PERSON rather than by thread. A    // contact reachable on a WhatsApp number and an iMessage number has two    // contacts and two threads in the file; drawing both would show the same    // human twice, one channel mark each, with whatever they last said split    // between the two rows. The inbox has no toggle — a person is a person —    // and core's own fold is what this read asks the tool for.    let (_dir, client) = attached();    let stamp = "2026-09-05T00:00:00.000Z";    let person = "55555555-5555-4555-8555-555555555501";    run(        &client,        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \         VALUES (?,?,'Alpaca Friend',?,?)",        &[person, WS, stamp, stamp],    );    for (contact, thread, name, channel, last) in [        (            "contact-w",            THREAD_A,            "Alpaca on one number",            "whatsapp",            "2026-09-05T09:00:00.000Z",        ),        (            "contact-i",            THREAD_B,            "Alpaca on the other",            "imessage",            "2026-09-05T11:00:00.000Z",        ),    ] {        run(            &client,            "INSERT INTO cotton_msg_contacts (id, workspace_id, person_id, display_name, \             created_at, updated_at) VALUES (?,?,?,?,?,?)",            &[contact, WS, person, name, stamp, stamp],        );        run(            &client,            "INSERT INTO cotton_msg_threads (id, workspace_id, contact_id, kind, archived, \             last_message_at, created_at, updated_at) VALUES (?,?,?,'dm','0',?,?,?)",            &[thread, WS, contact, last, stamp, stamp],        );        run(            &client,            "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, \             origin, body, sent_at, created_at) VALUES (?,?,?,'in',?,'live','A synthetic line',?,?)",            &[                &format!("msg-{contact}"),                thread,                WS,                channel,                last,                last,            ],        );    }    let inbox = read(&client, "threads", &Map::new());    let rows = inbox["threads"].as_array().expect("threads");    assert_eq!(rows.len(), 1, "one human, one row: {rows:?}");    let row = &rows[0];    assert_eq!(row["personId"], json!(person));    assert_eq!(row["name"], json!("Alpaca Friend"), "the PERSON's name");    // Both transports on one row, in the vocabulary's own order.    let channels: Vec<&str> = row["channels"]        .as_array()        .expect("channels")        .iter()        .filter_map(Value::as_str)        .collect();    assert_eq!(channels.len(), 2, "{channels:?}");    assert!(channels.contains(&"whatsapp") && channels.contains(&"imessage"));    // And the tap opens the thread they last wrote on — the tool leaves `id`    // out of a merged conversation and answers `threadIds` sorted by id, so    // the newest is resolved by the read.    assert_eq!(row["id"], json!(THREAD_B));    let ids: Vec<&str> = row["threadIds"]        .as_array()        .expect("threadIds")        .iter()        .filter_map(Value::as_str)        .collect();    assert_eq!(ids.len(), 2, "{ids:?}");}#[test]fn a_window_bigger_than_one_read_is_assembled_in_order_and_says_there_is_more() {    // The screen's window grows as the person pulls at the top — fifty, then a    // hundred, then a hundred and fifty — and one read of the tool answers a    // hundred. So a window past that is built from the tool's own `before`    // cursor, and the conversation still reads top to bottom exactly once.    let (_dir, client) = attached();    seed_chats(&client);    for minute in 0..150 {        seed_message(            &client,            &format!("msg-{minute:03}"),            THREAD_A,            &format!("2026-09-05T{:02}:{:02}:00.000Z", minute / 60, minute % 60),            &format!("A synthetic line {minute}"),        );    }    let answer = read(        &client,        "thread",        &args(&[("threadId", json!(THREAD_A)), ("limit", json!(120))]),    );    let messages = answer["messages"].as_array().expect("messages");    assert_eq!(messages.len(), 120, "the whole window, across two reads");    assert_eq!(answer["hasMore"], json!(true));    // Oldest first, no repeats, no gaps at the seam between the two pages.    let ids: Vec<&str> = messages        .iter()        .filter_map(|message| message["id"].as_str())        .collect();    let unique: std::collections::BTreeSet<&str> = ids.iter().copied().collect();    assert_eq!(unique.len(), ids.len(), "a page was read twice");    let mut sorted = ids.clone();    sorted.sort_unstable();    assert_eq!(ids, sorted, "the window is one conversation, in order");    assert_eq!(ids[119], "msg-149", "and it ends at the newest message");}#[test]fn a_conversation_shorter_than_the_window_says_there_is_no_more() {    let (_dir, client) = attached();    seed_chats(&client);    for minute in 0..5 {        seed_message(            &client,            &format!("short-{minute}"),            THREAD_A,            &format!("2026-09-05T00:0{minute}:00.000Z"),            "A synthetic line",        );    }    let answer = read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]));    assert_eq!(answer["messages"].as_array().expect("messages").len(), 5);    assert_eq!(answer["hasMore"], json!(false));}#[test]fn a_conversation_asked_for_by_nothing_at_all_says_which_argument_it_wanted() {    let (_dir, client) = attached();    let entry = super::reads::read_for("read.thread").expect("declared");    let error = super::answer_read(&client, entry, &Map::new()).expect_err("a refusal");    assert!(        error.contains("threadId") && error.contains("personId"),        "{error}"    );}#[test]fn a_dm_is_named_for_the_person_on_the_other_end_of_it() {    let (_dir, client) = attached();    seed_chats(&client);    let answer = read(        &client,        "threadInfo",        &args(&[("threadId", json!(THREAD_A))]),    );    assert_eq!(answer["thread"]["title"], json!("Alpaca One"));    assert_eq!(answer["thread"]["kind"], json!("dm"));    assert_eq!(answer["thread"]["archived"], json!(false));}#[test]fn a_conversation_that_is_not_here_is_refused_the_same_way_one_in_another_file_is() {    // One answer for "absent" and "not this workspace" — the tool's own    // probe-resistance rule, which a phone read must not undo by being more    // helpful.    let (_dir, client) = attached();    let entry = super::reads::read_for("read.threadInfo").expect("declared");    let error = super::answer_read(&client, entry, &args(&[("threadId", json!(THREAD_A))]))        .expect_err("a refusal");    assert!(error.contains("no such conversation"), "{error}");}#[test]fn the_kept_messages_are_the_starred_ones_newest_kept_first_and_they_name_their_chat() {    let (_dir, client) = attached();    seed_chats(&client);    seed_message(        &client,        "star-old",        THREAD_A,        "2026-09-01T00:00:00.000Z",        "Older",    );    seed_message(        &client,        "star-new",        THREAD_A,        "2026-09-02T00:00:00.000Z",        "Newer",    );    seed_message(        &client,        "plain",        THREAD_A,        "2026-09-03T00:00:00.000Z",        "Not kept",    );    // Starred in the opposite order to the way they were sent, because the list    // is ordered by when the person kept them.    run(        &client,        "UPDATE cotton_msg_messages SET starred_at = '2026-09-06T00:00:00.000Z' WHERE id = ?",        &["star-old"],    );    run(        &client,        "UPDATE cotton_msg_messages SET starred_at = '2026-09-07T00:00:00.000Z' WHERE id = ?",        &["star-new"],    );    let answer = read(&client, "starred", &Map::new());    let kept = answer["messages"].as_array().expect("messages");    assert_eq!(kept.len(), 2);    assert_eq!(kept[0]["id"], json!("star-new"));    assert_eq!(kept[1]["id"], json!("star-old"));    assert_eq!(kept[0]["threadName"], json!("Alpaca One"));}#[test]fn a_message_the_person_hid_is_not_among_the_ones_they_kept() {    let (_dir, client) = attached();    seed_chats(&client);    seed_message(        &client,        "hidden",        THREAD_A,        "2026-09-01T00:00:00.000Z",        "Gone",    );    run(        &client,        "UPDATE cotton_msg_messages SET starred_at = '2026-09-06T00:00:00.000Z', \         hidden_at = '2026-09-06T01:00:00.000Z' WHERE id = ?",        &["hidden"],    );    let answer = read(&client, "starred", &Map::new());    assert!(answer["messages"].as_array().expect("messages").is_empty());}#[test]fn what_a_conversation_has_carried_is_listed_newest_first_and_left_in_its_own_shape() {    let (_dir, client) = attached();    seed_chats(&client);    seed_message(        &client,        "with-media",        THREAD_A,        "2026-09-02T00:00:00.000Z",        "Look",    );    seed_message(        &client,        "no-media",        THREAD_A,        "2026-09-03T00:00:00.000Z",        "Words only",    );    run(        &client,        "UPDATE cotton_msg_messages SET media = '[{\"key\":\"a\",\"contentType\":\"image/jpeg\"}]' \         WHERE id = ?",        &["with-media"],    );    let answer = read(        &client,        "threadMedia",        &args(&[("threadId", json!(THREAD_A))]),    );    let carried = answer["media"].as_array().expect("media");    assert_eq!(carried.len(), 1);    assert_eq!(carried[0]["messageId"], json!("with-media"));    assert_eq!(carried[0]["media"][0]["key"], json!("a"));}const EMAIL_THREAD: &str = "55555555-5555-4555-8555-555555555501";#[test]fn a_long_correspondence_opens_whole_rather_than_on_its_newest_fifty() {    // `emailsService.readThread` reads the WHOLE thread and    // `read_email_thread` defaults to fifty. On a page whose entire job is the    // record of a conversation, being short by default and silent about it is    // the worst possible way to be short.    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \         updated_at) VALUES (?,?,'synthetic-long-thread','A long alpaca thread',?,?)",        &[EMAIL_THREAD, WS, stamp, stamp],    );    for at in 0..60 {        run(            &client,            "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \             sent_at, subject, body, created_at) VALUES (?,?,?,?,'nobody@example.invalid',?,?,?,?)",            &[                &format!("long-{at:03}"),                WS,                EMAIL_THREAD,                &format!("long-{at:03}"),                &format!("2026-09-01T{:02}:{:02}:00.000Z", at / 60, at % 60),                "A long alpaca thread",                &format!("A synthetic message {at}"),                stamp,            ],        );    }    let answer = read(        &client,        "emailThread",        &args(&[("threadId", json!(EMAIL_THREAD))]),    );    let messages = answer["emails"].as_array().expect("the thread's messages");    assert_eq!(        messages.len(),        60,        "the whole thread, not the tool's default"    );}#[test]fn a_correspondence_stamped_to_one_instant_still_reads_to_its_beginning() {    // Sixty imported emails whose headers all said the same second. A page    // cursor that is an INSTANT with a strict `<` returns an arbitrary fifty    // on page one and NOTHING on page two, for ever — the screen would draw    // fifty under a header saying sixty. The keyset cursor is `(sent_at, id)`,    // which is the rule `packages/core/src/services/chat/queries.ts:365-375`    // already states on the other side.    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \         updated_at) VALUES (?,?,'synthetic-tied-thread','A tied alpaca thread',?,?)",        &[EMAIL_THREAD, WS, stamp, stamp],    );    for at in 0..60 {        run(            &client,            "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \             sent_at, subject, body, created_at) VALUES (?,?,?,?,'nobody@example.invalid',?,?,?,?)",            &[                &format!("tied-{at:03}"),                WS,                EMAIL_THREAD,                &format!("tied-{at:03}"),                // Every one of them, to the same second.                "2026-09-01T10:00:00.000Z",                "A tied alpaca thread",                &format!("A synthetic message {at}"),                stamp,            ],        );    }    let answer = read(        &client,        "emailThread",        &args(&[("threadId", json!(EMAIL_THREAD))]),    );    let messages = answer["emails"].as_array().expect("the thread's messages");    assert_eq!(messages.len(), 60, "every one of them, not the first page");    let mut ids: Vec<&str> = messages        .iter()        .filter_map(|email| email["id"].as_str())        .collect();    ids.sort_unstable();    ids.dedup();    assert_eq!(ids.len(), 60, "and each exactly once");}#[test]fn a_threads_unread_mark_is_folded_over_every_message_not_over_the_newest_page() {    // `emailsService.readThread` folds `unread` / `starred` / `inInbox` over    // EVERY message; `read_email_thread` folds over the page it read. A sixty-    // email correspondence whose one unread message is the third would answer    // `unread: false` in the header while `list_email_threads` — folding over    // all of them — draws the dot on the mailbox row. `markReadOnce` is gated    // on that header, so it would never fire and the dot would never clear.    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \         updated_at) VALUES (?,?,'synthetic-fold-thread','A folded alpaca thread',?,?)",        &[EMAIL_THREAD, WS, stamp, stamp],    );    for at in 0..60 {        run(            &client,            "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \             sent_at, subject, body, unread, starred, created_at) \             VALUES (?,?,?,?,'nobody@example.invalid',?,?,?,?,?,?)",            &[                &format!("fold-{at:03}"),                WS,                EMAIL_THREAD,                &format!("fold-{at:03}"),                &format!("2026-09-01T{:02}:{:02}:00.000Z", at / 60, at % 60),                "A folded alpaca thread",                &format!("A synthetic message {at}"),                // The third-oldest is the only unread one, and the second the                // only kept one — both far outside the newest fifty.                if at == 2 { "1" } else { "0" },                if at == 1 { "1" } else { "0" },                stamp,            ],        );    }    let answer = read(        &client,        "emailThread",        &args(&[("threadId", json!(EMAIL_THREAD))]),    );    assert_eq!(answer["thread"]["unread"], json!(true));    assert_eq!(answer["thread"]["starred"], json!(true));}#[test]fn a_walk_the_ceiling_cut_short_keeps_its_handle_rather_than_claiming_the_end() {    // The forty-page ceiling is a ceiling on the WALK, and it is declared. What    // must not happen is the answer claiming the correspondence is whole: a    // screen reading `nextBefore: null` states in terms that everything is    // drawn. A finished walk nulls the handle; a truncated one carries the last    // cursor out.    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(        &client,        "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, created_at, \         updated_at) VALUES (?,?,'synthetic-short-thread','A short alpaca thread',?,?)",        &[EMAIL_THREAD, WS, stamp, stamp],    );    for at in 0..3 {        run(            &client,            "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, from_email, \             sent_at, subject, body, created_at) VALUES (?,?,?,?,'nobody@example.invalid',?,?,?,?)",            &[                &format!("short-{at:03}"),                WS,                EMAIL_THREAD,                &format!("short-{at:03}"),                &format!("2026-09-01T00:{at:02}:00.000Z"),                "A short alpaca thread",                &format!("A synthetic message {at}"),                stamp,            ],        );    }    let answer = read(        &client,        "emailThread",        &args(&[("threadId", json!(EMAIL_THREAD))]),    );    assert_eq!(answer["emails"].as_array().expect("emails").len(), 3);    assert_eq!(        answer["nextBefore"],        Value::Null,        "this walk did reach the beginning, so the handle is spent"    );    assert_eq!(answer["nextBeforeId"], Value::Null);}#[test]fn a_kept_message_from_before_a_clear_is_not_shown_and_a_deleted_one_still_is() {    // `listStarred` filters `cleared_before` and checks `hidden_at`, NOT    // `deleted_at`. Clearing a conversation on another of the owner's devices    // must take its old messages out of the one list that reaches a message    // without its thread; a message deleted for everyone keeps its tombstone,    // because the row a person starred is still a row they starred.    let (_dir, client) = attached();    seed_chats(&client);    for (id, sent_at, starred_at) in [        ("kept-old", "2026-09-01T00:00:00.000Z", "2026-09-06T00:00:00.000Z"),        ("kept-new", "2026-09-05T00:00:00.000Z", "2026-09-06T00:01:00.000Z"),        ("kept-gone", "2026-09-05T00:00:00.000Z", "2026-09-06T00:02:00.000Z"),    ] {        seed_message(&client, id, THREAD_A, sent_at, "A synthetic kept line");        run(            &client,            "UPDATE cotton_msg_messages SET starred_at = ? WHERE id = ?",            &[starred_at, id],        );    }    run(        &client,        "UPDATE cotton_msg_messages SET deleted_at = ? WHERE id = 'kept-gone'",        &["2026-09-06T01:00:00.000Z"],    );    run(        &client,        "UPDATE cotton_msg_threads SET cleared_before = ? WHERE id = ?",        &["2026-09-03T00:00:00.000Z", THREAD_A],    );    let answer = read(&client, "starred", &Map::new());    let ids: Vec<&str> = answer["messages"]        .as_array()        .expect("messages")        .iter()        .filter_map(|one| one["id"].as_str())        .collect();    assert!(!ids.contains(&"kept-old"), "cleared away: {ids:?}");    assert!(ids.contains(&"kept-new"), "{ids:?}");    assert!(        ids.contains(&"kept-gone"),        "a deletion keeps its tombstone here: {ids:?}"    );}#[test]fn a_search_answers_past_the_tool_s_own_default_and_is_refused_with_a_blank_query() {    // `search_messages` defaults to twenty hits where the screen shows thirty    // at a time and keeps scrolling. Fifty is that tool's maximum and the    // most this read can answer — the tail past it is in the ledger, because    // the tool has no cursor to page with.    let (_dir, client) = attached();    seed_chats(&client);    for at in 0..40 {        seed_message(            &client,            &format!("find-{at:03}"),            THREAD_A,            &format!("2026-09-05T{:02}:{:02}:00.000Z", at / 60, at % 60),            "A synthetic sentence about alpacas",        );    }    // The pill is on `/messages`, so its read is that screen's: `threads`,    // asked with a query.    let answer = read(&client, "threads", &args(&[("query", json!("alpacas"))]));    let hits = answer["matches"].as_array().expect("the hits");    assert!(        hits.len() > 20,        "the read stated its ceiling rather than taking the tool's default: {}",        hits.len()    );    let entry = super::reads::read_for("read.threads").expect("declared");    let error = super::answer_read(&client, entry, &args(&[("query", json!("  "))]))        .expect_err("a refusal");    assert!(error.contains("query"), "{error}");}#[test]fn the_review_row_counts_things_to_decide_not_pictures_to_look_at() {    // "Duplicates (N)" counts GROUPS — one picture with three look-alikes is    // one thing to decide, and saying "3" over it would send a person to a page    // with one card on it.    let (_dir, client) = attached();    for seed in ['a', 'b', 'c', 'd'] {        seed_photo(&client, seed, "2026-09-01T00:00:00.000Z", "[]", NIL);    }    let stamp = "2026-09-05T00:00:00.000Z";    for (id, copy) in [("dup-b", 'b'), ("dup-c", 'c'), ("dup-d", 'd')] {        run(            &client,            "INSERT INTO cotton_media_duplicates (id, workspace_id, record_kind, keep_id, \             copy_id, distance, method, state, created_at, updated_at) \             VALUES (?,?,'photo',?,?,'2','phash','open',?,?)",            &[id, WS, &photo_id('a'), &photo_id(copy), stamp, stamp],        );    }    let answer = read(&client, "photos", &Map::new());    assert_eq!(        answer["duplicates"],        json!(1),        "one keeper with three look-alikes is ONE decision"    );}// ── 4m: the OWNER'S own half of a conversation read ─────────────────────────//// The tools answer what was SAID; these hold what only the owner's own devices// write — and the visibility rule, without which two of 4m's verbs would write// a row and change nothing anybody can see.#[test]fn a_line_this_device_hid_is_gone_from_the_window_and_the_others_stay() {    // `hide_chat_messages` is the one delete that must visibly delete. Neither    // tool filters `hidden_at` — the column is not an assistant's business —    // so the filter is the phone read's, and without it the verb is a no-op a    // person watches happen to nothing.    let (_dir, client) = attached();    seed_chats(&client);    for minute in 0..3 {        seed_message(            &client,            &format!("visible-{minute}"),            THREAD_A,            &format!("2026-09-05T00:0{minute}:00.000Z"),            "A synthetic line",        );    }    run(        &client,        "UPDATE cotton_msg_messages SET hidden_at = ? WHERE id = 'visible-1'",        &["2026-09-06T00:00:00.000Z"],    );    let answer = read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]));    let ids: Vec<&str> = answer["messages"]        .as_array()        .expect("messages")        .iter()        .filter_map(|one| one["id"].as_str())        .collect();    assert_eq!(ids, vec!["visible-0", "visible-2"], "{ids:?}");}#[test]fn hiding_one_line_inside_a_full_window_does_not_end_the_conversation() {    // 4m's review found this: `hasMore` was counted AFTER the visibility    // filter, so a single hidden row inside a full window turned it false, the    // Swift screen dropped "Load older" for that conversation, and it never    // came back — every later read of the same window hides the same row.    //    // `hasMore` answers "did this READ reach the top", which only the number of    // rows the STORE handed back can answer. The filter may shrink a page; it    // may not end the conversation.    let (_dir, client) = attached();    seed_chats(&client);    // A full default window (fifty) and one more behind it, so there genuinely    // IS an older message to load.    for minute in 0..51 {        seed_message(            &client,            &format!("full-{minute:03}"),            THREAD_A,            &format!("2026-09-05T{:02}:{:02}:00.000Z", minute / 60, minute % 60),            &format!("A synthetic line {minute}"),        );    }    // One row inside the window this device has put away.    run(        &client,        "UPDATE cotton_msg_messages SET hidden_at = ? WHERE id = 'full-025'",        &["2026-09-06T00:00:00.000Z"],    );    let answer = read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]));    let ids: Vec<&str> = answer["messages"]        .as_array()        .expect("messages")        .iter()        .filter_map(|one| one["id"].as_str())        .collect();    assert_eq!(ids.len(), 49, "the filter shrank the page by the hidden row");    assert!(!ids.contains(&"full-025"), "the hidden row is still gone");    assert_eq!(        answer["hasMore"],        json!(true),        "a full read is a full read — the hidden row is not the top of the conversation"    );}#[test]fn everything_before_a_clear_is_gone_from_the_window_without_a_row_being_touched() {    // Clearing is ONE marker rather than a stamp per message, which is only    // sound while every reader applies it. This is the phone's.    let (_dir, client) = attached();    seed_chats(&client);    seed_message(        &client,        "before-the-clear",        THREAD_A,        "2026-09-01T00:00:00.000Z",        "A synthetic line",    );    seed_message(        &client,        "after-the-clear",        THREAD_A,        "2026-09-05T00:00:00.000Z",        "A synthetic line",    );    run(        &client,        "UPDATE cotton_msg_threads SET cleared_before = ? WHERE id = ?",        &["2026-09-03T00:00:00.000Z", THREAD_A],    );    let answer = read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]));    let ids: Vec<&str> = answer["messages"]        .as_array()        .expect("messages")        .iter()        .filter_map(|one| one["id"].as_str())        .collect();    assert_eq!(ids, vec!["after-the-clear"], "{ids:?}");    // And the rows are still THERE — the marker hid them, nothing erased them.    assert_eq!(        client            .with_writer(|replica| replica                .driver                .get(                    "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = ?",                    &[SqlValue::Text(THREAD_A.to_string())],                )                .map_err(|error| error.to_string()))            .expect("a count")            .and_then(|row| row.int("n")),        Some(2)    );}#[test]fn the_conversation_carries_the_private_columns_the_owners_own_switches_write() {    // Pin, mute, the read cursor, the deliberate unread flag and the    // half-sentence in the composer. None is in either tool's projection; all    // five are drawn and written by the phone (4m).    let (_dir, client) = attached();    seed_chats(&client);    run(        &client,        "UPDATE cotton_msg_threads SET read_seq = 12, unread_marked_at = ?, draft = ?, \         muted_until = ?, pinned_at = ? WHERE id = ?",        &[            "2026-09-06T00:00:00.000Z",            "half six?",            "9999-12-31T00:00:00.000Z",            "2026-09-06T01:00:00.000Z",            THREAD_A,        ],    );    let head = &read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]))["thread"];    assert_eq!(head["readSeq"], json!(12));    assert_eq!(head["unreadMarkedAt"], json!("2026-09-06T00:00:00.000Z"));    assert_eq!(head["draft"], json!("half six?"));    assert_eq!(head["mutedUntil"], json!("9999-12-31T00:00:00.000Z"));    assert_eq!(head["pinnedAt"], json!("2026-09-06T01:00:00.000Z"));    assert_eq!(head["archived"], json!(false));}#[test]fn each_bubble_says_whether_its_two_windows_are_still_open() {    // ONE implementation of the window rule, asked by the read rather than    // recomputed by the menu: a long-press that offered "Edit" on its own    // arithmetic would be the app promising a write the verb then refuses.    let (_dir, client) = attached();    seed_chats(&client);    // The device's clock is what the read compares against, so the fixture is    // written relative to it rather than to a constant instant.    let now = client.now_iso();    let just_now = now.clone();    seed_message(&client, "fresh", THREAD_A, &just_now, "A synthetic line");    seed_message(        &client,        "last-year",        THREAD_A,        "2025-09-05T00:00:00.000Z",        "A synthetic line",    );    // Outbound: the window rule refuses an inbound row whatever its age,    // because the body is shared content written by its author.    run(        &client,        "UPDATE cotton_msg_messages SET direction = 'out' WHERE id IN ('fresh', 'last-year')",        &[],    );    let answer = read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]));    let by_id: std::collections::HashMap<&str, &Value> = answer["messages"]        .as_array()        .expect("messages")        .iter()        .filter_map(|one| Some((one["id"].as_str()?, one)))        .collect();    assert_eq!(by_id["fresh"]["canEdit"], json!(true));    assert_eq!(by_id["fresh"]["canDeleteForEveryone"], json!(true));    assert!(        by_id["fresh"]["editWindowRemainingMs"]            .as_i64()            .unwrap_or(0)            > 0    );    assert_eq!(by_id["last-year"]["canEdit"], json!(false));    assert_eq!(by_id["last-year"]["canDeleteForEveryone"], json!(false));    assert_eq!(by_id["last-year"]["editWindowRemainingMs"], json!(0));}#[test]fn a_bubble_names_the_star_and_this_persons_own_reaction() {    // Both are what the long-press menu draws its state from: a star that has    // to be toggled off, and an emoji already on the row that a second tap    // replaces rather than adds to.    let (_dir, client) = attached();    seed_chats(&client);    seed_message(        &client,        "one-line",        THREAD_A,        "2026-09-05T00:00:00.000Z",        "A synthetic line",    );    run(        &client,        "UPDATE cotton_msg_messages SET starred_at = ? WHERE id = 'one-line'",        &["2026-09-06T00:00:00.000Z"],    );    run(        &client,        "INSERT INTO cotton_msg_reactions (id, workspace_id, thread_id, message_id, actor, \         emoji, created_at) VALUES ('react:one-line:self',?,?,'one-line','self','👍',?)",        &[WS, THREAD_A, "2026-09-06T00:00:00.000Z"],    );    let answer = read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]));    let bubble = answer["messages"]        .as_array()        .expect("messages")        .iter()        .find(|one| one["id"] == json!("one-line"))        .expect("the line");    assert_eq!(bubble["starredAt"], json!("2026-09-06T00:00:00.000Z"));    assert_eq!(bubble["myReaction"], json!("👍"));}#[test]fn the_inbox_row_carries_the_pin_and_the_mute_the_person_set() {    // Without these the swipe actions could only ever offer one direction: a    // list that cannot see a pin cannot draw "unpin".    let (_dir, client) = attached();    seed_chats(&client);    run(        &client,        "UPDATE cotton_msg_threads SET pinned_at = ?, muted_until = ?, unread_marked_at = ? \         WHERE id = ?",        &[            "2026-09-06T01:00:00.000Z",            "9999-12-31T00:00:00.000Z",            "2026-09-06T02:00:00.000Z",            THREAD_A,        ],    );    let inbox = read(&client, "threads", &Map::new());    let row = inbox["threads"]        .as_array()        .expect("threads")        .iter()        .find(|thread| thread["id"] == json!(THREAD_A))        .expect("the row");    assert_eq!(row["pinnedAt"], json!("2026-09-06T01:00:00.000Z"));    assert_eq!(row["mutedUntil"], json!("9999-12-31T00:00:00.000Z"));    assert_eq!(row["unreadMarkedAt"], json!("2026-09-06T02:00:00.000Z"));}// RULE: The Email archive read can reach its declared blocked-sender reader and answers all three list sections on an empty archive.#[test]fn email_conversion_read_declares_its_blocked_sender_dependency() {    let (_dir, client) = attached();    let answer = read(&client, "email", &Map::new());    assert!(answer["threads"].is_array());    assert!(answer["senders"].is_array());    assert!(answer["blockedSenders"].is_array());}// RULE: Every Email definition's derived columns are produced by real Rust generic reads, including envelopes, sender groups and the state of a partly binned thread.#[test]fn email_conversion_definitions_read_the_engine_not_swift_placeholders() {    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(&client,"INSERT INTO cotton_email_threads (id,workspace_id,external_key,subject,created_at,updated_at) VALUES (?,?,'conversion','Example',?,?)", &[EMAIL_THREAD,WS,stamp,stamp]);    run(&client,"INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,from_name,recipients,sent_at,subject,body,unread,in_inbox,created_at) VALUES ('mail-conversion',?,?,'conversion','sender@example.invalid','Example Sender','[{\"kind\":\"cc\",\"email\":\"cc@example.invalid\"}]',?,'Example',' Preserved body ',1,1,?)", &[WS,EMAIL_THREAD,stamp,stamp]);    let call = |method: &str, args: Value| super::records::call(&client,method,&args).unwrap();    let thread = call("records.get",json!({"table":"email_thread","id":EMAIL_THREAD}));    assert_eq!(thread["data"]["sender"],"Example Sender");    assert_eq!(thread["data"]["read_state"],"unread");    assert_eq!(thread["data"]["in_inbox"],true);    let messages = call("records.list",json!({"table":"email","where":{"thread_id":EMAIL_THREAD}}));    assert_eq!(messages["records"][0]["data"]["body"]," Preserved body ");    assert_eq!(messages["records"][0]["data"]["cc_line"],"cc@example.invalid");    assert_eq!(messages["records"][0]["data"]["direction"],"in");    let senders = call("records.list",json!({"table":"email_sender","where":{"address":"sender@example.invalid"}}));    assert_eq!(senders["records"][0]["data"]["address"],"sender@example.invalid");    assert_eq!(senders["records"][0]["data"]["email_count"],1);    assert_eq!(senders["records"][0]["data"]["unread_count"],1);    assert_eq!(senders["records"][0]["data"]["blocked"],false);    let sender = call("records.get",json!({"table":"email_sender","id":"sender@example.invalid"}));    assert_eq!(sender["data"],senders["records"][0]["data"]);    run(&client,"INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,body,trashed_at,created_at) VALUES ('mail-binned',?,?,'binned','another@example.invalid',?,'Earlier message',?,?)", &[WS,EMAIL_THREAD,stamp,stamp,stamp]);    let inbox = call("records.list",json!({"table":"email_thread","where":{"in_inbox":true,"binned":false}}));    assert!(inbox["records"].as_array().unwrap().iter().any(|r|r["id"]==EMAIL_THREAD));    let search = call("records.list",json!({"table":"email_thread","query":"cc@example.invalid"}));    assert_eq!(search["records"][0]["id"],EMAIL_THREAD);}// RULE: An unread email conversation is marked read and then unread from the phone by the write its page sends, and its read state says so after each.#[test]fn an_email_conversation_is_marked_read_and_unread_from_the_phone() {    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(&client,"INSERT INTO cotton_email_threads (id,workspace_id,external_key,subject,created_at,updated_at) VALUES (?,?,'reading','Example',?,?)", &[EMAIL_THREAD,WS,stamp,stamp]);    run(&client,"INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,subject,body,unread,in_inbox,created_at) VALUES ('c0000000-0000-4000-8000-0000000000a1',?,?,'reading','sender@example.invalid',?,'Example','Body',1,1,?)", &[WS,EMAIL_THREAD,stamp,stamp]);    // Seeded rows are given the receipts a replica folds them from, or the write drops them.    client.with_writer(|replica| { crate::fixture::receipted(replica.driver, "INSERT INTO cotton_email_threads"); crate::fixture::receipted(replica.driver, "INSERT INTO cotton_emails"); Ok(()) }).unwrap();    let state = || super::records::call(&client,"records.get",&json!({"table":"email_thread","id":EMAIL_THREAD})).unwrap()["data"]["read_state"].clone();    assert_eq!(state(), "unread");    for (read, expected) in [(true, "read"), (false, "unread")] {        let args = json!({"threadId":EMAIL_THREAD,"read":read});        client.write("update_email", args.as_object().unwrap()).unwrap_or_else(|error| panic!("{error}"));        assert_eq!(state(), expected);    }}/// RULE: Archiving an email conversation offers an Undo that restores inbox membership; archiving it twice is refused so an already archived conversation cannot be moved again.#[test]fn archiving_an_email_conversation_says_so_and_undo_puts_it_back() {    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(&client,"INSERT INTO cotton_email_threads (id,workspace_id,external_key,subject,created_at,updated_at) VALUES (?,?,'acts','Example picnic',?,?)", &[EMAIL_THREAD,WS,stamp,stamp]);    run(&client,"INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,subject,body,unread,in_inbox,created_at) VALUES ('c0000000-0000-4000-8000-0000000000b1',?,?,'acts','sender@example.invalid',?,'Example picnic','Body',1,1,?)", &[WS,EMAIL_THREAD,stamp,stamp]);    client.with_writer(|replica| { crate::fixture::receipted(replica.driver, "INSERT INTO cotton_email_threads"); crate::fixture::receipted(replica.driver, "INSERT INTO cotton_emails"); Ok(()) }).unwrap();    let call = |command: &str| super::records::call(&client, "records.command", &json!({"table":"email_thread","id":EMAIL_THREAD,"command":command}));    let data = || super::records::call(&client, "records.get", &json!({"table":"email_thread","id":EMAIL_THREAD})).unwrap()["data"].clone();    assert_eq!(data()["in_inbox"], json!(true));    let archived = call("archive").expect("Archive runs on a conversation in the inbox");    assert_eq!(archived["undo"], "inbox");    assert_eq!(data()["in_inbox"], json!(false));    assert_eq!(call("archive").expect_err("an archived conversation is not archived again").code, "not_offered");    let back = call("inbox").expect("the Undo moves it back");    assert_eq!(back["undo"], "archive");    assert_eq!(data()["in_inbox"], json!(true));    call("star").expect("Star");    assert_eq!(data()["starred"], json!(true));}// RULE: An email's attachments are answered as its media, in a chat message's shape, so its conversation draws them as prints; a message with none answers no media, so nothing offers to browse it.#[test]fn an_emails_attachments_are_its_media() {    let (_dir, client) = attached();    let stamp = "2026-09-01T00:00:00.000Z";    run(&client,"INSERT INTO cotton_email_threads (id,workspace_id,external_key,subject,created_at,updated_at) VALUES (?,?,'media','Example',?,?)", &[EMAIL_THREAD,WS,stamp,stamp]);    run(&client,"INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,subject,body,attachments,created_at) VALUES ('mail-attached',?,?,'attached','sender@example.invalid',?,'Example','Body','[{\"name\":\"Example.jpg\",\"mime\":\"image/jpeg\",\"size\":2048},{\"name\":\"Example.bin\"},{\"name\":\"Example.pdf\",\"mime\":\"application/pdf\",\"size\":9,\"key\":\"'||?||'/messages/example/aa.pdf\"}]',?)", &[WS,EMAIL_THREAD,stamp,WS,stamp]);    run(&client,"INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,subject,body,created_at) VALUES ('mail-bare',?,?,'bare','sender@example.invalid',?,'Example','Body',?)", &[WS,EMAIL_THREAD,stamp,stamp]);    let media = |id: &str| super::records::call(&client,"records.get",&json!({"table":"email","id":id})).unwrap()["data"].get("media").cloned().unwrap_or(Value::Null);    assert_eq!(media("mail-attached"), json!([        {"contentType":"image/jpeg","name":"Example.jpg","sizeBytes":2048},        {"contentType":"application/octet-stream","name":"Example.bin"},        {"key":format!("{WS}/messages/example/aa.pdf"),"contentType":"application/pdf","name":"Example.pdf","sizeBytes":9},    ]));    assert_eq!(media("mail-bare"), Value::Null);}// RULE: Generic Email folders admit the same message set as the archive engine, including binned members of mixed threads and folder-local unread state.#[test]fn email_definition_folders_match_the_archive_engine() {    let (_dir, client) = attached();    run(&client, "DELETE FROM cotton_emails", &[]);    let stamp = "2026-09-01T00:00:00.000Z";    let bin = "c0000000-0000-4000-8000-000000000001";    let mix = "c0000000-0000-4000-8000-000000000002";    let live = "c0000000-0000-4000-8000-000000000003";    for thread in [bin, mix, live] {        run(&client, "INSERT INTO cotton_email_threads (id,workspace_id,external_key,subject,created_at,updated_at) VALUES (?,?,?,'Folder probe',?,?)", &[thread,WS,thread,stamp,stamp]);    }    for (id, thread, unread, inbox, trashed) in [        ("bin-one",bin,"1","1",stamp),        ("mix-bin",mix,"1","1",stamp),        ("mix-live",mix,"0","0",""),        ("live-inbox",live,"0","1",""),        ("live-archive",live,"1","0",""),    ] {        run(&client, "INSERT INTO cotton_emails (id,workspace_id,thread_id,external_id,from_email,sent_at,unread,in_inbox,trashed_at,created_at) VALUES (?,?,?,?,'folder@example.invalid',?,CAST(? AS INTEGER),CAST(? AS INTEGER),NULLIF(?,''),?)", &[id,WS,thread,id,stamp,unread,inbox,trashed,stamp]);    }    for (folder, filter, wanted) in [        ("bin", json!({"binned":true}), vec![bin,mix]),        ("inbox", json!({"binned":false,"in_inbox":true}), vec![live]),        ("archived", json!({"binned":false,"in_inbox":false}), vec![mix,live]),        ("all", json!({"binned":false}), vec![mix,live]),    ] {        let archive = read(&client,"email",&json!({"folder":folder}).as_object().unwrap().clone());        let generic = super::records::call(&client,"records.list",&json!({"table":"email_thread","where":filter})).unwrap();        let rows = generic["records"].as_array().unwrap();        let mut ids = rows.iter().map(|r|r["id"].as_str().unwrap()).collect::<Vec<_>>();        ids.sort();        let mut wanted = wanted; wanted.sort();        assert_eq!(ids,wanted,"{folder}");        let old = archive["threads"].as_array().unwrap();        assert_eq!(rows.len(),old.len(),"{folder}");        assert_eq!(generic["total"], json!(wanted.len()), "{folder} total");        for row in rows {            let original = old.iter().find(|r|r["id"]==row["id"]).unwrap();            assert_eq!(row["data"]["read_state"],if original["unread"]==true { "unread" } else { "read" },"{folder}");            assert_eq!(row["data"]["in_inbox"],original["inInbox"],"{folder}");        }    }}#[test]fn a_threads_attachments_say_their_kind_and_how_long_they_play() {    let (_dir, client) = attached();    seed_chats(&client);    let media = json!([        {"key": format!("{WS}/messages/{THREAD_A}/a.ogg"), "contentType": "audio/ogg", "kind": "voice", "durationMs": 65_000},        {"key": format!("{WS}/messages/{THREAD_A}/b.mp4"), "contentType": "video/mp4", "durationMs": 3_725_000},        {"key": format!("{WS}/messages/{THREAD_A}/c.jpg"), "contentType": "image/jpeg"},        {"key": format!("{WS}/messages/{THREAD_A}/d.vcf"), "contentType": "text/vcard"},    ])    .to_string();    run(        &client,        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, \         origin, body, media, sent_at, created_at) VALUES (?,?,?,'in','whatsapp','live',?,?,?,?)",        &["media-1", THREAD_A, WS, "", &media, "2026-09-05T00:00:00.000Z", "2026-09-05T00:00:00.000Z"],    );    let answer = read(&client, "thread", &args(&[("threadId", json!(THREAD_A))]));    let message = answer["messages"].as_array().unwrap().iter().find(|message| message["id"] == "media-1").expect("the message");    let said: Vec<(Value, Value)> = message["media"].as_array().unwrap().iter().map(|entry| (entry["kind"].clone(), entry.get("length").cloned().unwrap_or(Value::Null))).collect();    assert_eq!(said, vec![        (json!("voice"), json!("1:05")),        (json!("video"), json!("1:02:05")),        (json!("image"), Value::Null),        (json!("contact"), Value::Null),    ], "{message}");}