//! The bin as a table — the generic verbs over the built-in `bin`, a view over//! every binned row of every kind the bin engine keeps (`BinKind`): emails,//! conversations, passwords, decisions and notes. `list_records` lists them,//! `get_record_by_table` reads one, `update_record {state: "restored"}` is//! `restore_from_bin`, `delete_record` erases one row for good, and every//! other write is refused.//!//! The rows are seeded straight into the file, the shapes the kinds' own//! verbs write. Every value is invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use cotton_tools::mcp::handlers::tables::tools_reached;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::{call_tool, call_tool_as_owner, call_tool_raw, mint_token};const AT: &str = "2026-08-20T09:00:00.000Z";const MAIL_BINNED: &str = "2026-08-25T10:00:00.000Z";const DECISION_BINNED: &str = "2026-08-26T10:00:00.000Z";const SECRET_BINNED: &str = "2026-08-27T10:00:00.000Z";structBin { h: Harness, secret: String, thread: String, email: String, alone: String, password: String, decision: String, kept_decision: String,}fn sql_text(value: &str) -> SqlValue {SqlValue::Text(value.to_string())}fn or_null(value: Option<&str>) -> SqlValue { value.map_or(SqlValue::Null, sql_text)}fn thread(h: &Harness, key: &str, subject: &str, trashed: Option<&str>) -> String {let id = synthetic_uuid(key); h.run("INSERT INTO cotton_email_threads \ (id, workspace_id, external_key, subject, first_at, last_at, email_count, \ trashed_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)", &[ sql_text(&id), sql_text(&h.workspace_id), sql_text(key), sql_text(subject), sql_text(AT), sql_text(AT), or_null(trashed), sql_text(AT), sql_text(AT), ], ); id}fn email(h: &Harness, thread: &str, external: &str, trashed: Option<&str>) -> String {let id = synthetic_uuid(external); h.run("INSERT INTO cotton_emails \ (id, workspace_id, thread_id, external_id, subject, from_email, from_name, recipients, \ sent_at, body, snippet, attachments, labels, unread, starred, in_inbox, trashed_at, \ created_at) \ VALUES (?, ?, ?, ?, 'This week at Acme', 'news@acme.example', 'Acme', '[]', ?, \ 'The newsletter.', 'The newsletter.', '[]', '[]', 0, 0, 0, ?, ?)", &[ sql_text(&id), sql_text(&h.workspace_id), sql_text(thread), sql_text(external), sql_text(AT), or_null(trashed), sql_text(AT), ], ); id}fn password(h: &Harness, name: &str, trashed: Option<&str>) -> String {let id = synthetic_uuid(name); h.run("INSERT INTO cotton_secrets (id, workspace_id, kind, name, trashed_at, created_at, updated_at) \ VALUES (?, ?, 'login', ?, ?, ?, ?)", &[ sql_text(&id), sql_text(&h.workspace_id), sql_text(name), or_null(trashed), sql_text(AT), sql_text(AT), ], ); id}fn decision(h: &Harness, title: &str, trashed: Option<&str>) -> String {let id = synthetic_uuid(title); h.run("INSERT INTO cotton_decisions (id, workspace_id, title, trashed_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, ?)", &[ sql_text(&id), sql_text(&h.workspace_id), sql_text(title), or_null(trashed), sql_text(AT), sql_text(AT), ], ); id}/// One binned row of every kind, and one decision that is not binned. `email`/// sits inside the binned conversation, so the bin's list names the/// conversation and not that message beside it; `alone` was binned on its own/// out of a conversation that is still there, and is listed.fn seeded() -> Bin {letmut h = Harness::new();let secret = mint_token(&mut h, &["read", "write"], "Claude");let thread = thread(&h, "gmail:acme-news", "This week at Acme", Some(MAIL_BINNED));let email = email(&h, &thread, "<news@acme.example>", Some(MAIL_BINNED));let open = self::thread(&h, "gmail:still-here", "Still here", None);let alone = self::email(&h, &open, "<alone@acme.example>", Some(MAIL_BINNED));let password = password(&h, "Old router", Some(SECRET_BINNED));let decision_id = decision(&h, "Move the standup to ten", Some(DECISION_BINNED));let kept_decision = decision(&h, "Keep Fridays free", None);Bin { h, secret, thread, email, alone, password, decision: decision_id, kept_decision, }}fn call(bin: &Bin, tool: &str, args: Value) -> Value { call_tool(&bin.h, &bin.secret, tool, args)}/// The same call from the owner's own app — the only caller that erases.fn owner(bin: &Bin, tool: &str, args: Value) -> Value { call_tool_as_owner(&bin.h, "device:phone", tool, args).json()}fn owner_refused(bin: &Bin, tool: &str, args: Value) -> String {let answer = call_tool_as_owner(&bin.h, "device:phone", tool, args); assert!(answer.is_error, "{tool} was expected to refuse: {}", answer.text); answer.text}fn refused(bin: &Bin, tool: &str, args: Value) -> String {let answer = call_tool_raw(&bin.h, &bin.secret, tool, args); assert!(answer.is_error, "{tool} was expected to refuse: {}", answer.text); answer.text}fn listed(bin: &Bin, args: Value) -> Value {letmut args = args; args["table"] = json!("bin"); call(bin, "list_records", args)}fn ids(page: &Value) -> Vec<String> { page["records"] .as_array() .unwrap() .iter() .map(|record| record["id"].as_str().unwrap().to_string()) .collect()}fn count(bin: &Bin, table: &str, id: &str) -> i64 { bin.h.count( &format!("SELECT count(*) AS c FROM {table} WHERE id = ?"), &[sql_text(id)], )}// ── reads ───────────────────────────────────────────────────────────────────/// RULE: The bin table lists every binned row of every kind the bin engine keeps, newest first, each as its title, kind, when it went in and the state binned, and nothing that is out of the bin.#[test]fn the_bin_lists_every_binned_row_of_every_kind_newest_first() {let bin = seeded();// A deleted note, binned before everything else here.let note = synthetic_uuid("a binned note"); bin.h.run("INSERT INTO cotton_notes (id, workspace_id, kind, title, body, trashed_at, created_at, updated_at) \ VALUES (?, ?, 'note', 'Kite flying', 'Bring the long string.', '2026-08-24T10:00:00.000Z', ?, ?)", &[sql_text(¬e), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT)], );// A deleted event, goal, mood and alarm, each binned a day earlier still.let calendar = synthetic_uuid("a calendar"); bin.h.run("INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at) \ VALUES (?, ?, 'calendar', 'Personal', 1, ?)", &[sql_text(&calendar), sql_text(&bin.h.workspace_id), sql_text(AT)], );let event = synthetic_uuid("a binned event"); bin.h.run("INSERT INTO cotton_events (id, collection_id, title, starts_at, trashed_at, created_at, updated_at) \ VALUES (?, ?, 'Kite festival', '2026-10-12T09:00:00.000Z', '2026-08-23T10:00:00.000Z', ?, ?)", &[sql_text(&event), sql_text(&calendar), sql_text(AT), sql_text(AT)], );let goal = synthetic_uuid("a binned goal"); bin.h.run("INSERT INTO cotton_goals (id, workspace_id, title, trashed_at, created_at, updated_at) \ VALUES (?, ?, 'Learn the cello', '2026-08-22T10:00:00.000Z', ?, ?)", &[sql_text(&goal), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT)], );let mood = synthetic_uuid("a binned mood"); bin.h.run("INSERT INTO cotton_moods (id, workspace_id, at, line, local_day, trashed_at, created_at, updated_at) \ VALUES (?, ?, ?, 'Calm after the swim', '2026-08-20', '2026-08-21T10:00:00.000Z', ?, ?)", &[sql_text(&mood), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT), sql_text(AT)], );let alarm = synthetic_uuid("a binned alarm"); bin.h.run("INSERT INTO cotton_alarms (id, workspace_id, label, hour, minute, trashed_at, created_at, updated_at) \ VALUES (?, ?, 'Ferry', 7, 15, '2026-08-20T10:00:00.000Z', ?, ?)", &[sql_text(&alarm), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT)], );let meeting = synthetic_uuid("a binned meeting"); bin.h.run("INSERT INTO cotton_meetings (id, workspace_id, title, status, source, started_at, status_changed_at, \ trashed_at, created_at, updated_at) \ VALUES (?, ?, 'Kite club', 'ready', 'recorded', ?, ?, '2026-08-19T10:00:00.000Z', ?, ?)", &[sql_text(&meeting), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT), sql_text(AT), sql_text(AT)], );let photo = format!("photo:{}", "a".repeat(64)); bin.h.run("INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, caption, \ trashed_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, 'image/jpeg', 1, ?, 'Kite on the beach', '2026-08-18T10:00:00.000Z', ?, ?)", &[sql_text(&photo), sql_text(&bin.h.workspace_id), sql_text(&format!("{}/photos/a.jpg", bin.h.workspace_id)), sql_text(&"a".repeat(64)), sql_text(AT), sql_text(AT), sql_text(AT)], );let video = format!("video:{}", "b".repeat(64)); bin.h.run("INSERT INTO cotton_videos (id, workspace_id, key, sha256, content_type, size_bytes, taken_at, \ trashed_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, 'video/mp4', 1, ?, '2026-08-17T10:00:00.000Z', ?, ?)", &[sql_text(&video), sql_text(&bin.h.workspace_id), sql_text(&format!("{}/videos/b.mp4", bin.h.workspace_id)), sql_text(&"b".repeat(64)), sql_text(AT), sql_text(AT), sql_text(AT)], );let document = synthetic_uuid("a binned document"); bin.h.run("INSERT INTO cotton_documents (id, workspace_id, original_name, mime, byte_size, sha256, storage_path, \ status, doc_type, title, facts, source, text_extracted, status_changed_at, trashed_at, created_at, updated_at) \ VALUES (?, ?, 'kites.pdf', 'application/pdf', 1, ?, ?, 'ready', 'other', 'Kite manual', \ '{}', 'app', 1, ?, '2026-08-16T10:00:00.000Z', ?, ?)", &[sql_text(&document), sql_text(&bin.h.workspace_id), sql_text(&"c".repeat(64)), sql_text(&format!("{}/{document}/original.pdf", bin.h.workspace_id)), sql_text(AT), sql_text(AT), sql_text(AT)], );// A text of the owner's that failed to send, the one message Delete bins.let message = synthetic_uuid("a binned message");let chat = synthetic_uuid("a chat"); bin.h.run("INSERT INTO cotton_msg_threads (id, workspace_id, kind, title, created_at, updated_at) \ VALUES (?, ?, 'group', 'Kite club', ?, ?)", &[sql_text(&chat), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT)], ); bin.h.run("INSERT INTO cotton_msg_messages (id, thread_id, workspace_id, direction, channel, origin, body, sent_at, \ created_at, send_state, send_error, trashed_at) \ VALUES (?, ?, ?, 'out', 'whatsapp', 'live', 'Kites at six?', ?, ?, 'failed', 'WhatsApp refused it: example', \ '2026-08-15T10:00:00.000Z')", &[sql_text(&message), sql_text(&chat), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT)], );let page = listed(&bin, json!({})); assert_eq!(page["table"], "bin"); assert_eq!(page["next_page"], Value::Null);// Newest first; the email and its conversation went in at the same// instant, and then the engine's own kind order holds. assert_eq!( ids(&page), [ bin.password.as_str(), bin.decision.as_str(), bin.alone.as_str(), bin.thread.as_str(), note.as_str(), event.as_str(), goal.as_str(), mood.as_str(), alarm.as_str(), meeting.as_str(), photo.as_str(), video.as_str(), document.as_str(), message.as_str(), ] );let records = page["records"].as_array().unwrap(); assert_eq!(records[4]["data"]["title"], "Kite flying"); assert_eq!( records[0]["data"], json!({"title": "Old router", "kind": "secret", "table": "secret","trashed_at": SECRET_BINNED, "state": "binned" }) ); assert_eq!(records[0]["deleted_at"], Value::Null, "a binned row is a live row of the bin"); assert_eq!(records[1]["data"]["title"], "Move the standup to ten"); assert_eq!(records[2]["data"]["kind"], "email"); assert_eq!(records[3]["data"]["kind"], "email_thread"); assert!(!ids(&page).contains(&bin.kept_decision), "a decision not in the bin is not listed");// The same rows list_bin answers, less the one message the list leaves// to its binned conversation (no group or made record is binned here).let entries = call(&bin, "list_bin", json!({}))["entries"].clone(); assert_eq!(entries.as_array().unwrap().len(), records.len());}/// RULE: The bin pages by the generic offset with no cap of its own and narrows by its title words.#[test]fn the_bin_pages_and_searches() {let bin = seeded();let first = listed(&bin, json!({ "limit": 3 })); assert_eq!(ids(&first), [bin.password.as_str(), bin.decision.as_str(), bin.alone.as_str()]); assert_eq!(first["next_page"], 3);let rest = listed(&bin, json!({ "limit": 3, "page": 3 })); assert_eq!(ids(&rest), [bin.thread.as_str()]); assert_eq!(rest["next_page"], Value::Null);let acme = listed(&bin, json!({ "query": "ACME week" })); assert_eq!(ids(&acme), [bin.alone.as_str(), bin.thread.as_str()]);}/// RULE: Reading one bin record answers it binned while it is in the bin, restored once it is out, and refuses an id no binnable kind holds.#[test]fn one_bin_record_reads_binned_restored_or_refused() {let bin = seeded();let one = call(&bin, "get_record_by_table", json!({ "table": "bin", "id": bin.decision })); assert_eq!(one["data"]["state"], "binned"); assert_eq!(one["data"]["kind"], "decision");let out = call(&bin, "get_record_by_table", json!({ "table": "bin", "id": bin.kept_decision })); assert_eq!(out["data"], json!({ "title": "Keep Fridays free", "kind": "decision", "table": "decision", "state": "restored" }));let text = refused( &bin,"get_record_by_table", json!({ "table": "bin", "id": synthetic_uuid("nowhere") }), ); assert!(text.contains("is no longer here"), "{text}");}/// RULE: A bin row names the table its record is a row of, and that table's read answers the binned record itself, so the Bin opens the record's own page with everything it held rather than the bin's few columns.#[test]fn a_bin_row_names_the_table_its_record_is_read_from() {let bin = seeded();for (id, table) in [(&bin.password, "secret"), (&bin.thread, "email_thread")] {let row = call(&bin, "get_record_by_table", json!({ "table": "bin", "id": id })); assert_eq!(row["data"]["table"], table, "{row}");let own = call(&bin, "get_record_by_table", json!({ "table": table, "id": id })); assert_eq!(own["id"], json!(id), "the binned record reads by its own table: {own}"); }}// ── restore ─────────────────────────────────────────────────────────────────/// RULE: Setting a bin record's state to restored is restore_from_bin — the row leaves the bin, its kind's restore rule holds, and the change says binned before and restored after, and its Undo bins the record again.#[test]fn restoring_through_the_bin_is_restore_from_bin() {let bin = seeded();let out = call( &bin,"update_record", json!({ "table": "bin", "id": bin.decision, "patch": { "state": "restored" } }), );let change = &out["change"]; assert_eq!(change["verb"], "update"); assert_eq!(change["table"], "bin"); assert_eq!(change["byline"], "Claude"); assert_eq!(change["before"]["state"], "binned"); assert_eq!(change["before"]["trashed_at"], DECISION_BINNED); assert_eq!(change["after"]["state"], "restored"); assert_eq!(change["undoable"], true); assert_eq!(out["record"]["data"]["state"], "restored");let trashed = bin.h.one("SELECT trashed_at FROM cotton_decisions WHERE id = ?", &[sql_text(&bin.decision)], ); assert_eq!(trashed.unwrap()["trashed_at"], Value::Null, "the decision is out of the bin"); assert!(!ids(&listed(&bin, json!({}))).contains(&bin.decision));// An email's restore tells the mailbox, as restore_from_bin does.let restored = call( &bin,"update_record", json!({ "table": "bin", "id": bin.email, "patch": { "state": "restored" } }), );let row = bin .h .one("SELECT trashed_at, sync_state FROM cotton_emails WHERE id = ?", &[sql_text(&bin.email)]) .unwrap(); assert_eq!(row["trashed_at"], Value::Null); assert_eq!(row["sync_state"], "pending");// … and its Undo bins it again through the mailbox, which tells Gmail. call(&bin, "undo", json!({ "change_id": restored["change"]["id"] }));let row = bin .h .one("SELECT trashed_at, sync_state FROM cotton_emails WHERE id = ?", &[sql_text(&bin.email)]) .unwrap(); assert!(!row["trashed_at"].is_null(), "the email is back in the bin"); assert_eq!(row["sync_state"], "pending");}/// RULE: The bin takes one change, state restored; any other patch, or restoring a row already out of the bin, is refused and changes nothing.#[test]fn the_bin_refuses_every_other_change() {let bin = seeded();for patch in [ json!({ "state": "binned" }), json!({ "title": "Renamed" }), json!({ "state": "restored", "title": "Renamed" }), json!({ "kind": "email" }), ] {let text = refused( &bin,"update_record", json!({ "table": "bin", "id": bin.password, "patch": patch }), ); assert!( text.contains("takes one change") || text.contains("changes nothing"),"{patch}: {text}" ); } assert_eq!( bin.h.count("SELECT count(*) AS c FROM cotton_secrets WHERE trashed_at IS NOT NULL", &[]),1,"the password is still in the bin" );let text = refused( &bin,"update_record", json!({ "table": "bin", "id": bin.kept_decision, "patch": { "state": "restored" } }), ); assert!(text.contains("changes nothing"), "{text}"); assert_eq!(bin.h.count("SELECT count(*) AS c FROM cotton_changes", &[]), 0);}// ── erase ───────────────────────────────────────────────────────────────────/// RULE: Deleting a bin record erases that one row for good, as emptying the bin erases each, and the erase cannot be undone.#[test]fn deleting_a_bin_record_erases_that_row_for_good() {let bin = seeded();let out = owner(&bin, "delete_record", json!({ "table": "bin", "id": bin.password })); assert_eq!(out["record"], Value::Null);let change = &out["change"]; assert_eq!(change["verb"], "delete"); assert_eq!(change["before"]["kind"], "secret"); assert_eq!(change["after"], Value::Null); assert_eq!(change["undoable"], false); assert_eq!(change["reason"], "an erased record is gone for good"); assert_eq!(count(&bin, "cotton_secrets", &bin.password), 0, "the password is erased");let text = refused(&bin, "undo", json!({ "change_id": change["id"] })); assert!(text.contains("gone for good"), "{text}");// The rest of the bin is untouched. assert_eq!( ids(&listed(&bin, json!({}))), [bin.decision.as_str(), bin.alone.as_str(), bin.thread.as_str()] ); owner(&bin, "delete_record", json!({ "table": "bin", "id": bin.decision })); assert_eq!(count(&bin, "cotton_decisions", &bin.decision), 0); assert_eq!(count(&bin, "cotton_decisions", &bin.kept_decision), 1);}/// RULE: Erasing a row out of the bin leaves nothing it said in the synced change log — every change naming it goes, and the erase's own change says only its kind and state.#[test]fn an_erase_leaves_nothing_the_row_said_in_the_change_log() {let bin = seeded();// A restore through the bin writes a change naming the password … call( &bin,"update_record", json!({ "table": "bin", "id": bin.password, "patch": { "state": "restored" } }), );// … and it goes back in from its own table. bin.h.run("UPDATE cotton_secrets SET trashed_at = ? WHERE id = ?", &[sql_text(SECRET_BINNED), sql_text(&bin.password)], );// The conversation's message carries a change of its own too. call( &bin,"update_record", json!({ "table": "bin", "id": bin.email, "patch": { "state": "restored" } }), ); bin.h.run("UPDATE cotton_emails SET trashed_at = ? WHERE id = ?", &[sql_text(MAIL_BINNED), sql_text(&bin.email)], );let out = owner(&bin, "delete_record", json!({ "table": "bin", "id": bin.password })); assert_eq!(out["change"]["before"], json!({ "kind": "secret", "state": "binned" })); owner(&bin, "delete_record", json!({ "table": "bin", "id": bin.thread }));for (id, words) in [ (&bin.password, "Old router"), (&bin.thread, "This week at Acme"), (&bin.email, "This week at Acme"), ] {let saying = bin.h.count("SELECT count(*) AS c FROM cotton_changes \ WHERE instr(COALESCE(before, ''), ?) > 0 OR instr(COALESCE(after, ''), ?) > 0", &[sql_text(words), sql_text(words)], ); assert_eq!(saying, 0, "a change row still says {words:?}");let naming = bin.h.count("SELECT count(*) AS c FROM cotton_changes WHERE record_id = ? AND verb <> 'delete'", &[sql_text(id)], ); assert_eq!(naming, 0, "an earlier change still names {id}"); }let trashed = bin.h.count("SELECT count(*) AS c FROM cotton_changes WHERE instr(COALESCE(before, ''), ?) > 0", &[sql_text(SECRET_BINNED)], ); assert_eq!(trashed, 0, "not even when it went in");// The decision nobody erased keeps its own story. call( &bin,"update_record", json!({ "table": "bin", "id": bin.decision, "patch": { "state": "restored" } }), ); assert_eq!( bin.h.count(// The restore's own row, and no second one for the engine's act."SELECT count(*) AS c FROM cotton_changes WHERE record_id = ?", &[sql_text(&bin.decision)], ),1 );}/// RULE: Emptying the bin leaves nothing an erased row said in the synced change log either — the one eraser forgets every change naming the row, whichever verb erased it.#[test]fn emptying_the_bin_leaves_nothing_the_rows_said_in_the_change_log() {let bin = seeded();// Restores through the bin write changes carrying the titles …for (id, table, at) in [ (&bin.password, "cotton_secrets", SECRET_BINNED), (&bin.email, "cotton_emails", MAIL_BINNED), (&bin.decision, "cotton_decisions", DECISION_BINNED), ] { call( &bin,"update_record", json!({ "table": "bin", "id": id, "patch": { "state": "restored" } }), );// … and each goes back in from its own table. bin.h.run( &format!("UPDATE {table} SET trashed_at = ? WHERE id = ?"), &[sql_text(at), sql_text(id)], ); }// The generic verbs' own rows, and no second one for an engine's act. assert_eq!(bin.h.count("SELECT count(*) AS c FROM cotton_changes", &[]), 3);// Emptied by `empty_bin`, the verb the app's "Empty the bin" calls. assert_eq!(owner(&bin, "empty_bin", json!({}))["total"], 5); assert_eq!(count(&bin, "cotton_secrets", &bin.password), 0); assert_eq!(count(&bin, "cotton_email_threads", &bin.thread), 0);for words in ["Old router", "This week at Acme", "Move the standup to ten"] {let saying = bin.h.count("SELECT count(*) AS c FROM cotton_changes \ WHERE instr(COALESCE(before, ''), ?) > 0 OR instr(COALESCE(after, ''), ?) > 0", &[sql_text(words), sql_text(words)], ); assert_eq!(saying, 0, "a change row still says {words:?}"); } assert_eq!(bin.h.count("SELECT count(*) AS c FROM cotton_changes", &[]), 0);}/// RULE: Emptying the bin of a conversation forgets the change rows of every message the store takes away with it, a message that was out of the bin included.#[test]fn a_conversations_erase_forgets_the_changes_of_the_messages_it_takes() {let bin = seeded();// The message comes out of the bin through the bin table — a change// naming it — while its conversation stays in. call( &bin,"update_record", json!({ "table": "bin", "id": bin.email, "patch": { "state": "restored" } }), ); assert_eq!( bin.h.count("SELECT count(*) AS c FROM cotton_changes WHERE record_id = ?", &[sql_text(&bin.email)]),1 ); owner(&bin, "empty_bin", json!({ "kind": "email_thread" })); assert_eq!(count(&bin, "cotton_email_threads", &bin.thread), 0); assert_eq!(count(&bin, "cotton_emails", &bin.email), 0, "the store took the message with it"); assert_eq!( bin.h.count("SELECT count(*) AS c FROM cotton_changes WHERE record_id = ?", &[sql_text(&bin.email)]),0 ); assert_eq!( bin.h.count("SELECT count(*) AS c FROM cotton_changes \ WHERE instr(COALESCE(before, ''), ?) > 0 OR instr(COALESCE(after, ''), ?) > 0", &[sql_text("This week at Acme"), sql_text("This week at Acme")], ),0 );}/// RULE: A `where` on the bin narrows it by its own columns, matched in memory — `table` is what a table's "Deleted · n" link reads — and the read writes nothing.#[test]fn a_where_on_the_bin_narrows_it_by_its_own_columns() {let bin = seeded();// One kind of record: the way back to what was deleted from one table. assert_eq!(ids(&listed(&bin, json!({ "where": { "table": "decision" } }))), vec![bin.decision.clone()]); assert_eq!(ids(&listed(&bin, json!({ "where": { "kind": "email_thread" } }))), vec![bin.thread.clone()]);let page = listed(&bin, json!({ "where": { "table": "secret" } })); assert_eq!(page["records"][0]["data"]["title"], "Old router", "{page}"); assert_eq!(ids(&page).len(), 1, "{page}");let page = listed(&bin, json!({ "where": { "table": "note" } })); assert!(ids(&page).is_empty(), "{page}");// A key the bin does not have, or a value its column cannot hold, is// refused the way every table refuses it.let text = refused(&bin, "list_records", json!({ "table": "bin", "where": { "colour": "red" } })); assert!(text.ends_with("no column \"colour\""), "{text}");let text = refused(&bin, "list_records", json!({ "table": "bin", "where": { "kind": "person" } })); assert!(text.contains("\"person\" is not one"), "{text}");// An empty `where` narrows nothing. assert_eq!(ids(&listed(&bin, json!({ "where": {} }))).len(), 4); assert_eq!(bin.h.count("SELECT count(*) AS c FROM cotton_changes", &[]), 0);}/// RULE: Only a binned row can be erased through the bin; a row out of the bin is refused and kept.#[test]fn a_row_out_of_the_bin_is_never_erased() {let bin = seeded();let text = owner_refused(&bin, "delete_record", json!({ "table": "bin", "id": bin.kept_decision })); assert!(text.contains("not in the bin"), "{text}"); assert!(!text.contains(&bin.kept_decision), "a refusal printed a record id: {text}"); assert_eq!(count(&bin, "cotton_decisions", &bin.kept_decision), 1);}/// RULE: Erasing a binned conversation erases its binned messages with it, each its own delete, and a conversation with a message out of the bin is refused and nothing is erased.#[test]fn a_conversation_is_erased_with_its_binned_messages_and_never_with_kept_ones() {let bin = seeded(); owner(&bin, "delete_record", json!({ "table": "bin", "id": bin.thread })); assert_eq!(count(&bin, "cotton_email_threads", &bin.thread), 0); assert_eq!(count(&bin, "cotton_emails", &bin.email), 0, "its message went with it");let other = thread(&bin.h, "gmail:acme-mixed", "Invoices", Some(MAIL_BINNED));let binned = email(&bin.h, &other, "<binned@acme.example>", Some(MAIL_BINNED));let kept = email(&bin.h, &other, "<kept@acme.example>", None);let text = owner_refused(&bin, "delete_record", json!({ "table": "bin", "id": other })); assert!(text.contains("1 message(s) out of the bin"), "{text}"); assert_eq!(count(&bin, "cotton_email_threads", &other), 1); assert_eq!(count(&bin, "cotton_emails", &binned), 1); assert_eq!(count(&bin, "cotton_emails", &kept), 1);}// ── refused verbs ───────────────────────────────────────────────────────────/// RULE: Nothing is created in the bin, and it has no order and no links, so create, reorder and link are refused.#[test]fn create_reorder_and_link_are_refused_on_the_bin() {let bin = seeded();let text = refused(&bin, "create_record", json!({ "table": "bin", "data": {} })); assert!(text.contains("Nothing is created in the bin"), "{text}");let text = refused( &bin,"reorder_records", json!({ "table": "bin", "ids": [bin.password, bin.decision] }), ); assert!(!text.is_empty());let text = refused( &bin,"link_records", json!({ "table": "bin", "id": bin.password, "column": "kind", "target_id": null }), ); assert!(!text.is_empty()); assert_eq!(bin.h.count("SELECT count(*) AS c FROM cotton_changes", &[]), 0);}/// RULE: A generic verb over the bin names the bin tool it stands in for, so a run that refuses that tool by name refuses the verb too.#[test]fn a_generic_verb_over_the_bin_reaches_the_bin_tools() { assert_eq!(tools_reached("list_records", "bin"), ["list_bin"]); assert_eq!(tools_reached("get_record_by_table", "bin"), ["list_bin"]); assert_eq!(tools_reached("update_record", "bin"), ["restore_from_bin"]); assert_eq!(tools_reached("delete_record", "bin"), ["empty_bin"]); assert!(tools_reached("create_record", "bin").is_empty());}// ── only the owner's app erases (F1) ────────────────────────────────────────/// RULE: A write token cannot erase a row through delete_record on the bin: only the owner's own app erases, whatever scope any tool in the catalogue carries.#[test]fn write_token_cannot_erase_through_delete_record_on_the_bin() {let bin = seeded();let text = refused(&bin, "delete_record", json!({ "table": "bin", "id": bin.password })); assert!(text.contains("only the owner's own app"), "{text}"); assert_eq!( bin.h.count("SELECT count(*) AS c FROM cotton_secrets WHERE trashed_at IS NOT NULL", &[]),1,"the password is still in the bin" );}/// RULE: empty_bin is the owner's own app's tool: a token with read and write scope is refused it and nothing in the bin is erased.#[test]fn write_token_cannot_call_empty_bin() {let bin = seeded();let before = listed(&bin, json!({}))["total"].clone();let answer = call_tool_raw(&bin.h, &bin.secret, "empty_bin", json!({})); assert!(answer.is_error, "empty_bin answered a write token: {}", answer.text); assert_eq!(listed(&bin, json!({}))["total"], before, "nothing left the bin"); assert_eq!( cotton_tools::mcp::protocol::tool_by_name("empty_bin").map(|tool| tool.scope),Some(cotton_tools::mcp::protocol::McpScope::Owner) );}/// RULE: The owner's own app empties the bin: empty_bin called from a paired device erases what is in it.#[test]fn owner_app_empties_the_bin() {let bin = seeded();let emptied = owner(&bin, "empty_bin", json!({})); assert!(emptied["total"].as_i64().unwrap_or(0) > 0, "{emptied}"); assert_eq!(listed(&bin, json!({}))["total"], 0);}/// RULE: A binned conversation is listed once in the bin, never again as each message inside it; a message binned on its own is still listed.#[test]fn a_binned_conversation_is_listed_once() {let bin = seeded();let listed = ids(&listed(&bin, json!({}))); assert!(listed.contains(&bin.thread), "the conversation is listed"); assert!(!listed.contains(&bin.email), "its message is not listed beside it"); assert!(listed.contains(&bin.alone), "a message binned on its own is listed");}// RULE: a thread's page reads that thread's emails alone, never every email in the file — a row of another thread that cannot be read does not empty this one.#[test]fn a_threads_emails_are_read_without_reading_every_other_email() {let bin = seeded();let kept = thread(&bin.h, "gmail:grant", "Grant letter", None);let first = email(&bin.h, &kept, "<grant-1@acme.example>", None);let second = email(&bin.h, &kept, "<grant-2@acme.example>", None);// A row no read can shape, written past the file's own check: were every// email read, this one would refuse the whole answer. bin.h.run("PRAGMA ignore_check_constraints = 1", &[]); bin.h.run("UPDATE cotton_emails SET recipients = '{}' WHERE id = ?", &[sql_text(&bin.alone)], ); bin.h.run("PRAGMA ignore_check_constraints = 0", &[]);let page = call( &bin,"list_records", json!({ "table": "email", "where": { "thread_id": kept } }), );letmut found = ids(&page); found.sort();letmut wanted = vec![first, second]; wanted.sort(); assert_eq!(found, wanted); assert_eq!(page["total"], 2);}/// RULE: The bin's count (list_bin's counts, Settings' "In the bin") is exactly what its list shows: a binned conversation of several messages counts once.#[test]fn the_bins_count_is_what_its_list_shows() {let bin = seeded(); email(&bin.h, &bin.thread, "<more@acme.example>", Some(MAIL_BINNED));let page = listed(&bin, json!({}));letmut shown = ids(&page);let answer = owner(&bin, "list_bin", json!({}));let counted: i64 = answer["counts"].as_object().unwrap().values().filter_map(Value::as_i64).sum(); assert_eq!(counted, page["total"].as_i64().unwrap(), "{answer}");letmut entries: Vec<String> = answer["entries"] .as_array() .unwrap() .iter() .map(|entry| entry["id"].as_str().unwrap().to_string()) .collect(); shown.sort(); entries.sort(); assert_eq!(entries, shown, "list_bin names what the bin table lists");}// ── a restore's receipt and its Undo ────────────────────────────────────────/// RULE: A restore from the bin answers "Restored <name>" with Undo offered, its Undo bins the record again, and the record keeps the edited time it had before it was binned, so a restored note never jumps to the top.#[test]fn a_restore_from_the_bin_offers_undo_and_keeps_the_edited_time() {let bin = seeded();let note = synthetic_uuid("a live note"); bin.h.run("INSERT INTO cotton_notes (id, workspace_id, kind, title, body, created_at, updated_at) \ VALUES (?, ?, 'note', 'Kite flying', 'Bring the long string.', ?, ?)", &[sql_text(¬e), sql_text(&bin.h.workspace_id), sql_text(AT), sql_text(AT)], );let password = password(&bin.h, "Garden shed lock", None);// A note and a password are binned through their own tables; no verb bins// a decision, so the seeded one is already in the bin.for (table, id) in [("note", ¬e), ("secret", &password)] { call(&bin, "delete_record", json!({ "table": table, "id": id })); }for (store, id, name) in [ ("cotton_notes", ¬e, "Kite flying"), ("cotton_decisions", &bin.decision, "Move the standup to ten"), ("cotton_secrets", &password, "Garden shed lock"), ] {let row = || { bin.h .one(&format!("SELECT updated_at, trashed_at FROM {store} WHERE id = ?"), &[sql_text(id)]) .unwrap() };let went_in = row()["trashed_at"].clone(); assert!(!went_in.is_null(), "{name} is in the bin"); assert_eq!(row()["updated_at"], AT, "{name}: binning is not an edit");let out = call( &bin,"update_record", json!({ "table": "bin", "id": id, "patch": { "state": "restored" } }), );let change = &out["change"]; assert_eq!(change["receipt"]["said"], format!("Restored {name}")); assert_eq!(change["undoable"], true, "{name}: {}", change["reason"]); assert_eq!(row()["trashed_at"], Value::Null, "{name} is out of the bin"); assert_eq!(row()["updated_at"], AT, "{name} keeps its edited time from before the bin"); assert!(!ids(&listed(&bin, json!({}))).contains(id));let undone = call(&bin, "undo", json!({ "change_id": change["id"] })); assert_eq!(undone["undone"]["undone_by"], undone["change"]["id"], "{name}: {undone}"); assert_eq!(row()["trashed_at"], went_in, "{name} goes back in when it first went in"); assert_eq!(row()["updated_at"], AT, "{name}: the Undo is not an edit either");let bin_now = call(&bin, "list_bin", json!({})); assert!(bin_now.to_string().contains(id.as_str()), "{name} is listed again: {bin_now}"); assert!(ids(&listed(&bin, json!({}))).contains(id)); }}