Cotton code
251 lines · 10.9 KB · RustRaw
//! A record made ONLY YOU from the new-record form: the create carries its//! mark in the same write (`create_record { audience: "only_you" }`, the//! owner's own app), so there is no instant in which a member's device, a//! member's assistant seat or a replica holds the record without its mark//! (`cotton_store::audience`).//!//! Synthetic throughout: a shared database with the owner's phone and one//! invented member's phone.mod support;use std::collections::BTreeMap;use cotton_tools::clock::Clock;use cotton_store::audience;use cotton_store::keep::{self, Keep};use cotton_store::protocol::derived_id::audience_id;use cotton_tools::mcp::dispatch::{self, Ctx};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use support::harness::Harness;use support::mcp::{call_tool_as_owner, call_tool_raw};const OWNER_PHONE: &str = "device:onlyyou-owner-phone";const MEMBER_PHONE: &str = "device:onlyyou-member-phone";const MEMBER: &str = "person-key-of-an-invented-member";const PRIVATE: &str = "Invented quiet plan for a surprise";const OPEN: &str = "Invented shared grocery run";fn text(value: &str) -> SqlValue {    SqlValue::Text(value.to_string())}/// A shared database with an invented member's phone admitted to it.fn shared() -> Harness {    let h = Harness::new();    h.run("UPDATE cotton_workspaces SET kind = 'shared'", &[]);    // The file's own device — the owner's phone that mints here — approved    // as the owner's, as a joined phone's file holds it: the fold places a    // writer by it.    h.run(        "INSERT OR IGNORE INTO cotton_devices (id, workspace_id, device_id, name, platform, approved_at, \         approved_by_device, created_at, updated_at) SELECT 'row-own-device', ?, device_id, 'Invented phone', 'ios', \         '2026-09-08T09:00:00.000Z', 'self', '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z' FROM _meta",        &[text(&h.workspace_id)],    );    h.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, platform, person_key, approved_at, \         approved_by_device, created_at, updated_at) VALUES ('row-member-phone', ?, ?, 'Invented phone', 'ios', ?, \         '2026-09-08T09:00:00.000Z', 'self', '2026-09-08T09:00:00.000Z', '2026-09-08T09:00:00.000Z')",        &[text(&h.workspace_id), text(MEMBER_PHONE), text(MEMBER)],    );    h}/// The owner's form: a todo made with or without Only you chosen.fn make(h: &Harness, title: &str, audience: Option<&str>) -> String {    let mut args = json!({ "table": "todo", "data": { "title": title } });    if let Some(audience) = audience {        args["audience"] = json!(audience);    }    let made = call_tool_as_owner(h, OWNER_PHONE, "create_record", args).json();    made["record"]["id"].as_str().expect("the made record's id").to_string()}fn audience_of(h: &Harness, record: &str) -> Option<String> {    h.with(|db| audience::of_record(db, "cotton_todos", record)).unwrap()}/// `(table, row, hlc)` of every receipt this file holds, oldest first.fn receipts(h: &Harness) -> Vec<(String, String, String)> {    h.all("SELECT tbl, row_id, hlc FROM _writes ORDER BY hlc", &[])        .into_iter()        .map(|row| {            let field = |key: &str| row[key].as_str().unwrap_or_default().to_string();            (field("tbl"), field("row_id"), field("hlc"))        })        .collect()}/// One read tool as the member's assistant seat — another person's token.fn as_seat(h: &Harness, name: &str, args: Value) -> String {    let scopes = vec!["read".to_string()];    let owner = format!("{}{MEMBER}", audience::SEAT_PREFIX);    let audit = |_: &str, _: &str| {};    let args: Map<String, Value> = args.as_object().cloned().unwrap_or_default();    let mut ctx = Ctx::new(        &h.db,        &h.file,        &owner,        "Invented member's assistant",        "seat-token",        &scopes,        h.clock.now(),        std::sync::Arc::clone(&h.random),        None,        &h.services.services,        &audit,    );    match dispatch::call_tool(&mut ctx, name, &args) {        Ok(answer) => answer.to_string(),        Err(refusal) => format!("refused: {}", refusal.message()),    }}/// RULE: A record the owner makes Only you from the new-record form is minted in the same write as its mark, the mark's receipt first, so no reader or replica ever has the record without it.#[test]fn the_create_carries_its_mark_in_one_write_mark_first() {    let h = shared();    let before = receipts(&h).len();    let record = make(&h, PRIVATE, Some("only_you"));    assert_eq!(audience_of(&h, &record).as_deref(), Some(audience::ONLY_YOU));    let hold = audience_id("cotton_todos", &record);    let written = receipts(&h);    let new = &written[before..];    let mark = new.iter().position(|(table, row, _)| table == audience::TABLE && *row == hold).expect("the mark's receipt");    let made = new.iter().position(|(table, row, _)| table == "cotton_todos" && *row == record).expect("the record's receipt");    assert!(mark < made, "the mark is minted before the record: {new:?}");    // One act: the phone queued both for the serving Mac together, the mark    // first — the push reads the outbox in stamp order.    let queued: Vec<String> = h        .all("SELECT row_id FROM _outbox ORDER BY hlc, op_id", &[])        .into_iter()        .filter_map(|row| row["row_id"].as_str().map(str::to_string))        .filter(|row| *row == hold || *row == record)        .collect();    assert_eq!(queued, vec![hold.clone(), record.clone()], "both travel, the mark first");}/// RULE: Only you is chosen when a record is made: a create then a separate mark, once a member's device is admitted, is refused, and the form's create never takes that path.#[test]fn a_create_then_a_mark_in_two_steps_is_refused() {    let h = shared();    let record = make(&h, PRIVATE, None);    let late = call_tool_as_owner(        &h,        OWNER_PHONE,        "set_audience",        json!({ "table": "todo", "id": record, "audience": "only_you" }),    );    assert!(late.is_error && late.text.contains(audience::ALREADY_SHARED), "{}", late.text);    assert_eq!(audience_of(&h, &record), None);}/// RULE: Only the owner's own app makes a record only-you at its create; an assistant asking for it is refused and nothing is written.#[test]fn an_assistant_never_makes_a_record_only_you() {    let h = shared();    let secret = h.connect(&["read", "write"], "Invented assistant");    let todos = h.count("SELECT COUNT(*) AS n FROM cotton_todos", &[]);    let asked = call_tool_raw(        &h,        &secret,        "create_record",        json!({ "table": "todo", "data": { "title": PRIVATE }, "audience": "only_you" }),    );    assert!(asked.is_error, "{}", asked.text);    assert_eq!(h.count("SELECT COUNT(*) AS n FROM cotton_todos", &[]), todos, "nothing was kept");    assert_eq!(h.count("SELECT COUNT(*) AS n FROM cotton_audiences", &[]), 0);}/// RULE: The form remembers nothing: a create that chose Only you and was refused leaves no hold behind, and the next record made without the choice is everyone's.#[test]fn the_next_record_is_everyones_unless_chosen_again() {    let h = shared();    let refused = call_tool_as_owner(        &h,        OWNER_PHONE,        "create_record",        json!({ "table": "todo", "data": {}, "audience": "only_you" }),    );    assert!(refused.is_error, "a todo with no title is refused: {}", refused.text);    let next = make(&h, OPEN, None);    assert_eq!(audience_of(&h, &next), None, "made without the choice, it is everyone's");    assert_eq!(h.count("SELECT COUNT(*) AS n FROM cotton_audiences", &[]), 0);}/// RULE: A record made Only you is in no read door a member has, from its first receipt: not the exchange answer, an opening by name, a first copy, nor any read of the member's assistant seat — by id or by its words.#[test]fn every_member_read_door_finds_nothing_of_a_record_made_only_you() {    let h = shared();    let held = make(&h, PRIVATE, Some("only_you"));    let open = make(&h, OPEN, None);    let hold = audience_id("cotton_todos", &held);    let names_held = |said: &str| said.contains(&held) || said.contains(PRIVATE) || said.contains(&hold);    h.with(|db| {        let keep = Keep::of_device(db, MEMBER_PHONE).unwrap();        let answered = every_op(db);        let sent = keep.leave_out(db, answered, 0).unwrap();        assert!(sent.iter().any(|op| op.row_id == open), "the shared todo travels");        assert!(!sent.iter().any(|op| names_held(&serde_json::to_string(op).unwrap())), "exchange: {sent:?}");        assert!(keep::open(db, &keep, "cotton_todos", &held, 0, 0).is_err(), "opened by name: refused");        assert!(keep::open(db, &keep, "cotton_audiences", &hold, 0, 0).is_err(), "its mark by name: refused");        // The owner's own devices hold it all.        let owners = Keep::of_device(db, OWNER_PHONE).unwrap();        let answered = every_op(db);        let kept = owners.leave_out(db, answered, 0).unwrap();        let at = |id: &str| kept.iter().position(|op| op.row_id == id);        assert!(at(&hold).is_some() && at(&held).is_some(), "the owner's other device is answered both");        assert!(at(&hold) < at(&held), "and reads the mark before the record it holds");    });    let listed = as_seat(&h, "list_records", json!({ "table": "todo" }));    assert!(listed.contains(&open), "the seat reads the shared database at all: {listed}");    for (tool, args) in [        ("list_records", json!({ "table": "todo" })),        ("list_todos", json!({})),        ("search_records", json!({ "query": "Invented" })),        ("summarize_records", json!({ "table": "todo" })),        ("today_agenda", json!({ "today": "2026-09-08" })),        ("get_record", json!({ "table": "todo", "id": held })),    ] {        let said = as_seat(&h, tool, args);        assert!(!names_held(&said), "{tool} told the member's assistant of the only-you record: {said}");    }    // The member's first copy, cut last: it removes what the member may not hold.    h.with(|db| {        let keep = Keep::of_device(db, MEMBER_PHONE).unwrap();        keep::cut_copy(db, &keep, 0).unwrap();        let left = db            .get(                "SELECT 1 AS x FROM _writes WHERE row_id IN (?1, ?2) UNION ALL SELECT 1 FROM cotton_todos WHERE id = ?1 \                 UNION ALL SELECT 1 FROM cotton_audiences WHERE id = ?2",                &[text(&held), text(&hold)],            )            .unwrap();        assert!(left.is_none(), "the member's copy holds nothing of it");    });}/// Every op this file would hand a peer starting from nothing, page by page:/// the kit and the shell a harness holds fill more than one page.fn every_op(db: &cotton_store::Driver) -> Vec<cotton_store::protocol::types::CottonOp> {    let mut seen = BTreeMap::new();    let mut ops = Vec::new();    loop {        let page = cotton_store::exchange::answer(db, &seen, 5_000).unwrap();        ops.extend(page.ops);        seen = page.cursors;        if !page.has_more {            return ops;        }    }}