//! The three owner verbs the day surface adds to `records_1` — answering an//! invitation, setting a guest list, and bringing the phone's contacts in.//!//! Every case runs over `dispatch::call_tool` against a real store.//!//! They live in their own file rather than in `mcp_records_1.rs` because their//! CALLER is different: every one of them is owner-scope, reached only through//! `Ctx::phone`, and none appears in any `tools/list`. `mcp_owner.rs` holds//! that half — an assistant refused each of them by name — over the//! catalogue's own list of owner tools, so nothing is written down twice.mod support;use std::sync::atomic::{AtomicU64, Ordering};use cotton_store::schema::ddl::SCHEMA_VERSION;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Value};use support::harness::Harness;use support::mcp::{call_tool_as_owner, ToolAnswer};/// The device the owner's app writes under. Synthetic, like every fixture in/// this tree ([nothing-real-ever-goes-in-cotton-s-public-tree]).const DEVICE: &str = "device:00000000000000000000000000";/// When every seeded row says it was written.const AT: &str = "2026-08-22T10:00:00.000Z";/// An op the way a device would mint one — the id derived from a per-process/// counter, never random.fn op(table: &str, row_id: &str, patch: Value) -> Value {static NEXT: AtomicU64 = AtomicU64::new(0);let n = NEXT.fetch_add(1, Ordering::Relaxed); json!({"opId": format!("01K{:023}", n),"deviceId": "device:seed","kind": "upsert","table": table,"rowId": row_id,"patch": patch,"hlc": format!("1700000000{:03}:0000:device:seed", n),"schemaVersion": SCHEMA_VERSION, })}fn owner(h: &Harness, name: &str, args: Value) -> ToolAnswer { call_tool_as_owner(h, DEVICE, name, args)}fn column(h: &Harness, table: &str, column: &str, id: &str) -> Option<String> { h.one( &format!("SELECT {column} AS value FROM {table} WHERE id = ?"), &[SqlValue::Text(id.to_string())], ) .and_then(|row| row.get("value").and_then(Value::as_str).map(str::to_string))}// ── respond_to_invite ───────────────────────────────────────────────────────/// A calendar with one invitation on it, and the invitation's id.structInvite { h: Harness, calendar: String, event: String,}fn invite(linked: bool) -> Invite {let h = Harness::new();let calendar = support::synthetic_uuid("calendar");let event = support::synthetic_uuid("invite");letmut patch = json!({"collection_id": calendar,"title": "Invite","starts_at": "2026-09-01T09:00:00.000Z","ends_at": "2026-09-01T10:00:00.000Z","all_day": false,"my_response": "needs_action","created_at": AT,"updated_at": AT, });if linked {// The three columns the TS test set by hand before responding. patch["gcal_id"] = json!("g1"); patch["sync_state"] = json!("synced"); } h.seed(&[ op("cotton_collections", &calendar, json!({"kind": "calendar","name": "Personal","is_default": true,"workspace_id": h.workspace_id,"created_at": AT, }), ), op("cotton_events", &event, patch), ]);Invite { h, calendar, event }}#[test]fn records_the_response_here_and_says_google_still_shows_the_earlier_reply() {let inv = invite(true);let answer = owner( &inv.h,"respond_to_invite", json!({ "id": inv.event, "response": "accepted" }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!(answer.json()["response"], json!("accepted")); assert_eq!( column(&inv.h, "cotton_events", "my_response", &inv.event).as_deref(),Some("accepted") );// Nothing writes to Google (Days, 20 Nov 2026), so nothing is marked for a// push, and the screen is told, in a sentence, that the answer stays here. assert_eq!( column(&inv.h, "cotton_events", "sync_state", &inv.event).as_deref(),Some("synced") ); assert_eq!(answer.json()["synced"], json!(true)); assert!(answer.json()["note"].as_str().is_some_and(|note| note.contains("kept here only")), "{}", answer.text);}#[test]fn an_event_that_lives_only_here_is_answered_without_a_sync_mark() {// `pendingMarkFor` returns nothing for a row with no `gcal_id`, and a// `pending` stamp on one would queue a push that has nowhere to go.let inv = invite(false);let answer = owner( &inv.h,"respond_to_invite", json!({ "id": inv.event, "response": "declined" }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!( column(&inv.h, "cotton_events", "my_response", &inv.event).as_deref(),Some("declined") ); assert_eq!(column(&inv.h, "cotton_events", "sync_state", &inv.event), None); assert_eq!(answer.json().get("synced"), None);}#[test]fn an_answer_the_calendar_has_no_word_for_is_refused_before_the_write() {let inv = invite(true);for bad in [json!("maybe"), json!("yes"), Value::Null] {let refused = owner( &inv.h,"respond_to_invite", json!({ "id": inv.event, "response": bad }), ); assert!(refused.is_error, "{bad} was accepted"); assert!(refused.text.contains("accepted"), "{}", refused.text); }// Untouched — the guard runs before the row is read, let alone written. assert_eq!( column(&inv.h, "cotton_events", "my_response", &inv.event).as_deref(),Some("needs_action") );}#[test]fn answering_an_invitation_that_is_not_there_says_so() {let inv = invite(true);let refused = owner( &inv.h,"respond_to_invite", json!({ "id": support::synthetic_uuid("gone"), "response": "accepted" }), ); assert!(refused.is_error);// One event on the calendar still, and no half-written second one. assert_eq!( inv.h.count("SELECT COUNT(*) FROM cotton_events WHERE collection_id = ?", &[SqlValue::Text(inv.calendar.clone())], ),1 );}// ── update_attendees ────────────────────────────────────────────────────────// The `invite(linked:)` fixture serves as the event here too: what matters to// the guest list is whether `gcal_id` is set, which is the one thing the guard// reads, and `invite(false)` is a plain local event on a real calendar.fn attendee_rows(h: &Harness, event_id: &str) -> Vec<serde_json::Map<String, Value>> { h.all("SELECT id, email, display_name, response FROM cotton_event_attendees \ WHERE event_id = ? ORDER BY created_at, id", &[SqlValue::Text(event_id.to_string())], )}fn person_links(h: &Harness, event_id: &str) -> Vec<String> { h.all("SELECT to_id FROM cotton_links \ WHERE from_kind = 'event' AND from_id = ? AND to_kind = 'person' ORDER BY to_id", &[SqlValue::Text(event_id.to_string())], ) .iter() .filter_map(|row| row.get("to_id").and_then(Value::as_str).map(str::to_string)) .collect()}fn a_person(h: &Harness, name: &str) -> String {let id = support::synthetic_uuid(name); h.seed(&[op("cotton_people", &id, json!({"workspace_id": h.workspace_id,"full_name": name,"contact_source": "manual","created_at": AT,"updated_at": AT, }), )]); id}#[test]fn the_list_replaces_and_every_response_goes_back_to_needs_action() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone()); owner( h,"update_attendees", json!({"eventId": event,"attendees": [ { "email": "one@example.invalid", "displayName": "Guest One" }, { "email": "two@example.invalid" }, ], }), );// An answered guest, exactly as a Google pull or a hand edit would leave// one — the rewrite must not preserve it. h.with(|db| { db.run("UPDATE cotton_event_attendees SET response = 'accepted' WHERE event_id = ?", &[SqlValue::Text(event.clone())], ) .expect("the answer lands"); });let answer = owner( h,"update_attendees", json!({"eventId": event,"attendees": [{ "email": "one@example.invalid", "displayName": "Guest One" }], }), ); assert!(!answer.is_error, "{}", answer.text);let rows = attendee_rows(h, &event); assert_eq!(rows.len(), 1, "a guest left out is removed: {rows:?}"); assert_eq!(rows[0]["email"], json!("one@example.invalid"));// The rule the description states: a list rewritten is a list nobody has// answered yet. assert_eq!(rows[0]["response"], json!("needs_action"));}#[test]fn an_empty_list_removes_everyone_rather_than_being_refused() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone()); owner( h,"update_attendees", json!({ "eventId": event, "attendees": [{ "email": "one@example.invalid" }] }), ); assert_eq!(attendee_rows(h, &event).len(), 1);let answer = owner( h,"update_attendees", json!({ "eventId": event, "attendees": [] }), ); assert!(!answer.is_error, "{}", answer.text); assert!(attendee_rows(h, &event).is_empty()); assert_eq!(answer.json()["attendees"], json!([]));}#[test]fn a_person_named_twice_is_two_guests_and_one_edge() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone());let quiet = a_person(h, "Quiet Tester");let answer = owner( h,"update_attendees", json!({"eventId": event,"attendees": [ { "displayName": "Quiet Tester", "personId": quiet }, { "email": "quiet@example.invalid", "personId": quiet }, ], }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!(attendee_rows(h, &event).len(), 2); assert_eq!(person_links(h, &event), vec![quiet.clone()]); assert_eq!(answer.json()["linkedPeople"], json!([quiet]));}#[test]fn the_old_edges_go_with_the_old_list() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone());let quiet = a_person(h, "Quiet Tester");let other = a_person(h, "Other Tester"); owner( h,"update_attendees", json!({"eventId": event,"attendees": [{ "displayName": "Quiet Tester", "personId": quiet }], }), ); assert_eq!(person_links(h, &event), vec![quiet.clone()]); owner( h,"update_attendees", json!({"eventId": event,"attendees": [{ "displayName": "Other Tester", "personId": other }], }), );// Not "both" — the edge to the guest who left has to go, or the person page// keeps drawing an event they were uninvited from. assert_eq!(person_links(h, &event), vec![other]);}#[test]fn rewriting_the_same_pair_does_not_trip_the_edge_tables_unique_index() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone());let quiet = a_person(h, "Quiet Tester");let guests = json!({"eventId": event,"attendees": [{ "displayName": "Quiet Tester", "personId": quiet }], }); owner(h, "update_attendees", guests.clone());// `cotton_links` carries UNIQUE (from_kind, from_id, to_kind, to_id): the// second pass deletes the edge and writes it again in one batch, and the// derived id makes both halves name the same row.let answer = owner(h, "update_attendees", guests); assert!(!answer.is_error, "{}", answer.text); assert_eq!(person_links(h, &event), vec![quiet]);}/// RULE: An edit that removes a guest and a later edit that re-adds them while keeping another both land, each guest's edge live at its first derived id: a Retract never blocks a later create at the same id.#[test]fn guest_edit_keeping_a_guest_succeeds() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone());let quiet = a_person(h, "Quiet Tester");let other = a_person(h, "Other Tester");let edge = |person: &str| { h.one("SELECT id FROM cotton_links WHERE from_kind = 'event' AND from_id = ? AND to_kind = 'person' AND to_id = ?", &[SqlValue::Text(event.clone()), SqlValue::Text(person.to_string())], ) .and_then(|row| row.get("id").and_then(Value::as_str).map(str::to_string)) };let both = json!({"eventId": event,"attendees": [ { "displayName": "Quiet Tester", "personId": quiet }, { "displayName": "Other Tester", "personId": other }, ], });let answer = owner(h, "update_attendees", both.clone()); assert!(!answer.is_error, "{}", answer.text);let (quiet_edge, other_edge) = (edge(&quiet).expect("quiet's edge"), edge(&other).expect("other's edge"));let answer = owner( h,"update_attendees", json!({ "eventId": event, "attendees": [{ "displayName": "Other Tester", "personId": other }] }), ); assert!(!answer.is_error, "removing a guest was refused: {}", answer.text); assert_eq!(edge(&quiet), None, "the removed guest's edge stands"); assert_eq!(edge(&other).as_deref(), Some(other_edge.as_str()), "the kept guest's edge moved");let answer = owner(h, "update_attendees", both); assert!(!answer.is_error, "re-adding a removed guest was refused: {}", answer.text); assert_eq!(edge(&quiet), Some(quiet_edge), "the re-added guest's edge did not land live at its first id"); assert_eq!(edge(&other), Some(other_edge), "the kept guest's edge did not land live at its first id");}/// RULE: An event's edge names a person in its own database: in a shared database, a guest whose person this database holds gets the edge, a guest whose person it does not hold (one from another database) gets none and is counted in droppedPersonLinks, and every guest row is still saved.#[test]fn update_attendees_drops_links_to_people_the_database_does_not_hold_and_saves_guests() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone()); h.with(|db| { db.run("UPDATE cotton_workspaces SET kind = 'shared' WHERE id = ?", &[SqlValue::Text(h.workspace_id.clone())], ) .expect("the database is a shared one"); });let teammate = a_person(h, "Team Tester");let elsewhere = support::synthetic_uuid("a person this database does not hold");let answer = owner( h,"update_attendees", json!({"eventId": event,"attendees": [ { "displayName": "Team Tester", "personId": teammate }, { "displayName": "Elsewhere Tester", "personId": elsewhere }, ], }), ); assert!(!answer.is_error, "{}", answer.text); assert_eq!(attendee_rows(h, &event).len(), 2, "both guests are saved"); assert_eq!(person_links(h, &event), vec![teammate.clone()]);let out = answer.json(); assert_eq!(out["linkedPeople"], json!([teammate])); assert_eq!(out["droppedPersonLinks"], json!(1));}#[test]fn a_google_synced_events_guests_belong_to_google() {let inv = invite(true);let answer = owner( &inv.h,"update_attendees", json!({"eventId": inv.event,"attendees": [{ "email": "one@example.invalid" }], }), ); assert!(answer.is_error, "{}", answer.text); assert!(answer.text.contains("Google"), "{}", answer.text); assert!(attendee_rows(&inv.h, &inv.event).is_empty());}#[test]fn a_guest_with_nothing_on_them_is_refused_before_anything_is_written() {let inv = invite(false);let (h, event) = (&inv.h, inv.event.clone()); owner( h,"update_attendees", json!({ "eventId": event, "attendees": [{ "email": "one@example.invalid" }] }), );let answer = owner( h,"update_attendees", json!({ "eventId": event, "attendees": [{}] }), ); assert!(answer.is_error, "{}", answer.text);// The refusal is BEFORE the deletes: the list that was there is still// there, rather than half-replaced by a call that then failed. assert_eq!(attendee_rows(h, &event).len(), 1);}#[test]fn an_event_this_workspace_does_not_hold_is_not_reachable() {let inv = invite(false);let answer = owner( &inv.h,"update_attendees", json!({"eventId": support::synthetic_uuid("nowhere"),"attendees": [], }), ); assert!(answer.is_error, "{}", answer.text); assert!(answer.text.contains("no event"), "{}", answer.text);}// ── sync_device_contacts ────────────────────────────────────────────────────//// The insert half, which is the half the phone's import screen calls.fn contact(device_id: &str, name: &str) -> Value { json!({ "deviceContactId": device_id, "fullName": name })}fn imported(h: &Harness) -> Vec<serde_json::Map<String, Value>> { h.all("SELECT id, full_name, contact_source, device_contact_id, birth_month, birth_day, \ birth_year FROM cotton_people ORDER BY full_name", &[], )}#[test]fn every_person_arrives_carrying_the_device_contacts_own_id() {let h = Harness::new();let answer = owner( &h,"sync_device_contacts", json!({"contacts": [ {"deviceContactId": "ABPerson-0001","fullName": "Quiet Tester","phones": ["+91 90000 00001", "", "+91 90000 00001"],"emails": ["quiet@example.invalid"],"org": "Nowhere Ltd","roleTitle": "Tester","city": "Nowhere", }, ], }), ); assert!(!answer.is_error, "{}", answer.text);let out = answer.json(); assert_eq!(out["inserted"], json!(1)); assert_eq!(out["skipped"], json!(0));let rows = imported(&h); assert_eq!(rows.len(), 1); assert_eq!(rows[0]["contact_source"], json!("import")); assert_eq!(rows[0]["device_contact_id"], json!("ABPerson-0001"));// Deduped and stripped, order preserved — `contacts.ts::cleanStrings`. assert_eq!(out["people"][0]["phones"], json!(["+91 90000 00001"]));}#[test]fn a_contact_already_linked_is_skipped_never_duplicated() {let h = Harness::new();let batch = json!({ "contacts": [contact("ABPerson-0001", "Quiet Tester")] }); owner(&h, "sync_device_contacts", batch.clone());let again = owner(&h, "sync_device_contacts", batch).json(); assert_eq!(again["inserted"], json!(0)); assert_eq!(again["skipped"], json!(1)); assert_eq!(imported(&h).len(), 1, "running twice is safe");}#[test]fn renaming_somebody_here_does_not_let_a_re_import_make_a_twin() {// The whole reason the id is the key rather than the name: the TS's own// idempotence test, and the defect the per-contact `create_person` loop had.let h = Harness::new();let batch = json!({ "contacts": [contact("ABPerson-0001", "Quiet Tester")] });let first = owner(&h, "sync_device_contacts", batch.clone()).json();let id = first["people"][0]["id"].as_str().expect("an id").to_string(); h.with(|db| { db.run("UPDATE cotton_people SET full_name = 'Renamed Tester' WHERE id = ?", &[SqlValue::Text(id)], ) .expect("the rename lands"); });let again = owner(&h, "sync_device_contacts", batch).json(); assert_eq!(again["skipped"], json!(1)); assert_eq!(imported(&h).len(), 1);}/// RULE (PEOPLE BUILD 1): a card whose number or address a person already/// holds is attached to that person, with its source kept, never made a twin.#[test]fn a_card_whose_number_a_person_holds_is_attached_not_a_twin() {let h = Harness::new();let made = owner(&h, "create_person", json!({ "fullName": "Asha Menon", "phones": ["+91 98765 43210"] })); assert!(!made.is_error, "{}", made.text);let out = owner( &h,"sync_device_contacts", json!({ "contacts": [{ "deviceContactId": "card-7", "fullName": "asha menon", "phones": ["+91 98765 43210", "098765 43210"] }] }), ) .json(); assert_eq!(out["inserted"], json!(0), "{out}"); assert_eq!(out["attached"], json!(1), "{out}");let people = h.all("SELECT id, full_name FROM cotton_people WHERE trashed_at IS NULL", &[]); assert_eq!(people.len(), 1, "one Asha: {people:?}");let sources = h.all("SELECT person, kind, source_id FROM cotton_person_source", &[]); assert_eq!(sources.len(), 1, "{sources:?}"); assert_eq!(sources[0]["person"], people[0]["id"]); assert_eq!(sources[0]["kind"], json!("address_book"));// Again: matched by its source first, so nothing changes.let again = owner(&h, "sync_device_contacts", json!({ "contacts": [{ "deviceContactId": "card-7", "fullName": "Asha Menon" }] })).json(); assert_eq!((again["inserted"].clone(), again["attached"].clone(), again["skipped"].clone()), (json!(0), json!(0), json!(1)));}fn who_of(h: &Harness, raw: &str) -> cotton_store::protocol::who::Who {let (kind, value) = cotton_store::protocol::who::who_key(cotton_store::protocol::person_handles::HandleKind::Phone, raw, None).expect("a number"); cotton_store::protocol::who::who(&h.db, &h.workspace_id, kind, &value).expect("who")}fn holder_names(who: &cotton_store::protocol::who::Who) -> Vec<String> {use cotton_store::protocol::who::Who;match who {Who::Nobody => Vec::new(),Who::One(holder) => vec![holder.full_name.clone()],Who::Shared(holders) => holders.iter().map(|h| format!("shared:{}", h.full_name)).collect(), }}fn live_names(h: &Harness) -> Vec<String> { h.all("SELECT full_name FROM cotton_people WHERE trashed_at IS NULL AND archived_at IS NULL ORDER BY full_name", &[]) .into_iter() .map(|row| row["full_name"].as_str().unwrap_or_default().to_string()) .collect()}/// RULE (PEOPLE BUILD 1b, review H1): an import never folds two people into/// one. Dad holds the landline and his mobile; Mom's card carries the/// landline and her own mobile: Mom is a person of her own, her mobile is/// hers, and the landline is shared by both, never Dad's as if certain. The/// same when both cards come in one run.#[test]fn a_shared_landline_never_folds_mom_into_dad() {let h = Harness::new();let dad = owner(&h, "create_person", json!({ "fullName": "Dad Kumar", "phones": ["+44 20 7946 0001", "+44 7700 900101"] })); assert!(!dad.is_error, "{}", dad.text);let out = owner( &h,"sync_device_contacts", json!({ "contacts": [{ "deviceContactId": "card-mom", "fullName": "Mom Kumar", "phones": ["+44 20 7946 0001", "+44 7700 900102"] }] }), ) .json(); assert_eq!((out["inserted"].clone(), out["attached"].clone()), (json!(1), json!(0)), "{out}"); assert_eq!(live_names(&h), ["Dad Kumar", "Mom Kumar"]); assert_eq!(holder_names(&who_of(&h, "+447700900102")), ["Mom Kumar"], "her mobile is hers"); assert_eq!(holder_names(&who_of(&h, "+442079460001")), ["shared:Dad Kumar", "shared:Mom Kumar"]);let both = Harness::new();let out = owner( &both,"sync_device_contacts", json!({ "contacts": [ { "deviceContactId": "card-dad", "fullName": "Dad Kumar", "phones": ["+44 20 7946 0001", "+44 7700 900101"] }, { "deviceContactId": "card-mom", "fullName": "Mom Kumar", "phones": ["+44 20 7946 0001", "+44 7700 900102"] }, ] }), ) .json(); assert_eq!(out["inserted"], json!(2), "{out}"); assert_eq!(holder_names(&who_of(&both, "+442079460001")), ["shared:Dad Kumar", "shared:Mom Kumar"]);}/// RULE (PEOPLE BUILD 1b, review H1): an office's main number on a colleague's/// card makes the colleague a person of their own, sharing the line.#[test]fn an_office_number_never_makes_two_colleagues_one() {let h = Harness::new();let made = owner(&h, "create_person", json!({ "fullName": "Priya Rao", "phones": ["+91 80 4000 1000"] })); assert!(!made.is_error, "{}", made.text);let out = owner( &h,"sync_device_contacts", json!({ "contacts": [{ "deviceContactId": "card-rahul", "fullName": "Rahul Iyer", "phones": ["+91 80 4000 1000"], "emails": ["rahul@office.invalid"] }] }), ) .json(); assert_eq!((out["inserted"].clone(), out["attached"].clone()), (json!(1), json!(0)), "{out}"); assert_eq!(live_names(&h), ["Priya Rao", "Rahul Iyer"]); assert_eq!(holder_names(&who_of(&h, "+918040001000")), ["shared:Priya Rao", "shared:Rahul Iyer"]);// Even under the same name, one shared handle never attaches: every handle must be one person's alone.let out = owner( &h,"sync_device_contacts", json!({ "contacts": [{ "deviceContactId": "card-p2", "fullName": "Priya Rao", "phones": ["+91 80 4000 1000"] }] }), ) .json(); assert_eq!(out["inserted"], json!(1), "{out}");}/// RULE (PEOPLE BUILD 1b, review H1): a recycled number an archived contact/// still carries attaches nobody to them: the new card is its own person and/// the number is theirs.#[test]fn a_recycled_number_with_an_archived_holder_is_the_new_cards() {let h = Harness::new();let made = owner(&h, "create_person", json!({ "fullName": "Old Holder", "phones": ["+44 7700 900777"] })).json();let old = made["id"].as_str().or(made["person"]["id"].as_str()).expect("an id").to_string();let archived = owner(&h, "archive_person", json!({ "id": old })); assert!(!archived.is_error, "{}", archived.text);let out = owner( &h,"sync_device_contacts", json!({ "contacts": [{ "deviceContactId": "card-new", "fullName": "Old Holder", "phones": ["+44 7700 900777"] }] }), ) .json(); assert_eq!((out["inserted"].clone(), out["attached"].clone()), (json!(1), json!(0)), "{out}");let new = out["people"][0]["id"].as_str().unwrap().to_string(); assert_ne!(new, old);match who_of(&h, "+447700900777") { cotton_store::protocol::who::Who::One(holder) => assert_eq!(holder.id, new), other => panic!("the new card's: {other:?}"), }}const PHONE_B: &str = "device:0000000000000000000000000B";/// One of his phones, over its own copy of the same database: its own device (`device`, `meta_device`) and its own/// stream of changes.fn phone(device: &str, meta_device: &str) -> Harness {structIds(u32, String);impl cotton_store::mint::IdSourceforIds {fn next_op_id(&mutself, _now_ms: i64) -> cotton_store::Result<String> {self.0 += 1;Ok(format!("01J{}{:012}", self.1, self.0)) } }let h = Harness::new_as_first(); h.run("UPDATE _meta SET device_id = ?", &[SqlValue::Text(meta_device.to_string())]);for known in [DEVICE, PHONE_B] { support::mcp::owner_at(&h.db, &h.workspace_id, known); }let tag: String = meta_device.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_uppercase(); cotton_store::mint::first_author( &h.db, device,None, cotton_store::mint::AuthorReason::TakeOver, &cotton_store::mint::Clock::wall(1_788_000_000_000), &mutIds(0, format!("{tag:0>11}")), cotton_store::mint::Held::Served, ) .expect("the phone's own stream"); h}fn on_b(h: &Harness, name: &str, args: Value) -> ToolAnswer { call_tool_as_owner(h, PHONE_B, name, args)}/// Everything `from` holds that `to` has not seen, folded into `to`: a sync.fn sync(from: &Harness, to: &Harness) {letmut seen = to.cursors();loop {let page = cotton_store::exchange::answer(&from.db, &seen, 5_000).expect("answers");let result = cotton_store::fold::fold_ops(&to.db, &page.ops).expect("folds"); assert!(result.rejected.is_empty(), "{:?}", result.rejected); assert!(result.waiting.is_empty(), "{:?}", result.waiting); seen = page.cursors;if !page.has_more {return; } }}fn sources_of(h: &Harness) -> Vec<(String, String)> { h.all("SELECT s.person AS person, p.full_name AS name FROM cotton_person_source s JOIN cotton_people p ON p.id = s.person ORDER BY p.full_name, s.id", &[]) .into_iter() .map(|row| (row["person"].as_str().unwrap_or_default().to_string(), row["name"].as_str().unwrap_or_default().to_string())) .collect()}const MEERA: &str = r#"{ "fullName": "Meera Nair", "phones": ["+91 98450 11111"] }"#;fn card(id: &str, body: &str) -> Value {letmut card: Value = serde_json::from_str(body).unwrap(); card["deviceContactId"] = json!(id); card}/// RULE (PEOPLE BUILD 1b, review M1): his second phone holds the same cards/// under its own ids; bringing them in there makes no twin, a card with only/// a name included: each lands on the contact the first phone made, and/// keeps its own source.#[test]fn the_second_phone_makes_no_twin() {let a = phone(DEVICE, "phone-a");let b = phone(PHONE_B, "phone-b");let first = owner(&a, "sync_device_contacts", json!({ "contacts": [card("A-1", MEERA), card("A-2", r#"{ "fullName": "Gran" }"#)] })).json(); assert_eq!(first["inserted"], json!(2), "{first}"); sync(&a, &b);let second = on_b(&b, "sync_device_contacts", json!({ "contacts": [card("B-77", MEERA), card("B-78", r#"{ "fullName": "gran" }"#)] })).json(); assert_eq!((second["inserted"].clone(), second["attached"].clone()), (json!(0), json!(2)), "{second}"); assert_eq!(live_names(&b), ["Gran", "Meera Nair"]); sync(&b, &a); assert_eq!(live_names(&a), ["Gran", "Meera Nair"]); assert_eq!(sources_of(&a).len(), 4, "each phone's card is kept: {:?}", sources_of(&a));}/// RULE (PEOPLE BUILD 1b, review M1): two phones bringing the same cards in/// at once, before either has synced, converge on one contact each once they/// do; two different cards that say the same thing on one phone stay two.#[test]fn two_phones_at_once_converge() {let a = phone(DEVICE, "phone-a");let b = phone(PHONE_B, "phone-b");let on_a = owner(&a, "sync_device_contacts", json!({ "contacts": [card("A-1", MEERA), card("A-2", r#"{ "fullName": "Uncle" }"#), card("A-3", r#"{ "fullName": "Uncle" }"#)] })).json();let on_b = on_b(&b, "sync_device_contacts", json!({ "contacts": [card("B-9", MEERA), card("B-8", r#"{ "fullName": "Uncle" }"#), card("B-7", r#"{ "fullName": "Uncle" }"#)] })).json(); assert_eq!((on_a["inserted"].clone(), on_b["inserted"].clone()), (json!(3), json!(3))); sync(&a, &b); sync(&b, &a);for phone in [&a, &b] { assert_eq!(live_names(phone), ["Meera Nair", "Uncle", "Uncle"], "one Meera and his two uncles, on each phone"); assert_eq!(sources_of(phone).len(), 6);let meera = phone.all("SELECT COUNT(*) AS n FROM cotton_person_handles WHERE normalised = '919845011111' AND trashed_at IS NULL", &[]); assert_eq!(meera[0]["n"], json!(1)); }}/// RULE (PEOPLE BUILD 1): every merged contact keeps its sources, so a later/// import of either card lands on the one kept and never makes a duplicate.#[test]fn after_a_merge_a_re_import_of_either_card_makes_no_twin() {let h = Harness::new();let first = owner( &h,"sync_device_contacts", json!({ "contacts": [ { "deviceContactId": "card-1", "fullName": "Ravi Shah", "phones": ["+44 7700 900001"] }, { "deviceContactId": "card-2", "fullName": "Ravi S (work)", "emails": ["ravi@work.invalid"] }, ] }), ) .json(); assert_eq!(first["inserted"], json!(2), "{first}");let a = first["people"][0]["id"].as_str().unwrap().to_string();let b = first["people"][1]["id"].as_str().unwrap().to_string();let merged = owner(&h, "merge_people", json!({ "survivorId": a, "duplicateId": b })); assert!(!merged.is_error, "{}", merged.text);let again = owner( &h,"sync_device_contacts", json!({ "contacts": [ { "deviceContactId": "card-1", "fullName": "Ravi Shah", "phones": ["+44 7700 900001"] }, { "deviceContactId": "card-2", "fullName": "Ravi S (work)", "emails": ["ravi@work.invalid"] }, ] }), ) .json(); assert_eq!(again["inserted"], json!(0), "{again}");let live = h.all("SELECT id FROM cotton_people WHERE trashed_at IS NULL AND archived_at IS NULL", &[]); assert_eq!(live.len(), 1, "{live:?}");let sources = h.all("SELECT person FROM cotton_person_source ORDER BY source_id", &[]); assert_eq!(sources.iter().map(|row| row["person"].clone()).collect::<Vec<_>>(), vec![json!(a), json!(a)], "both cards are Ravi's now");}/// RULE (PEOPLE BUILD 1): a contact may be a name alone, with no number or/// address; a re-import of that card still finds it.#[test]fn a_card_with_only_a_name_is_a_contact_and_found_again() {let h = Harness::new();let out = owner(&h, "sync_device_contacts", json!({ "contacts": [contact("card-9", "Grandma")] })).json(); assert_eq!(out["inserted"], json!(1), "{out}"); assert_eq!(h.all("SELECT id FROM cotton_person_handles", &[]).len(), 0);let again = owner(&h, "sync_device_contacts", json!({ "contacts": [contact("card-9", "Grandma")] })).json(); assert_eq!(again["skipped"], json!(1)); assert_eq!(imported(&h).len(), 1);}#[test]fn the_pass_guards_against_itself_as_well_as_against_the_file() {// Two entries sharing a device id in ONE call would hit// `uq_cotton_people_device_contact` and the fold refuses the whole batch,// so a single malformed pair would otherwise lose the entire sync.let h = Harness::new();let out = owner( &h,"sync_device_contacts", json!({"contacts": [ contact("ABPerson-0001", "Quiet Tester"), contact("ABPerson-0001", "Quiet Tester Again"), contact("ABPerson-0002", "Other Tester"), ], }), ) .json(); assert_eq!(out["inserted"], json!(2)); assert_eq!(out["skipped"], json!(1)); assert_eq!(imported(&h).len(), 2);}#[test]fn a_whole_birthday_lands_and_a_broken_one_never_costs_the_contact() {let h = Harness::new();let out = owner( &h,"sync_device_contacts", json!({"contacts": [ {"deviceContactId": "ABPerson-0001","fullName": "Aa Whole","birthday": { "month": 3, "day": 14, "year": 1990 }, }, {// Out of range — dropped, and the person is kept."deviceContactId": "ABPerson-0002","fullName": "Bb Broken","birthday": { "month": 13, "day": 40 }, }, {// Partial: no day at all."deviceContactId": "ABPerson-0003","fullName": "Cc Partial","birthday": { "month": 5 }, }, {// iOS writes 1604 for "no year"; nobody was born in 1604."deviceContactId": "ABPerson-0004","fullName": "Dd Yearless","birthday": { "month": 7, "day": 2, "year": 1604 }, }, ], }), ) .json(); assert_eq!(out["inserted"], json!(4), "nobody is lost to a bad date");let rows = imported(&h); assert_eq!(rows[0]["birth_month"], json!(3)); assert_eq!(rows[0]["birth_year"], json!(1990)); assert_eq!(rows[1]["birth_month"], json!(Value::Null)); assert_eq!(rows[2]["birth_month"], json!(Value::Null)); assert_eq!(rows[3]["birth_day"], json!(2)); assert_eq!(rows[3]["birth_year"], json!(Value::Null));}#[test]fn a_card_with_no_stable_id_or_no_name_is_refused_rather_than_filed() {let h = Harness::new();for bad in [ json!({ "contacts": [{ "fullName": "Quiet Tester" }] }), json!({ "contacts": [{ "deviceContactId": "ABPerson-0001" }] }), json!({ "contacts": [{ "deviceContactId": "ABPerson-0001", "fullName": " " }] }), ] {let answer = owner(&h, "sync_device_contacts", bad); assert!(answer.is_error, "{}", answer.text); } assert!(imported(&h).is_empty());}#[test]fn an_empty_batch_is_an_answer_not_a_refusal() {let h = Harness::new();let out = owner(&h, "sync_device_contacts", json!({ "contacts": [] })).json(); assert_eq!(out["inserted"], json!(0)); assert_eq!(out["skipped"], json!(0)); assert_eq!(out["people"], json!([]));}// RULE: An import run that added or skipped something leaves exactly one cotton_imports row naming its source and counts; a run that changed nothing leaves none.#[test]fn an_import_run_leaves_one_line_in_the_imports_history() {let h = Harness::new();let runs = |h: &Harness| { h.all("SELECT source, title, added, skipped, device_id FROM cotton_imports ORDER BY rowid", &[], ) };let batch = json!({ "contacts": [contact("ABPerson-0001", "Quiet Tester"), contact("ABPerson-0002", "Loud Tester")] }); owner(&h, "sync_device_contacts", batch.clone());let first = runs(&h); assert_eq!(first.len(), 1, "one run, one line"); assert_eq!(first[0]["source"], json!("contacts")); assert_eq!(first[0]["title"], json!("Phone contacts")); assert_eq!(first[0]["added"], json!(2)); assert_eq!(first[0]["skipped"], json!(0)); assert!(first[0]["device_id"].is_string(), "the device that ran it: {:?}", first[0]);// Running it again skips both — still a run, still one line of its own. owner(&h, "sync_device_contacts", batch);let second = runs(&h); assert_eq!(second.len(), 2); assert_eq!((second[1]["added"].clone(), second[1]["skipped"].clone()), (json!(0), json!(2)));// Nothing to sync is nothing to list. owner(&h, "sync_device_contacts", json!({ "contacts": [] })); assert_eq!(runs(&h).len(), 2, "an empty run writes no line");}#[test]fn the_snapshot_records_what_the_phone_showed_and_no_photo_it_did_not_read() {let h = Harness::new(); owner( &h,"sync_device_contacts", json!({"contacts": [{"deviceContactId": "ABPerson-0001","fullName": "Quiet Tester","emails": ["quiet@example.invalid"],"org": "Nowhere Ltd", }], }), );let row = h .one("SELECT device_contact_snapshot AS snap FROM cotton_people WHERE device_contact_id = ?", &[SqlValue::Text("ABPerson-0001".to_string())], ) .expect("the person is in the file");// The column is `Codec::Json`, so a raw SQL read hands back the TEXT the// codec would decode — parsed here rather than asserted as a string, which// would pin key order this test has no opinion about.let snapshot: Value = serde_json::from_str(row["snap"].as_str().expect("the snapshot's text")) .expect("the snapshot is JSON"); assert_eq!(snapshot["v"], json!(1)); assert_eq!(snapshot["fullName"], json!("Quiet Tester")); assert_eq!(snapshot["emails"], json!(["quiet@example.invalid"])); assert_eq!(snapshot["org"], json!("Nowhere Ltd"));// PORT GAP [contacts-import-brings-no-avatar]: both are null because no// photo crossed, not because the card had none. assert_eq!(snapshot["photoSha"], json!(Value::Null)); assert_eq!(snapshot["avatarKey"], json!(Value::Null));}#[test]fn an_import_leaves_ops_so_the_other_devices_see_the_new_people() {let h = Harness::new();let before = h.cursors(); owner( &h,"sync_device_contacts", json!({"contacts": [ contact("ABPerson-0001", "Quiet Tester"), contact("ABPerson-0002", "Other Tester"), ], }), );let tables: Vec<String> = h .ops_since(&before) .iter() .filter_map(|op| op.get("tbl").and_then(Value::as_str).map(str::to_string)) .collect();// Creation and the kit's import wrote first, so this author's// `cotton_authors` fact is already out; the run's line in the Imports// history follows the people, so the other devices list the import too. assert_eq!( tables,// each person with the source it came from, then each person's// history row (slice 6b). vec!["cotton_people", "cotton_person_source", "cotton_people", "cotton_person_source", "cotton_imports", "cotton_changes", "cotton_changes"],"{tables:?}" );}