Cotton code
549 lines · 20.9 KB · RustRaw
//! The chat write verbs the owner's own app authors, over an imported archive.//!//! Called the way the app really calls one — `Ctx::phone`, through//! `dispatch::call_tool` — so what is under test is the answer the screen//! receives rather than a handler's return value.//!//! **Half of this file went in 5m.** The verbs that SENT — `send_message`, the//! edit and take-back pair, reactions, forwards, drafts, the delivered sweep//! and the six group verbs — belonged to the multi-person sharing data plane,//! which was removed whole because it had never executed in production. Their//! cases went with them: a case asserting how a tool refuses is worth nothing//! once the tool answers `unknown tool`, which is a guard passing for the wrong//! reason. The rulings themselves are kept in Cotton note "Messages — the archive, and the sharing that was removed" and//! the code on the branch `archive/sharing-v1`, for whoever rebuilds this.//!//! What is left is the ARCHIVE and the owner's own private state over it, and//! the rules a naive port would still lose://!//!   * a read cursor is monotonic and writes NOTHING when it has nothing to//!     say — the screen calls it on every arrival;//!   * clearing a conversation is ONE marker, never one write per message;//!   * hiding the newest line walks the conversation's own preview back;//!   * pin, archive, mute and star are STATES rather than toggles; and//!   * no connected assistant reaches a single one of these writes.//!//! Every fixture is synthetic ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use rusqlite::types::Value as SqlValue;use serde_json::{json, Value};use std::collections::BTreeMap;use support::harness::{synthetic_uuid, Harness, HARNESS_NOW};use support::mcp::{call_tool_as_owner, call_tool_raw, mint_token};/// The device id the owner's app writes under.const DEVICE: &str = "device:00000000000000000000000000";/// Ten minutes before the harness clock — inside the fifteen-minute edit window/// and inside the forty-eight-hour take-back window.const RECENT: &str = "2026-09-08T09:50:00.000Z";/// Twenty minutes before — outside the edit window, inside the take-back one.const STALE: &str = "2026-09-08T09:40:00.000Z";/// Three days before — outside both.const OLD: &str = "2026-09-05T10:00:00.000Z";fn call(h: &Harness, name: &str, args: Value) -> support::mcp::ToolAnswer {    call_tool_as_owner(h, DEVICE, name, args)}fn t(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}// ── the fixture ─────────────────────────────────────────────────────────────struct Chat {    h: Harness,    /// A live Cotton group the owner is an admin of.    group: String,    /// A live direct conversation with somebody who is on Cotton.    dm: String,    /// The owner's own newest line in the direct conversation.    mine: String,    /// A line the other person sent.    theirs: String,}// The fixture still SEEDS two seats and two contacts — a group with no// participants is not a group, and the surviving cases read a conversation that// has to look like one. It no longer HANDS THEM OUT: the cases that named a// seat or a contact were the group verbs' and the direct-conversation opener's,// and those went in 5m. A field nobody reads is a field clippy fails the build// over, which is the right answer — it is the fixture telling you what the// suite stopped being about.fn chat() -> Chat {    let h = Harness::new();    let ws = h.workspace_id.clone();    let priya_contact = synthetic_uuid("contact-priya");    h.run(        "INSERT INTO cotton_msg_contacts \           (id, workspace_id, phone_e164, display_name, on_cotton_at, created_at, updated_at) \         VALUES (?, ?, '919876500001', 'Priya Nair', ?, ?, ?)",        &[t(&priya_contact), t(&ws), t(HARNESS_NOW), t(HARNESS_NOW), t(HARNESS_NOW)],    );    let stranger_contact = synthetic_uuid("contact-stranger");    h.run(        "INSERT INTO cotton_msg_contacts \           (id, workspace_id, phone_e164, display_name, created_at, updated_at) \         VALUES (?, ?, '919876500002', 'Ravi Kumar', ?, ?)",        &[t(&stranger_contact), t(&ws), t(HARNESS_NOW), t(HARNESS_NOW)],    );    // A live Cotton group: `external_key` carries the group's identity, which    // is what tells a live conversation from an imported archive.    let group = synthetic_uuid("thread-group");    h.run(        "INSERT INTO cotton_msg_threads \           (id, workspace_id, kind, title, external_key, last_message_at, created_at, updated_at) \         VALUES (?, ?, 'group', 'Kitchen rebuild', 'cotton:group:01J0ABCDEFGHJKMNPQRSTVWXYZ', ?, ?, ?)",        &[t(&group), t(&ws), t(OLD), t(HARNESS_NOW), t(HARNESS_NOW)],    );    let self_seat = synthetic_uuid("seat-self");    h.run(        "INSERT INTO cotton_msg_thread_participants \           (id, thread_id, workspace_id, contact_id, display_name, role, is_self, created_at) \         VALUES (?, ?, ?, NULL, NULL, 'admin', 1, ?)",        &[t(&self_seat), t(&group), t(&ws), t(HARNESS_NOW)],    );    let priya_seat = synthetic_uuid("seat-priya");    h.run(        "INSERT INTO cotton_msg_thread_participants \           (id, thread_id, workspace_id, contact_id, display_name, role, is_self, created_at) \         VALUES (?, ?, ?, ?, 'Priya', 'member', 0, ?)",        &[t(&priya_seat), t(&group), t(&ws), t(&priya_contact), t(HARNESS_NOW)],    );    let dm = synthetic_uuid("thread-dm");    h.run(        "INSERT INTO cotton_msg_threads \           (id, workspace_id, contact_id, kind, external_key, last_message_at, created_at, updated_at) \         VALUES (?, ?, ?, 'dm', 'chat:asha-r|priya-n', ?, ?, ?)",        &[t(&dm), t(&ws), t(&priya_contact), t(RECENT), t(HARNESS_NOW), t(HARNESS_NOW)],    );    let line = |thread: &str, direction: &str, body: &str, sent_at: &str, seq: Option<i64>| {        let id = synthetic_uuid("message");        h.run(            "INSERT INTO cotton_msg_messages \               (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, \                created_at, seq) \             VALUES (?, ?, ?, ?, 'cotton', 'live', ?, ?, ?, ?)",            &[                t(&id),                t(thread),                t(&ws),                t(direction),                t(body),                t(sent_at),                t(sent_at),                seq.map(SqlValue::Integer).unwrap_or(SqlValue::Null),            ],        );        id    };    let theirs = line(&dm, "in", "Are we still on for Friday?", STALE, Some(7));    let mine = line(&dm, "out", "Yes — six o'clock", RECENT, Some(8));    Chat {        h,        group,        dm,        mine,        theirs,    }}fn column(c: &Chat, table: &str, id: &str, name: &str) -> Value {    c.h.one(        &format!("SELECT {name} AS value FROM {table} WHERE id = ?"),        &[t(id)],    )    .and_then(|row| row.get("value").cloned())    .unwrap_or(Value::Null)}/// Every op this file has minted, newest last — what the outbox will carry.fn ops(c: &Chat, since: &BTreeMap<String, String>) -> Vec<(String, String, String)> {    c.h.ops_since(since)        .into_iter()        .map(|row| {            let get = |key: &str| {                row.get(key)                    .and_then(Value::as_str)                    .unwrap_or_default()                    .to_string()            };            (get("kind"), get("tbl"), get("row_id"))        })        .collect()}// ── the scope ───────────────────────────────────────────────────────────────#[test]fn no_connected_assistant_can_reach_a_single_chat_write() {    // THE RULE THIS CASE EXISTS FOR. `owner` is not a word a token can be    // minted with, so the widest grant that exists still cannot hide, clear,    // mute or delete anything anybody said. The verb grid already refuses each    // of these in writing; this is that refusal at the dispatch, where it    // actually holds.    //    // The list is SHORTER than it was: the verbs that SENT — edit, take back,    // react, forward, the group verbs — went with the multi-person sharing    // data plane in 5m, and a refusal of a tool that does not exist would be a    // guard passing on `unknown tool`. What is left is the owner's own private    // state over an imported archive, which is exactly what an assistant must    // still not reach.    let mut c = chat();    let secret = mint_token(&mut c.h, &["read", "write"], "An assistant");    for (tool, args) in [        ("hide_chat_messages", json!({ "messageIds": [c.mine.clone()] })),        ("clear_thread", json!({ "threadId": c.dm, "before": HARNESS_NOW })),        ("set_thread_muted", json!({ "threadId": c.dm, "until": null })),        ("set_thread_archived", json!({ "threadId": c.dm, "archived": true })),        ("delete_thread", json!({ "threadId": c.dm })),    ] {        let refused = call_tool_raw(&c.h, &secret, tool, args);        assert!(refused.is_error, "{tool} answered an assistant");    }}// ── edit_chat_message ───────────────────────────────────────────────────────#[test]fn hiding_the_newest_line_walks_the_list_quote_back_to_the_one_before() {    // "Delete for me" is the one delete that must visibly delete: if the list    // kept quoting the line the person just removed from their own copy, the    // gesture would look broken.    let c = chat();    c.h.run(        "UPDATE cotton_msg_threads SET last_message_preview = 'Yes — six o''clock', \         last_message_at = ? WHERE id = ?",        &[t(RECENT), t(&c.dm)],    );    let answered = call(&c.h, "hide_chat_messages", json!({ "messageIds": [c.mine] })).json();    assert_eq!(answered["hidden"], json!(1));    assert_eq!(        column(&c, "cotton_msg_threads", &c.dm, "last_message_preview"),        json!("Are we still on for Friday?")    );}#[test]fn hiding_a_line_that_is_not_the_newest_leaves_the_list_exactly_where_it_is() {    let c = chat();    c.h.run(        "UPDATE cotton_msg_threads SET last_message_preview = 'Yes — six o''clock' WHERE id = ?",        &[t(&c.dm)],    );    call(&c.h, "hide_chat_messages", json!({ "messageIds": [c.theirs] })).json();    assert_eq!(        column(&c, "cotton_msg_threads", &c.dm, "last_message_preview"),        json!("Yes — six o'clock")    );}#[test]fn hiding_nothing_answers_nothing_hidden_rather_than_refusing() {    let c = chat();    let answered = call(&c.h, "hide_chat_messages", json!({ "messageIds": [] })).json();    assert_eq!(answered["hidden"], json!(0));    // And a second pass over rows already hidden is the same answer, which is    // why the verb is safe for a screen to call twice.    call(&c.h, "hide_chat_messages", json!({ "messageIds": [c.mine] })).json();    let again = call(&c.h, "hide_chat_messages", json!({ "messageIds": [c.mine] })).json();    assert_eq!(again["hidden"], json!(0));}// ── forward_chat_messages ───────────────────────────────────────────────────#[test]fn starring_stamps_the_private_column_and_unstarring_clears_it() {    let c = chat();    call(        &c.h,        "star_message",        json!({ "messageId": c.theirs, "starred": true }),    )    .json();    assert_eq!(        column(&c, "cotton_msg_messages", &c.theirs, "starred_at"),        json!(HARNESS_NOW)    );    call(        &c.h,        "star_message",        json!({ "messageId": c.theirs, "starred": false }),    )    .json();    assert_eq!(        column(&c, "cotton_msg_messages", &c.theirs, "starred_at"),        Value::Null    );}// ── the read cursor ─────────────────────────────────────────────────────────#[test]fn a_read_cursor_only_ever_moves_forward() {    // Two devices at different scroll positions: the one further back must not    // drag the cursor down, and a fold of its older patch has to be a no-op.    let c = chat();    call(        &c.h,        "mark_thread_read",        json!({ "threadId": c.dm, "upToSeq": 8 }),    )    .json();    let backwards = call(        &c.h,        "mark_thread_read",        json!({ "threadId": c.dm, "upToSeq": 3 }),    )    .json();    assert_eq!(backwards["readSeq"], json!(8));    assert_eq!(column(&c, "cotton_msg_threads", &c.dm, "read_seq"), json!(8));}#[test]fn a_read_cursor_with_nothing_to_say_writes_no_op_at_all() {    // THE RULE THIS CASE EXISTS FOR. The conversation screen calls this on    // every arrival while it is open, and an op per no-op would fill an    // append-only history — replayed by every device for ever — with the fact    // that somebody was looking at a screen.    let c = chat();    call(        &c.h,        "mark_thread_read",        json!({ "threadId": c.dm, "upToSeq": 8 }),    )    .json();    let before = c.h.cursors();    let again = call(        &c.h,        "mark_thread_read",        json!({ "threadId": c.dm, "upToSeq": 8 }),    )    .json();    assert_eq!(again["changed"], json!(false));    assert_eq!(c.h.cursors(), before);}#[test]fn a_read_cursor_with_no_sequence_named_goes_to_the_foot_of_the_conversation() {    // WHAT THE APP SENDS. Opening a conversation means "I have read all of it",    // and the app must not compute the number itself: the window it draws has    // had hidden and cleared rows taken out of it, so its own highest sequence    // number can be behind the conversation's — and a cursor short of the foot    // leaves an unread rule over messages that were just read.    let c = chat();    let moved = call(&c.h, "mark_thread_read", json!({ "threadId": c.dm })).json();    // The fixture's newest relayed row is seq 8.    assert_eq!(moved["readSeq"], json!(8));    assert_eq!(moved["changed"], json!(true));    assert_eq!(column(&c, "cotton_msg_threads", &c.dm, "read_seq"), json!(8));    // And the second open writes nothing, exactly as the numbered form does.    let before = c.h.cursors();    let again = call(&c.h, "mark_thread_read", json!({ "threadId": c.dm })).json();    assert_eq!(again["changed"], json!(false));    assert_eq!(c.h.cursors(), before);}#[test]fn a_conversation_nothing_was_ever_relayed_in_reads_to_zero_rather_than_refusing() {    // An imported archive carries no sequence number at all — a cursor is a    // position in the RELAY's order, and an archive was never in it. Opening    // one is not an error, it just has no cursor to move.    let c = chat();    c.h.run(        "UPDATE cotton_msg_messages SET seq = NULL WHERE thread_id = ?",        &[t(&c.dm)],    );    let before = c.h.cursors();    let moved = call(&c.h, "mark_thread_read", json!({ "threadId": c.dm })).json();    assert_eq!(moved["readSeq"], json!(0));    assert_eq!(moved["changed"], json!(false));    assert_eq!(c.h.cursors(), before);}#[test]fn marking_unread_flags_the_conversation_and_never_rewinds_the_cursor() {    // Rewinding would tell every other participant's receipts that these    // messages had been un-read, which is not what somebody means by the    // gesture: they meant "come back to this".    let c = chat();    call(        &c.h,        "mark_thread_read",        json!({ "threadId": c.dm, "upToSeq": 8 }),    )    .json();    call(&c.h, "mark_thread_unread", json!({ "threadId": c.dm })).json();    assert_eq!(column(&c, "cotton_msg_threads", &c.dm, "read_seq"), json!(8));    assert_eq!(        column(&c, "cotton_msg_threads", &c.dm, "unread_marked_at"),        json!(HARNESS_NOW)    );    // And reading it again clears the flag.    call(        &c.h,        "mark_thread_read",        json!({ "threadId": c.dm, "upToSeq": 9 }),    )    .json();    assert_eq!(        column(&c, "cotton_msg_threads", &c.dm, "unread_marked_at"),        Value::Null    );}// ── the private switches ────────────────────────────────────────────────────#[test]fn mute_takes_an_instant_and_refuses_anything_that_is_not_one() {    let c = chat();    call(        &c.h,        "set_thread_muted",        json!({ "threadId": c.group, "until": "9999-12-31T00:00:00Z" }),    )    .json();    // Stored as the codec normalises an instant — the same instant, spelled    // with its milliseconds, which is what every other timestamp column holds.    assert_eq!(        column(&c, "cotton_msg_threads", &c.group, "muted_until"),        json!("9999-12-31T00:00:00.000Z")    );    let refused = call(        &c.h,        "set_thread_muted",        json!({ "threadId": c.group, "until": "next Tuesday" }),    );    assert!(refused.is_error);    assert!(refused.text.contains("not a time"), "{}", refused.text);    call(        &c.h,        "set_thread_muted",        json!({ "threadId": c.group, "until": null }),    )    .json();    assert_eq!(        column(&c, "cotton_msg_threads", &c.group, "muted_until"),        Value::Null    );}#[test]fn pin_and_archive_are_states_rather_than_toggles() {    // Asking for the state a conversation is already in writes the same row,    // which is what lets a screen call either of these twice without inventing    // a third outcome.    let c = chat();    call(        &c.h,        "set_thread_pinned",        json!({ "threadId": c.dm, "pinned": true }),    )    .json();    call(        &c.h,        "set_thread_pinned",        json!({ "threadId": c.dm, "pinned": true }),    )    .json();    assert_eq!(        column(&c, "cotton_msg_threads", &c.dm, "pinned_at"),        json!(HARNESS_NOW)    );    call(        &c.h,        "set_thread_archived",        json!({ "threadId": c.dm, "archived": true }),    )    .json();    assert_eq!(column(&c, "cotton_msg_threads", &c.dm, "archived"), json!(1));}#[test]fn clearing_a_conversation_is_one_marker_and_never_one_write_per_message() {    // THE RULE THIS CASE EXISTS FOR. Stamping every row would mint one op per    // message, and the history is append-only and replayed by every device    // for ever: a forty-thousand-message archive would cost forty thousand    // permanent ops for one tap.    let c = chat();    let before = c.h.cursors();    let answered = call(&c.h, "clear_thread", json!({ "threadId": c.dm })).json();    assert_eq!(answered["clearedBefore"], json!(HARNESS_NOW));    let mut written = ops(&c, &before);    // A file's first write by an author carries that author's    // `cotton_authors` fact first (slice 2c); creation and the kit import may    // already have written it. The clear's own ops are what follow it.    if written.first().is_some_and(|op| op.1 == "cotton_authors") {        written.remove(0);    }    assert_eq!(written.len(), 1, "{written:?}");    assert_eq!(written[0].1, "cotton_msg_threads");    assert_eq!(        column(&c, "cotton_msg_threads", &c.dm, "last_message_preview"),        Value::Null    );}#[test]fn a_clear_marker_never_moves_backwards() {    // Two devices clearing at different moments: the earlier one must not    // un-hide what the later one already hid.    let c = chat();    let later = "2027-01-01T00:00:00.000Z";    c.h.run(        "UPDATE cotton_msg_threads SET cleared_before = ? WHERE id = ?",        &[t(later), t(&c.dm)],    );    let answered = call(&c.h, "clear_thread", json!({ "threadId": c.dm })).json();    assert_eq!(answered["clearedBefore"], json!(later));}#[test]fn deleting_a_conversation_removes_its_children_before_its_parent() {    // The database enforces foreign keys, so a conversation removed before its    // messages would be refused — and a half-applied delete is a conversation    // whose messages point at nothing.    let c = chat();    let before = c.h.cursors();    call(&c.h, "delete_thread", json!({ "threadId": c.dm })).json();    let removed: Vec<String> = ops(&c, &before)        .into_iter()        .filter(|(kind, _, _)| kind == "delete")        .map(|(_, table, _)| table)        .collect();    assert_eq!(        removed.last().map(String::as_str),        Some("cotton_msg_threads"),        "the conversation goes LAST: {removed:?}"    );    assert_eq!(        c.h.count(            "SELECT COUNT(*) FROM cotton_msg_messages WHERE thread_id = ?",            &[t(&c.dm)]        ),        0    );}#[test]fn a_conversation_in_another_database_reads_the_same_as_one_that_never_existed() {    let c = chat();    let elsewhere = synthetic_uuid("thread-elsewhere");    let absent = call(&c.h, "clear_thread", json!({ "threadId": elsewhere }));    assert!(absent.is_error);    assert!(        absent.text.contains("no such conversation"),        "{}",        absent.text    );}