//! What a phone keeps, as the owner reads and changes it: the rules these //! verbs write are the rows keep's judge reads, a Mac takes none, and nothing //! narrows a phone until keep's guard is on. use std::sync::Arc; use chrono::{DateTime, Utc}; use cotton_store::driver::Driver; use cotton_store::keep::{self, Verdict, KIND_GROUP, KIND_RECORD, KIND_TABLE, NARROWABLE}; use cotton_store::protocol::derived_id::device_keep_id; use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use super::*; use crate::mcp::dispatch::{call_tool, Ctx, ToolServices}; const WORKSPACE: &str = "00000000-0000-4000-8000-00000000cee9"; const OWNER: &str = "00000000-0000-4000-8000-0000000000dd"; const AUTHOR: &str = "device:keep-fixture"; const PHONE: &str = "phone-key"; const MAC: &str = "mac-key"; const NOW: &str = "2026-10-12T00:00:00.000Z"; const NOW_MS: i64 = 1_791_763_200_000; const OLD_THREAD: &str = "thread-old"; const OTHER_OLD_THREAD: &str = "thread-old-too"; const ALBUM: &str = "album-goa"; static FILE: std::sync::LazyLock = std::sync::LazyLock::new(|| cotton_store::file_identity::FileIdentity::for_tests(WORKSPACE)); fn sql(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } fn device(db: &Driver, key: &str, platform: &str) { db.run( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, approved_at, \ approved_by_device, created_at, updated_at) VALUES (?, ?, ?, 'Invented device', ?, ?, 'self', ?, ?)", &[sql(&format!("row-{key}")), sql(WORKSPACE), sql(key), sql(platform), sql(NOW), sql(NOW), sql(NOW)], ) .expect("a device row"); } fn thread(db: &Driver, id: &str, subject: &str, last_at: &str) { db.run( "INSERT INTO cotton_email_threads (id, workspace_id, external_key, subject, last_at, created_at, updated_at) \ VALUES (?, ?, ?, ?, ?, ?, ?)", &[sql(id), sql(WORKSPACE), sql(id), sql(subject), sql(last_at), sql(last_at), sql(last_at)], ) .expect("a thread"); } /// A file with a phone, a Mac, two threads from January and an album. fn household() -> Driver { let db = cotton_store::test_template::create_workspace_in_memory_for_test(&cotton_store::meta::Meta { workspace_id: WORKSPACE.to_string(), owner_id: OWNER.to_string(), device_id: AUTHOR.to_string(), last_server_seq: 0, last_hlc: None, }) .expect("a fresh file"); db.run( "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, _hlc) VALUES (?, 'Keep', ?, ?, '')", &[sql(WORKSPACE), sql(OWNER), sql(NOW)], ) .expect("the workspace row"); device(&db, PHONE, "ios"); device(&db, MAC, "mac"); thread(&db, OLD_THREAD, "Tickets to Goa", "2026-01-05T09:00:00.000Z"); thread(&db, OTHER_OLD_THREAD, "Old newsletter", "2026-01-06T09:00:00.000Z"); db.run( "INSERT INTO cotton_media_albums (id, workspace_id, kind, title, starts_at, ends_at, created_at, updated_at) \ VALUES (?, ?, 'trip', 'Goa', ?, ?, ?, ?)", &[sql(ALBUM), sql(WORKSPACE), sql(NOW), sql(NOW), sql(NOW), sql(NOW)], ) .expect("an album"); db } fn actor(db: &Driver) -> cotton_store::actor::Actor { cotton_store::actor::Actor::Owner( cotton_store::actor::DeviceId::in_file(db, &format!("row-{PHONE}")).expect("the phone's row"), ) } /// The owner at the phone, as the phone's own screen writes. fn ctx<'a>(db: &'a Driver, services: &'a ToolServices) -> Ctx<'a> { Ctx::phone( db, &FILE, OWNER, AUTHOR, actor(db), cotton_store::mint::Held::Replica, NOW.parse::>().expect("a fixed instant"), Arc::new(crate::random::SystemRandom), services, ) } fn args(value: Value) -> Map { value.as_object().cloned().expect("an object") } fn rule_count(db: &Driver) -> i64 { db.get("SELECT count(*) AS n FROM cotton_device_keep", &[]).unwrap().unwrap().int("n").unwrap_or(-1) } fn line<'a>(list: &'a Value, target: &str) -> &'a Value { list["rules"] .as_array() .expect("lines") .iter() .find(|line| line["target"] == target) .unwrap_or_else(|| panic!("no line for {target}: {list}")) } /// RULE: a rule written by `set_keep_rule` is the `cotton_device_keep` row /// keep's judge reads — the row `keep::set_rule` itself writes, at the id the /// store derives — and no copy of it is kept anywhere else. The write's ops /// are in the answer, so the screen that wrote it redraws and a serving Mac /// wakes its phones. #[test] fn a_rule_set_here_is_the_row_keep_set_rule_writes() { let db = household(); let services = ToolServices::none(); let mut ctx = ctx(&db, &services); let target = keep::record_target_of("cotton_email_threads", OLD_THREAD); let answer = call_tool( &mut ctx, "set_keep_rule", &args(json!({ "device": PHONE, "kind": KIND_RECORD, "target": target, "rule": "always" })), ) .expect("a pin is written"); let id = device_keep_id(PHONE, KIND_RECORD, &target); assert_eq!(answer["id"], json!(id)); assert_eq!(answer["rule"]["says"], json!("Tickets to Goa: always")); assert!( ctx.written_ops().iter().any(|op| op.table == keep::TABLE && op.row_id == id), "the write's own op is what the screen and the phones are told by" ); // The store's own reading of the table sees it. let rules = keep::rules_of(&db, PHONE).expect("the rules read"); assert_eq!(rules.len(), 1); assert_eq!((rules[0].id.as_str(), rules[0].kind.as_str(), rules[0].rule.as_str()), (id.as_str(), KIND_RECORD, "always")); // And the JUDGE acts on it: with a horizon set (straight into the table, // as the store would once narrowing is allowed), the pinned January // thread is still kept and the other one is not. db.run( "INSERT INTO cotton_device_keep (id, workspace_id, device_id, kind, target, rule, created_at, updated_at) \ VALUES (?, ?, ?, 'table', 'cotton_email_threads', 'days:30', ?, ?)", &[sql(&device_keep_id(PHONE, KIND_TABLE, "cotton_email_threads")), sql(WORKSPACE), sql(PHONE), sql(NOW), sql(NOW)], ) .expect("a horizon"); let judge = keep::Keep::of_device(&db, PHONE).expect("the judge reads the rules"); assert_eq!(judge.verdict(&db, "cotton_email_threads", OLD_THREAD, NOW_MS).unwrap(), Verdict::Inside); assert_eq!(judge.verdict(&db, "cotton_email_threads", OTHER_OLD_THREAD, NOW_MS).unwrap(), Verdict::Outside); // The row is the one `keep::set_rule` writes for the same rule. let other = household(); let mut ids = cotton_store::protocol::ulid::Monotonic::new(|bytes: &mut [u8]| bytes.fill(7)); keep::set_rule( &other, WORKSPACE, PHONE, KIND_RECORD, &target, "always", actor(&other), NOW_MS, &mut ids, cotton_store::mint::Held::Replica, ) .expect("the store writes the same rule"); let columns = "SELECT id, workspace_id, device_id, kind, target, rule, created_at, updated_at FROM cotton_device_keep"; let ours = db.get(&format!("{columns} WHERE kind = 'record'"), &[]).unwrap().expect("ours"); let theirs = other.get(&format!("{columns} WHERE kind = 'record'"), &[]).unwrap().expect("the store's"); for column in ["id", "workspace_id", "device_id", "kind", "target", "rule", "created_at", "updated_at"] { assert_eq!(ours.text(column), theirs.text(column), "{column}"); } } /// RULE: a Mac takes no rule — it may take over serving, so it keeps /// everything — and its list says so with no lines. #[test] fn a_mac_refuses_a_rule() { let db = household(); let services = ToolServices::none(); let mut ctx = ctx(&db, &services); for (kind, target, rule) in [ (KIND_TABLE, "cotton_email_threads", "all"), (KIND_GROUP, ALBUM, "always"), (KIND_RECORD, "cotton_email_threads:thread-old", "always"), ] { let refused = call_tool( &mut ctx, "set_keep_rule", &args(json!({ "device": MAC, "kind": kind, "target": target, "rule": rule })), ) .expect_err("a Mac takes no rule"); assert!(refused.to_string().contains("A Mac keeps every row"), "{refused}"); let refused = call_tool(&mut ctx, "clear_keep_rule", &args(json!({ "device": MAC, "kind": kind, "target": target }))) .expect_err("nor clears one"); assert!(refused.to_string().contains("A Mac keeps every row"), "{refused}"); } assert_eq!(rule_count(&db), 0); let list = call_tool(&mut ctx, "list_keep_rules", &args(json!({ "device": format!("row-{MAC}") }))).expect("a list"); assert_eq!(list["phone"], json!(false)); assert_eq!(list["rules"], json!([])); } /// RULE: until keep's guard is on (`keep::NARROWING_GUARDED`), no rule that /// keeps less than everything can be written — `none` and `days:N` are /// refused with "after the next update", and the list offers them greyed — /// while a table kept `all` and a group or record kept `always` are written. #[test] fn a_narrowing_rule_cannot_be_written_while_the_guard_is_off() { let db = household(); let services = ToolServices::none(); let mut ctx = ctx(&db, &services); for rule in ["none", "days:90"] { let written = call_tool( &mut ctx, "set_keep_rule", &args(json!({ "device": PHONE, "kind": KIND_TABLE, "target": "cotton_stories", "rule": rule })), ); if keep::NARROWING_GUARDED { written.expect("keep's guard is on, so a phone may keep less"); } else { let refused = written.expect_err("nothing narrows a phone yet"); assert!(refused.to_string().contains(AFTER_THE_NEXT_UPDATE), "{refused}"); } } if !keep::NARROWING_GUARDED { assert_eq!(rule_count(&db), 0, "a refused rule left no row"); } for (kind, target, rule) in [ (KIND_TABLE, "cotton_email_threads", "all"), (KIND_GROUP, ALBUM, "always"), (KIND_RECORD, "cotton_email_threads:thread-old", "always"), ] { call_tool(&mut ctx, "set_keep_rule", &args(json!({ "device": PHONE, "kind": kind, "target": target, "rule": rule }))) .unwrap_or_else(|refused| panic!("{kind} {rule} widens or pins and is written: {refused}")); } let list = call_tool(&mut ctx, "list_keep_rules", &args(json!({ "device": PHONE }))).expect("a list"); assert_eq!(list["narrowing"], json!(keep::NARROWING_GUARDED)); for choice in list["choices"].as_array().expect("choices") { let narrowing = narrows(KIND_TABLE, choice["rule"].as_str().unwrap()); let offered = keep::NARROWING_GUARDED || !narrowing; assert_eq!(choice["offered"], json!(offered), "{choice}"); if !offered { assert_eq!(choice["note"], json!(AFTER_THE_NEXT_UPDATE), "{choice}"); } } } /// RULE: clearing a rule removes its row, so the judge no longer reads it; /// clearing one that is not there says so and writes nothing. #[test] fn clear_removes_the_rule() { let db = household(); let services = ToolServices::none(); let mut ctx = ctx(&db, &services); let pin = json!({ "device": PHONE, "kind": KIND_GROUP, "target": ALBUM, "rule": "always" }); call_tool(&mut ctx, "set_keep_rule", &args(pin)).expect("kept"); assert_eq!(keep::rules_of(&db, PHONE).unwrap().len(), 1); let cleared = call_tool(&mut ctx, "clear_keep_rule", &args(json!({ "device": PHONE, "kind": KIND_GROUP, "target": ALBUM }))) .expect("cleared"); assert_eq!(cleared["cleared"], json!(true)); assert!(keep::rules_of(&db, PHONE).unwrap().is_empty()); let again = call_tool(&mut ctx, "clear_keep_rule", &args(json!({ "device": PHONE, "kind": KIND_GROUP, "target": ALBUM }))) .expect("nothing to clear is no failure"); assert_eq!(again["cleared"], json!(false)); } /// RULE: the device row's list shows a rule the moment it is written, in /// words, and Cotton's defaults are marked as defaults until changed. #[test] fn the_list_shows_a_rule_the_moment_it_is_written() { let db = household(); let services = ToolServices::none(); let mut ctx = ctx(&db, &services); let before = call_tool(&mut ctx, "list_keep_rules", &args(json!({ "device": PHONE }))).expect("a list"); assert_eq!(before["phone"], json!(true)); assert_eq!(line(&before, "cotton_email_threads")["says"], json!("Mail: 6 months"), "a phone behind a Mac keeps six months of mail"); assert_eq!(line(&before, "cotton_email_threads")["default"], json!(true)); assert_eq!(line(&before, "cotton_stories")["default"], json!(true)); call_tool( &mut ctx, "set_keep_rule", &args(json!({ "device": PHONE, "kind": KIND_TABLE, "target": "cotton_email_threads", "rule": "all" })), ) .expect("mail kept whole"); call_tool(&mut ctx, "set_keep_rule", &args(json!({ "device": PHONE, "kind": KIND_GROUP, "target": ALBUM, "rule": "always" }))) .expect("the album kept"); // A record named by its table's definition id is kept from the table its // records live in. call_tool( &mut ctx, "set_keep_rule", &args(json!({ "device": PHONE, "kind": KIND_RECORD, "target": "email_thread:thread-old", "rule": "always" })), ) .expect("the thread kept"); let after = call_tool(&mut ctx, "list_keep_rules", &args(json!({ "device": PHONE }))).expect("a list"); assert_eq!(line(&after, "cotton_email_threads")["default"], json!(false)); assert_eq!(line(&after, "cotton_email_threads")["says"], json!("Mail: everything")); assert_eq!(line(&after, ALBUM)["says"], json!("Album Goa: always")); assert_eq!(line(&after, "cotton_email_threads:thread-old")["says"], json!("Tickets to Goa: always")); assert_eq!(line(&after, "cotton_stories")["default"], json!(true)); } /// RULE: the list says what the phone keeps: six months of mail, chats and /// imports by default while a Mac serves behind it, everything with none. #[test] fn the_list_says_a_phone_with_no_mac_behind_it_keeps_everything() { let db = household(); let services = ToolServices::none(); let behind = call_tool(&mut ctx(&db, &services), "list_keep_rules", &args(json!({ "device": PHONE }))).expect("a list"); for (table, says) in [("cotton_msg_threads", "Messages: 6 months"), ("cotton_imports", "Message imports: 6 months")] { assert_eq!(line(&behind, table)["says"], json!(says)); } db.run("UPDATE cotton_devices SET revoked_at = ? WHERE device_id = ?", &[sql(NOW), sql(MAC)]).expect("the Mac revoked"); let alone = call_tool(&mut ctx(&db, &services), "list_keep_rules", &args(json!({ "device": PHONE }))).expect("a list"); assert_eq!(line(&alone, "cotton_email_threads")["says"], json!("Mail: everything")); assert_eq!(line(&alone, "cotton_email_threads")["default"], json!(true)); } /// RULE: every table a rule may narrow has words a page can say it by. #[test] fn every_table_a_rule_may_narrow_has_words() { for (table, _column) in NARROWABLE { assert!(TABLE_WORDS.iter().any(|(name, _)| name == table), "{table} has no words on a page"); } } #[test] fn a_rule_reads_as_words() { for (rule, words) in [ ("all", "everything"), ("none", "never"), ("always", "always"), ("days:30", "1 month"), ("days:90", "3 months"), ("days:365", "1 year"), ("days:14", "2 weeks"), ("days:3", "3 days"), ] { assert_eq!(rule_words(rule), words, "{rule}"); } } /// RULE: setting the rule a phone already has writes nothing — the /// catalogue calls the verb idempotent, and a retry after a timeout must not /// mint a second change. #[test] fn the_same_rule_twice_is_written_once() { let db = household(); let services = ToolServices::none(); let pin = json!({ "device": PHONE, "kind": KIND_GROUP, "target": ALBUM, "rule": "always" }); let mut first = ctx(&db, &services); call_tool(&mut first, "set_keep_rule", &args(pin.clone())).expect("kept"); assert!(first.written_ops().iter().any(|op| op.table == keep::TABLE)); let mut second = ctx(&db, &services); let again = call_tool(&mut second, "set_keep_rule", &args(pin)).expect("kept again"); assert!(second.written_ops().is_empty(), "nothing was written the second time"); assert_eq!(again["rule"]["says"], json!("Album Goa: always")); } fn storage_rules_of(db: &Driver, device: &str) -> Vec<(String, String)> { db.all("SELECT tool, keep_rule FROM cotton_storage_rules WHERE device_id = ? ORDER BY tool", &[sql(device)]) .unwrap() .iter() .map(|row| (row.text("tool").unwrap().to_string(), row.text("keep_rule").unwrap().to_string())) .collect() } /// RULE: what a Mac keeps of its files is ONE choice through the same verbs — `bytes` everything or rows_only — written as the Mac's Storage rules for every byte tool and read back off them, so the device row and Storage never disagree; the list says when the Mac serves (it keeps everything while it does); clearing it is everything; a phone is refused it, and so is any other word (sync programme, lane D, 12 Oct 2026). #[test] fn a_macs_bytes_rule_is_its_storage_rules() { let db = household(); let services = ToolServices::none(); let mut ctx = ctx(&db, &services); let list = call_tool(&mut ctx, "list_keep_rules", &args(json!({ "device": MAC }))).expect("a list"); assert_eq!((list["keeps"].clone(), list["serving"].clone()), (json!("everything"), json!(false))); assert_eq!(list["keepsChoices"].as_array().map(Vec::len), Some(2)); let answer = call_tool(&mut ctx, "set_keep_rule", &args(json!({ "device": MAC, "kind": "bytes", "rule": "rows_only" }))) .expect("rows only"); assert_eq!(answer["rule"], json!("rows_only")); let every = |rule: &str| -> Vec<(String, String)> { let mut tools: Vec<(String, String)> = cotton_store::storage_rules::BYTE_TOOLS.iter().map(|tool| (tool.to_string(), rule.to_string())).collect(); tools.sort(); tools }; assert_eq!(storage_rules_of(&db, MAC), every("only_opened")); let list = call_tool(&mut ctx, "list_keep_rules", &args(json!({ "device": MAC }))).expect("a list"); assert_eq!(list["keeps"], json!("rows_only")); assert!(!cotton_store::storage_rules::keeps_everything(&db, WORKSPACE, MAC).unwrap()); db.run( "INSERT INTO cotton_serving_machine (id, workspace_id, epoch, device_credential_id, author_id, since) \ VALUES ('serving', ?, 1, ?, 'device:mac', ?)", &[sql(WORKSPACE), sql(MAC), sql(NOW)], ) .expect("this Mac serves"); let list = call_tool(&mut ctx, "list_keep_rules", &args(json!({ "device": MAC }))).expect("a list"); assert_eq!(list["serving"], json!(true)); assert!(list["servingNote"].as_str().is_some_and(|note| note.contains("keeps everything"))); call_tool(&mut ctx, "clear_keep_rule", &args(json!({ "device": MAC, "kind": "bytes" }))).expect("back to everything"); assert_eq!(storage_rules_of(&db, MAC), every("all")); assert!(call_tool(&mut ctx, "set_keep_rule", &args(json!({ "device": PHONE, "kind": "bytes", "rule": "rows_only" }))).is_err()); assert!(call_tool(&mut ctx, "set_keep_rule", &args(json!({ "device": MAC, "kind": "bytes", "rule": "half" }))).is_err()); }