Cotton code
611 lines · 27.8 KB · RustRaw
//! The link rule (design 5.3) and the file's identity, asked where every write//! meets them: `mint` on the writer, and the serving Mac's fold for a write a//! device pushes — a device can push any row, so `mint` alone is not enough.//!//! A shared database is made here with a raw `cotton_workspaces` row of kind//! `shared`; nothing makes one for real until project databases are made (P4).use cotton_store::actor::{Actor, JobName};use cotton_store::exchange::{    answer_excluding, exchange_once, fold_incoming, handled, Handover, SyncTransport,};use cotton_store::file_identity::FileId;use cotton_store::fixtures::{file_at_version, parked, NOW, OWNER, WORKSPACE};use cotton_store::fold::fold_ops;use cotton_store::link_rule::{ACKS_ARE_PERSONAL, FILING_ACTOR, INTO_MINE, MARKS_ARE_PERSONAL, ONLY_A_FILING};use cotton_store::meta::{seed_meta, Meta};use cotton_store::mint::{mint, Act, Change, Clock, Held, History, IdSource, Minted};use cotton_store::protocol::derived_id::{link_id_for, LinkRow};use cotton_store::protocol::hlc::next_hlc;use cotton_store::protocol::types::{CottonOp, ExchangeRequest, ExchangeResponse};use cotton_store::schema::ddl::SCHEMA_VERSION;use cotton_store::wire::op_of_change;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};const T0: i64 = 1_759_480_000_000;const OTHER_DATABASE: &str = "33333333-3333-4333-8333-333333333333";struct Ids(u32, &'static str);static ACTS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);impl IdSource for Ids {    fn next_op_id(&mut self, _now_ms: i64) -> cotton_store::Result<String> {        self.0 += 1;        Ok(format!("{}{:04}", self.1, self.0))    }}/// A file whose workspace row says `kind` (`None`: a row written before/// kinds), held by `device`.fn file(kind: Option<&str>, device: &str) -> Driver {    let db = file_at_version(SCHEMA_VERSION);    seed_meta(        &db,        &Meta {            workspace_id: WORKSPACE.to_string(),            owner_id: OWNER.to_string(),            device_id: device.to_string(),            last_server_seq: 0,            last_hlc: None,        },        SCHEMA_VERSION,    )    .expect("seeds the identity");    db.run(        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at, kind, namespace) \         VALUES (?, 'A file', ?, ?, ?, ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(OWNER.to_string()),            SqlValue::Text(NOW.to_string()),            kind.map_or(SqlValue::Null, |kind| SqlValue::Text(kind.to_string())),            kind.map_or(SqlValue::Null, |_| SqlValue::Text(WORKSPACE.to_string())),        ],    )    .expect("the workspace row");    db}fn object(value: Value) -> Map<String, Value> {    value.as_object().expect("an object").clone()}fn mint_one(db: &Driver, change: Change, held: Held) -> cotton_store::Result<Minted> {    mint(        db,        &Act {            actor: Actor::device_job(JobName::named("link-rule-test").expect("a name")),            verb: "test".into(),            history: History::None,            changes: vec![change],        },        &Clock::wall(T0 + 10),        // A fresh run of op ids per act: a file folds an op id it already        // holds as a replay, so two acts never share one.        &mut Ids(ACTS.fetch_add(100, std::sync::atomic::Ordering::Relaxed), "op-"),        held,    )}/// A `cotton_links` row from note `n1` to `(to_kind, to_id)` in `to_database`,/// at the id `link_id_for` gives it in this file.fn link(to_kind: &str, to_database: Option<&str>) -> Change {    let ends = LinkRow {        from_kind: "note",        from_id: "n1",        to_kind,        to_id: "x1",        to_database,    };    let id = link_id_for(&ends, &FileId::for_tests(WORKSPACE));    Change::create(        "cotton_links",        &id,        object(json!({            "id": id,            "workspace_id": WORKSPACE,            "from_kind": "note",            "from_id": "n1",            "to_kind": to_kind,            "to_id": "x1",            "to_database": to_database,            "created_at": NOW,        })),    )}/// One op as a device that skipped `mint` would push it: the receipt `mint`/// would make for `change`, with none of `mint`'s own rules asked.fn pushed(change: Change) -> CottonOp {    let hlc = next_hlc("device:pusher", None, T0).expect("a stamp");    let actor = Actor::device_job(JobName::named("pusher").expect("a name"));    let schema = file_at_version(SCHEMA_VERSION);    let op_id = format!("op-pushed-{}-{}", change.table, change.row_id);    op_of_change(&schema, &change, &hlc, "device:pusher", &actor, op_id).expect("a receipt")}fn refusal(result: cotton_store::Result<Minted>) -> String {    match result {        Ok(minted) => panic!("the write was accepted: {:?}", minted.ops),        Err(error) => error.to_string(),    }}/// A serving Mac that IS a file: the route's two calls, fold then answer.struct Server(Driver);impl SyncTransport for Server {    fn exchange(&mut self, request: &ExchangeRequest) -> Result<ExchangeResponse, String> {        let already = handled(&request.ops);        let folded = fold_incoming(&self.0, &request.ops).map_err(|error| error.to_string())?;        let answered = answer_excluding(&self.0, &request.cursors, 500, &already)            .map_err(|error| error.to_string())?;        Ok(ExchangeResponse {            answered_by: None,            wanted: Vec::new(),            copy: None,            schema_version: Some(SCHEMA_VERSION),            ops: answered.ops,            cursors: answered.cursors,            has_more: answered.has_more,            applied_rows: folded.applied_rows,            rejected: folded.rejected,            seen: answered.seen,            serving_epoch: None,            server_time: None,            workspace_id: WORKSPACE.to_string(),            restored: None,            copy_night: None,            behind_by: None,            owed_at_start: None,            owed_by_table: None,            passed: None,            wake_refusal: None,        })    }}/// Push `device`'s outbox to `server` once.fn push(device: &Driver, server: Driver) -> Driver {    let mut server = Server(server);    exchange_once(device, &mut server, WORKSPACE, None, NOW, &mut Handover::shut())        .expect("an exchange");    server.0}/// The reasons `db` holds parked.fn parked_reasons(db: &Driver) -> Vec<String> {    db.all("SELECT reason FROM _parked ORDER BY reason", &[])        .expect("reads")        .iter()        .filter_map(|row| row.text("reason").map(str::to_string))        .collect()}fn count(db: &Driver, sql: &str) -> i64 {    db.get(sql, &[]).expect("reads").and_then(|row| row.int("n")).unwrap_or(-1)}/// RULE: A device's write changing a file's kind, namespace or owner is refused at the serving Mac's fold, as mint refuses it on the writer, a null kind gaining one included./// A device can push any row, and reach and routing read these, so a synced rewrite would turn a project's database into the personal one.#[test]fn a_devices_identity_change_is_refused_at_the_fold() {    let change = || Change::update("cotton_workspaces", WORKSPACE, object(json!({"kind": "personal"})));    let server = file(Some("shared"), "device:mac");    let result = fold_ops(&server, &[pushed(change())]).expect("folds");    assert_eq!(result.rejected.len(), 1, "{result:?}");    assert!(result.rejected[0].reason.contains("never changed"), "{:?}", result.rejected);    assert_eq!(count(&server, "SELECT count(*) AS n FROM cotton_workspaces WHERE kind = 'shared'"), 1);    // A row written before kinds does not gain one by a device's patch either.    let unset = file(None, "device:mac");    let result = fold_ops(&unset, &[pushed(change())]).expect("folds");    assert_eq!(result.rejected.len(), 1, "{result:?}");}/// RULE: In a shared database, mint refuses every form of a link into the personal database, while people and every ordinary tool are the shared database's own and the same links in the personal database land./// A token reference and a project link to imported mail remain Personal; ordinary tools link within their own database.#[test]fn link_into_mine_from_a_place_is_refused() {    let place = file(Some("shared"), "device:mac");    // People are ordinary — a team's contacts live in the team's database —    // and so is every other tool: a link to one in the shared database lands.    for kind in ["transaction", "person", "person_note", "document", "secret", "meeting", "repository"] {        mint_one(&place, link(kind, None), Held::Served)            .unwrap_or_else(|error| panic!("a link to a {kind} in the shared database lands: {error}"));    }    // A typed (soft) column naming a personal-only table.    let document = |token: Option<&str>| {        Change::create(            "cotton_documents",            "d1",            object(json!({                "id": "d1", "workspace_id": WORKSPACE, "original_name": "brief.pdf",                "mime": "application/pdf", "byte_size": 1, "sha256": "a".repeat(64),                "storage_path": format!("{WORKSPACE}/documents/d1"), "status": "ready",                "status_changed_at": NOW, "mcp_token_id": token,                "created_at": NOW, "updated_at": NOW,            })),        )    };    let reason = refusal(mint_one(&place, document(Some("t1")), Held::Served));    assert!(reason.contains(INTO_MINE), "{reason}");    // A project link.    let project_link = |kind: &str, id: &str| {        Change::create(            "cotton_project_links",            id,            object(json!({                "id": id, "workspace_id": WORKSPACE, "project_id": "pr1",                "record_kind": kind, "record_id": "r1", "applied_by": "user",                "created_at": NOW, "updated_at": NOW,            })),        )    };    let reason = refusal(mint_one(&place, project_link("email_thread", "pl1"), Held::Served));    assert!(reason.contains(INTO_MINE), "{reason}");    // The same in the personal database is a link inside it.    let mine = file(Some("personal"), "device:mac");    mint_one(&mine, link("transaction", None), Held::Served).expect("Mine links to its own money");}/// RULE: A link naming another database is refused in a place, at mint and at the serving Mac's fold; Mine may name one, and a link naming its own file is stored with none at the same id, while a device pushing that explicit form is refused.#[test]fn place_link_naming_another_database_is_refused_at_mint_and_parked_at_fold() {    let place = file(Some("shared"), "device:mac");    let reason = refusal(mint_one(&place, link("document", Some(OTHER_DATABASE)), Held::Served));    assert!(reason.contains("another database"), "{reason}");    let mine = file(Some("personal"), "device:mac");    mint_one(&mine, link("document", Some(OTHER_DATABASE)), Held::Served).expect("Mine points into a place");    let own = mint_one(&mine, link("document", Some(WORKSPACE)), Held::Served).expect("its own file, named");    let stored = link_id_for(        &LinkRow { from_kind: "note", from_id: "n1", to_kind: "document", to_id: "x1", to_database: None },        &FileId::for_tests(WORKSPACE),    );    assert_eq!(own.ops[0].row_id, stored);    assert_eq!(        count(&mine, &format!("SELECT count(*) AS n FROM cotton_links WHERE id = '{stored}' AND to_database IS NULL")),        1,        "the link into its own file is stored with no database"    );    assert_eq!(count(&mine, "SELECT count(*) AS n FROM cotton_links"), 2, "Mine's X and the place's X are two rows");    // A device whose replica calls itself Mine pushes into the place.    let device = file(Some("personal"), "device:phone");    mint_one(&device, link("document", Some(OTHER_DATABASE)), Held::Replica).expect("the device's own write");    let server = push(&device, file(Some("shared"), "device:mac"));    assert_eq!(count(&server, "SELECT count(*) AS n FROM cotton_links"), 0);    assert_eq!(parked(&device), 1, "{:?}", parked_reasons(&device));    assert!(parked_reasons(&device)[0].contains("another database"), "{:?}", parked_reasons(&device));    // The explicit own-file form, from a device that skipped mint.    let explicit = pushed(Change::create(        "cotton_links",        "l-explicit",        object(json!({            "id": "l-explicit", "workspace_id": WORKSPACE, "from_kind": "note", "from_id": "n2",            "to_kind": "document", "to_id": "x2", "to_database": WORKSPACE, "created_at": NOW,        })),    ));    let result = fold_ops(&file(Some("personal"), "device:mac"), &[explicit]).expect("folds");    assert_eq!(result.rejected.len(), 1, "{result:?}");    assert!(result.rejected[0].reason.contains("names this file"), "{:?}", result.rejected);}// ── the audit ───────────────────────────────────────────────────────────────/// A shared file with the foreign keys off, so a crossing row can be planted/// past every check the way a raw `sqlite3` session would.fn shared_file_for_planting() -> Driver {    let db = file(Some("shared"), "device:audit");    db.run("PRAGMA foreign_keys = OFF", &[]).expect("keys off");    db}fn audit(db: &Driver) -> Vec<(String, String)> {    cotton_store::link_rule::crossing_links(db)        .expect("the audit reads")        .into_iter()        .map(|crossing| (crossing.table, crossing.row_id))        .collect()}#[test]fn audit_finds_a_crossing_link_planted_by_raw_sql_in_the_links_table() {    let db = shared_file_for_planting();    assert!(audit(&db).is_empty(), "a fresh file has nothing to report");    db.run(        "INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, to_database, created_at) \         VALUES ('l1', ?, 'note', 'n1', 'todo', 't1', ?, ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(OTHER_DATABASE.to_string()),            SqlValue::Text(NOW.to_string()),        ],    )    .expect("planted");    db.run(        "INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) \         VALUES ('l2', ?, 'note', 'n1', 'transaction', 'x1', ?)",        &[SqlValue::Text(WORKSPACE.to_string()), SqlValue::Text(NOW.to_string())],    )    .expect("planted");    assert_eq!(        audit(&db),        vec![            ("cotton_links".to_string(), "l1".to_string()),        ]    );}#[test]fn audit_finds_a_crossing_link_planted_by_raw_sql_in_a_soft_column() {    let db = shared_file_for_planting();    db.run(        "INSERT INTO cotton_documents (id, workspace_id, original_name, mime, byte_size, sha256, \         storage_path, status_changed_at, created_at, updated_at, mcp_token_id) \         VALUES ('d1', ?, 'a.pdf', 'application/pdf', 1, 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'p', ?, ?, ?, 'tok-1')",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),        ],    )    .expect("planted");    assert_eq!(audit(&db), vec![("cotton_documents".to_string(), "d1".to_string())]);}#[test]fn audit_finds_a_crossing_link_planted_by_raw_sql_in_a_project_link() {    let db = shared_file_for_planting();    db.run(        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id, \         applied_by, created_at, updated_at) VALUES ('p1', ?, 'proj', 'email_thread', 'x1', 'user', ?, ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),        ],    )    .expect("planted");    assert_eq!(        audit(&db),        vec![("cotton_project_links".to_string(), "p1".to_string())]    );}#[test]fn audit_finds_a_crossing_link_planted_by_raw_sql_in_a_soft_pairs_database_column() {    let db = shared_file_for_planting();    db.run(        "INSERT INTO cotton_meetings (id, workspace_id, source, started_at, status, status_changed_at, \         created_at, updated_at, event_id, event_database) \         VALUES ('m1', ?, 'recorded', ?, 'ready', ?, ?, ?, 'e1', ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(OTHER_DATABASE.to_string()),        ],    )    .expect("planted");    assert_eq!(audit(&db), vec![("cotton_meetings".to_string(), "m1".to_string())]);    // The personal database may hold the same row: the pair's database column    // is how Mine points into a project.    let mine = file(Some("personal"), "device:audit");    mine.run("PRAGMA foreign_keys = OFF", &[]).expect("keys off");    mine.run(        "INSERT INTO cotton_meetings (id, workspace_id, source, started_at, status, status_changed_at, \         created_at, updated_at, event_id, event_database) \         VALUES ('m1', ?, 'recorded', ?, 'ready', ?, ?, ?, 'e1', ?)",        &[            SqlValue::Text(WORKSPACE.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(NOW.to_string()),            SqlValue::Text(OTHER_DATABASE.to_string()),        ],    )    .expect("planted");    assert!(audit(&mine).is_empty());}// ── media keys ──────────────────────────────────────────────────────────────/// A `cotton_photos` row `id` whose bytes are at `key`.fn photo(sha256: &str, key: &str) -> Change {    let id = format!("photo:{sha256}");    Change::create(        "cotton_photos",        &id,        object(json!({            "id": id, "workspace_id": WORKSPACE, "key": key, "sha256": sha256, "content_type": "image/jpeg",            "size_bytes": 1, "taken_at": NOW, "created_at": NOW, "updated_at": NOW,        })),    )}/// RULE: A row naming a media key outside its own file's {file id}/ prefix is refused at mint and parked at the serving Mac's fold, so no erasure, quota or leave here reaches another database's bytes.#[test]fn row_naming_a_media_key_outside_its_files_prefix_is_refused_at_mint_and_parked_at_fold() {    let place = file(Some("shared"), "device:mac");    mint_one(&place, photo("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", &format!("{WORKSPACE}/photos/aa.jpg")), Held::Served).expect("its own prefix");    for outside in [format!("{OTHER_DATABASE}/photos/bb.jpg"), "photos/cc.jpg".to_string(), format!("{WORKSPACE}/")] {        let reason = refusal(mint_one(&place, photo("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", &outside), Held::Served));        assert!(reason.contains(cotton_store::link_rule::MEDIA_OUTSIDE_PREFIX), "{outside}: {reason}");    }    // Mine holds to the same wall: no database names another's bytes.    let mine = file(Some("personal"), "device:mac");    let reason = refusal(mint_one(&mine, photo("cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc", &format!("{OTHER_DATABASE}/photos/bb.jpg")), Held::Served));    assert!(reason.contains(cotton_store::link_rule::MEDIA_OUTSIDE_PREFIX), "{reason}");    // A device that skipped mint pushes one: the fold refuses it.    let crossing = pushed(photo("dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd", &format!("{OTHER_DATABASE}/photos/dd.jpg")));    let result = fold_ops(&file(Some("shared"), "device:mac"), &[crossing]).expect("folds");    assert_eq!(result.rejected.len(), 1, "{result:?}");    assert!(result.rejected[0].reason.contains(cotton_store::link_rule::MEDIA_OUTSIDE_PREFIX), "{:?}", result.rejected);    assert_eq!(count(&place, "SELECT count(*) AS n FROM cotton_photos"), 1, "only the photo under its own prefix");}/// One change, minted as `actor`.fn mint_as(db: &Driver, actor: Actor, change: Change, held: Held) -> cotton_store::Result<Minted> {    mint(        db,        &Act { actor, verb: "test".into(), history: History::None, changes: vec![change] },        &Clock::wall(T0 + 10),        &mut Ids(ACTS.fetch_add(100, std::sync::atomic::Ordering::Relaxed), "op-"),        held,    )}/// RULE: A shared database's Messages hold only the chats filed there — a row of a Messages table is written in a shared file by a filing and by nothing else: refused at mint for any other job of the serving Mac, and refused at the serving Mac's fold for a device that pushes one. The personal database takes a chat from whatever writes it.////// A filing is the owner's own act on one chat, checked against that/// database's people. Ingest writing there, or a device pushing a chat it/// holds, would put a conversation nobody filed in front of everybody in the/// database.#[test]fn a_chat_in_a_shared_database_is_written_by_a_filing_and_by_nothing_else() {    let chat = || {        Change::create(            "cotton_msg_threads",            "t1",            object(json!({ "id": "t1", "workspace_id": WORKSPACE, "kind": "group", "title": "Site crew", "created_at": NOW, "updated_at": NOW })),        )    };    let message = |id: &str| {        Change::create(            "cotton_msg_messages",            id,            object(json!({                "id": id, "workspace_id": WORKSPACE, "thread_id": "t1", "direction": "in", "channel": "whatsapp",                "origin": "live", "body": "Slab is poured", "sent_at": NOW, "created_at": NOW,            })),        )    };    let ingest = || Actor::Job(JobName::named("whatsapp").expect("a name"));    let filing = || Actor::Job(JobName::named("filing").expect("a name"));    assert_eq!(filing().to_string(), FILING_ACTOR);    // The serving Mac's own ingest, writing into the shared file: refused.    let shared = file(Some("shared"), "device:mac");    let reason = refusal(mint_as(&shared, ingest(), chat(), Held::Served));    assert!(reason.contains(ONLY_A_FILING), "{reason}");    assert_eq!(count(&shared, "SELECT count(*) AS n FROM cotton_msg_threads"), 0);    // A filing files the chat and a message of it.    mint_as(&shared, filing(), chat(), Held::Served).expect("a filing writes the chat");    mint_as(&shared, filing(), message("m1"), Held::Served).expect("a filing writes its message");    let reason = refusal(mint_as(&shared, ingest(), message("m2"), Held::Served));    assert!(reason.contains(ONLY_A_FILING), "{reason}");    // A device that holds a chat pushes it: the serving Mac's fold refuses    // every row, and the device parks them.    let device = file(None, "device:phone");    mint_one(&device, chat(), Held::Replica).expect("the device's own chat");    mint_one(&device, message("m3"), Held::Replica).expect("the device's own message");    let shared = push(&device, shared);    assert_eq!(count(&shared, "SELECT count(*) AS n FROM cotton_msg_messages"), 1, "only the filed message is there");    assert_eq!(parked(&device), 2, "{:?}", parked_reasons(&device));    assert!(parked_reasons(&device).iter().all(|reason| reason.contains(ONLY_A_FILING)), "{:?}", parked_reasons(&device));    // The personal database is where every chat arrives.    let mine = file(Some("personal"), "device:mac");    mint_as(&mine, ingest(), chat(), Held::Served).expect("ingest writes the personal database");    mint_as(&mine, ingest(), message("m1"), Held::Served).expect("and its messages");}/// RULE: A reader's pin, mute, archive or clear of a filed chat is a row in that reader's PERSONAL database (cotton_msg_thread_marks), never in the shared one: in a shared file that table takes no row from anybody, a filing included, and a patch of the filed copy naming only those columns is refused like every other write a filing did not make.////// Marks are per member (architect, 12 Oct 2026): pin, mute, archive and/// clear are how ONE PERSON reads a chat, and the shared database holds only/// the filing — the copy and its lines. Before this one member's pin on a/// filed copy was every member's.#[test]fn a_readers_marks_on_a_filed_chat_live_in_their_personal_database_and_never_in_the_shared_one() {    let filing = || Actor::Job(JobName::named("filing").expect("a name"));    let chat = || {        Change::create(            "cotton_msg_threads",            "t1",            object(json!({ "id": "t1", "workspace_id": WORKSPACE, "kind": "group", "title": "Site crew", "created_at": NOW, "updated_at": NOW })),        )    };    let marks = |id: &str, thread: &str| {        Change::create(            "cotton_msg_thread_marks",            id,            object(json!({                "id": id, "workspace_id": WORKSPACE, "database_id": "db-crew", "thread_id": thread,                "pinned_at": NOW, "archived": false, "created_at": NOW, "updated_at": NOW,            })),        )    };    let shared = file(Some("shared"), "device:mac");    mint_as(&shared, filing(), chat(), Held::Served).expect("a filing writes the chat");    // The copy takes no mark: each is a write no filing made.    for patch in [        json!({ "pinned_at": NOW }),        json!({ "muted_until": "9999-12-31T00:00:00Z" }),        json!({ "archived": true, "updated_at": NOW }),        json!({ "cleared_before": NOW, "updated_at": NOW }),    ] {        let reason = refusal(mint_one(&shared, Change::update("cotton_msg_threads", "t1", object(patch.clone())), Held::Served));        assert!(reason.contains(ONLY_A_FILING), "{patch}: {reason}");    }    assert_eq!(count(&shared, "SELECT count(*) AS n FROM cotton_msg_threads WHERE pinned_at IS NULL AND archived = 0"), 1);    // No marks row in a shared file, minted there by anyone — a filing too.    for actor in [filing(), Actor::Job(JobName::named("whatsapp").expect("a name"))] {        let reason = refusal(mint_as(&shared, actor, marks("k1", "t1"), Held::Served));        assert!(reason.contains(MARKS_ARE_PERSONAL), "{reason}");    }    // Nor pushed into it by a member's device.    let device = file(None, "device:phone");    mint_one(&device, marks("k2", "t1"), Held::Replica).expect("the device's own row");    let shared = push(&device, shared);    assert_eq!(count(&shared, "SELECT count(*) AS n FROM cotton_msg_thread_marks"), 0);    assert_eq!(parked(&device), 1, "{:?}", parked_reasons(&device));    assert!(parked_reasons(&device).iter().all(|reason| reason.contains(MARKS_ARE_PERSONAL)), "{:?}", parked_reasons(&device));    // The personal database is where a reader keeps them, from the Mac and    // from a device of its own.    let mine = file(Some("personal"), "device:mac");    mint_one(&mine, marks("k3", "t1"), Held::Served).expect("a reader's own marks in their personal database");    let phone = file(Some("personal"), "device:phone");    mint_one(&phone, marks("k4", "t2"), Held::Replica).expect("the phone's own marks");    let mine = push(&phone, mine);    assert_eq!(parked(&phone), 0, "{:?}", parked_reasons(&phone));    assert_eq!(count(&mine, "SELECT count(*) AS n FROM cotton_msg_thread_marks"), 2);}/// RULE: A phone's receipt for a push (cotton_push_acks) lives in its owner's personal database and never in a shared one: it is about the person's own devices, and a shared file syncs to other people.#[test]fn a_push_receipt_cannot_be_written_into_a_shared_database() {    let ack = |id: &str| {        Change::create(            "cotton_push_acks",            id,            object(json!({                "id": id, "workspace_id": WORKSPACE, "device_id": "device:phone", "push_id": "push-1",                "received_at": NOW, "how": "shown", "created_at": NOW, "updated_at": NOW,            })),        )    };    let shared = file(Some("shared"), "device:mac");    let reason = refusal(mint_one(&shared, ack("a1"), Held::Served));    assert!(reason.contains(ACKS_ARE_PERSONAL), "{reason}");}