//! A phone copy's served columns are read (27 Oct 2026): the copy adds to a //! shipped table the columns the object's definition names that this build's //! table lacks (`cotton_store::schema::package_shape::add_served`) — the //! running balance the object's money engine writes on every transaction — //! and every read of the table answers them, typed by the definition. //! //! Every value is invented ([nothing-real-ever-goes-in-cotton-s-public-tree]). mod support; use cotton_store::schema::package_shape::{add_served, served_column}; use rusqlite::types::Value as SqlValue; use serde_json::json; use support::harness::{synthetic_uuid, Harness}; use support::mcp::{call_tool, mint_token}; const AT: &str = "2026-10-20T09:00:00.000Z"; /// The author the personal object stamps every row it hands down as /// (`cotton_client::transport::object::OBJECT_AUTHOR`). const OBJECT: &str = "object"; /// The object's receipt of `patch` on money row `id`, folded as a pull folds /// it (`cotton_client::transport::object`): the object's author fact first, /// as a copy takes it before any row the object stamps, then a served change /// at the object's stamp. fn pulled_from_the_object(h: &Harness, id: &str, patch: serde_json::Value) { use cotton_store::actor::{Actor, JobName}; use cotton_store::mint::{served, served_change, ServedRow}; let actor = Actor::job(JobName::named("object-sync").expect("a job name")); let first = format!("{:013}:0000:{OBJECT}", 0); let fact: std::collections::BTreeMap = [ ("workspace_id", json!(h.workspace_id)), ("device_id", json!(OBJECT)), ("device_name", serde_json::Value::Null), ("minted_at", json!("1970-01-01T00:00:00.000Z")), ("reason", json!("first")), ("first_stamp", json!(first)), ] .into_iter() .map(|(key, value)| (key.to_owned(), value)) .collect(); let author = served("object-author-fact".into(), "cotton_authors", OBJECT, &first, &actor, ServedRow::Live(fact), None).expect("the object's author fact"); let stamp = format!("{:013}:0000:{OBJECT}", 1_760_950_800_000_i64); let serde_json::Value::Object(patch) = patch else { panic!("a patch is an object") }; let row = served_change(&h.db, format!("object-{id}"), "cotton_money_transactions", id, &stamp, &actor, patch).expect("the object's receipt"); let folded = cotton_store::fold::fold_pulled(&h.db, &[author, row]).expect("the pull folds"); assert!(folded.rejected.is_empty() && folded.waiting.is_empty(), "the object's receipts fold: {:?} {:?}", folded.rejected, folded.waiting); } /// RULE (owner, 27 Oct 2026): a transaction whose copy kept the balance columns of an object that works the run (its money row unsealed) answers them on its list row and on get_record — the card's facts read them from there — typed by the definition, and a column the object never filled is simply absent. #[test] fn a_copys_served_balance_columns_are_answered_on_every_read() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); let columns = [ served_column("balance_before_minor", "amount", false).expect("an amount"), served_column("balance_after_minor", "amount", false).expect("an amount"), served_column("balance_state", "choice", false).expect("a choice"), ]; add_served(&h.db, "cotton_money_transactions", &columns).expect("the copy keeps the object's columns"); // An object that still works the run: its money row unsealed. Once the // copy's transaction definition is sealed (e2e rulings R3, 16 Nov 2026) // the phone figures every balance itself, the object's too // (`money_run::a_sealed_money_row_is_figured_on_the_phone_alone`). h.db.run( &format!("UPDATE {} SET definition = json_remove(definition, '$.seal') WHERE id = 'transaction'", cotton_tools::definitions::TABLE_DEFINITIONS), &[], ) .expect("the object's unsealed money row"); let filled = synthetic_uuid("served-filled"); let empty = synthetic_uuid("served-empty"); h.run( "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, description, status, amount_minor, amount_known, direction, currency, created_at, updated_at) \ VALUES (?, ?, '2026-10-20', 'Invented grocer', 'actual', 25000, 1, 'out', 'INR', ?, ?)", &[SqlValue::Text(filled.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], ); // The object's balance, as the copy's pull leaves it on the row: under // the object's receipt, so the phone's money run, which works out every // row the object has not stamped (`cotton_tools::money_run`), leaves it // the object's at the next fold. h.db.run( "UPDATE cotton_money_transactions SET balance_before_minor = 120000, balance_after_minor = 95000, balance_state = 'ok' WHERE id = ?", &[SqlValue::Text(filled.clone())], ) .expect("the pulled balance"); pulled_from_the_object( &h, &filled, json!({"balance_before_minor": 120000, "balance_after_minor": 95000, "balance_state": "ok"}), ); h.run( "INSERT INTO cotton_money_transactions (id, workspace_id, occurred_on, description, status, amount_minor, amount_known, direction, currency, created_at, updated_at) \ VALUES (?, ?, '2026-10-19', 'Invented bakery', 'actual', 4000, 1, 'out', 'INR', ?, ?)", &[SqlValue::Text(empty.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], ); let record = call_tool(&h, &secret, "get_record", json!({"table": "transaction", "id": filled})); assert_eq!(record["data"]["balance_before_minor"], json!(120000), "{record}"); assert_eq!(record["data"]["balance_after_minor"], json!(95000), "{record}"); assert_eq!(record["data"]["balance_state"], json!("ok"), "{record}"); let list = call_tool(&h, &secret, "list_records", json!({"table": "transaction"})); let rows = list["records"].as_array().unwrap_or_else(|| panic!("{list}")); let row = |id: &str| rows.iter().find(|row| row["id"] == json!(id)).unwrap_or_else(|| panic!("{id} in {list}")); assert_eq!(row(&filled)["data"]["balance_after_minor"], json!(95000), "{list}"); assert!(row(&empty)["data"].get("balance_after_minor").is_none_or(|value| value.is_null()), "a balance the object never filled is not made up: {list}"); } /// RULE (owner, 29 Oct 2026): a served column the definition leaves the person (an event's kind, the object's calendar engine fills and the fan chooses) is written by an edit of the record into the copy's column — never refused as the engine's — and every read answers the choice. #[test] fn an_events_kind_is_written_into_the_copys_served_column() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Claude"); add_served(&h.db, "cotton_events", &[served_column("kind", "choice", false).expect("a choice")]).expect("the copy keeps the object's kind"); let event = synthetic_uuid("served-kind"); h.run( "INSERT INTO cotton_events (id, title, starts_at, created_at, updated_at) VALUES (?, 'Invented gym at 7', '2026-11-02T07:00:00.000Z', ?, ?)", &[SqlValue::Text(event.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], ); h.db.run("UPDATE cotton_events SET kind = 'gym' WHERE id = ?", &[SqlValue::Text(event.clone())]).expect("the object's kind"); let record = call_tool(&h, &secret, "get_record", json!({"table": "event", "id": event})); assert_eq!(record["data"]["kind"], json!("gym"), "{record}"); let changed = call_tool(&h, &secret, "update_record", json!({"table": "event", "id": event, "patch": {"kind": "dinner"}})); assert!(changed.get("error").is_none(), "{changed}"); let record = call_tool(&h, &secret, "get_record", json!({"table": "event", "id": event})); assert_eq!(record["data"]["kind"], json!("dinner"), "{record}"); assert_eq!(record["data"]["title"], json!("Invented gym at 7"), "the engine's columns are as they were: {record}"); } /// Related counts and decks include the object's link arrays as well as native /// engine links, counting each record once before a one-row page is taken. #[test] fn served_people_are_in_related_totals_and_the_deck_they_open() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Synthetic reader"); add_served(&h.db, "cotton_events", &[served_column("people", "link", true).unwrap()]).unwrap(); let person = synthetic_uuid("served-person"); let other = synthetic_uuid("served-other"); for n in 0..3 { let id = synthetic_uuid(&format!("served-event-{n}")); h.run("INSERT INTO cotton_events (id, title, starts_at, created_at, updated_at) VALUES (?, 'Synthetic event', '2026-11-02T07:00:00Z', ?, ?)", &[SqlValue::Text(id.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())]); h.db.run("UPDATE cotton_events SET people = ? WHERE id = ?", &[ SqlValue::Text(json!([if n < 2 { &person } else { &other }]).to_string()), SqlValue::Text(id.clone())]).unwrap(); // A native link to the same person must not double count the record. if n == 0 { h.run("INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at) VALUES (?, ?, 'event', ?, 'person', ?, ?)", &[SqlValue::Text(synthetic_uuid("served-native-link")), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(id), SqlValue::Text(person.clone()), SqlValue::Text(AT.into())]); } } let page = call_tool(&h, &secret, "list_records", json!({"table":"event", "where":{"people":person}, "limit":1})); assert_eq!(page["total"], json!(2), "{page}"); assert_eq!(page["records"].as_array().unwrap().len(), 1); let deck = call_tool(&h, &secret, "list_records", json!({"table":"event", "where":{"people":{"values":[person,other]}}})); assert_eq!(deck["total"], json!(3), "{deck}"); } /// RULE (Birthdays on a signed-in phone, 6 Nov 2026): a person whose birthday the object keeps as the date itself — the copy's served `birthday`, its month, day and year columns empty — has a birthday every read agrees on: a `where` that asks for one finds them, as a person whose month and day the phone keeps is found, and their record says it. #[test] fn a_birthday_the_object_keeps_whole_is_found_by_a_where() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Synthetic reader"); add_served(&h.db, "cotton_people", &[served_column("birthday", "date", false).expect("a date")]).expect("the copy keeps the object's birthday"); let served = synthetic_uuid("served-birthday"); let native = synthetic_uuid("native-birthday"); let none = synthetic_uuid("no-birthday"); for (id, name) in [(&served, "Invented Asha"), (&native, "Invented Bela"), (&none, "Invented Chitra")] { h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)", &[SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(name.into()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], ); } // The object's date, as the copy's pull leaves it; the phone's own month and day for the other. h.db.run("UPDATE cotton_people SET birthday = '1991-11-09' WHERE id = ?", &[SqlValue::Text(served.clone())]).expect("the pulled birthday"); h.db.run("UPDATE cotton_people SET birth_month = 3, birth_day = 2 WHERE id = ?", &[SqlValue::Text(native.clone())]).expect("the phone's birthday"); let found = call_tool(&h, &secret, "list_records", json!({"table": "person", "where": {"birthday": {"present": true}}})); let rows = found["records"].as_array().unwrap_or_else(|| panic!("{found}")); let mut ids: Vec<&str> = rows.iter().filter_map(|row| row["id"].as_str()).collect(); ids.sort(); let mut wanted = vec![served.as_str(), native.as_str()]; wanted.sort(); assert_eq!(ids, wanted, "{found}"); assert_eq!(found["total"], json!(2), "{found}"); let asha = rows.iter().find(|row| row["id"] == json!(served)).unwrap(); assert_eq!(asha["data"]["birthday"], json!("1991-11-09"), "{found}"); let without = call_tool(&h, &secret, "list_records", json!({"table": "person", "where": {"birthday": {"present": false}}})); let ids: Vec<&str> = without["records"].as_array().unwrap_or_else(|| panic!("{without}")).iter().filter_map(|row| row["id"].as_str()).collect(); assert_eq!(ids, [none.as_str()], "{without}"); let november = call_tool(&h, &secret, "list_records", json!({"table": "person", "where": {"birthday": {"month": 11}}})); let ids: Vec<&str> = november["records"].as_array().unwrap_or_else(|| panic!("{november}")).iter().filter_map(|row| row["id"].as_str()).collect(); assert_eq!(ids, [served.as_str()], "{november}"); } /// RULE (a birthday written on a signed-in phone, 6 Nov 2026): a birthday set or cleared on a copy that keeps the object's whole date moves both its forms in the one write, the phone's month, day and year and the object's `birthday`, so what the copy pushes says the day it shows; set over parts the phone already keeps, the new day wins in both. #[test] fn a_birthday_written_on_a_signed_in_copy_moves_both_its_forms() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Synthetic writer"); add_served(&h.db, "cotton_people", &[served_column("birthday", "date", false).expect("a date")]).expect("the copy keeps the object's birthday"); let id = synthetic_uuid("written-birthday"); h.run( "INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, birth_year, birthday, created_at, updated_at) VALUES (?, ?, 'Invented Dara', 3, 2, 1980, '1980-03-02', ?, ?)", &[SqlValue::Text(id.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], ); let forms = |h: &Harness| -> (Option, Option, Option, Option) { let row = h.db.get("SELECT birth_month, birth_day, birth_year, birthday FROM cotton_people WHERE id = ?", &[SqlValue::Text(id.clone())]).expect("read").expect("the person"); (row.int("birth_month"), row.int("birth_day"), row.int("birth_year"), row.text("birthday").map(str::to_string)) }; let set = call_tool(&h, &secret, "update_record", json!({"table": "person", "id": id, "patch": {"birthday": "1992-08-17"}})); assert!(set.get("error").is_none(), "{set}"); assert_eq!(forms(&h), (Some(8), Some(17), Some(1992), Some("1992-08-17".into()))); call_tool(&h, &secret, "update_record", json!({"table": "person", "id": id, "patch": {"birthday": "--12-25"}})); assert_eq!(forms(&h), (Some(12), Some(25), None, Some("--12-25".into()))); call_tool(&h, &secret, "update_record", json!({"table": "person", "id": id, "patch": {"birthday": null}})); assert_eq!(forms(&h), (None, None, None, None)); } /// RULE (12 Nov 2026): a shipped table with no engine /// (a device key, mapped onto `cotton_vault_keys`) answers the served columns /// its copy keeps like any other: Keys › Devices drew every device card with /// no title, because the device's `name` was never read off the copy. #[test] fn a_device_keys_served_name_is_answered_on_every_read() { let mut h = Harness::new(); let secret = mint_token(&mut h, &["read", "write"], "Synthetic owner"); add_served(&h.db, "cotton_vault_keys", &[served_column("name", "text", false).expect("a text")]).expect("the copy keeps the object's name"); let key = synthetic_uuid("served-device"); h.run( "INSERT INTO cotton_vault_keys (id, workspace_id, device_id, public_key, vmk_version, created_at, updated_at) \ VALUES (?, ?, 'synthetic-device', 'c3ludGhldGljLXB1YmxpYy1rZXk', 0, ?, ?)", &[SqlValue::Text(key.clone()), SqlValue::Text(h.workspace_id.clone()), SqlValue::Text(AT.into()), SqlValue::Text(AT.into())], ); h.db.run("UPDATE cotton_vault_keys SET name = 'Invented iPad' WHERE id = ?", &[SqlValue::Text(key.clone())]).expect("the object's name"); let record = call_tool(&h, &secret, "get_record_by_table", json!({"table": "vault_key", "id": key})); assert_eq!(record["data"]["name"], json!("Invented iPad"), "{record}"); let list = call_tool(&h, &secret, "list_records", json!({"table": "vault_key"})); let rows = list["records"].as_array().unwrap_or_else(|| panic!("{list}")); let row = rows.iter().find(|row| row["id"] == json!(key)).unwrap_or_else(|| panic!("{key} in {list}")); assert_eq!(row["data"]["name"], json!("Invented iPad"), "{list}"); }