Cotton code
1515 lines · 53.3 KB · RustRaw
//! The small MCP groups, end to end over `dispatch::call_tool`: calls,//! storage, summaries and the kind-generic bin.//!//! Every case that exercises one of these groups' tools is here; a case for//! another group's tool belongs in that group's file.//!//! Nothing here reaches into a handler's internals. A tool is called the way//! the transport calls one — `dispatch::call_tool` over a fake `ToolServices`//! on a real file — so what is under test is the answer an assistant actually//! receives, and it is asserted in the crate the phone links.mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool_as_owner, call_tool, call_tool_raw, mint_token};/// When every row seeded straight into the file says it was written.const AT: &str = "2026-09-01T09:00:00.000Z";// ── the shared floor ────────────────────────────────────────────────────────/// A harness plus a connection that may write, the `writerHarness()` of every/// one of these suites.fn writer_harness() -> (Harness, String) {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    (h, secret)}/// Run one statement against the workspace's own file.fn run(h: &Harness, sql: &str, params: Vec<SqlValue>) {    h.with(|db| db.run(sql, &params))        .expect("the statement runs");}fn text_of(h: &Harness, sql: &str, params: Vec<SqlValue>, column: &str) -> Option<String> {    h.with(|db| db.get(sql, &params))        .expect("the read runs")        .and_then(|row| row.text(column).map(str::to_string))}fn count_of(h: &Harness, sql: &str) -> i64 {    h.with(|db| db.get(sql, &[]))        .expect("the read runs")        .and_then(|row| row.int("n"))        .unwrap_or_default()}fn at(iso: &str) -> chrono::DateTime<chrono::Utc> {    iso.parse().expect("an instant")}/// A uuid-shaped id a fixture can name. DERIVED, never random.fn fixture_id(label: &str) -> String {    synthetic_uuid(label)}// ════════════════════════════════════════════════════════════════════════════// list_calls / get_call// ════════════════════════════════════════════════════════════════════════════struct CallFixture {    h: Harness,    secret: String,    ravi: String,    ids: std::collections::BTreeMap<&'static str, String>,}/// One person with two calls, one stranger's number with one, and a project/// that Ravi is linked to.fn seeded_calls() -> CallFixture {    let mut h = Harness::new();    let ws = h.workspace_id.clone();    let ravi = fixture_id("ravi");    run(        &h,        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \         VALUES (?, ?, 'Ravi Kumar', ?, ?)",        vec![            SqlValue::Text(ravi.clone()),            SqlValue::Text(ws.clone()),            SqlValue::Text(AT.to_string()),            SqlValue::Text(AT.to_string()),        ],    );    let project_id = fixture_id("kitchen-project");    run(        &h,        "INSERT INTO cotton_memory_projects \           (id, workspace_id, slug, name, status, created_at, updated_at) \         VALUES (?, ?, 'kitchen', 'Kitchen rebuild', 'active', ?, ?)",        vec![            SqlValue::Text(project_id.clone()),            SqlValue::Text(ws.clone()),            SqlValue::Text(AT.to_string()),            SqlValue::Text(AT.to_string()),        ],    );    run(        &h,        "INSERT INTO cotton_project_links \           (id, workspace_id, project_id, record_kind, record_id, applied_by, created_at, updated_at) \         VALUES (?, ?, ?, 'person', ?, 'user', ?, ?)",        vec![            SqlValue::Text(cotton_store::protocol::derived_id::project_link_id(                &project_id,                "person",                &ravi,            )),            SqlValue::Text(ws.clone()),            SqlValue::Text(project_id),            SqlValue::Text(ravi.clone()),            SqlValue::Text(AT.to_string()),            SqlValue::Text(AT.to_string()),        ],    );    let mut ids: std::collections::BTreeMap<&'static str, String> =        std::collections::BTreeMap::new();    let mut call = |label: &'static str,                    provider: &str,                    direction: &str,                    outcome: &str,                    started_at: &str,                    duration_s: i64,                    handle: &str,                    person_id: Option<&str>| {        let id = fixture_id(label);        ids.insert(label, id.clone());        run(            &h,            "INSERT INTO cotton_call_log \               (id, workspace_id, source, external_id, provider, direction, outcome, \                started_at, duration_s, handle, contact_id, person_id, device, meta, \                created_at, updated_at) \             VALUES (?, ?, 'ios_call_history', ?, ?, ?, ?, ?, ?, ?, NULL, ?, 'mac-a', ?, ?, ?)",            vec![                SqlValue::Text(id),                SqlValue::Text(ws.clone()),                SqlValue::Text(format!("ZUNIQUE-{label}")),                SqlValue::Text(provider.to_string()),                SqlValue::Text(direction.to_string()),                SqlValue::Text(outcome.to_string()),                SqlValue::Text(started_at.to_string()),                SqlValue::Integer(duration_s),                SqlValue::Text(handle.to_string()),                person_id                    .map(|id| SqlValue::Text(id.to_string()))                    .unwrap_or(SqlValue::Null),                SqlValue::Text(json!({ "disconnectedCause": 2 }).to_string()),                SqlValue::Text(AT.to_string()),                SqlValue::Text(AT.to_string()),            ],        );    };    call(        "raviMorning",        "cellular",        "out",        "answered",        "2026-09-01T09:00:00.000Z",        312,        "919876543210",        Some(&ravi),    );    call(        "raviMissed",        "facetime_video",        "in",        "missed",        "2026-09-02T18:30:00.000Z",        0,        "919876543210",        Some(&ravi),    );    call(        "stranger",        "cellular",        "in",        "answered",        "2026-09-03T11:15:00.000Z",        44,        "918000000001",        None,    );    let secret = mint_token(&mut h, &["read", "write"], "Claude");    CallFixture {        h,        secret,        ravi,        ids,    }}fn call_ids(answer: &Value) -> Vec<String> {    answer["calls"]        .as_array()        .expect("calls")        .iter()        .filter_map(|call| call["id"].as_str().map(str::to_string))        .collect()}#[test]fn answers_newest_first_naming_the_person_where_the_file_resolved_one() {    let f = seeded_calls();    let result = call_tool(&f.h, &f.secret, "list_calls", json!({}));    let calls = result["calls"].as_array().expect("calls");    assert_eq!(        call_ids(&result),        vec![            f.ids["stranger"].clone(),            f.ids["raviMissed"].clone(),            f.ids["raviMorning"].clone()        ]    );    // The unnamed number reads as the number — no invented attribution.    assert_eq!(calls[0]["handle"], json!("918000000001"));    assert!(calls[0].get("person").is_none());    assert!(calls[0].get("personId").is_none());    assert_eq!(calls[1]["provider"], json!("facetime_video"));    assert_eq!(calls[1]["direction"], json!("in"));    assert_eq!(calls[1]["outcome"], json!("missed"));    assert_eq!(calls[1]["durationS"], json!(0));    assert_eq!(calls[1]["person"], json!("Ravi Kumar"));    assert_eq!(calls[1]["personId"], json!(f.ravi));}#[test]fn narrows_by_person_provider_direction_outcome_and_a_time_window() {    let f = seeded_calls();    let by_person = call_tool(&f.h, &f.secret, "list_calls", json!({ "personId": f.ravi }));    assert_eq!(        call_ids(&by_person),        vec![f.ids["raviMissed"].clone(), f.ids["raviMorning"].clone()]    );    let by_provider = call_tool(        &f.h,        &f.secret,        "list_calls",        json!({ "provider": "cellular" }),    );    assert_eq!(        call_ids(&by_provider),        vec![f.ids["stranger"].clone(), f.ids["raviMorning"].clone()]    );    let outgoing = call_tool(&f.h, &f.secret, "list_calls", json!({ "direction": "out" }));    assert_eq!(call_ids(&outgoing), vec![f.ids["raviMorning"].clone()]);    let missed = call_tool(        &f.h,        &f.secret,        "list_calls",        json!({ "outcome": "missed" }),    );    assert_eq!(call_ids(&missed), vec![f.ids["raviMissed"].clone()]);    let window = call_tool(        &f.h,        &f.secret,        "list_calls",        json!({ "since": "2026-09-02T00:00:00.000Z", "until": "2026-09-02T23:59:59.000Z" }),    );    assert_eq!(call_ids(&window), vec![f.ids["raviMissed"].clone()]);}#[test]fn a_project_answers_with_the_calls_of_the_people_linked_to_it() {    let f = seeded_calls();    // Nothing links a CALL to the project; Ravi is linked, and that is what    // brings his two calls in (§D8).    let calls = call_tool(        &f.h,        &f.secret,        "list_calls",        json!({ "project": "kitchen" }),    );    assert_eq!(        call_ids(&calls),        vec![f.ids["raviMissed"].clone(), f.ids["raviMorning"].clone()]    );}#[test]fn list_calls_refuses_a_project_nobody_has_by_name() {    let f = seeded_calls();    let answer = call_tool_raw(        &f.h,        &f.secret,        "list_calls",        json!({ "project": "no-such-project" }),    );    assert!(answer.is_error);    assert!(answer.text.contains("no-such-project"), "{}", answer.text);}#[test]fn expands_one_call_with_its_provenance_the_source_the_device_and_the_raw_meta() {    let f = seeded_calls();    let call = call_tool(        &f.h,        &f.secret,        "get_call",        json!({ "id": f.ids["raviMorning"] }),    );    assert_eq!(call["id"], json!(f.ids["raviMorning"]));    assert_eq!(call["source"], json!("ios_call_history"));    assert_eq!(call["externalId"], json!("ZUNIQUE-raviMorning"));    assert_eq!(call["provider"], json!("cellular"));    assert_eq!(call["direction"], json!("out"));    assert_eq!(call["outcome"], json!("answered"));    assert_eq!(call["durationS"], json!(312));    assert_eq!(call["handle"], json!("919876543210"));    assert_eq!(call["person"], json!("Ravi Kumar"));    assert_eq!(call["personId"], json!(f.ravi));    assert_eq!(call["device"], json!("mac-a"));    assert_eq!(call["meta"], json!({ "disconnectedCause": 2 }));}#[test]fn get_call_refuses_an_id_this_workspace_does_not_hold() {    let f = seeded_calls();    let answer = call_tool_raw(        &f.h,        &f.secret,        "get_call",        json!({ "id": fixture_id("not-a-call") }),    );    assert!(answer.is_error);    assert!(        answer.text.to_lowercase().contains("no such call"),        "{}",        answer.text    );}// ════════════════════════════════════════════════════════════════════════════// storage_summary// ════════════════════════════════════════════════════════════════════════════const PHOTO_SHA: &str = "1111111111111111111111111111111111111111111111111111111111111111";const VIDEO_SHA: &str = "2222222222222222222222222222222222222222222222222222222222222222";const STORAGE_AT: &str = "2026-09-01T00:00:00.000Z";/// A `message` sighting (v39) — where the row's bytes live, and which chat it/// is charged to.fn seed_sighting(h: &Harness, record_id: &str, thread_id: &str, key: &str, label: &str) {    let message_id = fixture_id(label);    let kind = if record_id.starts_with("video:") {        "video"    } else {        "photo"    };    run(        h,        "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 (?, ?, ?, ?, 'message', ?, ?, ?, ?, ?, ?)",        vec![            SqlValue::Text(cotton_store::protocol::derived_id::media_sighting_id(                kind,                record_id,                "message",                Some(&message_id),            )),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(kind.to_string()),            SqlValue::Text(record_id.to_string()),            SqlValue::Text(message_id),            SqlValue::Text(thread_id.to_string()),            SqlValue::Text(key.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),        ],    );}fn seed_message(h: &Harness, thread_id: &str, media: Value, label: &str) {    run(        h,        "INSERT INTO cotton_msg_messages \           (id, thread_id, workspace_id, direction, channel, origin, body, media, external_id, \            sent_at, created_at, reactions, meta) \         VALUES (?, ?, ?, 'in', 'whatsapp', 'imported', NULL, ?, ?, ?, ?, '[]', '{}')",        vec![            SqlValue::Text(fixture_id(label)),            SqlValue::Text(thread_id.to_string()),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(media.to_string()),            SqlValue::Text(format!("txt2:{}", fixture_id(label))),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),        ],    );}struct StorageFixture {    h: Harness,    secret: String,    thread_id: String,}fn seeded_storage() -> StorageFixture {    let mut h = Harness::new();    let ws = h.workspace_id.clone();    let thread_id = fixture_id("storage-thread");    run(        &h,        "INSERT INTO cotton_msg_threads \           (id, workspace_id, kind, title, last_message_at, created_at, updated_at) \         VALUES (?, ?, 'group', 'Kitchen rebuild', ?, ?, ?)",        vec![            SqlValue::Text(thread_id.clone()),            SqlValue::Text(ws.clone()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),        ],    );    // ONE picture, sent into the chat FOUR times. Four messages, one photo row.    let key = format!("{ws}/messages/{thread_id}/{PHOTO_SHA}.jpg");    for index in 0..4 {        seed_message(            &h,            &thread_id,            json!([{ "key": key, "contentType": "image/jpeg", "sizeBytes": 1_000_000 }]),            &format!("storage-photo-message-{index}"),        );    }    run(        &h,        "INSERT INTO cotton_photos \           (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, caption, created_at, updated_at) \         VALUES (?, ?, ?, ?, 'image/jpeg', 1000000, ?, 'the finished shelf', ?, ?)",        vec![            SqlValue::Text(format!("photo:{PHOTO_SHA}")),            SqlValue::Text(ws.clone()),            SqlValue::Text(key.clone()),            SqlValue::Text(PHOTO_SHA.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),        ],    );    seed_sighting(        &h,        &format!("photo:{PHOTO_SHA}"),        &thread_id,        &key,        "storage-photo-sighting",    );    // A video, flagged for review by an assistant.    let video_key = format!("{ws}/messages/{thread_id}/{VIDEO_SHA}.mp4");    run(        &h,        "INSERT INTO cotton_videos \           (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, \            summary, summary_by, summary_at, review_note, review_by, review_at, \            created_at, updated_at) \         VALUES (?, ?, ?, ?, 'video/mp4', 48000000, ?, \                 'A hand-held clip of a wall.', 'job:media-describe', ?, \                 '48 MB of a wall — probably done with', 'Claude', ?, ?, ?)",        vec![            SqlValue::Text(format!("video:{VIDEO_SHA}")),            SqlValue::Text(ws.clone()),            SqlValue::Text(video_key.clone()),            SqlValue::Text(VIDEO_SHA.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),        ],    );    seed_sighting(        &h,        &format!("video:{VIDEO_SHA}"),        &thread_id,        &video_key,        "storage-video-sighting",    );    // A voice note and a PDF in the same chat — audio and "other".    seed_message(        &h,        &thread_id,        json!([            { "key": format!("{ws}/messages/{thread_id}/voice.m4a"), "contentType": "audio/mp4", "sizeBytes": 300_000 },            { "key": format!("{ws}/messages/{thread_id}/quote.pdf"), "contentType": "application/pdf", "sizeBytes": 90_000, "name": "quote.pdf" },        ]),        "storage-voice-message",    );    run(        &h,        "INSERT INTO cotton_documents \           (id, workspace_id, title, original_name, mime, byte_size, sha256, storage_path, status, \            status_changed_at, created_at, updated_at) \         VALUES (?, ?, 'August statement', 'aug.pdf', 'application/pdf', 2000000, ?, ?, 'ready', ?, ?, ?)",        vec![            SqlValue::Text(fixture_id("storage-document")),            SqlValue::Text(ws.clone()),            SqlValue::Text("f".repeat(64)),            SqlValue::Text(format!("{ws}/doc.pdf")),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),            SqlValue::Text(STORAGE_AT.to_string()),        ],    );    let secret = mint_token(&mut h, &["read", "write"], "Claude");    StorageFixture {        h,        secret,        thread_id,    }}fn kind_line<'a>(answer: &'a Value, kind: &str) -> &'a Value {    answer["byKind"]        .as_array()        .expect("byKind")        .iter()        .find(|line| line["kind"] == json!(kind))        .unwrap_or_else(|| panic!("no {kind} line in {answer}"))}#[test]fn counts_one_forwarded_picture_once_not_once_per_message() {    let f = seeded_storage();    let answer = call_tool(&f.h, &f.secret, "storage_summary", json!({}));    let photos = kind_line(&answer, "photos");    assert_eq!(photos["items"], json!(1));    assert_eq!(photos["bytes"], json!(1_000_000));}#[test]fn splits_bytes_by_kind_photos_videos_documents_audio_everything_else() {    let f = seeded_storage();    let answer = call_tool(&f.h, &f.secret, "storage_summary", json!({}));    assert_eq!(kind_line(&answer, "videos")["items"], json!(1));    assert_eq!(kind_line(&answer, "videos")["bytes"], json!(48_000_000));    assert_eq!(kind_line(&answer, "documents")["items"], json!(1));    assert_eq!(kind_line(&answer, "documents")["bytes"], json!(2_000_000));    assert_eq!(kind_line(&answer, "audio")["items"], json!(1));    assert_eq!(kind_line(&answer, "audio")["bytes"], json!(300_000));    assert_eq!(kind_line(&answer, "other")["items"], json!(1));    assert_eq!(kind_line(&answer, "other")["bytes"], json!(90_000));}#[test]fn names_the_chat_beside_its_number() {    let f = seeded_storage();    let answer = call_tool(&f.h, &f.secret, "storage_summary", json!({}));    let by_chat = answer["byChat"].as_array().expect("byChat");    // "3.2 GB in one chat" is not actionable without knowing which chat.    assert_eq!(by_chat[0]["threadId"], json!(f.thread_id));    assert_eq!(by_chat[0]["name"], json!("Kitchen rebuild"));    assert_eq!(        by_chat[0]["bytes"],        json!(1_000_000 + 48_000_000 + 300_000 + 90_000)    );}#[test]fn lists_the_largest_items_biggest_first_recognisable_by_their_own_words() {    let f = seeded_storage();    let answer = call_tool(&f.h, &f.secret, "storage_summary", json!({}));    let largest = answer["largest"].as_array().expect("largest");    assert_eq!(largest[0]["kind"], json!("video"));    assert_eq!(largest[0]["bytes"], json!(48_000_000));    assert!(        largest[0]["text"]            .as_str()            .unwrap_or_default()            .contains("hand-held clip"),        "{}",        largest[0]    );    let bytes: Vec<i64> = largest        .iter()        .map(|item| item["bytes"].as_i64().unwrap_or_default())        .collect();    let mut sorted = bytes.clone();    sorted.sort_unstable_by(|a, b| b.cmp(a));    assert_eq!(bytes, sorted);}#[test]fn carries_every_row_an_assistant_has_flagged_with_the_note_and_its_byline() {    let f = seeded_storage();    let answer = call_tool(&f.h, &f.secret, "storage_summary", json!({}));    let flagged = answer["flagged"].as_array().expect("flagged");    assert_eq!(flagged.len(), 1);    assert_eq!(flagged[0]["kind"], json!("video"));    assert_eq!(flagged[0]["reviewBy"], json!("Claude"));    assert!(        flagged[0]["reviewNote"]            .as_str()            .unwrap_or_default()            .contains("probably done with"),        "{}",        flagged[0]    );}#[test]fn counts_an_attachment_whose_size_nobody_recorded_rather_than_guessing_it() {    let f = seeded_storage();    seed_message(        &f.h,        &f.thread_id,        json!([{ "key": format!("{}/messages/{}/old.bin", f.h.workspace_id, f.thread_id), "contentType": "application/octet-stream" }]),        "storage-unmeasured-message",    );    let answer = call_tool(&f.h, &f.secret, "storage_summary", json!({}));    let other = kind_line(&answer, "other");    // Counted, never guessed: a total that looks low is explicable, an invented    // one is not.    assert_eq!(other["items"], json!(2));    assert_eq!(other["bytes"], json!(90_000));    assert_eq!(other["unmeasured"], json!(1));}#[test]fn counts_a_forwarded_pictures_objects_one_row_four_copies_of_the_bytes() {    // The other half of the rule above. The row is one because the bytes are    // one picture; the SPACE is four, because a message media key is scoped to    // its thread and the bytes were copied under each. Counting the row once    // would tell the owner deleting it frees a quarter of what it does.    let f = seeded_storage();    for index in 2..=4 {        let thread = format!("th-{index}");        let key = format!("{}/messages/{thread}/{PHOTO_SHA}.jpg", f.h.workspace_id);        seed_sighting(            &f.h,            &format!("photo:{PHOTO_SHA}"),            &thread,            &key,            &format!("storage-forward-{index}"),        );    }    let answer = call_tool(&f.h, &f.secret, "storage_summary", json!({}));    let photos = kind_line(&answer, "photos");    // Still ONE item — one picture, one thing to decide about — and four times    // the bytes.    assert_eq!(photos["items"], json!(1));    assert_eq!(photos["bytes"], json!(4_000_000));    // …and the summary says why, so a figure the owner cannot explain is not a    // figure they cannot act on.    assert!(        answer["note"]            .as_str()            .unwrap_or_default()            .contains("3 extra copies"),        "{}",        answer["note"]    );}#[test]fn deletes_nothing_it_is_a_read_and_the_deciding_is_the_owners() {    let f = seeded_storage();    call_tool(&f.h, &f.secret, "storage_summary", json!({}));    assert_eq!(count_of(&f.h, "SELECT COUNT(*) AS n FROM cotton_photos"), 1);    assert_eq!(count_of(&f.h, "SELECT COUNT(*) AS n FROM cotton_videos"), 1);}// ════════════════════════════════════════════════════════════════════════════// update_summary// ════════════════════════════════════════════════════════════════════════════/// The label the owner typed on the Connected AIs screen — the provenance.const LABEL: &str = "Claude Code";/// When the summary is written, in every case that freezes the clock.const WRITTEN_AT: &str = "2026-08-29T09:00:00.000Z";const SEEDED_AT: &str = "2026-08-20T08:00:00.000Z";struct SummaryFixture {    h: Harness,    secret: String,    person: String,    thread: String,    email_thread: String,}/// One person, one group chat and one email conversation, seeded straight into/// the file — the shapes an importer writes, which is where most of a person's/// records come from. Nothing here goes through a create verb: `create_person`/// is not this tool's business, and a chat has no MCP creator at all.fn summary_fixture(label: &str, tag: &str) -> SummaryFixture {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], label);    let person = fixture_id(&format!("summary-person-{tag}"));    let thread = fixture_id(&format!("summary-thread-{tag}"));    let email_thread = fixture_id(&format!("summary-email-thread-{tag}"));    run(        &h,        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \         VALUES (?, ?, 'Priya Nair', ?, ?)",        vec![            SqlValue::Text(person.clone()),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(SEEDED_AT.to_string()),            SqlValue::Text(SEEDED_AT.to_string()),        ],    );    run(        &h,        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \         VALUES (?, ?, 'group', 'Meridian core', ?, ?)",        vec![            SqlValue::Text(thread.clone()),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(SEEDED_AT.to_string()),            SqlValue::Text(SEEDED_AT.to_string()),        ],    );    run(        &h,        "INSERT INTO cotton_email_threads \           (id, workspace_id, external_key, subject, first_at, last_at, email_count, created_at, updated_at) \         VALUES (?, ?, 'gmail:meridian-contract', 'Meridian contract', ?, ?, 1, ?, ?)",        vec![            SqlValue::Text(email_thread.clone()),            SqlValue::Text(h.workspace_id.clone()),            SqlValue::Text(SEEDED_AT.to_string()),            SqlValue::Text(SEEDED_AT.to_string()),            SqlValue::Text(SEEDED_AT.to_string()),            SqlValue::Text(SEEDED_AT.to_string()),        ],    );    SummaryFixture {        h,        secret,        person,        thread,        email_thread,    }}/// One inbound line on a chat, at an instant the test chooses.fn seed_chat_message(f: &SummaryFixture, sent_at: &str, label: &str) {    run(        &f.h,        "INSERT INTO cotton_msg_messages \           (id, thread_id, workspace_id, direction, channel, origin, body, media, external_id, \            sent_at, created_at, reactions, meta) \         VALUES (?, ?, ?, 'in', 'whatsapp', 'imported', 'the drawings are through', '[]', ?, ?, ?, '[]', '{}')",        vec![            SqlValue::Text(fixture_id(label)),            SqlValue::Text(f.thread.clone()),            SqlValue::Text(f.h.workspace_id.clone()),            SqlValue::Text(format!("txt2:{}", fixture_id(label))),            SqlValue::Text(sent_at.to_string()),            SqlValue::Text(sent_at.to_string()),        ],    );}/// One note about a person, at an instant the test chooses.fn seed_person_note(f: &SummaryFixture, created_at: &str, label: &str) {    run(        &f.h,        "INSERT INTO cotton_person_notes (id, person_id, body, noted_at, created_at) \         VALUES (?, ?, 'said the survey is booked', ?, ?)",        vec![            SqlValue::Text(fixture_id(label)),            SqlValue::Text(f.person.clone()),            SqlValue::Text(created_at.to_string()),            SqlValue::Text(created_at.to_string()),        ],    );}/// The three columns as the file holds them, for the row-level assertions.fn summary_row(    h: &Harness,    table: &str,    column: &str,    id: &str,) -> (Option<String>, Option<String>, Option<String>) {    let row = h        .with(|db| {            db.get(                &format!(                    "SELECT {column} AS text, summary_by AS by, summary_updated_at AS at \                     FROM {table} WHERE id = ?"                ),                &[SqlValue::Text(id.to_string())],            )        })        .expect("the read runs");    match row {        None => (None, None, None),        Some(row) => (            row.text("text").map(str::to_string),            row.text("by").map(str::to_string),            row.text("at").map(str::to_string),        ),    }}#[test]fn writes_a_persons_summary_and_stamps_the_assistants_label() {    let f = summary_fixture(LABEL, "person-stamp");    f.h.clock.set(at(WRITTEN_AT));    call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer on the Meridian job; signs off the drawings.",        }),    );    assert_eq!(        summary_row(&f.h, "cotton_people", "summary", &f.person),        (            Some("Structural engineer on the Meridian job; signs off the drawings.".to_string()),            Some(LABEL.to_string()),            Some(WRITTEN_AT.to_string())        )    );}#[test]fn writes_a_chat_threads_summary() {    let f = summary_fixture(LABEL, "thread-stamp");    f.h.clock.set(at(WRITTEN_AT));    call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "thread",            "id": f.thread,            "summary": "The site group: drawings, the survey, and who is on site when.",        }),    );    assert_eq!(        summary_row(&f.h, "cotton_msg_threads", "summary", &f.thread),        (            Some("The site group: drawings, the survey, and who is on site when.".to_string()),            Some(LABEL.to_string()),            Some(WRITTEN_AT.to_string())        )    );}#[test]fn writes_an_email_threads_summary() {    let f = summary_fixture(LABEL, "email-stamp");    f.h.clock.set(at(WRITTEN_AT));    call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "email_thread",            "id": f.email_thread,            "summary": "Contract redlines with Meridian; finance is copied throughout.",        }),    );    assert_eq!(        summary_row(&f.h, "cotton_email_threads", "summary", &f.email_thread),        (            Some("Contract redlines with Meridian; finance is copied throughout.".to_string()),            Some(LABEL.to_string()),            Some(WRITTEN_AT.to_string())        )    );}#[test]fn answers_with_the_summary_and_its_provenance_not_just_an_acknowledgement() {    let f = summary_fixture(LABEL, "provenance");    f.h.clock.set(at(WRITTEN_AT));    let answer = call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer on the Meridian job.",        }),    );    assert_eq!(answer["updated"], json!(true));    assert_eq!(answer["kind"], json!("person"));    assert_eq!(answer["id"], json!(f.person));    // The caller reads back what the owner will read — the text, who is on the    // hook for it, and when. `{ok:true}` would make the next turn guess.    assert_eq!(        answer["summary"],        json!({            "text": "Structural engineer on the Meridian job.",            "by": LABEL,            "updatedAt": WRITTEN_AT,        })    );}#[test]fn counts_what_has_arrived_since_messages_on_a_chat() {    let f = summary_fixture(LABEL, "since-messages");    f.h.clock.set(at(WRITTEN_AT));    seed_chat_message(&f, "2026-08-28T10:00:00.000Z", "since-msg-before");    seed_chat_message(&f, "2026-08-29T10:00:00.000Z", "since-msg-after-1");    seed_chat_message(&f, "2026-08-29T11:00:00.000Z", "since-msg-after-2");    let answer = call_tool(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "thread", "id": f.thread, "summary": "The site group." }),    );    assert_eq!(        answer["summary"]["since"],        json!({ "count": 2, "noun": "message" })    );}#[test]fn counts_a_persons_notes_not_their_messages() {    // The registry's choice, held where a reader can see it: a person's cue is    // their note stream — the page's own content and the material a summary is    // written from — never a two-hop join through their chats.    let f = summary_fixture(LABEL, "since-notes");    f.h.clock.set(at(WRITTEN_AT));    seed_person_note(&f, "2026-08-28T09:00:00.000Z", "since-note-before");    seed_person_note(&f, "2026-08-29T12:00:00.000Z", "since-note-after");    seed_chat_message(&f, "2026-08-29T13:00:00.000Z", "since-note-chat");    let answer = call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer on the Meridian job.",        }),    );    assert_eq!(        answer["summary"]["since"],        json!({ "count": 1, "noun": "note" })    );}#[test]fn says_nothing_about_staleness_when_nothing_has_arrived() {    // Figure or silence: `{count: 0}` is not a fact anyone needs.    let f = summary_fixture(LABEL, "no-staleness");    f.h.clock.set(at(WRITTEN_AT));    seed_chat_message(&f, "2026-08-28T10:00:00.000Z", "no-staleness-msg");    let answer = call_tool(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "thread", "id": f.thread, "summary": "The site group." }),    );    let keys: Vec<&String> = answer["summary"]        .as_object()        .expect("a summary")        .keys()        .collect();    assert_eq!(keys, vec!["text", "by", "updatedAt"]);}#[test]fn clears_the_summary_and_its_provenance_when_passed_null() {    // R73: provenance for prose that is not there is a claim about nothing.    let f = summary_fixture(LABEL, "clear");    f.h.clock.set(at(WRITTEN_AT));    call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer on the Meridian job.",        }),    );    let cleared = call_tool(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "person", "id": f.person, "summary": null }),    );    assert_eq!(        summary_row(&f.h, "cotton_people", "summary", &f.person),        (None, None, None)    );    // And the answer carries no summary key at all, rather than a null one.    assert_eq!(cleared["updated"], json!(true));    assert!(cleared.get("summary").is_none());}#[test]fn refuses_more_than_1200_characters_and_says_the_number() {    let f = summary_fixture(LABEL, "too-long");    let max = cotton_core::rules::summaries::SUMMARY_MAX_CHARS;    let too_long = "a".repeat(max + 1);    let refused = call_tool_raw(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "person", "id": f.person, "summary": too_long }),    );    assert!(refused.is_error);    assert!(refused.text.contains(&max.to_string()), "{}", refused.text);    assert!(        refused.text.contains(&(max + 1).to_string()),        "{}",        refused.text    );    assert_eq!(        summary_row(&f.h, "cotton_people", "summary", &f.person).0,        None    );}#[test]fn refuses_a_blank_string_and_points_at_null() {    let f = summary_fixture(LABEL, "blank");    let refused = call_tool_raw(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "person", "id": f.person, "summary": "   " }),    );    assert!(refused.is_error);    assert!(refused.text.contains("null"), "{}", refused.text);}#[test]fn refuses_a_kind_it_does_not_write_and_names_the_verb_that_does() {    let f = summary_fixture(LABEL, "wrong-kind");    let project = call_tool_raw(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "project", "id": f.person, "summary": "…" }),    );    assert!(project.is_error);    assert!(project.text.contains("update_project"), "{}", project.text);    let document = call_tool_raw(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "document", "id": f.person, "summary": "…" }),    );    assert!(document.is_error);    assert!(document.text.contains("document"), "{}", document.text);}#[test]fn refuses_a_record_in_another_workspace_with_the_same_words_as_one_that_does_not_exist() {    // Probe resistance, the rule every record read here follows: an assistant    // holding somebody else's id learns nothing about whether it is real.    let mine = summary_fixture(LABEL, "probe-mine");    let theirs = summary_fixture(LABEL, "probe-theirs");    let foreign = call_tool_raw(        &mine.h,        &mine.secret,        "update_summary",        json!({ "kind": "person", "id": theirs.person, "summary": "Structural engineer." }),    );    let absent = call_tool_raw(        &mine.h,        &mine.secret,        "update_summary",        json!({ "kind": "person", "id": fixture_id("nobody-at-all"), "summary": "Structural engineer." }),    );    assert!(foreign.is_error);    assert_eq!(foreign.text, absent.text);    // And nothing crossed: their row is untouched.    assert_eq!(        summary_row(&theirs.h, "cotton_people", "summary", &theirs.person).0,        None    );}#[test]fn overwrites_a_summary_that_was_already_there_and_leaves_an_unchanged_resend_alone() {    // What the annotations CLAIM, asserted as behaviour: `destructiveHint`    // says the second write replaces prose the first one left, and    // `idempotentHint` says sending the same paragraph again lands exactly    // where it already was — the STAMP included (R67).    //    // The stamp is the whole point. Moving it on an unchanged resend would    // reset the staleness cue, so a record reading "6 messages since this was    // written" would go silent because an assistant sent back the paragraph it    // had just read.    let mut f = summary_fixture(LABEL, "overwrite");    f.h.clock.set(at(WRITTEN_AT));    let second = mint_token(&mut f.h, &["read", "write"], "Cursor");    call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer on the Meridian job.",        }),    );    let overwritten_at = "2026-08-29T15:00:00.000Z";    f.h.clock.set(at(overwritten_at));    call_tool(        &f.h,        &second,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer; now leading the survey too.",        }),    );    assert_eq!(        summary_row(&f.h, "cotton_people", "summary", &f.person),        (            Some("Structural engineer; now leading the survey too.".to_string()),            Some("Cursor".to_string()),            Some(overwritten_at.to_string())        )    );    f.h.clock.set(at("2026-08-29T16:00:00.000Z"));    let resent = call_tool(        &f.h,        &second,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer; now leading the survey too.",        }),    );    assert_eq!(        summary_row(&f.h, "cotton_people", "summary", &f.person),        (            Some("Structural engineer; now leading the survey too.".to_string()),            Some("Cursor".to_string()),            Some(overwritten_at.to_string())        )    );    // And the tool says so, rather than reporting a write it did not make.    assert_eq!(resent["updated"], json!(false));    assert!(        resent["note"]            .as_str()            .unwrap_or_default()            .contains("nothing changed"),        "{}",        resent["note"]    );}#[test]fn re_sending_the_same_paragraph_under_a_new_name_does_not_re_attribute_it() {    // The author is not part of the comparison: the paragraph is the same    // paragraph, so the person who wrote it keeps the credit.    let mut f = summary_fixture(LABEL, "re-attribute");    f.h.clock.set(at(WRITTEN_AT));    let other = mint_token(&mut f.h, &["read", "write"], "Cursor");    call_tool(        &f.h,        &f.secret,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer on the Meridian job.",        }),    );    f.h.clock.set(at("2026-08-29T18:00:00.000Z"));    call_tool(        &f.h,        &other,        "update_summary",        json!({            "kind": "person",            "id": f.person,            "summary": "Structural engineer on the Meridian job.",        }),    );    assert_eq!(        summary_row(&f.h, "cotton_people", "summary", &f.person),        (            Some("Structural engineer on the Meridian job.".to_string()),            Some(LABEL.to_string()),            Some(WRITTEN_AT.to_string())        )    );}#[test]fn a_clear_over_an_already_clear_record_writes_nothing() {    // The one no-op a clear may be — and the reason the decision reads the    // provenance and not just the prose.    let f = summary_fixture(LABEL, "clear-noop");    f.h.clock.set(at(WRITTEN_AT));    let answer = call_tool(        &f.h,        &f.secret,        "update_summary",        json!({ "kind": "person", "id": f.person, "summary": null }),    );    assert_eq!(answer["updated"], json!(false));    assert_eq!(        summary_row(&f.h, "cotton_people", "summary", &f.person),        (None, None, None)    );}// The `describe("every kind that can be summarized has a read that answers it")`// loop is NOT here: its four cases belong to the READERS, not to the writer.// `person` (`get_record`) and `thread` (`read_message_thread`) are records part// 2's; `project` (`get_project`) is `tests/mcp_projects.rs`; `email_thread`// (`read_email_thread`) is owed by the email group. What this file owns of that// totality is the WRITER's own kinds, asserted case by case above.// ════════════════════════════════════════════════════════════════════════════// the bin — kind-generic (ported from mcpEmailState.test.ts)// ════════════════════════════════════════════════════════════════════════════//// PORT NOTE: the TypeScript seeds through `ingest_emails` and bins through// `update_email`, both of which belong to the EMAIL group and are not ported// yet. The rows are seeded straight into the file here instead — the same// shapes those verbs write — because what is under test is the BIN, which is// kind-generic and owns none of that.struct BinFixture {    h: Harness,    secret: String,    news_thread: String,    news_email: String,    kept_thread: String,}fn seeded_bin() -> BinFixture {    let mut h = Harness::new();    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let ws = h.workspace_id.clone();    let binned_at = "2026-08-25T10:00:00.000Z";    let thread = |label: &str, key: &str, subject: &str, trashed: Option<&str>| -> String {        let id = fixture_id(label);        run(            &h,            "INSERT INTO cotton_email_threads \               (id, workspace_id, external_key, subject, first_at, last_at, email_count, \                trashed_at, created_at, updated_at) \             VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)",            vec![                SqlValue::Text(id.clone()),                SqlValue::Text(ws.clone()),                SqlValue::Text(key.to_string()),                SqlValue::Text(subject.to_string()),                SqlValue::Text(AT.to_string()),                SqlValue::Text(AT.to_string()),                trashed                    .map(|at| SqlValue::Text(at.to_string()))                    .unwrap_or(SqlValue::Null),                SqlValue::Text(AT.to_string()),                SqlValue::Text(AT.to_string()),            ],        );        id    };    let news_thread = thread(        "bin-news-thread",        "gmail:acme-news",        "This week at Acme",        Some(binned_at),    );    let kept_thread = thread("bin-kept-thread", "gmail:acme-kept", "The contract", None);    let news_email = fixture_id("bin-news-email");    run(        &h,        "INSERT INTO cotton_emails \           (id, workspace_id, thread_id, external_id, subject, from_email, from_name, recipients, \            sent_at, body, snippet, attachments, labels, unread, starred, in_inbox, trashed_at, \            created_at) \         VALUES (?, ?, ?, ?, 'This week at Acme', 'news@acme.example', 'Acme', '[]', ?, \                 'The newsletter.', 'The newsletter.', '[]', '[]', 0, 0, 0, ?, ?)",        vec![            SqlValue::Text(news_email.clone()),            SqlValue::Text(ws.clone()),            SqlValue::Text(news_thread.clone()),            SqlValue::Text("<news@acme.example>".to_string()),            SqlValue::Text(AT.to_string()),            SqlValue::Text(binned_at.to_string()),            SqlValue::Text(AT.to_string()),        ],    );    BinFixture {        h,        secret,        news_thread,        news_email,        kept_thread,    }}#[test]fn lists_what_is_waiting_across_kinds_newest_first_counted_per_kind() {    let f = seeded_bin();    let out = call_tool(&f.h, &f.secret, "list_bin", json!({}));    // The conversation is counted once; its own message is listed with it.    // New empty Bin kinds must not change these fixture counts.    assert_eq!(out["counts"]["email_thread"], 1);    assert_eq!(out["counts"]["email"], 0);    assert_eq!(out["counts"].as_object().expect("counts").values()        .map(|n| n.as_u64().expect("a count")).sum::<u64>(), 1);    let kinds: Vec<&str> = out["entries"]        .as_array()        .expect("entries")        .iter()        .filter_map(|entry| entry["kind"].as_str())        .collect();    assert_eq!(kinds, vec!["email_thread"]);    assert!(out["entries"]        .as_array()        .expect("entries")        .iter()        .all(|entry| entry["title"] == json!("This week at Acme")));}#[test]fn restores_a_row_and_says_so_when_there_was_nothing_to_restore() {    let f = seeded_bin();    let restored = call_tool(        &f.h,        &f.secret,        "restore_from_bin",        json!({ "kind": "email_thread", "id": f.news_thread }),    );    assert_eq!(restored["restored"], json!(true));    let again = call_tool(        &f.h,        &f.secret,        "restore_from_bin",        json!({ "kind": "email_thread", "id": f.news_thread }),    );    assert_eq!(again["restored"], json!(false));}#[test]fn empties_the_bin_says_what_it_erased_and_says_what_gmail_still_holds() {    let f = seeded_bin();    let emptied = call_tool_as_owner(&f.h, "device:phone", "empty_bin", json!({})).json();    assert_eq!(emptied["erased"]["email"], 1);    assert_eq!(emptied["erased"]["email_thread"], 1);    assert_eq!(emptied["erased"].as_object().expect("erased counts").values()        .map(|n| n.as_u64().expect("an erased count")).sum::<u64>(), 2);    assert_eq!(emptied["total"], json!(2));    let listed = call_tool(&f.h, &f.secret, "list_bin", json!({}));    assert_eq!(listed["entries"], json!([]));    // The un-binned conversation is untouched.    assert_eq!(        text_of(            &f.h,            "SELECT subject FROM cotton_email_threads WHERE id = ?",            vec![SqlValue::Text(f.kept_thread.clone())],            "subject"        ),        Some("The contract".to_string())    );    assert_eq!(        count_of(&f.h, "SELECT COUNT(*) AS n FROM cotton_emails"),        0,        "the binned message was erased"    );    let _ = &f.news_email;}#[test]fn keeps_what_went_in_recently_when_only_the_old_ones_were_asked_for() {    let f = seeded_bin();    let emptied = call_tool_as_owner(&f.h, "device:phone", "empty_bin", json!({ "olderThanDays": 30 })).json();    assert_eq!(emptied["total"], json!(0));}/// RULE: list_bin refuses a kind with no Bin and names every kind that has/// one, read from `BinKind::ALL` — the kind asked about is a primitive whose/// registry entry says it is not binnable, so making a kind binnable (todo,/// 15 Oct 2026) never turns this guard red.#[test]fn refuses_a_kind_that_has_no_bin_naming_the_ones_that_do() {    let f = seeded_bin();    let unbinnable = cotton_core::constants::PrimitiveKind::ALL        .into_iter()        .find(|kind| !cotton_core::primitives::primitive(*kind).binnable.is_member())        .expect("some primitive kind has no bin");    let refused = call_tool_raw(&f.h, &f.secret, "list_bin", json!({ "kind": unbinnable.as_str() }));    assert!(refused.is_error, "{} has no bin: {}", unbinnable.as_str(), refused.text);    for kind in cotton_core::constants::BinKind::ALL {        assert!(refused.text.contains(kind.as_str()), "{} missing from: {}", kind.as_str(), refused.text);    }}// ════════════════════════════════════════════════════════════════════════════// media_repair (todo 5365af8f)// ════════════════════════════════════════════════════════════════════════════/// RULE: the dry run names every photo whose bytes are on no machine — by/// count, by chat and by created window — and a photo with bytes under any of/// its keys is not one of them. It writes nothing.#[test]fn media_repair_dry_run_names_the_photos_with_bytes_nowhere_by_chat() {    let f = seeded_storage();    let photo = format!("photo:{PHOTO_SHA}");    let answer = call_tool(&f.h, &f.secret, "media_repair", json!({ "dry_run": true }));    assert_eq!(answer["photos"], json!(1));    assert_eq!(answer["missing"], json!(1), "{answer}");    assert_eq!(answer["createdFrom"], json!(STORAGE_AT));    assert_eq!(answer["byChat"][0]["threadId"], json!(f.thread_id));    assert_eq!(answer["byChat"][0]["title"], json!("Kitchen rebuild"));    assert_eq!(answer["byChat"][0]["missing"], json!(1));    assert_eq!(answer["sample"], json!([photo]));    // The bytes arrive (a re-import's upload): no longer missing.    let key = format!("{}/messages/{}/{PHOTO_SHA}.jpg", f.h.workspace_id, f.thread_id);    f.h.services.media.put(&key, b"synthetic bytes".to_vec());    let answer = call_tool(&f.h, &f.secret, "media_repair", json!({ "dry_run": true }));    assert_eq!(answer["missing"], json!(0), "{answer}");}/// RULE: until the owner decides what a real run does, only the dry run runs.#[test]fn media_repair_refuses_a_real_run_by_name() {    let f = seeded_storage();    let refused = call_tool_raw(&f.h, &f.secret, "media_repair", json!({ "dry_run": false }));    assert!(refused.is_error, "{}", refused.text);    assert!(refused.text.contains("owner's decision"), "{}", refused.text);}/// RULE (ABSENCE 7, item 1): Empty the bin takes a failed text he put there, never a message the disappearing timer/// binned nor a timer line: those leave only by his act on the chat's line.#[test]fn empty_the_bin_never_takes_what_the_timer_binned_nor_a_timer_line() {    let (h, _secret) = writer_harness();    let ws = h.workspace_id.clone();    let binned_at = "2026-08-25T10:00:00.000Z";    run(&h, "INSERT INTO cotton_msg_threads (id, workspace_id, kind, external_key, title, read_seq, created_at, updated_at) VALUES ('t-invented', ?, 'dm', 'whatsapp:t-invented', 'Invented', 0, ?, ?)", vec![SqlValue::Text(ws.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())]);    let message = |id: &str, meta: &str| {        run(            &h,            "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, created_at, external_id, meta, trashed_at) VALUES (?, 't-invented', ?, 'out', 'whatsapp', 'imported', 'invented words', ?, ?, ?, ?, ?)",            vec![SqlValue::Text(id.into()), SqlValue::Text(ws.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into()), SqlValue::Text(format!("x-{id}")), SqlValue::Text(meta.into()), SqlValue::Text(binned_at.into())],        );    };    message("m-failed", "{}");    message("m-timer", r#"{"cotton":{"timer_binned":"2026-08-20T00:00:00.000Z"}}"#);    message("m-line", r#"{"cotton":{"timer":0}}"#);    let emptied = call_tool_as_owner(&h, "device:phone", "empty_bin", json!({ "kind": "message" })).json();    assert_eq!(emptied["total"], json!(1), "{emptied}");    assert_eq!(count_of(&h, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE id IN ('m-timer', 'm-line')"), 2, "the timer's stay");    assert_eq!(count_of(&h, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE id = 'm-failed'"), 0, "his failed text goes");}