Cotton code
905 lines · 33.7 KB · RustRaw
//! The wiring: the arguments this read defends, and the four queries plus the//! join, over a real replica.//!//! The DECISION is `cotton_core::rules::reminders`, whose 64 cases are the//! exhaustive ones. What this file proves is what only this layer can get//! wrong — that the queries read the columns the tools write, that recurrence//! comes from `expand_calendar` rather than from a second expansion here, that//! `my_response` and `all_day` survive the join, and that a missing zone is a//! refusal.//!//! The behaviour cases of `reconcileFromCache.test.ts` land here (permission//! and the master switch reduce to an EMPTY desired set, which is a wipe);//! its CACHE-READING cases are dropped, and the reason is that there is no//! cache: the TypeScript read the query client by key prefix and took the//! freshest of two sibling keys, and this read goes to the replica, which is//! strictly simpler and is the same answer.//!//! Every fixture is synthetic//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).use serde_json::json;use super::*;use crate::shell::client::phone_tests::attached;use crate::shell::client::ClientController;const ZONE: &str = "Asia/Kolkata";/// Tuesday 11 August 2026, 08:00 IST.const NOW: &str = "2026-08-11T02:30:00.000Z";fn args(pairs: &[(&str, Value)]) -> Map<String, Value> {    pairs        .iter()        .map(|(key, value)| ((*key).to_string(), value.clone()))        .collect()}/// The call every case makes, with a fresh install's switches.fn call_args() -> Map<String, Value> {    args(&[        ("now", json!(NOW)),        ("timeZone", json!(ZONE)),        ("prefs", json!({})),    ])}fn run(client: &ClientController, args: &Map<String, Value>) -> Value {    let request = read_request(args, None).expect("a readable request");    client        .with_writer(|replica| answer(replica, &request))        .expect("the read")}fn identifiers(answer: &Value) -> Vec<String> {    answer["reminders"]        .as_array()        .expect("a list")        .iter()        .map(|row| row["identifier"].as_str().unwrap_or_default().to_string())        .collect()}fn write(client: &ClientController, sql: &str, params: &[&str]) {    client        .with_writer(|replica| {            replica                .driver                .run(                    sql,                    &params                        .iter()                        .map(|value| {                            if *value == "\0" {                                rusqlite::types::Value::Null                            } else {                                rusqlite::types::Value::Text((*value).to_string())                            }                        })                        .collect::<Vec<_>>(),                )                .map_err(|error| error.to_string())        })        .expect("the row");}fn add_todo(client: &ClientController, id: &str, title: &str, due_at: &str, status: &str) {    write(        client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at)         VALUES (?,?,?,?,?,?,?)",        &[            id,            crate::fixture::WORKSPACE,            title,            status,            due_at,            NOW,            NOW,        ],    );}/// The one calendar every event fixture hangs off — `cotton_events` has a/// foreign key on it, which is the schema saying an event belongs to a/// calendar.fn ensure_calendar(client: &ClientController) {    write(        client,        "INSERT OR IGNORE INTO cotton_collections (id, workspace_id, kind, name, created_at)         VALUES (?,?,'calendar',?,?)",        &["cal-1", crate::fixture::WORKSPACE, "Synthetic", NOW],    );}fn add_event(client: &ClientController, id: &str, title: &str, starts_at: &str, rrule: &str) {    ensure_calendar(client);    write(        client,        "INSERT INTO cotton_events             (id, collection_id, title, starts_at, all_day, my_response, rrule, created_at, updated_at)         VALUES (?,?,?,?,0,'accepted',?,?,?)",        &[            id,            "cal-1",            title,            starts_at,            if rrule.is_empty() { "\0" } else { rrule },            NOW,            NOW,        ],    );}// ── the arguments ─────────────────────────────────────────────────────────#[test]fn a_call_with_no_zone_is_refused_and_the_refusal_says_why_nothing_is_guessed() {    // AGENTS.md's rule made a refusal: the host runs `TZ=UTC`, and a workspace    // with no zone is skipped rather than guessed.    let refusal = read_request(&args(&[("now", json!(NOW))]), None).expect_err("a refusal");    assert!(refusal.contains("timeZone"), "{refusal}");    assert!(refusal.contains("never guesses"), "{refusal}");}#[test]fn a_blank_zone_is_the_same_refusal_as_an_absent_one() {    for zone in [json!(""), json!("   "), Value::Null, json!(42)] {        assert!(            read_request(                &args(&[("now", json!(NOW)), ("timeZone", zone.clone())]),                None            )            .is_err(),            "{zone}"        );    }}#[test]fn a_caller_with_no_clock_and_no_named_now_is_told_which_of_the_two_is_missing() {    let refusal = read_request(&args(&[("timeZone", json!(ZONE))]), None).expect_err("a refusal");    assert!(refusal.contains("`now`"), "{refusal}");}#[test]fn the_clock_supplies_now_when_the_caller_does_not() {    let request =        read_request(&args(&[("timeZone", json!(ZONE))]), Some(NOW)).expect("a readable request");    assert_eq!(        cotton_store::protocol::js::to_iso_string(request.now_ms).as_deref(),        Some(NOW)    );}#[test]fn a_named_now_wins_over_the_clock_so_a_test_can_pin_an_instant() {    let named = "2026-01-01T00:00:00.000Z";    let request = read_request(        &args(&[("now", json!(named)), ("timeZone", json!(ZONE))]),        Some(NOW),    )    .expect("a readable request");    assert_eq!(        cotton_store::protocol::js::to_iso_string(request.now_ms).as_deref(),        Some(named)    );}#[test]fn a_now_that_is_not_an_instant_is_refused_rather_than_read_as_the_epoch() {    let refusal = read_request(        &args(&[("now", json!("yesterday")), ("timeZone", json!(ZONE))]),        None,    )    .expect_err("a refusal");    assert!(refusal.contains("not an instant"), "{refusal}");}#[test]fn the_horizon_defaults_to_the_engines_own_fourteen_and_refuses_nonsense() {    let with = |horizon: Value| {        read_request(            &args(&[                ("now", json!(NOW)),                ("timeZone", json!(ZONE)),                ("horizonDays", horizon),            ]),            None,        )        .expect("a readable request")        .horizon_days    };    let refusing = |horizon: Value| {        read_request(            &args(&[                ("now", json!(NOW)),                ("timeZone", json!(ZONE)),                ("horizonDays", horizon),            ]),            None,        )        .expect_err("a refusal")    };    // ABSENT is the only thing that takes the default.    assert_eq!(with(Value::Null), HORIZON_DAYS);    assert_eq!(with(json!(3)), 3);    // Zero is a real answer — today only — and not the same as absent.    assert_eq!(with(json!(0)), 0);    assert_eq!(with(json!(365)), 365);    // And a present-but-impossible one is a REFUSAL, never a clamp back to the    // default: the earlier shape here answered a fortnight to a caller that    // asked to schedule nothing, which is the silent fallback the zone rule two    // fields up exists to forbid. Each refusal NAMES the value, so a Swift    // caller reads what it sent rather than a generic "bad request".    assert!(refusing(json!(-1)).contains("-1"));    assert!(refusing(json!(10_000)).contains("10000"));    assert!(refusing(json!("7")).contains("whole number"));}#[test]fn the_prefs_come_in_through_the_one_migration_and_never_raw() {    // A stored record from an older build, or nonsense: either way it lands on    // a total shape rather than reaching the engine half-formed.    let request = read_request(        &args(&[            ("now", json!(NOW)),            ("timeZone", json!(ZONE)),            ("prefs", json!({ "enabled": "yes", "moodHour": 99 })),        ]),        None,    )    .expect("a readable request");    assert!(request.prefs.enabled);    // Absent prefs are a fresh install's, which is what a first pass sees.    let fresh = read_request(        &args(&[("now", json!(NOW)), ("timeZone", json!(ZONE))]),        None,    )    .expect("a readable request");    assert_eq!(fresh.prefs, NotificationPrefs::default());}// ── the queries, over a real replica ──────────────────────────────────────#[test]fn a_file_with_nothing_in_it_answers_an_empty_set_rather_than_a_refusal() {    let (_dir, client) = attached();    let answer = run(&client, &call_args());    assert_eq!(answer["count"], json!(0));    assert_eq!(answer["reminders"], json!([]));    // What the pass was decided against, echoed back — a scheduler that    // reconciled against a horizon it did not ask for would cancel everything    // past the one it thought it had.    assert_eq!(answer["horizonDays"], json!(14));    assert_eq!(answer["timeZone"], json!(ZONE));    assert_eq!(answer["now"], json!(NOW));}#[test]fn a_todo_reaches_the_answer_with_its_title_its_instant_and_its_name() {    let (_dir, client) = attached();    add_todo(        &client,        "todo-1",        "Water the alpaca",        "2026-08-12T12:00:00.000Z",        "open",    );    let answer = run(&client, &call_args());    assert_eq!(identifiers(&answer), ["cotton:todo:todo-1:20260812T1730"]);    let row = &answer["reminders"][0];    assert_eq!(row["kind"], json!("todo"));    assert_eq!(row["recordId"], json!("todo-1"));    assert_eq!(row["title"], json!("Water the alpaca"));    assert_eq!(row["body"], json!("Due now"));    assert_eq!(row["at"], json!("2026-08-12T12:00:00.000Z"));}#[test]fn a_done_todo_is_read_and_then_refused_by_the_engine_rather_than_filtered_in_sql() {    // The status rule lives in ONE place. This asserts the query hands the row    // over — a `WHERE status = 'open'` here would be the same rule twice, and    // the copy without the tests.    let (_dir, client) = attached();    add_todo(        &client,        "todo-1",        "Already done",        "2026-08-12T12:00:00.000Z",        "done",    );    let answer = run(&client, &call_args());    assert_eq!(answer["count"], json!(0));    client        .with_writer(|replica| {            let pool = todos(replica)?;            let done = pool                .iter()                .find(|row| row.id == "todo-1")                .expect("the query handed the done todo over rather than filtering it");            assert_eq!(done.status, "done");            Ok(())        })        .expect("the pool");}#[test]fn an_event_reminds_ten_minutes_out_and_carries_the_row_s_title() {    let (_dir, client) = attached();    add_event(        &client,        "event-1",        "Standup",        "2026-08-12T03:30:00.000Z",        "",    );    let answer = run(&client, &call_args());    assert_eq!(identifiers(&answer), ["cotton:event:event-1:20260812T0850"]);    assert_eq!(answer["reminders"][0]["title"], json!("Standup"));    assert_eq!(        answer["reminders"][0]["body"],        json!("Starts in 10 minutes")    );}#[test]fn a_recurring_event_gets_one_reminder_per_occurrence_from_the_engine_that_owns_recurrence() {    // The whole of P14's sentence: the recurrence is `expand_calendar`'s — the    // SAME expansion `/calendar` uses — and this read never re-decides when a    // thing repeats.    let (_dir, client) = attached();    add_event(        &client,        "weekly",        "Standup",        "2026-08-12T03:30:00.000Z",        "FREQ=WEEKLY",    );    let answer = run(&client, &call_args());    assert_eq!(        identifiers(&answer),        [            "cotton:event:weekly:20260812T0850",            "cotton:event:weekly:20260819T0850",        ],        "a fortnight of a weekly event is two reminders, not one and not fourteen"    );}#[test]fn a_declined_event_and_an_all_day_one_survive_the_join_and_are_then_skipped() {    // `all_day` and `my_response` live on the ROW, not on the expansion, so    // this is the case a join that dropped them would pass anyway — both would    // simply become ordinary reminders.    let (_dir, client) = attached();    add_event(        &client,        "declined",        "No thanks",        "2026-08-12T03:30:00.000Z",        "",    );    write(        &client,        "UPDATE cotton_events SET my_response = 'declined' WHERE id = ?",        &["declined"],    );    add_event(&client, "allday", "Holiday", "2026-08-12T03:30:00.000Z", "");    write(        &client,        "UPDATE cotton_events SET all_day = 1 WHERE id = ?",        &["allday"],    );    let answer = run(&client, &call_args());    assert_eq!(answer["count"], json!(0));}#[test]fn a_person_with_a_birth_day_becomes_a_nine_am_reminder_naming_their_age() {    let (_dir, client) = attached();    write(        &client,        "INSERT INTO cotton_people             (id, workspace_id, full_name, birth_month, birth_day, birth_year, created_at, updated_at)         VALUES (?,?,?,8,17,1992,?,?)",        &["p1", crate::fixture::WORKSPACE, "Asha", NOW, NOW],    );    let answer = run(&client, &call_args());    assert_eq!(identifiers(&answer), ["cotton:birthday:p1:20260817T0900"]);    let row = &answer["reminders"][0];    // A tap opens the PERSON — a birthday has no record of its own.    assert_eq!(row["recordId"], json!("p1"));    assert_eq!(row["title"], json!("Asha's birthday"));    assert_eq!(row["body"], json!("Turns 34 today"));}/// A signed-in copy: the object's definition serves people's `birthday`/// whole, and the copy keeps it in a served column.fn keeps_the_whole_birthday(client: &ClientController) {    use cotton_store::schema::package_shape::{add_served, served_column};    client        .with_writer(|replica| {            let column = served_column("birthday", "date", false).map_err(|error| error.to_string())?;            add_served(replica.driver, "cotton_people", &[column]).map_err(|error| error.to_string())        })        .expect("the copy keeps the object's birthday");}// RULE (B1, 6 Nov 2026): a person whose birthday came whole from the object — the month, day and year empty — is reminded of like one the phone made, with the age they turn.#[test]fn a_birthday_the_object_keeps_whole_becomes_a_reminder_naming_their_age() {    let (_dir, client) = attached();    keeps_the_whole_birthday(&client);    write(        &client,        "INSERT INTO cotton_people (id, workspace_id, full_name, birthday, created_at, updated_at)         VALUES (?,?,?,'1992-08-17',?,?)",        &["p1", crate::fixture::WORKSPACE, "Asha", NOW, NOW],    );    let answer = run(&client, &call_args());    assert_eq!(identifiers(&answer), ["cotton:birthday:p1:20260817T0900"]);    let row = &answer["reminders"][0];    assert_eq!(row["recordId"], json!("p1"));    assert_eq!(row["title"], json!("Asha's birthday"));    assert_eq!(row["body"], json!("Turns 34 today"));}// RULE (B1, 6 Nov 2026): a birthday the object keeps whole with no year ("--08-17") is reminded of on its day, naming no age; and the phone's own month and day win over the whole date where both are set.#[test]fn a_whole_birthday_with_no_year_is_reminded_of_with_no_age_and_the_phones_parts_win() {    let (_dir, client) = attached();    keeps_the_whole_birthday(&client);    write(        &client,        "INSERT INTO cotton_people (id, workspace_id, full_name, birthday, created_at, updated_at)         VALUES (?,?,?,'--08-17',?,?)",        &["p1", crate::fixture::WORKSPACE, "Ravi", NOW, NOW],    );    write(        &client,        "INSERT INTO cotton_people (id, workspace_id, full_name, birth_month, birth_day, birthday, created_at, updated_at)         VALUES (?,?,?,8,20,'--08-30',?,?)",        &["p2", crate::fixture::WORKSPACE, "Bela", NOW, NOW],    );    let answer = run(&client, &call_args());    assert_eq!(identifiers(&answer), ["cotton:birthday:p1:20260817T0900", "cotton:birthday:p2:20260820T0900"]);    assert_eq!(answer["reminders"][0]["title"], json!("Ravi's birthday"));    assert_eq!(answer["reminders"][0]["body"], Value::Null, "no year, no age: {answer}");}#[test]fn an_archived_person_has_no_birthday_reminder() {    // They are out of the directory, and a notification naming them would be    // the one place they came back.    let (_dir, client) = attached();    write(        &client,        "INSERT INTO cotton_people             (id, workspace_id, full_name, birth_month, birth_day, archived_at, created_at, updated_at)         VALUES (?,?,?,8,17,?,?,?)",        &["p1", crate::fixture::WORKSPACE, "Gone", NOW, NOW, NOW],    );    assert_eq!(run(&client, &call_args())["count"], json!(0));}// Nothing asks about mood on a schedule (owner, 11 Oct 2026): a device whose// stored switches still say `mood` and `moodHour` from an older build is// reminded of nothing, moments or none.#[test]fn an_old_mood_switch_schedules_nothing() {    let (_dir, client) = attached();    write(        &client,        "INSERT INTO cotton_moods (id, workspace_id, at, line, emotions, emotions_by, local_day, created_at, updated_at)         VALUES (?,?,?,?,'[\"okay\"]','user',?,?,?)",        &[            "m1",            crate::fixture::WORKSPACE,            NOW,            "a synthetic moment",            "2026-08-11",            NOW,            NOW,        ],    );    let mut old = call_args();    old.insert(        "prefs".to_string(),        json!({ "categories": { "mood": true }, "moodHour": 21 }),    );    assert_eq!(run(&client, &old)["count"], json!(0));}// ── the master switch, which is a WIPE and not a no-op ─────────────────────#[test]fn the_master_switch_off_answers_an_empty_set_which_is_how_the_queue_is_wiped() {    // `reconcileFromCache.test.ts`'s behaviour case, ported. An empty desired    // set is not "nothing to do" — reconciled against a queue it cancels every    // Cotton reminder, which is exactly what switching notifications off, or    // revoking the OS permission, has to mean. The PERMISSION half of that gate    // stays in Swift, where the OS is.    let (_dir, client) = attached();    add_todo(        &client,        "todo-1",        "Water the alpaca",        "2026-08-12T12:00:00.000Z",        "open",    );    assert_eq!(run(&client, &call_args())["count"], json!(1));    let mut off = call_args();    off.insert("prefs".to_string(), json!({ "enabled": false }));    assert_eq!(run(&client, &off)["count"], json!(0));}#[test]fn a_category_off_removes_its_kind_and_leaves_the_others_standing() {    let (_dir, client) = attached();    add_todo(        &client,        "todo-1",        "Water the alpaca",        "2026-08-12T12:00:00.000Z",        "open",    );    add_event(        &client,        "event-1",        "Standup",        "2026-08-12T03:30:00.000Z",        "",    );    let mut without_todos = call_args();    without_todos.insert(        "prefs".to_string(),        json!({ "categories": { "reminders": false } }),    );    assert_eq!(        identifiers(&run(&client, &without_todos)),        ["cotton:event:event-1:20260812T0850"]    );}// ── the zone, end to end ──────────────────────────────────────────────────#[test]fn the_zone_decides_the_morning_and_two_zones_do_not_agree_on_it() {    // The same date-only todo read twice. Under a UTC fallback both would name    // one instant, which is the defect this argument exists to prevent.    let (_dir, client) = attached();    // Local midnight in Kolkata on 13 August.    add_todo(        &client,        "todo-1",        "A day-shaped promise",        "2026-08-12T18:30:00.000Z",        "open",    );    let kolkata = identifiers(&run(&client, &call_args()));    let mut utc = call_args();    utc.insert("timeZone".to_string(), json!("UTC"));    let elsewhere = identifiers(&run(&client, &utc));    assert_eq!(kolkata, ["cotton:todo:todo-1:20260813T0900"]);    assert_ne!(kolkata, elsewhere, "{elsewhere:?}");}#[test]fn an_unknown_zone_reaches_the_caller_as_a_refusal_naming_it() {    // Caught at the EDGE, where the zone is an argument: `read_request`    // resolves it, so `call` answers `bad_request` with the zone named rather    // than `unreadable`, which would send a Swift caller looking at the    // database over its own typo.    let mut nowhere = call_args();    nowhere.insert("timeZone".to_string(), json!("Middle/Earth"));    let refusal = read_request(&nowhere, None).expect_err("a refusal");    assert!(refusal.contains("Middle/Earth"), "{refusal}");}#[test]fn the_arithmetic_refuses_an_unknown_zone_too_even_though_the_edge_gets_there_first() {    // The backstop, asserted so it stays one: `answer` does the local-hour    // arithmetic and cannot be allowed to guess a zone if some future caller    // ever reaches it without passing the edge. Built by hand for that reason —    // `read_request` would refuse this before it could be constructed.    let (_dir, client) = attached();    let mut request = read_request(&call_args(), None).expect("a readable request");    request.timezone = "Middle/Earth".to_string();    let refusal = client        .with_writer(|replica| answer(replica, &request))        .expect_err("a refusal");    assert!(refusal.contains("Middle/Earth"), "{refusal}");}// ── the method, and the read it is written to become ──────────────────────#[test]fn the_answer_function_has_the_read_tables_own_signature() {    // The whole reason this is a method today rather than a `read.reminders`:    // the seam that lets a read name no screen belongs to the extensions lane.    // When it lands, THIS function is registered unchanged — so the signature    // is asserted here rather than trusted to a comment.    let entry: fn(&ReadFile<'_>, &Map<String, Value>) -> Result<Value, String> = desired;    let (_dir, client) = attached();    let answered = client        .with_writer(|replica| entry(replica, &call_args()))        .expect("the read");    assert_eq!(answered["count"], json!(0));}#[test]fn the_read_signature_has_no_clock_and_says_so_rather_than_defaulting_to_the_epoch() {    let (_dir, client) = attached();    let mut clockless = call_args();    clockless.remove("now");    let refusal = client        .with_writer(|replica| desired(replica, &clockless))        .expect_err("a refusal");    assert!(refusal.contains("`now`"), "{refusal}");}#[test]fn the_method_defaults_now_from_the_injected_clock() {    // `attached()` builds the controller with a `FixedClock`, so this is the    // clock seam reaching the one rule that needs it — never a wall clock.    let (_dir, _client) = attached();    let dir = tempfile::tempdir().expect("a temp container");    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone {            container_path: dir.path().to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: Some("0.1.0".to_string()),        time_zone: Some(ZONE.to_string()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    // No replica on this one, so the refusal is about the FILE and never about    // a missing `now` — which is the assertion: the clock supplied it.    let refusal = call(        &handle,        &json!({ "args": { "timeZone": ZONE, "prefs": {} } }),    )    .expect_err("a refusal");    assert_eq!(refusal.code, "unreadable");}// ── `reminders.reconcile` — the diff, over the same pass ───────────────────/// A phone core whose container already holds the connection record and the/// seeded replica, opened as a HANDLE — `reconcile_call` takes one, and the/// point of these cases is the method rather than the engine underneath it.fn attached_handle() -> (tempfile::TempDir, crate::handle::CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let layout = cotton_client::layout::Layout::new(dir.path());    std::fs::create_dir_all(layout.client_dir()).expect("the client folder");    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&json!({            "mode": "remote",            "baseUrl": "https://server.invalid",            "workspaceId": crate::fixture::WORKSPACE,            "ownerId": crate::fixture::OWNER,            "connectedAt": "2026-09-08T10:00:00.000Z",        }))        .expect("json"),    )    .expect("the connection record");    let path = layout.replica(crate::fixture::WORKSPACE);    std::fs::create_dir_all(path.parent().expect("a parent")).expect("the replica folder");    drop(crate::fixture::seeded(&path));    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone {            container_path: dir.path().to_string_lossy().to_string(),            previous_container_path: None,        },        app_version: Some("0.1.0".to_string()),        time_zone: Some(ZONE.to_string()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    (dir, handle)}/// The one todo every arm below is decided about, and the identifier the engine/// mints for it — written out rather than read back from the answer, so a/// change to the identifier shape fails HERE and not silently everywhere.const TODO_AT: &str = "2026-08-12T12:00:00.000Z";const TODO_ID: &str = "cotton:todo:todo-1:20260812T1730";fn reconcile_request(held: Value) -> Value {    json!({ "args": { "now": NOW, "timeZone": ZONE, "prefs": {}, "held": held } })}fn seed_one_todo(handle: &crate::handle::CottonHandle) {    write(        &handle.client(),        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at) \         VALUES (?, ?, ?, 'open', ?, ?, ?)",        &[            "todo-1",            crate::fixture::WORKSPACE,            "Water the alpaca",            TODO_AT,            TODO_AT,            TODO_AT,        ],    );}#[test]fn holding_nothing_schedules_the_whole_desired_set_and_cancels_nothing() {    let (_dir, handle) = attached_handle();    seed_one_todo(&handle);    let answer = reconcile_call(&handle, &reconcile_request(json!([]))).expect("an answer");    assert_eq!(answer["cancel"], json!([]));    assert_eq!(answer["noop"], json!(false));    // The FULL row, because Swift builds a `UNNotificationRequest` out of it —    // an identifier alone would send it back for a second answer that could    // disagree with this one.    let row = &answer["schedule"][0];    assert_eq!(row["identifier"], json!(TODO_ID));    assert_eq!(row["kind"], json!("todo"));    assert_eq!(row["title"], json!("Water the alpaca"));    assert_eq!(row["at"], json!(TODO_AT));    assert_eq!(answer["schedule"].as_array().expect("a list").len(), 1);}#[test]fn holding_exactly_what_is_wanted_is_the_noop_every_tick_takes() {    let (_dir, handle) = attached_handle();    seed_one_todo(&handle);    let answer =        reconcile_call(&handle, &reconcile_request(json!([TODO_ID]))).expect("an answer");    assert_eq!(answer["schedule"], json!([]));    assert_eq!(answer["cancel"], json!([]));    // The whole reason a caller asks: two `UNUserNotificationCenter` calls it    // can skip, on the overwhelmingly common tick where nothing changed.    assert_eq!(answer["noop"], json!(true));}#[test]fn a_cotton_identifier_nobody_wants_any_more_is_cancelled() {    let (_dir, handle) = attached_handle();    seed_one_todo(&handle);    // The shape of a todo that was completed, or whose due date moved: the    // instant is IN the identifier, so a moved reminder is a cancel and a    // schedule rather than an edit.    let stale = "cotton:todo:todo-1:20260810T1730";    let answer = reconcile_call(&handle, &reconcile_request(json!([stale, TODO_ID])))        .expect("an answer");    assert_eq!(answer["schedule"], json!([]));    assert_eq!(answer["cancel"], json!([stale]));    assert_eq!(answer["noop"], json!(false));}#[test]fn a_foreign_identifier_is_left_alone_rather_than_cancelled() {    // `getPendingNotificationRequests` answers EVERYTHING the app holds,    // including whatever a future feature scheduled. Cancelling one of those    // would be this method deleting another feature's notifications, so the    // `cotton:` prefix is the whole rule and it lives in the engine.    let (_dir, handle) = attached_handle();    seed_one_todo(&handle);    let answer = reconcile_call(        &handle,        &reconcile_request(json!(["some-other-feature:42", TODO_ID])),    )    .expect("an answer");    assert_eq!(answer["schedule"], json!([]));    assert_eq!(answer["cancel"], json!([]));    assert_eq!(answer["noop"], json!(true));}#[test]fn held_is_optional_and_a_non_string_entry_is_dropped_rather_than_refused() {    // iOS cannot send anything but strings here; a malformed call is a bug on    // the Swift side and the useful answer is the full schedule, not a refusal    // that leaves a person with no reminders at all.    let (_dir, handle) = attached_handle();    seed_one_todo(&handle);    let without = reconcile_call(        &handle,        &json!({ "args": { "now": NOW, "timeZone": ZONE, "prefs": {} } }),    )    .expect("an answer");    assert_eq!(without["schedule"].as_array().expect("a list").len(), 1);    let noisy =        reconcile_call(&handle, &reconcile_request(json!([7, TODO_ID]))).expect("an answer");    assert_eq!(noisy["noop"], json!(true));}#[test]fn the_diff_is_decided_against_the_same_zone_and_instant_it_echoes_back() {    let (_dir, handle) = attached_handle();    let answer = reconcile_call(&handle, &reconcile_request(json!([]))).expect("an answer");    assert_eq!(answer["timeZone"], json!(ZONE));    assert_eq!(answer["now"], json!(NOW));}#[test]fn reconcile_refuses_an_unknown_zone_at_the_edge_like_the_desired_set_does() {    let (_dir, handle) = attached_handle();    let refusal = reconcile_call(        &handle,        &json!({ "args": { "now": NOW, "timeZone": "Middle/Earth", "prefs": {}, "held": [] } }),    )    .expect_err("a refusal");    // `bad_request` and not `unreadable`: the caller's typo is not the file's    // problem, and sending Swift to look at the database over one would be the    // wrong screen.    assert_eq!(refusal.code, "bad_request");    assert!(refusal.message.contains("Middle/Earth"), "{}", refusal.message);}/// RULE (Android Todos, 12 Nov 2026): a pass that names no `prefs` is/// decided by this device's own preferences — every switch on where it kept/// none, nothing at all once its master switch is off.#[test]fn a_pass_naming_no_prefs_obeys_this_devices_own() {    let (_dir, handle) = attached_handle();    seed_one_todo(&handle);    let ask = json!({ "args": { "now": NOW, "timeZone": ZONE, "held": [] } });    let fresh = reconcile_call(&handle, &ask).expect("an answer");    assert_eq!(fresh["schedule"][0]["identifier"], json!(TODO_ID));    crate::methods::dispatch(&handle, "device.notifications.asked", &json!({"at": "2026-08-01T00:00:00Z"})).expect("asked");    crate::methods::dispatch(&handle, "device.preferences.set", &json!({"patch": {"notify": false}})).expect("off");    let off = reconcile_call(&handle, &ask).expect("an answer");    assert_eq!(off["schedule"], json!([]), "{off}");}/// An event's alert through its life, as a phone's passes see it (Days on Android, coordinator 24 Nov 2026: "an/// event alert ... is cleared when the event moves or is deleted"). The event arrives as any row does, by this phone/// or by sync from another device: the pass reads the copy, so where the row came from does not enter. Moved, its/// old alarm is cancelled and the new one scheduled; deleted, cancelled; and nothing stays held that is not wanted.#[test]fn an_event_s_alert_follows_it_when_it_moves_and_goes_when_it_is_deleted() {    let (_dir, handle) = attached_handle();    let client = handle.client();    add_event(&client, "event-1", "Invented review", "2026-08-12T03:30:00.000Z", "");    let first = "cotton:event:event-1:20260812T0850";    let arrived = reconcile_call(&handle, &reconcile_request(json!([]))).expect("an answer");    assert_eq!(arrived["schedule"][0]["identifier"], json!(first));    assert_eq!(arrived["schedule"][0]["at"], json!("2026-08-12T03:20:00.000Z"));    write(        &client,        "UPDATE cotton_events SET starts_at = ? WHERE id = ?",        &["2026-08-13T05:30:00.000Z", "event-1"],    );    let moved = reconcile_call(&handle, &reconcile_request(json!([first]))).expect("an answer");    let second = "cotton:event:event-1:20260813T1050";    assert_eq!(moved["cancel"], json!([first]), "the old alarm goes");    assert_eq!(moved["schedule"][0]["identifier"], json!(second), "and the new one is set");    write(        &client,        "UPDATE cotton_events SET trashed_at = ? WHERE id = ?",        &[NOW, "event-1"],    );    let deleted = reconcile_call(&handle, &reconcile_request(json!([second]))).expect("an answer");    assert_eq!(deleted["cancel"], json!([second]), "a deleted event's alarm goes");    assert_eq!(deleted["schedule"], json!([]));}