//! The only-you audience's guards, on synthetic files: a shared database the //! owner serves, with the owner's phone and a member's phone in it. use std::collections::BTreeMap; use serde_json::json; use super::*; use crate::fold::FoldResult; use crate::keep::{Keep, Verdict}; use crate::test_support::{seeded_file, WORKSPACE}; /// 12 Oct 2026, 00:00 UTC. const NOW: i64 = 1_791_763_200_000; const AT: &str = "2026-10-12T00:00:00.000Z"; /// The serving Mac, the owner's phone and an invented member's phone, by key. const MAC: &str = "mac-key"; const OWNER_PHONE: &str = "owner-phone-key"; const MEMBER_PHONE: &str = "member-phone-key"; /// Each device's author on this file. const MAC_AUTHOR: &str = "author-mac"; const OWNER_AUTHOR: &str = "author-owner-phone"; const MEMBER_AUTHOR: &str = "author-member-phone"; const HELD: &str = "aaaaaaaa-0000-4000-8000-000000000001"; const OPEN: &str = "aaaaaaaa-0000-4000-8000-000000000002"; const COMMENT: &str = "aaaaaaaa-0000-4000-8000-000000000003"; fn text(value: &str) -> SqlValue { SqlValue::Text(value.to_string()) } fn device(db: &Driver, key: &str, platform: &str, person_key: Option<&str>) { db.run( "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, person_key, approved_at, approved_by_device, created_at, updated_at) \ VALUES (?, ?, ?, 'Invented device', ?, ?, '2026-01-01', ?, '2026-01-01', '2026-01-01')", &[text(key), text(WORKSPACE), text(key), text(platform), person_key.map(text).unwrap_or(SqlValue::Null), text(MAC)], ) .unwrap(); } fn author(db: &Driver, id: &str, device_key: &str) { db.run( "INSERT INTO cotton_authors (id, workspace_id, device_id, minted_at, reason, first_stamp) \ VALUES (?, ?, ?, '2026-01-01', 'first', ?)", &[text(id), text(WORKSPACE), text(device_key), text(&format!("{:013}:0000:{id}", 1))], ) .unwrap(); } /// A file of `kind` with the three devices and their authors. fn file(kind: &str) -> Driver { let db = seeded_file(MAC); db.run("UPDATE cotton_workspaces SET kind = ? WHERE id = ?", &[text(kind), text(WORKSPACE)]).unwrap(); device(&db, MAC, "mac", None); device(&db, OWNER_PHONE, "ios", None); device(&db, MEMBER_PHONE, "ios", Some("person-key-of-an-invented-member")); author(&db, MAC_AUTHOR, MAC); author(&db, OWNER_AUTHOR, OWNER_PHONE); author(&db, MEMBER_AUTHOR, MEMBER_PHONE); db } fn owner_at(device_row: &str) -> Actor { Actor::from_wire(&format!("owner:{device_row}")).unwrap() } fn agent() -> Actor { Actor::from_wire("token:invented-assistant-token").unwrap() } /// `changes` written by `author` as `actor`, from `ms` on, folded as a device's /// handed-over write. fn write(db: &Driver, changes: &[Change], author: &str, actor: &Actor, ms: i64) -> FoldResult { let ops: Vec = changes .iter() .enumerate() .map(|(at, change)| { let hlc = format!("{:013}:{at:04}:{author}", ms); crate::wire::op_of_change(db, change, &hlc, author, actor, format!("op-{author}-{ms}-{at}")).unwrap() }) .collect(); crate::fold::fold_ops(db, &ops).unwrap() } fn todo(id: &str, title: &str) -> Change { Change::create( "cotton_todos", id, json!({"id": id, "workspace_id": WORKSPACE, "title": title, "created_at": AT, "updated_at": AT}) .as_object() .cloned() .unwrap(), ) } fn comment_on(id: &str, record: &str) -> Change { Change::create( "cotton_comments", id, json!({"id": id, "workspace_id": WORKSPACE, "record_kind": "todo", "record_id": record, "body": "Invented words", "author_kind": "user", "author_user_id": "owner-1", "created_at": AT, "updated_at": AT}) .as_object() .cloned() .unwrap(), ) } /// A shared database where the owner's phone made one todo only-you (the /// mark minted first, then the todo and a comment on it) and one todo for /// everyone. fn held_household() -> Driver { let db = file("shared"); let mark = mark(&db, WORKSPACE, "cotton_todos", HELD, AT).unwrap(); let made = write( &db, &[mark, todo(HELD, "Invented private plan"), comment_on(COMMENT, HELD)], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 100, ); assert!(made.rejected.is_empty(), "the owner's only-you todo lands: {made:?}"); let open = write(&db, &[todo(OPEN, "Invented shared plan")], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 200); assert!(open.rejected.is_empty(), "{open:?}"); db } fn page(db: &Driver) -> Vec { let answered = crate::exchange::answer(db, &BTreeMap::new(), 2_000).unwrap(); assert!(!answered.has_more); answered.ops } fn rows_sent_to(db: &Driver, device_key: &str) -> Vec<(String, String)> { Keep::of_device(db, device_key) .unwrap() .leave_out(db, page(db), NOW) .unwrap() .into_iter() .map(|op| (op.table, op.row_id)) .collect() } fn names(rows: &[(String, String)], id: &str) -> bool { rows.iter().any(|(_, row)| row == id) } /// RULE: An only-you record never appears in another person's device's exchange answer — not the record, not a row naming it, not its audience row; the owner's own devices get all of it. #[test] fn an_only_you_record_never_reaches_a_members_exchange_answer() { let db = held_household(); let hold = audience_id("cotton_todos", HELD); let member = rows_sent_to(&db, MEMBER_PHONE); assert!(names(&member, OPEN), "the shared todo travels to the member: {member:?}"); assert!(!names(&member, HELD), "the only-you todo never reaches the member: {member:?}"); assert!(!names(&member, COMMENT), "nor a comment on it: {member:?}"); assert!(!names(&member, &hold), "nor the audience row that names it: {member:?}"); for owners in [OWNER_PHONE, MAC] { let sent = rows_sent_to(&db, owners); assert!(names(&sent, HELD) && names(&sent, COMMENT) && names(&sent, &hold), "{owners} holds it all: {sent:?}"); } // A device this file cannot place is judged like a member's: closed. let stranger = rows_sent_to(&db, "a-device-this-file-never-approved"); assert!(!names(&stranger, HELD), "{stranger:?}"); } /// RULE: A held record's delete never travels to another person's device either: even its id is the owner's. #[test] fn an_only_you_records_delete_stays_with_the_owner() { let db = held_household(); let gone = write(&db, &[Change::retract("cotton_todos", HELD)], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 300); assert!(gone.rejected.is_empty(), "{gone:?}"); let member = rows_sent_to(&db, MEMBER_PHONE); assert!(!names(&member, HELD), "{member:?}"); } /// RULE: A member's first copy of a shared database holds no only-you row, receipt or tombstone, and opening one by name is refused. #[test] fn a_members_copy_and_openings_never_hold_an_only_you_record() { let db = held_household(); let keep = Keep::of_device(&db, MEMBER_PHONE).unwrap(); assert_eq!(keep.verdict(&db, "cotton_todos", HELD, NOW).unwrap(), Verdict::Never); assert_eq!(keep.verdict(&db, "cotton_comments", COMMENT, NOW).unwrap(), Verdict::Never); assert!(crate::keep::open(&db, &keep, "cotton_todos", HELD, 0, NOW).is_err(), "opening it by name is refused"); let opened = crate::keep::open(&db, &keep, "cotton_todos", OPEN, 0, NOW).unwrap(); assert!(!opened.ops.is_empty(), "an ordinary record still opens"); crate::keep::cut_copy(&db, &keep, NOW).unwrap(); let left = |sql: &str| db.get(sql, &[text(HELD), text(COMMENT), text(&audience_id("cotton_todos", HELD))]).unwrap(); assert!( left("SELECT 1 AS x FROM _writes WHERE row_id IN (?1, ?2, ?3) UNION ALL SELECT 1 FROM _tombstones WHERE row_id IN (?1, ?2, ?3)").is_none(), "no receipt of a held row is left in the member's copy" ); assert!(left("SELECT 1 AS x FROM cotton_todos WHERE id = ?1 UNION ALL SELECT 1 FROM cotton_comments WHERE id = ?2 UNION ALL SELECT 1 FROM cotton_audiences WHERE id = ?3").is_none()); assert!(db.get("SELECT 1 AS x FROM cotton_todos WHERE id = ?", &[text(OPEN)]).unwrap().is_some(), "the rest stays"); } /// RULE: The fold refuses, with the reason, a write of an only-you record that another person's device hands over, and an audience written from such a device. #[test] fn a_members_write_of_an_only_you_record_is_refused_with_the_reason() { let db = held_household(); let member = Actor::from_wire(&format!("member:{MEMBER_PHONE}")).unwrap(); let change = Change::update("cotton_todos", HELD, json!({"title": "Invented takeover"}).as_object().cloned().unwrap()); let refused = write(&db, &[change], MEMBER_AUTHOR, &member, 400); assert_eq!(refused.rejected.len(), 1, "{refused:?}"); assert!(refused.rejected[0].reason.contains(HELD_REFUSAL), "{refused:?}"); let reply = write(&db, &[comment_on("aaaaaaaa-0000-4000-8000-000000000009", HELD)], MEMBER_AUTHOR, &member, 410); assert!(reply.rejected[0].reason.contains(HELD_REFUSAL), "a comment naming it is a write of it: {reply:?}"); let release = release(&db, WORKSPACE, "cotton_todos", HELD, AT).unwrap(); let set = write(&db, &[release], MEMBER_AUTHOR, &member, 420); assert!(set.rejected[0].reason.contains(ONLY_THE_OWNER_SETS), "{set:?}"); assert_eq!(of_record(&db, "cotton_todos", HELD).unwrap().as_deref(), Some(ONLY_YOU)); } /// RULE: Only the owner releases an only-you record: an assistant's release is refused even from the owner's own Mac, and the owner's release lets the record travel whole from then on. #[test] fn the_owners_release_lets_it_travel_and_an_agents_is_refused() { let db = held_household(); let by_agent = write(&db, &[release(&db, WORKSPACE, "cotton_todos", HELD, AT).unwrap()], MAC_AUTHOR, &agent(), 500); assert_eq!(by_agent.rejected.len(), 1, "{by_agent:?}"); assert!(by_agent.rejected[0].reason.contains(ONLY_THE_OWNER_RELEASES), "{by_agent:?}"); assert!(!names(&rows_sent_to(&db, MEMBER_PHONE), HELD)); // The member's cursors passed everything so far. let cursors = crate::exchange::answer(&db, &BTreeMap::new(), 2_000).unwrap().cursors; let by_owner = write(&db, &[release(&db, WORKSPACE, "cotton_todos", HELD, AT).unwrap()], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 600); assert!(by_owner.rejected.is_empty(), "{by_owner:?}"); assert_eq!(of_record(&db, "cotton_todos", HELD).unwrap().as_deref(), Some(EVERYONE)); // The next page carries the audience row WHOLE, so a member that never // held it can read which record to ask for… let next = crate::exchange::answer(&db, &cursors, 2_000).unwrap().ops; let keep = Keep::of_device(&db, MEMBER_PHONE).unwrap(); let sent = keep.leave_out(&db, next, NOW).unwrap(); let hold = audience_id("cotton_todos", HELD); let restated: Vec<&CottonOp> = sent.iter().filter(|op| op.row_id == hold).collect(); assert!(!restated.is_empty(), "the release travels: {sent:?}"); let fields: BTreeSet = restated.iter().flat_map(|op| op.patch.iter().flat_map(|p| p.keys().cloned())).collect(); for column in ["record_table", "record_id", "audience", "workspace_id", "created_at"] { assert!(fields.contains(column), "the release restates {column}: {fields:?}"); } // …and the record now opens for it, with its comment. let opened = crate::keep::open(&db, &keep, "cotton_todos", HELD, 0, NOW).unwrap(); assert!(opened.rows.iter().any(|(_, id)| id == HELD), "{opened:?}"); assert!(names(&rows_sent_to(&db, MEMBER_PHONE), COMMENT)); } /// RULE: A member's copy that received a release names the record it still lacks, so the device opens it by name. #[test] fn a_release_names_what_a_member_still_lacks() { let owners = held_household(); let member = file("shared"); // The member's first page, the hold in force; its cursors pass it all. let first = crate::exchange::answer(&owners, &BTreeMap::new(), 2_000).unwrap(); let sent = Keep::of_device(&owners, MEMBER_PHONE).unwrap().leave_out(&owners, first.ops, NOW).unwrap(); assert!(crate::fold::fold_pulled(&member, &sent).unwrap().rejected.is_empty()); assert!(released_missing(&member, 10).unwrap().is_empty()); let by_owner = write(&owners, &[release(&owners, WORKSPACE, "cotton_todos", HELD, AT).unwrap()], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 600); assert!(by_owner.rejected.is_empty(), "{by_owner:?}"); let next = crate::exchange::answer(&owners, &first.cursors, 2_000).unwrap(); let sent = Keep::of_device(&owners, MEMBER_PHONE).unwrap().leave_out(&owners, next.ops, NOW).unwrap(); let folded = crate::fold::fold_pulled(&member, &sent).unwrap(); assert!(folded.rejected.is_empty(), "{folded:?}"); let hold = audience_id("cotton_todos", HELD); let wanted = released_missing(&member, 10).unwrap(); assert_eq!(wanted, vec![(TABLE.to_string(), hold.clone()), ("cotton_todos".to_string(), HELD.to_string())]); // Opening what it names, as the device's keep pass does, lands both whole. let keep = Keep::of_device(&owners, MEMBER_PHONE).unwrap(); for (table, id) in &wanted { let opened = crate::keep::open(&owners, &keep, table, id, 0, NOW).unwrap(); crate::keep::fold_fetched(&member, &opened.ops, NOW).unwrap(); } assert_eq!(of_record(&member, "cotton_todos", HELD).unwrap().as_deref(), Some(EVERYONE)); assert!(member.get("SELECT 1 AS x FROM cotton_todos WHERE id = ?", &[text(HELD)]).unwrap().is_some()); assert!(released_missing(&member, 10).unwrap().is_empty(), "nothing is asked for twice"); } /// RULE: Only-you is chosen before anyone else can hold the record: a mark on a record already in a file another person's device holds is refused. #[test] fn a_late_mark_is_refused() { let db = held_household(); let late = write(&db, &[mark(&db, WORKSPACE, "cotton_todos", OPEN, AT).unwrap()], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 700); assert!(late.rejected[0].reason.contains(ALREADY_SHARED), "{late:?}"); let alone = file("shared"); alone.run("UPDATE cotton_devices SET revoked_at = '2026-02-01' WHERE device_id = ?", &[text(MEMBER_PHONE)]).unwrap(); let made = write(&alone, &[todo(OPEN, "Invented plan")], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 100); assert!(made.rejected.is_empty()); let marked = write(&alone, &[mark(&alone, WORKSPACE, "cotton_todos", OPEN, AT).unwrap()], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 200); assert!(marked.rejected.is_empty(), "nobody else could hold it yet: {marked:?}"); } /// RULE: An audience is never deleted and names its record by its derived id: a delete or a mismatched id is refused. #[test] fn an_audience_is_never_deleted_or_misnamed() { let db = held_household(); let hold = audience_id("cotton_todos", HELD); let deleted = write(&db, &[Change::retract(TABLE, &hold)], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 800); assert!(deleted.rejected[0].reason.contains(NEVER_DELETED), "{deleted:?}"); let wrong = Change::create( TABLE, "aaaaaaaa-0000-4000-8000-0000000000ff", json!({"id": "aaaaaaaa-0000-4000-8000-0000000000ff", "workspace_id": WORKSPACE, "record_table": "cotton_todos", "record_id": OPEN, "audience": ONLY_YOU, "created_at": AT, "updated_at": AT}) .as_object() .cloned() .unwrap(), ); let misnamed = write(&db, &[wrong], OWNER_AUTHOR, &owner_at(OWNER_PHONE), 810); assert!(misnamed.rejected[0].reason.contains("derived"), "{misnamed:?}"); } /// RULE: A member's assistant seat never writes an only-you record or releases one, though the serving Mac stamps the write: the seat acts for another person. #[test] fn a_members_seat_never_writes_or_releases_an_only_you_record() { let db = held_household(); db.run( "INSERT INTO cotton_mcp_tokens (id, owner_user_id, workspace_id, name, token_hash, scopes, created_at) \ VALUES ('seat-token', 'person:person-key-of-an-invented-member', ?, 'Invented seat', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', '[\"read\",\"write\"]', '2026-01-01')", &[text(WORKSPACE)], ) .unwrap(); let seat = Actor::from_wire("token:seat-token").unwrap(); let change = Change::update("cotton_todos", HELD, json!({"title": "Invented takeover"}).as_object().cloned().unwrap()); let wrote = write(&db, &[change], MAC_AUTHOR, &seat, 900); assert!(wrote.rejected[0].reason.contains(HELD_REFUSAL), "{wrote:?}"); let released = write(&db, &[release(&db, WORKSPACE, "cotton_todos", HELD, AT).unwrap()], MAC_AUTHOR, &seat, 910); assert!(released.rejected[0].reason.contains(ONLY_THE_OWNER_SETS), "{released:?}"); assert!(acts_for_another_person(&db, "member:member-phone-key").unwrap()); assert!(!acts_for_another_person(&db, &agent().to_wire()).unwrap(), "the owner's own assistant is the owner's"); } /// RULE: An answer for another person loses every element naming an only-you record — a hit, a row, a comment on it — and still names one only where the answer is that record, which the seat's door then refuses whole. #[test] fn an_answer_for_another_person_loses_every_held_element() { let db = held_household(); let holds = Holds::for_seat(&db).unwrap(); let answer = json!({ "todos": [{"id": HELD, "title": "Invented private plan"}, {"id": OPEN, "title": "Invented shared plan"}], "comments": [{"id": COMMENT, "recordId": HELD, "body": "Invented words"}], "total": 2, }); let redacted = holds.redact(answer); assert!(!holds.names(&redacted), "{redacted}"); assert_eq!(redacted["todos"].as_array().unwrap().len(), 1); assert!(redacted["comments"].as_array().unwrap().is_empty()); let record = holds.redact(json!({"id": HELD, "title": "Invented private plan"})); assert!(holds.names(&record), "a record answered whole still names itself, and is refused"); assert!(Holds::for_seat(&file("shared")).unwrap().is_empty(), "a file nobody marked holds nothing back"); }