Cotton code
226 lines · 11.2 KB · RustRaw
//! The message archive is read, and it has exactly one door out: a text the//! owner writes in Comms in a WhatsApp chat, queued in the `outbox` the Mac//! drains (22 Nov 2026; `crates/cotton-ffi/src/phone/chat_whatsapp.rs`).//! No record verb on a message sends anything, the owner's included, and an//! assistant sends nothing.//!//! The multi-person sharing data plane — peers, scopes, grants, the chat relay//! and every verb that transmitted a message — was removed whole; the code is//! on the branch `archive/sharing-v1`. What is left is an ARCHIVE: WhatsApp,//! iMessage and SMS conversations imported off the Mac, plus that one door.//!//! The assistant's half is held over two registries that cannot be//! sidestepped: the verb grid, which every dispatchable tool must appear in//! (`tool_surface_tests::every_tool_is_owned_by_exactly_one_primitive_or_shared`),//! and the published tool catalogue. The owner's half is held through the//! generic record verbs: `create_record` and `update_record` on a message are//! refusals for everyone, and Delete bins only an old failed text of the//! owner's. Every value is invented.mod support;use cotton_tools::mcp::protocol::{tool_by_name, TOOLS};use cotton_tools::mcp::tool_surface::verb_set;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool_as_owner, call_tool_raw, mint_token, ToolAnswer};/// The device id the owner's app writes under.const DEVICE: &str = "device:00000000000000000000000000";const NOW: &str = "2026-09-08T09:00:00.000Z";const CHAT: &str = "c0000000-0000-4000-8000-000000000001";const QUOTED: &str = "c0000000-0000-4000-8000-0000000000b1";const ACCOUNT: &str = "15550001111@s.whatsapp.net";fn t(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}fn owner(h: &Harness, name: &str, args: Value) -> ToolAnswer {    call_tool_as_owner(h, DEVICE, name, args)}/// A direct WhatsApp chat the linked number brought in; `linked` says/// whether the number is linked and reading under Connections.fn chat(linked: bool) -> Harness {    let h = Harness::new();    let w = h.workspace_id.clone();    h.run(        "INSERT INTO cotton_msg_contacts (id, workspace_id, phone_e164, display_name, created_at, updated_at) \         VALUES ('contact-a', ?, '919800000001', 'Example Asha', ?, ?)",        &[t(&w), t(NOW), t(NOW)],    );    h.run(        "INSERT INTO cotton_msg_threads (id, workspace_id, kind, contact_id, created_at, updated_at) \         VALUES (?, ?, 'dm', 'contact-a', ?, ?)",        &[t(CHAT), t(&w), t(NOW), t(NOW)],    );    let meta = format!(        r#"{{"source":{{"service":"WhatsApp linked device","account":"{ACCOUNT}","chat":"919800000001@s.whatsapp.net","externalId":"WA-IN-1"}}}}"#    );    h.run(        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, external_id, \         sent_at, created_at, meta) VALUES (?, ?, ?, 'in', 'whatsapp', 'imported', 'are you coming?', 'WA-IN-1', ?, ?, ?)",        &[t(QUOTED), t(CHAT), t(&w), t(NOW), t(NOW), t(&meta)],    );    if linked {        h.run(            "INSERT INTO cotton_connections (id, workspace_id, kind, name, state, config, created_at, updated_at) \             VALUES ('conn:whatsapp:+15550001111', ?, 'whatsapp', 'WhatsApp', 'reading', ?, ?, ?)",            &[t(&w), t(&format!(r#"{{"account":"{ACCOUNT}","mac":"m"}}"#)), t(NOW), t(NOW)],        );    }    h}fn queued(h: &Harness) -> Vec<serde_json::Map<String, Value>> {    h.all(        "SELECT id, thread_id, direction, channel, origin, body, reply_to_id, external_id, send_state, send_error, \         send_attempts FROM cotton_msg_messages WHERE send_state IS NOT NULL",        &[],    )}/// RULE: An assistant has no tool that sends — every one of a message's five standard verbs is refused to it in writing.////// WHY: the verb grid is what a model reads to work out which tools exist, and/// every tool that can be called has to appear in it. A verb that started/// sending would have to be written into this row, so this row is where the/// answer is kept: the archive arrives by import, and the one text written out/// is the owner's own, from their own app.#[test]fn every_standard_verb_on_a_message_is_a_written_refusal() {    let row = verb_set("message").expect("the verb grid has a row for the message kind");    for (verb, cell) in row.verbs() {        let refusal = cell.refusal().unwrap_or_else(|| {            panic!(                "message.{verb} names the tool `{}` — an assistant sends nothing, so this verb belongs \                 refused with the reason in writing",                cell.tool().unwrap_or("?")            )        });        assert!(            !refusal.trim().is_empty(),            "message.{verb} is refused with no reason given"        );    }}/// RULE: Nothing in Cotton starts a conversation — a conversation exists because an import brought it in.////// WHY: a conversation that Cotton could create would be a conversation with/// nobody on the other end of it. The archive's conversations are read off/// WhatsApp, iMessage and SMS, and the only writes over them are the owner's own/// private state — read, muted, pinned, archived, cleared — and their texts.#[test]fn a_conversation_is_never_created_or_patched_by_a_tool() {    let row = verb_set("thread").expect("the verb grid has a row for the conversation kind");    for (verb, cell) in [("create", row.create), ("update", row.update)] {        assert!(            cell.refusal().is_some(),            "thread.{verb} names the tool `{}` — a conversation arrives with the import and \             nothing in Cotton starts or rewrites one",            cell.tool().unwrap_or("?")        );    }}/// RULE: The only tool in Cotton whose name begins with "send" addresses one of the owner's own assistant sessions, never a person.////// WHY: the verbs that transmitted a message to somebody else are gone, and the/// simplest way for one to come back is a new tool called `send_…`. The one/// sender that is legitimate puts a row on the owner's own session queue — it/// leaves the database for nobody. A WhatsApp text is a record write, not a tool.#[test]fn the_catalogue_carries_no_verb_that_sends_to_a_person() {    assert!(        tool_by_name("send_message").is_none(),        "`send_message` is a tool again — a text goes out only as the owner's record write"    );    let senders: Vec<&str> = TOOLS        .iter()        .map(|tool| tool.name)        .filter(|name| name.starts_with("send"))        .collect();    assert_eq!(        senders,        Vec::<&str>::new(),        "a sending verb is in the catalogue; none is legitimate since the session inbox went \         (15 Nov 2026)"    );}/// RULE (owner, 22 Nov 2026): no record verb on a message sends a text, the owner's own app's included: a text to/// WhatsApp goes out only from Comms, by the owner's tap, through the outbox the Mac drains. Create and update on a/// message are refused for everyone and write nothing.////// WHY: the old door (a `queued` message row a Mac pass would send) had no pass left to send it, and any second/// way to queue a send is a way for something other than the owner's tap to send.#[test]fn no_record_verb_on_a_message_sends_a_text() {    let mut h = chat(true);    let created = owner(&h, "create_record", json!({ "table": "message", "data": { "thread_id": CHAT, "body": "on my way" } }));    assert!(created.is_error, "the owner's create wrote a text: {}", created.text);    assert!(created.text.contains("sent from Comms"), "{}", created.text);    let secret = mint_token(&mut h, &["read", "write"], "Claude");    let answer = call_tool_raw(&h, &secret, "create_record", json!({ "table": "message", "data": { "thread_id": CHAT, "body": "on my way" } }));    assert!(answer.is_error, "an assistant wrote a text: {}", answer.text);    let updated = owner(&h, "update_record", json!({ "table": "message", "id": QUOTED, "patch": { "send_state": "queued" } }));    assert!(updated.is_error, "an update queued a message: {}", updated.text);    assert!(queued(&h).is_empty(), "nothing was queued");}/// RULE: A chat says whether it can send and, when it cannot, why — read by the page that offers the input.#[test]fn a_chat_reads_sendable_and_its_reason() {    let read = |h: &Harness| {        let listed = owner(h, "list_records", json!({ "table": "thread" })).json();        listed["records"].as_array().expect("records").iter().find(|record| record["id"] == CHAT).expect("the chat")["data"].clone()    };    let unlinked = read(&chat(false));    assert_eq!(unlinked["sendable"], json!(false), "{unlinked}");    assert_eq!(unlinked["send_blocked_reason"], json!("WhatsApp is not linked on your Mac"));    let linked = read(&chat(true));    assert_eq!(linked["sendable"], json!(true), "{linked}");    assert_eq!(linked["send_blocked_reason"], Value::Null);}/// RULE: Only a failed text of the owner's goes in the bin — Delete on a queued, sent or arrived message is refused — and in the bin it is never sent again, nor queued again until it is taken back out, still failed.#[test]fn only_a_failed_text_goes_in_the_bin_and_comes_back_still_failed() {    let h = chat(true);    // A text of the owner's from before Comms sent through the outbox, as such a row stands.    let id = "c0000000-0000-4000-8000-0000000000c1".to_string();    h.run(        "INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, send_state, send_attempts, \         sent_at, created_at) VALUES (?, ?, ?, 'out', 'whatsapp', 'live', 'on my way', 'queued', 0, ?, ?)",        &[t(&id), t(CHAT), t(&h.workspace_id), t(NOW), t(NOW)],    );    let bin = |id: &str| owner(&h, "delete_record", json!({ "table": "message", "id": id }));    let state = |column: &str| h.one(&format!("SELECT {column} AS v FROM cotton_msg_messages WHERE id = ?"), &[t(&id)]).unwrap()["v"].clone();    assert!(bin(&id).is_error, "a queued text went in the bin");    assert!(bin(QUOTED).is_error, "a message that arrived went in the bin");    h.run("UPDATE cotton_msg_messages SET send_state = 'sent' WHERE id = ?", &[t(&id)]);    assert!(bin(&id).is_error, "a sent text went in the bin");    h.run("UPDATE cotton_msg_messages SET send_state = 'failed', send_error = 'WhatsApp refused it: example' WHERE id = ?", &[t(&id)]);    let binned = bin(&id);    assert!(!binned.is_error, "{}", binned.text);    assert!(state("trashed_at").is_string());    assert_eq!(state("send_state"), json!("failed"));    let listed = owner(&h, "list_bin", json!({ "kind": "message" })).json();    assert_eq!(listed["entries"][0]["id"], json!(id), "{listed}");    assert_eq!(listed["entries"][0]["title"], json!("on my way"));    let again = owner(&h, "update_record", json!({ "table": "message", "id": id, "patch": { "send_state": "queued" } }));    assert!(again.is_error, "a binned text was queued again");    assert_eq!(state("send_state"), json!("failed"));    let restored = owner(&h, "restore_from_bin", json!({ "kind": "message", "id": id }));    assert!(!restored.is_error, "{}", restored.text);    assert_eq!(state("trashed_at"), Value::Null);    assert_eq!(state("send_state"), json!("failed"), "a restore leaves the text failed, not queued");}