//! Disappearing messages on a WhatsApp chat: the owner's own copy only//! (FEEDBACK-2 B.2, 23 Nov 2026; CONTRACT.md "WhatsApp through the Mac").//! The chats come in through the import the Mac's link writes with; every//! name, number, id and word is invented.use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};usecrate::handle::CottonHandle;usecrate::phone::cotton_chat::over;const ASHA: &str = "+15550190411";const RAVI: &str = "+15550190422";const DAY_MS: i64 = 86_400_000;fn phone() -> (tempfile::TempDir, CottonHandle) {let dir = tempfile::tempdir().unwrap();let handle = crate::phone::chat_app::mail::tests::comms(&dir, cotton_core::flavor::Flavor::Real); (dir, handle)}fn call(handle: &CottonHandle, method: &str, request: Value) -> Value { over(&handle.client(), method, &request).unwrap_or_else(|error| panic!("{method}: {} {}", error.code, error.message))}fn now_ms(handle: &CottonHandle) -> i64 {crate::phone::cotton_chat::now_ms(&handle.client())}fn iso(ms: i64) -> String {crate::phone::cotton_chat::iso(ms)}fn workspace(handle: &CottonHandle) -> String {let found = crate::phone::cotton_chat::read(&handle.client(), "test.ws", |ctx| Ok(json!(ctx.workspace_id))).unwrap(); found.as_str().unwrap().to_string()}fn sql(handle: &CottonHandle, statement: &str, params: &[SqlValue]) { handle.client().with_writer(|replica| replica.driver.run(statement, params).map(|_| ()).map_err(|e| e.to_string())).expect(statement);}fn rows(handle: &CottonHandle, statement: &str, params: &[SqlValue]) -> Vec<Map<String, Value>> {let (statement, params) = (statement.to_string(), params.to_vec());let found = crate::phone::cotton_chat::read(&handle.client(), "test.rows", |ctx| Ok(json!(crate::phone::cotton_chat::rows(ctx, &statement, ¶ms)?))).unwrap(); found.as_array().unwrap().iter().map(|r| r.as_object().unwrap().clone()).collect()}fn t(s: &str) -> SqlValue {SqlValue::Text(s.to_string())}/// WhatsApp messages from `phone`, as the Mac's link hands them to the import: `(WhatsApp id, words, sent ms ago, out)`.fn import(handle: &CottonHandle, phone: &str, messages: &[(&str, &str, i64, bool)]) -> i64 {let now = now_ms(handle);let batch: cotton_core::import::envelope::ImportBatch = serde_json::from_value(json!({"workspaceId": workspace(handle),"channel": "whatsapp","messages": messages.iter().map(|(id, body, ago, out)| json!({"externalId": id, "direction": if *out { "out" } else { "in" }, "body": body, "sentAt": iso(now - ago), "phone": phone, })).collect::<Vec<_>>(), })) .unwrap();let answer = handle .client() .import_rows("test.import", &["cotton_msg_threads", "cotton_msg_messages", "cotton_msg_thread_participants", "cotton_msg_contacts", "cotton_msg_reactions", "cotton_workspaces"], &mut |seams| {let namespace = seams.replica.identity.namespace().clone();let report = cotton_client::messages_import::import_messages(&seams.replica.driver, &namespace, &batch, seams.clock, seams.random, seams.ids).map_err(|e| e.to_string())?;Ok(json!({ "inserted": report.totals.inserted })) }) .unwrap(); answer["inserted"].as_i64().unwrap()}/// The thread a WhatsApp id landed in.fn thread_of(handle: &CottonHandle, external: &str) -> String { rows(handle, "SELECT thread_id FROM cotton_msg_messages WHERE external_id = ?", &[t(external)])[0]["thread_id"].as_str().unwrap().to_string()}fn held(handle: &CottonHandle, external: &str) -> Option<Map<String, Value>> { rows(handle, "SELECT * FROM cotton_msg_messages WHERE external_id = ? AND json_extract(meta, '$.cotton.erased') IS NULL", &[t(external)]).into_iter().next()}fn marker(handle: &CottonHandle, external: &str) -> Option<Map<String, Value>> { rows(handle, "SELECT * FROM cotton_msg_messages WHERE external_id = ? AND json_extract(meta, '$.cotton.erased') IS NOT NULL", &[t(external)]).into_iter().next()}fn set_timer(handle: &CottonHandle, thread: &str, seconds: u32) -> Value { call(handle, "chat.act", json!({ "act": "timer", "thread": thread, "seconds": seconds }))}/// Time passes: the chat's timer lines were set `days` earlier than they were.fn turned_on_days_ago(handle: &CottonHandle, thread: &str, days: i64) {let at = iso(now_ms(handle) - days * DAY_MS); sql(handle, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL", &[t(&at), t(thread)]);}fn sweep(handle: &CottonHandle) -> usize {crate::phone::chat_timer::sweep(&handle.client()).map_err(|e| e.message).unwrap()}/// A sweep, the Bin's 30 days passing for what the timer put there, and a sweep again: what the second erases.fn sweep_through(handle: &CottonHandle) -> usize { sweep(handle); erase_binned(handle)}/// His act, "Erase these for good", in every chat whose messages the timer binned: how many went.fn erase_binned(handle: &CottonHandle) -> usize {let chats: Vec<String> = rows(handle, "SELECT DISTINCT thread_id FROM cotton_msg_messages WHERE trashed_at IS NOT NULL AND json_extract(meta, '$.cotton.timer_binned') IS NOT NULL", &[]).iter().filter_map(|r| r["thread_id"].as_str().map(str::to_string)).collect();letmut erased = 0;for chat in chats {let erase = call(handle, "chat.thread", json!({ "thread": chat }))["timerBinned"]["erase"].clone(); erased += call(handle, "chat.timer.erase", json!({ "thread": chat, "count": erase["count"], "snapshot": erase["snapshot"] }))["erased"].as_u64().unwrap() as usize; } erased}fn reset_test_view() {crate::phone::chat_timer::TEST.with(|t| *t.borrow_mut() = crate::phone::chat_timer::TestClock::default());}fn binned(handle: &CottonHandle, external: &str) -> bool { held(handle, external).is_some_and(|m| !m["trashed_at"].is_null())}// RULE (ABSENCE 6): the timer puts a message in the Bin and never erases it: it stays restorable, with no marker, for// as long as it sits there; only his own "Erase these for good" erases it, with its marker.#[test]fn the_timer_bins_first_and_erases_only_after_the_bins_days() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0H0", "hello", 6 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0H0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 5); import(&phone, ASHA, &[("3EB0H1", "said under the timer", 3 * DAY_MS, false), ("3EB0H2", "and the newest", 60_000, false)]); assert_eq!(sweep(&phone), 1); assert!(binned(&phone, "3EB0H1"), "in the Bin"); assert!(marker(&phone, "3EB0H1").is_none(), "no marker while it can come back");// However long it sits there, the timer never erases it (ABSENCE 6).let a_year = iso(now_ms(&phone) - 365 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET trashed_at = ? WHERE json_extract(meta, '$.cotton.timer_binned') IS NOT NULL", &[t(&a_year)]);for _ in0..3 { assert_eq!(sweep(&phone), 0, "the timer never erases"); } assert!(binned(&phone, "3EB0H1") && marker(&phone, "3EB0H1").is_none()); assert_eq!(erase_binned(&phone), 1, "his act: erased for good"); assert!(held(&phone, "3EB0H1").is_none() && marker(&phone, "3EB0H1").is_some());}// RULE (ABSENCE 3): an "off" line that arrives later (written on another phone, on its clock) brings back every// message the timer put in the Bin that it covers; the ones sent while the timer was really on stay in the Bin.#[test]fn an_off_line_arriving_later_brings_binned_messages_back() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0J0", "hello", 40 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0J0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 30); import(&phone, ASHA, &[("3EB0J1", "while it was on", 20 * DAY_MS, false), ("3EB0J2", "after another phone turned it off", 10 * DAY_MS, true), ("3EB0J3", "the newest", 60_000, false)]); assert_eq!(sweep(&phone), 2, "both look due on this phone"); assert!(binned(&phone, "3EB0J1") && binned(&phone, "3EB0J2"));// The "off" another phone wrote fifteen days ago arrives now. set_timer(&phone, &chat, 0);let off = iso(now_ms(&phone) - 15 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') = 0", &[t(&off), t(&chat)]); sweep(&phone); assert!(!binned(&phone, "3EB0J2"), "covered by the off line: back"); assert!(binned(&phone, "3EB0J1"), "sent while it was on: stays in the Bin"); assert!(marker(&phone, "3EB0J2").is_none());}// RULE (ABSENCE 3): one rule for every reader of the lines: a binned "off" makes the chat say Off.#[test]fn a_binned_off_line_reads_as_off_in_the_chat() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0K0", "hello", 6 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0K0"); set_timer(&phone, &chat, 86_400); set_timer(&phone, &chat, 0); sql(&phone, "UPDATE cotton_msg_messages SET trashed_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') = 0", &[t(&iso(now_ms(&phone))), t(&chat)]);let page = call(&phone, "chat.thread", json!({ "thread": chat })); assert_eq!(page["timer"]["seconds"], 0, "{}", page["timer"]);}// RULE: A WhatsApp chat offers Disappearing messages, off by default, as the person's own copy: the sheet says "Only your copy in Cotton. WhatsApp keeps its own.", setting it sends nothing (no flush, nothing queued for the Mac), its line stands in the chat, and the chat stays WhatsApp's.#[test]fn a_whatsapp_chats_timer_is_his_own_copy_and_sends_nothing() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0A1", "see you at the station", 60_000, false)]);let chat = thread_of(&phone, "3EB0A1");let page = call(&phone, "chat.thread", json!({ "thread": chat })); assert_eq!(page["header"]["source"], "whatsapp"); assert_eq!(page["timer"]["seconds"], 0, "off by default"); assert_eq!(page["timer"]["note"], "Only your copy in Cotton. WhatsApp keeps its own."); assert_eq!(page["timer"]["choices"].as_array().unwrap().len(), 4);let set = set_timer(&phone, &chat, 86_400); assert_eq!(set["flush"], false, "nothing to send anywhere");let page = call(&phone, "chat.thread", json!({ "thread": chat })); assert_eq!(page["timer"]["seconds"], 86_400); assert_eq!(page["timer"]["label"], "Disappearing messages: 24 hours"); assert_eq!(page["header"]["source"], "whatsapp", "the line keeps the chat WhatsApp's"); assert!(page["items"].as_array().unwrap().iter().any(|i| i["item"] == "event" && i["text"].as_str().unwrap().starts_with("You turned on disappearing messages")), "{page}");let outbox = rows(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = ? AND channel = 'cotton'", &[t(&chat)]); assert_eq!(outbox[0]["n"], 0, "no Cotton message in a WhatsApp chat");// Setting what is already set writes nothing more. set_timer(&phone, &chat, 86_400); assert_eq!(rows(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL", &[t(&chat)])[0]["n"], 1);}// RULE: A timer off erases nothing: never turned on, or turned off before the messages came, every message stays however old.#[test]fn a_timer_off_erases_nothing() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0B1", "an old plan", 40 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0B1"); assert_eq!(sweep(&phone), 0); set_timer(&phone, &chat, 86_400); set_timer(&phone, &chat, 0); turned_on_days_ago(&phone, &chat, 30); import(&phone, ASHA, &[("3EB0B2", "after it was off", 20 * DAY_MS, true)]); assert_eq!(sweep(&phone), 0); assert!(held(&phone, "3EB0B1").is_some() && held(&phone, "3EB0B2").is_some()); assert!(marker(&phone, "3EB0B1").is_none() && marker(&phone, "3EB0B2").is_none());}// RULE (ABSENCE 2): a timer line in the Bin still marks when the timer changed: the "off" line binned never lets the// "on" span run past it, so a message sent after it was turned off stays.#[test]fn a_binned_off_line_still_ends_the_timer() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0E1", "the first", 40 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0E1"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 30); set_timer(&phone, &chat, 0);// The off line, twenty days ago, then put in the Bin.let off = iso(now_ms(&phone) - 20 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET sent_at = ?, trashed_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') = 0", &[t(&off), t(&iso(now_ms(&phone))), t(&chat)]); import(&phone, ASHA, &[("3EB0E2", "said while it was on", 25 * DAY_MS, false), ("3EB0E3", "said after it was off", 10 * DAY_MS, true)]); assert_eq!(sweep_through(&phone), 1, "only the one sent while it was on"); assert!(held(&phone, "3EB0E2").is_none()); assert!(held(&phone, "3EB0E3").is_some(), "sent after the off line: stays");}// RULE: With a timer on, only that chat's messages sent after it was turned on go, incoming and outgoing, once they pass the age; what came before it, what is not that old yet, and every other chat stay. The erase is whole (its reaction and search entry go) and a marker keeps only the WhatsApp id.#[test]fn only_that_chats_messages_from_then_on_go_as_they_pass_the_age() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0C1", "before the timer", 5 * DAY_MS, false)]); import(&phone, RAVI, &[("3EB0D1", "ravi keeps this", 2 * DAY_MS, false)]);let asha = thread_of(&phone, "3EB0C1");let ravi = thread_of(&phone, "3EB0D1"); set_timer(&phone, &asha, 86_400); turned_on_days_ago(&phone, &asha, 3); import( &phone, ASHA, &[("3EB0C2", "the picnic secret", 2 * DAY_MS, false), ("3EB0C3", "my own reply", 2 * DAY_MS - 60_000, true), ("3EB0C4", "not a day old", 3_600_000, false)], );let ws = workspace(&phone);let secret = held(&phone, "3EB0C2").unwrap()["id"].as_str().unwrap().to_string(); sql( &phone,"INSERT INTO cotton_msg_reactions (id, workspace_id, thread_id, message_id, actor, emoji, created_at) VALUES ('react-1', ?, ?, ?, 'self', '👍', ?)", &[t(&ws), t(&asha), t(&secret), t(&iso(now_ms(&phone)))], );// Its search entry stands until it goes (read directly: chat.search would sweep first). assert_eq!(rows(&phone, "SELECT m.id FROM fts_messages f JOIN cotton_msg_messages m ON m.rowid = f.rowid WHERE fts_messages MATCH 'picnic'", &[]).len(), 1); assert_eq!(sweep_through(&phone), 2, "the incoming and the outgoing message past a day"); assert!(held(&phone, "3EB0C2").is_none() && held(&phone, "3EB0C3").is_none(), "both erased"); assert!(held(&phone, "3EB0C1").is_some(), "from before the timer: untouched"); assert!(held(&phone, "3EB0C4").is_some(), "not a day old yet: stays"); assert!(held(&phone, "3EB0D1").is_some(), "another chat: untouched"); assert!(marker(&phone, "3EB0D1").is_none() && marker(&phone, "3EB0C1").is_none()); assert!(rows(&phone, "SELECT id FROM cotton_msg_reactions WHERE message_id = ?", &[t(&secret)]).is_empty(), "its reaction with it"); assert!(call(&phone, "chat.search", json!({ "text": "picnic" }))["messages"].as_array().unwrap().is_empty(), "and its search entry"); assert!(rows(&phone, "SELECT id FROM cotton_msg_messages WHERE body LIKE '%picnic%' OR body LIKE '%my own reply%'", &[]).is_empty()); assert_eq!(sweep_through(&phone), 0, "a marker is never swept again");let _ = ravi;}// RULE: An erased WhatsApp message is never imported again: the link's next run (Bring everything in again, a re-link's history) finds its marker under the same WhatsApp id and writes nothing, while a message it has not seen still lands.#[test]fn an_erased_whatsapp_message_is_not_imported_again() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0E0", "hello", 6 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0E0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 5);let again = [("3EB0E1", "a thing to forget", 3 * DAY_MS, false), ("3EB0E2", "and my answer", 3 * DAY_MS - 1_000, true)]; assert_eq!(import(&phone, ASHA, &again), 2); assert_eq!(sweep_through(&phone), 2); assert_eq!(import(&phone, ASHA, &again), 0, "brought in again, nothing lands"); assert!(held(&phone, "3EB0E1").is_none() && held(&phone, "3EB0E2").is_none()); assert_eq!(import(&phone, ASHA, &[("3EB0E1", "a thing to forget", 3 * DAY_MS, false), ("3EB0E3", "something new", 60_000, false)]), 1, "only the new one"); assert!(held(&phone, "3EB0E3").is_some());}// RULE: The erased-id record keeps no content: no words, media, sender, quote, reaction or mention, no time of its own (the timer line's), always "in"; only the chat, the channel and the WhatsApp id, hidden and deleted.#[test]fn the_erased_id_record_keeps_no_content() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0F0", "hi", 6 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0F0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 5); import(&phone, ASHA, &[("3EB0F1", "my bank pin hint", 3 * DAY_MS, true)]);let line_at = rows(&phone, "SELECT sent_at FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL", &[t(&chat)])[0]["sent_at"].clone(); sweep_through(&phone);let m = marker(&phone, "3EB0F1").expect("a marker"); assert_eq!(m["id"], json!(cotton_core::chat::ids::erased_marker_id(&chat, "whatsapp", "3EB0F1"))); assert_eq!(m["thread_id"], json!(chat)); assert_eq!(m["channel"], "whatsapp"); assert_eq!(m["direction"], "in", "not even who wrote it"); assert_eq!(m["body"], ""); assert_eq!(m["media"], "[]"); assert_eq!(m["reactions"], "[]"); assert_eq!(m["mentions"], "[]");for column in ["sender_participant_id", "sender_contact_id", "reply_to_id", "reply_to_external_id", "forward_of_id", "edited_at", "starred_at", "read_at", "send_state", "send_error", "trashed_at"] { assert!(m[column].is_null(), "{column} holds {}", m[column]); } assert_eq!(m["sent_at"], line_at, "its only time is the timer line's"); assert_eq!(m["deleted_at"], line_at); assert_eq!(m["hidden_at"], line_at); assert_eq!(serde_json::from_str::<Value>(m["meta"].as_str().unwrap()).unwrap(), json!({ "cotton": { "erased": "disappeared" } }));let text = Value::Object(m).to_string(); assert!(!text.contains("bank") && !text.contains("pin hint"));}// RULE: A marker is seen nowhere a message surfaces: the chat list's last line and time, unread, search, Starred, the person's page, Storage by chat, an export, and an assistant's get_record and list_records.#[test]fn the_marker_is_seen_nowhere() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0G0", "the kept hello", 6 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0G0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 5); import(&phone, ASHA, &[("3EB0G1", "the vanished words", 2 * DAY_MS, false)]);let gone = held(&phone, "3EB0G1").unwrap()["id"].as_str().unwrap().to_string(); call(&phone, "chat.act", json!({ "act": "star", "thread": chat, "message": gone })); sweep_through(&phone);let id = marker(&phone, "3EB0G1").expect("a marker")["id"].as_str().unwrap().to_string();let unseen = |what: &str, answer: &Value| {let text = answer.to_string(); assert!(!text.contains(&id), "{what} shows the marker: {text}"); assert!(!text.contains("vanished"), "{what} shows the erased words: {text}"); };// The list: its last line and time are the timer line's, nothing is unread.let list = call(&phone, "chat.list", json!({})); unseen("chat.list", &list);let row = list["rows"].as_array().unwrap().iter().find(|r| r["thread"] == json!(chat)).unwrap().clone(); assert!(row["lastLine"]["text"].as_str().unwrap().contains("isappearing"), "{row}"); assert_eq!(row["unread"], 0);let stored = rows(&phone, "SELECT last_message_preview FROM cotton_msg_threads WHERE id = ?", &[t(&chat)]); assert!(!stored[0]["last_message_preview"].as_str().unwrap_or_default().contains("vanished"), "the stored list line keeps no words"); unseen("chat.list unread", &call(&phone, "chat.list", json!({ "filter": "unread" }))); unseen("chat.thread", &call(&phone, "chat.thread", json!({ "thread": chat }))); unseen("chat.search", &call(&phone, "chat.search", json!({ "text": "the" })));let starred = call(&phone, "chat.starred", json!({})); unseen("chat.starred", &starred); assert!(starred["messages"].as_array().unwrap().is_empty());// The person's page: a WhatsApp chat's draws from the thread (its pictures are the thread's); chat.contact, where it answers.ifletOk(contact) = over(&phone.client(), "chat.contact", &json!({ "thread": chat })) { unseen("chat.contact", &contact); } unseen("chat.storage", &call(&phone, "chat.storage", json!({}))); unseen("chat.notices", &call(&phone, "chat.notices", json!({})));// An export packages the messages the person sees, never a marker.let exported = crate::phone::package::export_on(&phone.client(), "Comms", json!({ "tables": ["message"] }).as_object().unwrap()).expect("exports");let path = exported["path"].as_str().unwrap().to_string();let bytes = std::fs::read(&path).unwrap();let package = crate::phone::cotton_chat::read(&phone.client(), "test.package", |ctx| { cotton_tools::mcp::handlers::package::package_of_file(ctx, "x.cottonpkg", &bytes).map(|p| json!(format!("{p:?}"))).map_err(|f| f.to_string()) }) .unwrap(); unseen("package.export", &package); assert!(package.as_str().unwrap().contains("the kept hello"), "the visible message is exported");// An assistant: list_records never lists it, get_record never opens it.let tools = crate::phone::cotton_chat::read(&phone.client(), "test.tools", |ctx| {let listed = cotton_tools::mcp::handlers::tables::list_records(ctx, json!({ "table": "message", "limit": 200 }).as_object().unwrap()).map_err(|f| f.to_string())?;let got = cotton_tools::mcp::handlers::records_2::record::get_record(ctx, json!({ "table": "message", "id": id }).as_object().unwrap());Ok(json!({ "listed": listed, "got": got.map_err(|f| f.to_string()).unwrap_or_else(|why| json!({ "refused": why })) })) }) .unwrap(); unseen("list_records", &tools["listed"]); assert!(tools["listed"].to_string().contains("the kept hello"), "{}", tools["listed"]); assert!(tools["got"].get("refused").is_some() || tools["got"]["data"].is_null(), "get_record opened the marker: {}", tools["got"]);}/// Every `table.column` of the phone's file whose bytes hold `needle`: rows, receipts, parks, history and the search/// index's own pages alike.fn holding(handle: &CottonHandle, needle: &str) -> Vec<String> {let needle = needle.to_string(); handle .client() .with_writer(|replica| {let db = &replica.driver;let tables = db.all("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", &[]).map_err(|e| e.to_string())?;letmut found = Vec::new();for table in tables.iter().filter_map(|r| r.text("name").map(str::to_string)) {let columns = db.all(&format!("SELECT name FROM pragma_table_info('{table}')"), &[]).map_err(|e| e.to_string())?;for column in columns.iter().filter_map(|r| r.text("name").map(str::to_string)) {let statement = format!("SELECT count(*) AS n FROM \"{table}\" WHERE instr(CAST(\"{column}\" AS BLOB), CAST(?1 AS BLOB)) > 0");let n = db.get(&statement, &[t(&needle)]).map_err(|e| format!("{statement}: {e}"))?.and_then(|r| r.int("n")).unwrap_or(0);if n > 0 { found.push(format!("{table}.{column}")); } } }Ok(found) }) .unwrap()}/// Where the phone still names a file once its message is erased, beside the erasure fact that makes every device/// delete its bytes: the fact's row (`cotton_media_erasures`), its receipt, and the phone's unlink queue/// (`_media_unlinks`) name the key by design, and nothing else may.fn naming_the_file(handle: &CottonHandle, file: &str) -> Vec<String> {letmut places = holding(handle, file);if places.iter().any(|place| place.starts_with("_writes.")) {let receipts = rows(handle, "SELECT DISTINCT tbl FROM _writes WHERE instr(CAST(bytes AS BLOB), CAST(? AS BLOB)) > 0 OR instr(CAST(fields AS BLOB), CAST(? AS BLOB)) > 0", &[t(file), t(file)]);let only_the_fact = receipts.iter().all(|r| r.get("tbl").and_then(Value::as_str) == Some("cotton_media_erasures"));if only_the_fact { places.retain(|place| !place.starts_with("_writes.")); } } places.retain(|place| !place.starts_with("cotton_media_erasures.") && !place.starts_with("_media_unlinks.")); places}// RULE: A timer's erase leaves the message's words and its file's name in no table and no log of the phone: not its row, its receipts, its history, its search entry, nor the chat's stored list line or that line's earlier writes. Only the erasure fact (`cotton_media_erasures`, its row and its receipt) and the phone's unlink queue (`_media_unlinks`) name the file, so its bytes go on every device.#[test]fn an_erase_leaves_its_words_and_its_file_nowhere() {const WORDS: &str = "zebra quartz lantern";const FILE: &str = "fb2b-invented-photo.jpg";let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0E0", "an older hello", 6 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0E0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 5);// The chat's line as it stood then, so the message after it becomes the line. sql(&phone, "UPDATE cotton_msg_threads SET last_message_at = ? WHERE id = ?", &[t(&iso(now_ms(&phone) - 5 * DAY_MS)), t(&chat)]);let now = now_ms(&phone);let batch: cotton_core::import::envelope::ImportBatch = serde_json::from_value(json!({"workspaceId": workspace(&phone),"channel": "whatsapp","messages": [{ "externalId": "3EB0E1", "direction": "in", "body": WORDS, "sentAt": iso(now - 3 * DAY_MS), "phone": ASHA, "media": [{ "key": format!("{}/messages/{chat}/{FILE}", workspace(&phone)), "contentType": "image/jpeg" }] }], })) .unwrap(); phone .client() .import_rows("test.import", &["cotton_msg_threads", "cotton_msg_messages", "cotton_msg_thread_participants", "cotton_msg_contacts", "cotton_msg_reactions", "cotton_workspaces"], &mut |seams| {let namespace = seams.replica.identity.namespace().clone(); cotton_client::messages_import::import_messages(&seams.replica.driver, &namespace, &batch, seams.clock, seams.random, seams.ids).map_err(|e| e.to_string())?;Ok(json!({})) }) .unwrap();let before = holding(&phone, "quartz"); assert!(before.iter().any(|place| place == "cotton_msg_threads.last_message_preview"), "the list line names it: {before:?}"); assert!(before.iter().any(|place| place.starts_with("_writes.")), "and so do the receipts: {before:?}"); assert!(!holding(&phone, FILE).is_empty()); assert_eq!(sweep_through(&phone), 1);// The words leave the search pages once the background purge has run (DELETE FAST).crate::phone::mail_index::purge_now(&phone.client(), std::time::Duration::from_secs(60)).unwrap();for word in ["zebra", "quartz", "lantern"] { assert_eq!(holding(&phone, word), Vec::<String>::new(), "{word}"); } assert_eq!(naming_the_file(&phone, FILE), Vec::<String>::new()); assert!(!holding(&phone, "an older hello").is_empty(), "the message from before the timer keeps its words");}// ---- Deleted for everyone in WhatsApp (FEEDBACK-3; chat_revoked.rs) ----/// The Mac's link reports deletes for everyone, landed as the import's changes pass lands them.fn revoke(handle: &CottonHandle, externals: &[&str]) {let at = iso(now_ms(handle));let changes: Vec<cotton_core::import::messages_engine::MessageChange> = externals.iter().map(|id| cotton_core::import::messages_engine::MessageChange::Revoke { external_id: id.to_string(), at: at.clone() }).collect();let ws = workspace(handle); handle .client() .import_rows("test.revoke", &["cotton_msg_threads", "cotton_msg_messages", "cotton_msg_thread_participants", "cotton_msg_contacts", "cotton_msg_reactions", "cotton_workspaces"], &mut |seams| {let report = cotton_client::messages_import::apply_message_changes(&seams.replica.driver, &ws, "whatsapp", &changes, seams.clock, seams.ids).map_err(|e| e.to_string())?;Ok(json!({ "revoked": report.revoked })) }) .unwrap();}fn revoked_marker(handle: &CottonHandle, external: &str) -> Option<Map<String, Value>> { rows(handle, "SELECT * FROM cotton_msg_messages WHERE external_id = ? AND json_extract(meta, '$.cotton.erased') = 'revoked'", &[t(external)]).into_iter().next()}// RULE: A WhatsApp message deleted for everyone (by its sender, or by him from WhatsApp) is erased from his Cotton: its words and its file are in no table and no log; only that message goes; its place shows "This message was deleted", from the same side and at the same time.#[test]fn a_message_deleted_in_whatsapp_is_erased_and_only_that_one() {const FILE: &str = "fb2b-revoked-photo.jpg";let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0R0", "the kept hello", 3 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0R0");let now = now_ms(&phone);let batch: cotton_core::import::envelope::ImportBatch = serde_json::from_value(json!({"workspaceId": workspace(&phone),"channel": "whatsapp","messages": [ { "externalId": "3EB0R1", "direction": "in", "body": "walrus marmalade", "sentAt": iso(now - 2 * DAY_MS), "phone": ASHA, "media": [{ "key": format!("{}/messages/{chat}/{FILE}", workspace(&phone)), "contentType": "image/jpeg" }] }, { "externalId": "3EB0R2", "direction": "out", "body": "the reply that stays", "sentAt": iso(now - DAY_MS), "phone": ASHA }, ], })) .unwrap(); phone .client() .import_rows("test.import", &["cotton_msg_threads", "cotton_msg_messages", "cotton_msg_thread_participants", "cotton_msg_contacts", "cotton_msg_reactions", "cotton_workspaces"], &mut |seams| {let namespace = seams.replica.identity.namespace().clone(); cotton_client::messages_import::import_messages(&seams.replica.driver, &namespace, &batch, seams.clock, seams.random, seams.ids).map_err(|e| e.to_string())?;Ok(json!({})) }) .unwrap(); import(&phone, RAVI, &[("3EB0R9", "walrus in another chat", DAY_MS, false)]);let sent_at = held(&phone, "3EB0R1").unwrap()["sent_at"].clone(); revoke(&phone, &["3EB0R1"]); assert_eq!(sweep(&phone), 1, "only the message deleted for everyone");// The words leave the search pages once the background purge has run (DELETE FAST).crate::phone::mail_index::purge_now(&phone.client(), std::time::Duration::from_secs(60)).unwrap(); assert!(held(&phone, "3EB0R1").is_none(), "the message is erased"); assert!(holding(&phone, "marmalade").is_empty(), "{:?}", holding(&phone, "marmalade")); assert_eq!(naming_the_file(&phone, FILE), Vec::<String>::new());for kept in ["3EB0R0", "3EB0R2", "3EB0R9"] { assert!(held(&phone, kept).is_some(), "{kept} stays"); } assert!(!holding(&phone, "walrus in another chat").is_empty(), "the other chat is untouched");let m = revoked_marker(&phone, "3EB0R1").expect("a marker in its place"); assert_eq!(m["id"], json!(cotton_core::chat::ids::erased_marker_id(&chat, "whatsapp", "3EB0R1"))); assert_eq!(m["direction"], "in"); assert_eq!(m["sent_at"], sent_at, "where it was"); assert!(m["hidden_at"].is_null(), "drawn, not hidden"); assert_eq!(m["body"], ""); assert_eq!(m["media"], "[]");let page = call(&phone, "chat.thread", json!({ "thread": chat }));let items = page["items"].as_array().unwrap();let drawn = items.iter().find(|i| i["message"] == m["id"]).unwrap_or_else(|| panic!("the marker is drawn: {page}")); assert_eq!((drawn["kind"].as_str(), drawn["text"].as_str(), drawn["mine"].as_bool()), (Some("deleted"), Some("This message was deleted"), Some(false)), "{drawn}"); assert!(items.iter().any(|i| i["text"] == "the reply that stays"));}// RULE: A delete he made from WhatsApp itself goes the same way, on his side of the chat.#[test]fn his_own_delete_from_whatsapp_stands_on_his_side() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0S1", "sent by mistake", DAY_MS, true)]);let chat = thread_of(&phone, "3EB0S1"); revoke(&phone, &["3EB0S1"]); assert_eq!(sweep(&phone), 1); assert!(holding(&phone, "by mistake").is_empty());let m = revoked_marker(&phone, "3EB0S1").expect("a marker"); assert_eq!(m["direction"], "out");let list = call(&phone, "chat.list", json!({})); assert!(list.to_string().contains("This message was deleted"), "the chat's line says so: {list}"); assert!(!list.to_string().contains("by mistake"));let _ = chat;}// RULE: A message already deleted for everyone before this (kept as a blanked row, FEEDBACK-2 B.4) is erased by the first sweep: the rule holds for the past.#[test]fn a_message_deleted_before_this_goes_on_the_first_sweep() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0P1", "an old secret", 9 * DAY_MS, false), ("3EB0P2", "an old hello", 8 * DAY_MS, false)]);let id = held(&phone, "3EB0P1").unwrap()["id"].as_str().unwrap().to_string();// As the import left a delete for everyone until now: the row kept, its words blanked, deleted_at set. sql(&phone, "UPDATE cotton_msg_messages SET body = '', deleted_at = ? WHERE id = ?", &[t(&iso(now_ms(&phone) - 7 * DAY_MS)), t(&id)]); assert_eq!(sweep(&phone), 1); assert!(held(&phone, "3EB0P1").is_none()); assert!(revoked_marker(&phone, "3EB0P1").is_some()); assert!(held(&phone, "3EB0P2").is_some()); assert_eq!(sweep(&phone), 0, "nothing goes twice");}// RULE: A message erased because it was deleted in WhatsApp is never brought back: not by the same messages imported again, nor by a later edit, delete or reaction the link reports for it.#[test]fn a_message_deleted_in_whatsapp_is_not_imported_again() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0Q1", "a quokka waves", DAY_MS, false)]); revoke(&phone, &["3EB0Q1"]); sweep(&phone); assert_eq!(import(&phone, ASHA, &[("3EB0Q1", "a quokka waves", DAY_MS, false)]), 0); revoke(&phone, &["3EB0Q1"]); assert_eq!(sweep(&phone), 0);// The words leave the search pages once the background purge has run (DELETE FAST).crate::phone::mail_index::purge_now(&phone.client(), std::time::Duration::from_secs(60)).unwrap(); assert!(held(&phone, "3EB0Q1").is_none()); assert_eq!(holding(&phone, "quokka"), Vec::<String>::new());}// RULE: developer.revokeWhatsapp lands a delete for everyone only in Cotton Dev; the real Cotton (a live build declares `real`) refuses it by name, and nothing is blanked or erased.#[test]fn the_real_cotton_refuses_a_walks_revoke() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0T1", "a heron stays", DAY_MS, false)]);let refused = crate::methods::dispatch(&phone, "developer.revokeWhatsapp", &json!({ "externalIds": ["3EB0T1"] })).unwrap_err(); assert_eq!(refused.code, "not_dev"); assert_eq!(sweep(&phone), 0); assert_eq!(held(&phone, "3EB0T1").unwrap()["body"], "a heron stays");}// RULE (coordinator, 23 Nov 2026): a message must not stay on screen past its time while nothing else changes. The// chat answers `erasesIn`, the wait until its next message goes (the earliest held one under the timer standing when it// was sent), and the list the same for any chat; the phone asks again then, the core sweeps first, and the message is// gone from the answer. A chat with nothing set to go answers no moment.#[test]fn the_chat_and_the_list_answer_when_the_next_message_goes() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0E1", "before the timer", 5 * DAY_MS, false)]); import(&phone, RAVI, &[("3EB0F1", "no timer here", 60_000, false)]);let asha = thread_of(&phone, "3EB0E1");let ravi = thread_of(&phone, "3EB0F1"); assert!(call(&phone, "chat.thread", json!({ "thread": asha })).get("erasesIn").is_none(), "no timer: no moment"); set_timer(&phone, &asha, 86_400); turned_on_days_ago(&phone, &asha, 3); import(&phone, ASHA, &[("3EB0E2", "goes first", 20 * 3_600_000, false), ("3EB0E3", "goes later", 3_600_000, true)]);let wait = call(&phone, "chat.thread", json!({ "thread": asha }))["erasesIn"].as_i64().expect("a moment");let four_hours = 4 * 3_600_000; assert!((wait - four_hours).abs() < 60_000, "the one sent 20 hours ago goes in 4 hours: {wait}"); assert!(call(&phone, "chat.thread", json!({ "thread": ravi })).get("erasesIn").is_none(), "Ravi's chat has no timer");let list = call(&phone, "chat.list", json!({}))["erasesIn"].as_i64().expect("the list's moment"); assert!((list - four_hours).abs() < 60_000, "{list}");// The moment passes (the message is moved past its day, as the clock would) with nothing else changing: the sweep// after the next pass bins it, and the chat answers the next one's moment. sql(&phone, "UPDATE cotton_msg_messages SET sent_at = ? WHERE external_id = '3EB0E2'", &[t(&iso(now_ms(&phone) - DAY_MS - 1_000))]); sweep(&phone);let page = call(&phone, "chat.thread", json!({ "thread": asha })); assert!(!page.to_string().contains("goes first"), "gone from the answer: {page}"); assert!(page.to_string().contains("goes later"));let wait = page["erasesIn"].as_i64().expect("the next moment"); assert!((wait - 23 * 3_600_000).abs() < 60_000, "{wait}");}/// Many messages under one timer, imported at once.fn import_many(handle: &CottonHandle, prefix: &str, n: usize, ago: i64) {let ids: Vec<String> = (0..n).map(|i| format!("{prefix}{i:05}")).collect();let messages: Vec<(&str, &str, i64, bool)> = ids.iter().enumerate().map(|(i, id)| (id.as_str(), "an invented line", ago - i as i64, false)).collect(); import(handle, ASHA, &messages);}fn count_of(handle: &CottonHandle, statement: &str) -> i64 { rows(handle, statement, &[])[0]["n"].as_i64().unwrap()}// RULE (ABSENCE 4, B): what is in the Bin already never takes the cap: a chat with 5,000 due messages drains, 500 a// sweep, to the Bin; only his act erases them.#[test]fn five_thousand_due_messages_drain_across_sweeps() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0M0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0M0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import_many(&phone, "3EB0M1-", 5_000, 3 * DAY_MS); import(&phone, ASHA, &[("3EB0M2", "the newest", 60_000, false)]);letmut sweeps = 0;while count_of(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE external_id LIKE '3EB0M1-%' AND trashed_at IS NULL") > 0 { assert_eq!(sweep(&phone), 500, "each sweep bins the next 500"); sweeps += 1; assert!(sweeps <= 10, "drains in ten sweeps"); } assert_eq!(sweep(&phone), 0, "the timer never erases"); assert_eq!(erase_binned(&phone), 5_000, "his act takes all he was shown, 200 a write"); assert_eq!(count_of(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE external_id LIKE '3EB0M1-%' AND json_extract(meta, '$.cotton.erased') IS NULL"), 0);}// RULE (ABSENCE 4, A): one gate for every act on every span: a copy that may lack a line bins nothing and erases// nothing, middle spans too; restores still run.#[test]fn a_copy_that_may_lack_a_line_bins_nothing() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0N0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0N0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import(&phone, ASHA, &[("3EB0N1", "under the timer", 3 * DAY_MS, false), ("3EB0N2", "the newest", 60_000, false)]);let path = phone.client().layout().connection_json();let local = std::fs::read_to_string(&path).unwrap(); std::fs::write(&path, local.replace("\"local\"", "\"remote\"")).unwrap(); assert_eq!(sweep(&phone), 0, "not caught up: no act"); assert!(!binned(&phone, "3EB0N1")); std::fs::write(&path, &local).unwrap(); assert_eq!(sweep(&phone), 1);}// RULE (ABSENCE 4, C and D): the chat says what the timer binned, with Show and Restore; Restore brings each back, the// list line names the newest again, and the timer never takes them again; the trim never drops them meanwhile.#[test]fn he_sees_and_restores_what_the_timer_binned() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0P0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0P0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import(&phone, ASHA, &[("3EB0P1", "first under the timer", 3 * DAY_MS, false), ("3EB0P2", "the newest words", 2 * DAY_MS, false)]); assert_eq!(sweep(&phone), 2);// As the list line stands once the newest message it named went to the Bin.let newest = rows(&phone, "SELECT sent_at FROM cotton_msg_messages WHERE external_id = '3EB0P2'", &[])[0]["sent_at"].as_str().unwrap().to_string(); sql(&phone, "UPDATE cotton_msg_threads SET last_message_preview = '', last_message_at = ? WHERE id = ?", &[t(&newest), t(&chat)]);let page = call(&phone, "chat.thread", json!({ "thread": chat })); assert_eq!(page["timerBinned"]["line"], "2 messages removed by the timer", "{}", page["timerBinned"]); assert_eq!(page["timerBinned"]["restore"]["method"], "chat.timer.restore");let shown = call(&phone, "chat.timer.binned", json!({ "thread": chat })); assert_eq!(shown["rows"].as_array().unwrap().len(), 2, "{shown}");// Eight days in the Bin: the trim leaves them.let eight = iso(now_ms(&phone) - 8 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET trashed_at = ? WHERE json_extract(meta, '$.cotton.timer_binned') IS NOT NULL", &[t(&eight)]);let dropped = phone.client().with_file(|file| crate::phone::trim::binned_long_ago(&file.driver, chrono::Utc::now(), 100)).unwrap(); assert!(dropped.iter().all(|(table, _)| table != "cotton_msg_messages"), "{dropped:?}");let back = call(&phone, "chat.timer.restore", json!({ "thread": chat })); assert_eq!(back["restored"], 2); assert_eq!(back["said"], "2 messages are back"); assert!(!binned(&phone, "3EB0P1") && !binned(&phone, "3EB0P2"));let line = rows(&phone, "SELECT last_message_preview FROM cotton_msg_threads WHERE id = ?", &[t(&chat)]); assert_eq!(line[0]["last_message_preview"], "the newest words"); assert_eq!(sweep(&phone), 0, "the timer never takes them again"); assert!(call(&phone, "chat.thread", json!({ "thread": chat })).get("timerBinned").is_none());}/// A chat whose timer binned one message (3EB0Q1), the newest message after it.fn one_binned(phone: &CottonHandle, prefix: &str) -> String {let first = format!("{prefix}0"); import(phone, ASHA, &[(first.as_str(), "hello", 9 * DAY_MS, false)]);let chat = thread_of(phone, &first); set_timer(phone, &chat, 86_400); turned_on_days_ago(phone, &chat, 8);let (under, newest) = (format!("{prefix}1"), format!("{prefix}2")); import(phone, ASHA, &[(under.as_str(), "under the timer", 3 * DAY_MS, false), (newest.as_str(), "the newest", 60_000, false)]); assert_eq!(sweep(phone), 1); chat}// RULE (ABSENCE 5, item 1): a timer line stays in the copy for as long as its chat does, binned or not: the trim// never drops a binned "off", which still ends the span before it.#[test]fn the_trim_never_drops_a_timer_line() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0R0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0R0"); set_timer(&phone, &chat, 86_400); set_timer(&phone, &chat, 0);let eight = iso(now_ms(&phone) - 8 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET trashed_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL", &[t(&eight), t(&chat)]);// As once sent: nothing of them waits in the outbox. sql(&phone, "DELETE FROM _outbox WHERE row_id IN (SELECT id FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL)", &[t(&chat)]); sql(&phone, "UPDATE _writes SET held = 0 WHERE tbl = 'cotton_msg_messages' AND row_id IN (SELECT id FROM cotton_msg_messages WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') IS NOT NULL)", &[t(&chat)]);let dropped = phone.client().with_file(|file| crate::phone::trim::binned_long_ago(&file.driver, chrono::Utc::now(), 100)).unwrap(); assert!(dropped.iter().all(|(table, _)| table != "cotton_msg_messages"), "{dropped:?}");}// RULE (ABSENCE 5, A owed): no gate, no act: parked message rows stop the bin and the erase, middle spans too.#[test]fn parked_rows_stop_every_act_middle_spans_too() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0U0", "hello", 30 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0U0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 20); import(&phone, ASHA, &[("3EB0U1", "in the middle span", 15 * DAY_MS, false)]);// A later "on" line: the first span is a middle one. set_timer(&phone, &chat, 604_800);let ten = iso(now_ms(&phone) - 10 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') = 604800", &[t(&ten), t(&chat)]); import(&phone, ASHA, &[("3EB0U2", "the newest", 60_000, false)]); phone.client().with_writer(|f| f.driver.run("CREATE TABLE IF NOT EXISTS _seal_parked (tbl TEXT NOT NULL, row_id TEXT NOT NULL, code TEXT NOT NULL, reason TEXT NOT NULL, row TEXT NOT NULL, at TEXT NOT NULL, PRIMARY KEY (tbl, row_id)) WITHOUT ROWID", &[]).map(|_| ()).map_err(|e| e.to_string())).unwrap(); sql(&phone, "INSERT INTO _seal_parked (tbl, row_id, code, reason, row, at) VALUES ('message', 'm-later', 'no_key', 'invented', '{}', '2026-11-27T00:00:00Z')", &[]); assert_eq!(sweep(&phone), 0, "a message row parked: no act"); assert!(!binned(&phone, "3EB0U1"), "nor in a middle span"); sql(&phone, "DELETE FROM _seal_parked", &[]); assert_eq!(sweep(&phone), 1, "opened: the middle span bins"); assert!(binned(&phone, "3EB0U1"));}// RULE (ABSENCE 5, owed): a copy that once had an account and stands signed out acts on nothing.#[test]fn a_signed_out_former_copy_acts_on_nothing() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0W0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0W0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import(&phone, ASHA, &[("3EB0W1", "under the timer", 3 * DAY_MS, false), ("3EB0W2", "the newest", 60_000, false)]); sql(&phone, "INSERT INTO cotton_table_definitions (id, workspace_id, definition, created_at, updated_at, _hlc) SELECT 'invented-former', id, '{\"id\":\"invented-former\"}', '2026-11-27T00:00:00Z', '2026-11-27T00:00:00Z', '0001795600000000:0000:object' FROM cotton_workspaces LIMIT 1", &[]); assert_eq!(sweep(&phone), 0); assert!(!binned(&phone, "3EB0W1"));}// RULE (ABSENCE 5, owed): the restore of messages no timer covers pages past 500 in one sweep.#[test]fn the_restore_pages_past_five_hundred() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0X0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0X0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import_many(&phone, "3EB0X1-", 1_200, 3 * DAY_MS); import(&phone, ASHA, &[("3EB0X2", "the newest", 60_000, false)]);for _ in0..3 { sweep(&phone); } assert_eq!(count_of(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE external_id LIKE '3EB0X1-%' AND trashed_at IS NOT NULL"), 1_200);// The "off" another phone wrote before them arrives. set_timer(&phone, &chat, 0);let off = iso(now_ms(&phone) - 7 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') = 0", &[t(&off), t(&chat)]); sweep(&phone); assert_eq!(count_of(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE external_id LIKE '3EB0X1-%' AND trashed_at IS NOT NULL"), 0, "every one back in one sweep");}// RULE (ABSENCE 5, owed): a kill between the 200-row writes leaves each written chunk whole and the next sweep goes on.#[test]fn a_kill_between_writes_leaves_whole_chunks_and_the_next_sweep_goes_on() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0Y0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0Y0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import_many(&phone, "3EB0Y1-", 450, 3 * DAY_MS); import(&phone, ASHA, &[("3EB0Y2", "the newest", 60_000, false)]);crate::phone::chat_timer::TEST.with(|t| t.borrow_mut().chunks_left = Some(1)); assert!(crate::phone::chat_timer::sweep(&phone.client()).is_err(), "killed after the first write"); assert_eq!(count_of(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE external_id LIKE '3EB0Y1-%' AND trashed_at IS NOT NULL"), 200, "one whole chunk"); reset_test_view(); assert_eq!(sweep(&phone), 250, "the rest");}// RULE (ABSENCE 5, item 4): a timer-binned message brought back by any path (here a plain clear of trashed_at, as an// undo or an assistant writes it) is his: the timer never takes it again.#[test]fn any_restore_of_a_timer_binned_message_keeps_it() {let (_dir, phone) = phone(); one_binned(&phone, "3EB0Z");let id = held(&phone, "3EB0Z1").unwrap()["id"].as_str().unwrap().to_string();crate::phone::cotton_chat::write(&phone.client(), "test.restore", move |ctx| {letmut patch = serde_json::Map::new(); patch.insert("trashed_at".into(), Value::Null); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_msg_messages", &id, patch).map_err(|f| f.to_string())?;Ok(Value::Null) }) .unwrap(); assert!(!binned(&phone, "3EB0Z1")); assert_eq!(sweep(&phone), 0, "never taken again");let meta: Value = serde_json::from_str(held(&phone, "3EB0Z1").unwrap()["meta"].as_str().unwrap()).unwrap(); assert_eq!(meta["cotton"]["timer_kept"], true, "{meta}");}// RULE (ABSENCE 6): no code erases a message because of a timer: the WhatsApp sweep holds no erase and no marker./// Every place in the phone's core and its tools that hard-erases a row, by (file, function, what the line says), and/// why it may: nothing else erases, and none of these erases a message because of a WhatsApp timer.const ERASERS: &[(&str, &str, &str, &str)] = &[ ("cotton-ffi/src/phone/chat_timer.rs", "erase_these", "erase(MESSAGES, id, REASON)", "his act: chat.timer.erase"), ("cotton-ffi/src/phone/chat_timer.rs", "sweep_cotton", "erase(MESSAGES, id, REASON)", "the timer both people agreed in a Cotton chat"), ("cotton-ffi/src/phone/chat_revoked.rs", "sweep_revoked", "erase(MESSAGES, &r.id, REVOKED)", "deleted for everyone in WhatsApp"), ("cotton-ffi/src/phone/chat_app.rs", "act", "erase(MESSAGES, &id, DELETED_FOR_ME)", "his own delete of one message"), ("cotton-ffi/src/phone/chat_senders_erase.rs", "erase", "erase(d.table, &d.id, reason)", "his act on a blocked sender"), ("cotton-ffi/src/phone/chat_senders_erase.rs", "erase", "erase(EMAIL_THREADS, &thread, reason)", "a blocked sender's mail threads"), ("cotton-tools/src/mcp/writer.rs", "erase", "LocalChange::delete(table, row_id).erase(reason)", "the writer itself"), ("cotton-tools/src/mcp/handlers/bin.rs", "erase", "erase(table, &exception, \"bin\")", "Empty the bin: a timer-binned message is never its item (timer_held)"), ("cotton-tools/src/mcp/handlers/bin.rs", "erase", "erase(table, id, \"bin\")", "Empty the bin: a timer-binned message is never its item (timer_held)"), ("cotton-tools/src/mcp/handlers/bin.rs", "erase_documents", "erase(table, id, \"bin\")", "documents"), ("cotton-tools/src/mcp/handlers/tables/mod.rs", "erase_record", "erase(&storage_of(&located), id, reason)", "groups and made tables only"), ("cotton-tools/src/mcp/handlers/tables/mod.rs", "erase_one_binned", "erase(&storage_of(&located), id, \"bin\")", "groups and made tables only"), ("cotton-tools/src/mcp/handlers/tables/mod.rs", "erase_binned", "erase(table, id, \"bin\")", "groups and made tables only"), ("cotton-tools/src/mcp/handlers/tables/mod.rs", "forget_changes", "erase(CHANGES, change, \"bin\")", "change rows, not messages"),];// RULE (ABSENCE 6, ABSENCE 7 item 8): no code erases a message because of a WhatsApp timer. Every file of the phone's// core and its tools is read: each hard erase, and each DELETE of a message row, is one of ERASERS (his erase,// delete-for-everyone, the agreed timer and the acts that were his before the timer), or the test fails; the timer's// own sweep reaches none of them; the counted days for the timer are gone.#[test]fn no_code_erases_a_message_because_of_a_timer() {let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap().to_path_buf();letmut files = Vec::new();letmut dirs = vec![crates.join("cotton-ffi/src"), crates.join("cotton-tools/src")];whileletSome(dir) = dirs.pop() {for entry in std::fs::read_dir(&dir).unwrap() {let path = entry.unwrap().path();if path.is_dir() { dirs.push(path); } elseif path.extension().is_some_and(|e| e == "rs") && !path.file_name().unwrap().to_string_lossy().contains("test") { files.push(path); } } } assert!(files.len() > 100, "read every file: {}", files.len());letmut found = Vec::new();for path in &files {let source = std::fs::read_to_string(path).unwrap();let name = path.strip_prefix(&crates).unwrap().to_string_lossy().replace('\\', "/");letmut function = String::new();letmut in_tests = false;for line in source.lines() {let code = line.trim();if code.starts_with("#[cfg(test)]") { in_tests = true; }ifletSome(at) = code.find("fn ") {if code[..at].split_whitespace().all(|w| ["pub", "pub(crate)", "pub(super)", "async", "const", "unsafe"].contains(&w)) { function = code[at + 3..].split(|c: char| !(c.is_alphanumeric() || c == '_')).next().unwrap_or_default().to_string(); } }if code.starts_with("//") || in_tests {continue; }let erases = code.contains(".erase(") && !code.contains("fn erase(");let deletes = code.contains("DELETE FROM cotton_msg_messages") || code.contains("DELETE FROM {MESSAGES}");if erases || deletes { found.push((name.clone(), function.clone(), code.to_string())); } } }for (file, function, code) in &found { assert!( ERASERS.iter().any(|(f, func, says, _)| f == file && func == function && code.contains(says)),"{file} {function} erases outside the known erasers: {code}" ); }let source = include_str!("chat_timer.rs");for body in ["fn sweep_whatsapp(", "fn restore_uncovered(", "fn put_back("] {let start = source.find(body).expect(body);let end = source[start..].find("\n}\n").map(|e| start + e).expect("its end");for word in [".erase(", "marker_columns", "erased_marker_id", "forget_changes", "erase_these", "erase_binned", "finish_erasing"] { assert!(!source[start..end].contains(word), "{body} holds {word}"); } }for word in ["_timer_seen", "_timer_clock", "BIN_MS", "count_days"] { assert!(!source.contains(&format!("{word} ")) && !source.contains(&format!("{word}:")) && !source.contains(&format!("{word}(")), "{word} is gone"); }}// RULE (ABSENCE 7, item 8): the timer's counted-day tables of an older build are dropped, and nothing writes them again.#[test]fn the_timers_day_tables_are_dropped() {let (_dir, phone) = phone(); sql(&phone, "CREATE TABLE IF NOT EXISTS _timer_seen (k TEXT PRIMARY KEY, v TEXT NOT NULL)", &[]); sql(&phone, "CREATE TABLE IF NOT EXISTS _timer_clock (k TEXT PRIMARY KEY, v TEXT NOT NULL)", &[]); one_binned(&phone, "3EB1E"); sweep(&phone);let left = rows(&phone, "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN ('_timer_seen', '_timer_clock')", &[]); assert!(left.is_empty(), "{left:?}");}// RULE (ABSENCE 7, item 3): his erase is of the set he was shown: a set swapped for another of the same size (one// restored, another binned) is refused, nothing goes, and the answer asks again with the set as it stands.#[test]fn a_swapped_set_of_the_same_size_is_refused() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB1F0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB1F0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import(&phone, ASHA, &[("3EB1F1", "first under the timer", 3 * DAY_MS, false), ("3EB1F9", "the newest", 60_000, false)]); assert_eq!(sweep(&phone), 1);let shown = call(&phone, "chat.thread", json!({ "thread": chat }))["timerBinned"]["erase"].clone(); assert_eq!(shown["count"], 1);// He restores the one he saw; another goes to the Bin: the same count, another message. call(&phone, "chat.timer.restore", json!({ "thread": chat })); import(&phone, ASHA, &[("3EB1F2", "second under the timer", 2 * DAY_MS, false)]); assert_eq!(sweep(&phone), 1);let asked = call(&phone, "chat.timer.erase", json!({ "thread": chat, "count": shown["count"], "snapshot": shown["snapshot"] })); assert_eq!(asked["ask"]["count"], 1, "{asked}"); assert_ne!(asked["ask"]["snapshot"], shown["snapshot"]); assert!(binned(&phone, "3EB1F2"), "nothing went");let again = call(&phone, "chat.timer.erase", json!({ "thread": chat, "count": asked["ask"]["count"], "snapshot": asked["ask"]["snapshot"] })); assert_eq!(again["erased"], 1); assert!(held(&phone, "3EB1F2").is_none()); assert!(held(&phone, "3EB1F1").is_some(), "the one he brought back stays");// No snapshot at all: refused as a bad request. assert!(over(&phone.client(), "chat.timer.erase", &json!({ "thread": chat, "count": 0 })).is_err());}// RULE (ABSENCE 7, item 3): his erase goes 200 a write; stopped part way, what went stays gone, the rest is finished by// the next sweep, and the answer says how many went.#[test]fn his_erase_stopped_part_way_is_finished_by_the_next_sweep() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB1G0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB1G0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import_many(&phone, "3EB1G1-", 450, 3 * DAY_MS); import(&phone, ASHA, &[("3EB1G2", "the newest", 60_000, false)]); assert_eq!(sweep(&phone), 450);let shown = call(&phone, "chat.thread", json!({ "thread": chat }))["timerBinned"]["erase"].clone();// The first write (200) and one more go; the third stops.crate::phone::chat_timer::TEST.with(|t| t.borrow_mut().erase_left = Some(1)); assert!(over(&phone.client(), "chat.timer.erase", &json!({ "thread": chat, "count": shown["count"], "snapshot": shown["snapshot"] })).is_err()); reset_test_view();let left = || count_of(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE external_id LIKE '3EB1G1-%' AND json_extract(meta, '$.cotton.erased') IS NULL"); assert_eq!(left(), 50, "whole writes of 200 went"); sweep(&phone); assert_eq!(left(), 0, "the next sweep finished his act"); assert!(call(&phone, "chat.thread", json!({ "thread": chat })).get("timerBinned").is_none());}// RULE (ABSENCE 7, item 4): an undo of the timer's own bin, whose meta is from before the bin (no timer_binned), is his// act: kept, never binned again. The timer's own put-back leaves no mark on the row.#[test]fn an_undo_with_the_meta_from_before_the_bin_stays() {let (_dir, phone) = phone(); one_binned(&phone, "3EB1H");let row = held(&phone, "3EB1H1").unwrap();let id = row["id"].as_str().unwrap().to_string();letmut meta: Value = serde_json::from_str(row["meta"].as_str().unwrap()).unwrap(); meta["cotton"].as_object_mut().unwrap().remove("timer_binned");crate::phone::cotton_chat::write(&phone.client(), "test.undo", move |ctx| {letmut patch = serde_json::Map::new(); patch.insert("trashed_at".into(), Value::Null); patch.insert("meta".into(), meta.clone()); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_msg_messages", &id, patch).map_err(|f| f.to_string())?;Ok(Value::Null) }) .unwrap();let meta: Value = serde_json::from_str(held(&phone, "3EB1H1").unwrap()["meta"].as_str().unwrap()).unwrap(); assert_eq!(meta["cotton"]["timer_kept"], true, "{meta}"); assert_eq!(sweep(&phone), 0, "never taken again"); assert!(!binned(&phone, "3EB1H1"));// The timer's own put-back (an "off" line came): back, not kept, and no mark stored.let chat = one_binned(&phone, "3EB1J"); set_timer(&phone, &chat, 0);let off = iso(now_ms(&phone) - 7 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') = 0", &[t(&off), t(&chat)]); sweep(&phone);let meta: Value = serde_json::from_str(held(&phone, "3EB1J1").unwrap()["meta"].as_str().unwrap()).unwrap(); assert!(!binned(&phone, "3EB1J1")); assert!(meta["cotton"]["timer_kept"].is_null() && meta["cotton"]["timer_back"].is_null(), "{meta}");}// RULE (ABSENCE 7, item 5): the agreed timer erases only once the phone's clock AND the server's time this copy heard// are both past the moment; with no server time, or one behind, the message is hidden where it is read, not erased.#[test]fn the_agreed_timer_waits_for_the_servers_time_too() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB1K0", "hello", 60 * 60_000, false), ("3EB1K1", "agreed to go", 30 * 60_000, false), ("3EB1K2", "the newest", 60_000, false)]);let chat = thread_of(&phone, "3EB1K1");let past = iso(now_ms(&phone) - 10 * 60_000); sql(&phone, "UPDATE cotton_msg_messages SET meta = json_set(COALESCE(meta, '{}'), '$.cotton.expiresAt', ?) WHERE external_id = '3EB1K1'", &[t(&past)]);for judged in [None, Some(now_ms(&phone) - 60 * 60_000)] {crate::phone::chat_timer::TEST.with(|t| t.borrow_mut().judge = Some(judged)); sweep(&phone); assert!(held(&phone, "3EB1K1").is_some(), "not erased while judge time is {judged:?}");let page = call(&phone, "chat.thread", json!({ "thread": chat })); assert!(!page.to_string().contains("agreed to go"), "hidden at read: {page}"); }crate::phone::chat_timer::TEST.with(|t| t.borrow_mut().judge = Some(Some(now_ms(&phone)))); sweep(&phone); reset_test_view(); assert!(held(&phone, "3EB1K1").is_none(), "both clocks past: erased"); assert!(held(&phone, "3EB1K2").is_some());}// RULE (ABSENCE 7, item 2): a message the WhatsApp timer says is due, before the sweep after a pass bins it, is gone// from the chat, the list line and a search, with no write.#[test]fn a_due_message_is_hidden_at_read_before_the_sweep() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB1L0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB1L0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import(&phone, ASHA, &[("3EB1L1", "a quiet invented line", 3 * DAY_MS, false), ("3EB1L2", "the zebra invented line", 2 * DAY_MS, false)]);let writes = count_of(&phone, "SELECT COUNT(*) AS n FROM _writes");let page = call(&phone, "chat.thread", json!({ "thread": chat })); assert!(!page.to_string().contains("quiet invented") && !page.to_string().contains("zebra"), "{page}");let list = call(&phone, "chat.list", json!({})); assert!(!list.to_string().contains("zebra"), "the list line names it not: {list}");let found = call(&phone, "chat.search", json!({ "text": "zebra" })); assert!(!found["messages"].to_string().contains("zebra"), "{found}"); assert_eq!(count_of(&phone, "SELECT COUNT(*) AS n FROM _writes"), writes, "no write"); assert!(!binned(&phone, "3EB1L2"), "binning waits for the sweep");}// RULE (ABSENCE 7, item 6): the put-back walk is bounded per sweep and goes on from where it stopped.#[test]fn the_put_back_walk_is_bounded_and_goes_on() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB1M0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB1M0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import_many(&phone, "3EB1M1-", 2_500, 3 * DAY_MS); import(&phone, ASHA, &[("3EB1M2", "the newest", 60_000, false)]);while sweep(&phone) > 0 {}// The "off" another phone wrote before them arrives. set_timer(&phone, &chat, 0);let off = iso(now_ms(&phone) - 7 * DAY_MS); sql(&phone, "UPDATE cotton_msg_messages SET sent_at = ? WHERE thread_id = ? AND json_extract(meta, '$.cotton.timer') = 0", &[t(&off), t(&chat)]);let binned_now = || count_of(&phone, "SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE external_id LIKE '3EB1M1-%' AND trashed_at IS NOT NULL"); assert_eq!(binned_now(), 2_500); sweep(&phone); assert_eq!(binned_now(), 500, "four pages of 500 a sweep"); sweep(&phone); assert_eq!(binned_now(), 0, "the next sweep goes on");}// RULE (ABSENCE 6, H1): a restore that comes by pull (out of the Bin, timer_binned still on it, as an older build or// seal.restoreBinned sends it) is never binned again, and the next write here keeps it.#[test]fn a_restore_arriving_by_pull_stays() {let (_dir, phone) = phone(); one_binned(&phone, "3EB1A");// As the pull lays it: trashed_at cleared, nothing else. sql(&phone, "UPDATE cotton_msg_messages SET trashed_at = NULL WHERE external_id = '3EB1A1'", &[]); assert_eq!(sweep(&phone), 0, "not binned again"); assert!(!binned(&phone, "3EB1A1"));let id = held(&phone, "3EB1A1").unwrap()["id"].as_str().unwrap().to_string();crate::phone::cotton_chat::write(&phone.client(), "test.touch", move |ctx| {letmut patch = serde_json::Map::new(); patch.insert("body".into(), json!("under the timer")); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_msg_messages", &id, patch).map_err(|f| f.to_string())?;Ok(Value::Null) }) .unwrap();let meta: Value = serde_json::from_str(held(&phone, "3EB1A1").unwrap()["meta"].as_str().unwrap()).unwrap(); assert_eq!(meta["cotton"]["timer_kept"], true, "{meta}"); assert!(meta["cotton"]["timer_binned"].is_null());}// RULE (ABSENCE 6, H1): an undo whose patch names meta (with timer_binned still in it) keeps the message too.#[test]fn an_undo_naming_meta_stays() {let (_dir, phone) = phone(); one_binned(&phone, "3EB1B");let row = held(&phone, "3EB1B1").unwrap();let id = row["id"].as_str().unwrap().to_string();let meta: Value = serde_json::from_str(row["meta"].as_str().unwrap()).unwrap();crate::phone::cotton_chat::write(&phone.client(), "test.undo", move |ctx| {letmut patch = serde_json::Map::new(); patch.insert("trashed_at".into(), Value::Null); patch.insert("meta".into(), meta.clone()); cotton_tools::mcp::handlers::common::update_row(ctx, "cotton_msg_messages", &id, patch).map_err(|f| f.to_string())?;Ok(Value::Null) }) .unwrap(); assert_eq!(sweep(&phone), 0, "never taken again"); assert!(!binned(&phone, "3EB1B1"));}// RULE (ABSENCE 6, H2): a pulled message row waiting in _parked (a newer build's, one waiting on a parent) closes the// gate as an unopened one does.#[test]fn a_parked_pull_row_closes_the_gate() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB1C0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB1C0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import(&phone, ASHA, &[("3EB1C1", "under the timer", 3 * DAY_MS, false), ("3EB1C2", "the newest", 60_000, false)]); sql(&phone, "INSERT INTO _parked (op_id, direction, class, reason, first_at, tries, tbl, row_id) VALUES ('op-invented', 'pull', 'newer-shape', 'invented', '2026-11-27T00:00:00Z', 0, 'cotton_msg_messages', 'm-later')", &[]); assert_eq!(sweep(&phone), 0, "a pulled message waiting: no act"); sql(&phone, "DELETE FROM _parked WHERE op_id = 'op-invented'", &[]); assert_eq!(sweep(&phone), 1);}// RULE (ABSENCE 6): his act erases only what he was shown: a different count asks again, nothing goes; a timer line// is never among what it erases.#[test]fn his_erase_takes_only_what_he_was_shown() {let (_dir, phone) = phone();let chat = one_binned(&phone, "3EB1D");let shown = call(&phone, "chat.timer.binned", json!({ "thread": chat, "limit": 50 }));let asked = call(&phone, "chat.timer.erase", json!({ "thread": chat, "count": 5, "snapshot": shown["snapshot"] })); assert_eq!(asked["ask"]["count"], 1, "{asked}"); assert!(binned(&phone, "3EB1D1"));let lines = count_of(&phone, &format!("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = '{chat}' AND json_extract(meta, '$.cotton.timer') IS NOT NULL")); assert_eq!(call(&phone, "chat.timer.erase", json!({ "thread": chat, "count": 1, "snapshot": shown["snapshot"] }))["erased"], 1); assert_eq!(count_of(&phone, &format!("SELECT COUNT(*) AS n FROM cotton_msg_messages WHERE thread_id = '{chat}' AND json_extract(meta, '$.cotton.timer') IS NOT NULL")), lines, "every timer line stays");}// RULE (TIMER LINE iPhone): Show's page is keyed and newest first: each page starts after the last one's key, the last// page answers no next, and every page carries the chat's count and line as they stand with the page's own words;// Erase sends that count.#[test]fn shows_page_walks_the_binned_messages_newest_first_by_key() {let (_dir, phone) = phone(); import(&phone, ASHA, &[("3EB0T0", "hello", 9 * DAY_MS, false)]);let chat = thread_of(&phone, "3EB0T0"); set_timer(&phone, &chat, 86_400); turned_on_days_ago(&phone, &chat, 8); import_many(&phone, "3EB0T1-", 7, 3 * DAY_MS); import(&phone, ASHA, &[("3EB0T2", "the newest", 60_000, false)]); assert_eq!(sweep(&phone), 7);letmut seen: Vec<String> = Vec::new();letmut before: Option<String> = None;letmut pages = 0;loop {letmut ask = json!({ "thread": chat, "limit": 3 });ifletSome(key) = &before { ask["before"] = json!(key); }let page = call(&phone, "chat.timer.binned", ask); pages += 1; assert_eq!(page["count"], 7, "{page}"); assert_eq!(page["line"], "7 messages removed by the timer"); assert_eq!(page["words"]["title"], "Removed by the timer"); assert_eq!(page["words"]["erase_ask"], "Erase 7 messages for good?");let rows = page["rows"].as_array().unwrap(); assert!(!rows.is_empty() && rows.len() <= 3, "{page}"); seen.extend(rows.iter().map(|r| format!("{}|{}", r["at"].as_str().unwrap(), r["id"].as_str().unwrap())));match page["next"].as_str() {Some(next) => before = Some(next.to_string()),None => break, } } assert_eq!(pages, 3); assert_eq!(seen.len(), 7);letmut newest_first = seen.clone(); newest_first.sort(); newest_first.reverse(); assert_eq!(seen, newest_first, "newest first, none twice");let shown = call(&phone, "chat.timer.binned", json!({ "thread": chat, "limit": 3 })); assert_eq!(call(&phone, "chat.timer.erase", json!({ "thread": chat, "count": 7, "snapshot": shown["snapshot"] }))["erased"], 7); assert_eq!(call(&phone, "chat.timer.binned", json!({ "thread": chat, "limit": 3 }))["count"], 0);}