Cotton code
1855 lines · 94.6 KB · RustRaw
//! The day surface's reads, over a real replica.//!//! Every fixture is synthetic — a workspace of zeroes, an event nobody is//! going to, a person who does not exist//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).//!//! What these pin is the CLAUSES, because a clause quietly dropped in a port is//! a screen that shows somebody rows they had put away — and because the SQL//! here is written out rather than composed, so nothing but a test that runs it//! can tell whether a column name is real.use serde_json::{json, Map, Value};use crate::shell::client::phone_tests::{args, attached};use crate::shell::client::ClientController;fn read(client: &ClientController, name: &str, args: &Map<String, Value>) -> Value {    let entry = crate::phone::reads::read_for(name).unwrap_or_else(|| panic!("{name} is declared"));    match entry.source {        crate::phone::reads::ReadSource::Query(query) => {            client.with_writer(|replica| query(replica, args))        }        _ => panic!("{name} is not a query read"),    }    .unwrap_or_else(|reason| panic!("{name} answered: {reason}"))}fn refuse(client: &ClientController, name: &str, args: &Map<String, Value>) -> String {    let entry = crate::phone::reads::read_for(name).unwrap_or_else(|| panic!("{name} is declared"));    match entry.source {        crate::phone::reads::ReadSource::Query(query) => {            client.with_writer(|replica| query(replica, args))        }        _ => panic!("{name} is not a query read"),    }    .expect_err("the read was supposed to refuse")}fn sql(client: &ClientController, statement: &str) {    client        .with_writer(|replica| {            replica                .driver                .run(                    &statement.replace("$WS", replica.workspace_id),                    &[],                )                .map(|_| ())                .map_err(|error| error.to_string())        })        .expect("the fixture lands");}/// A calendar to hang events on, and the workspace's own zone.fn calendared(client: &ClientController) {    sql(        client,        "INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at)         VALUES ('cal-1', '$WS', 'calendar', 'Personal', 1, '2026-08-01T00:00:00.000Z')",    );    sql(        client,        "INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at)         VALUES ('$WS', 'UTC', '2026-08-01T00:00:00.000Z', '2026-08-01T00:00:00.000Z')",    );}/// The window the phone would compute for 4 September 2026 in UTC.fn day_window() -> Map<String, Value> {    args(&[        ("timezone", json!("UTC")),        ("from", json!("2026-09-04T00:00:00.000Z")),        ("to", json!("2026-09-04T23:59:59.999Z")),    ])}// ── /alarms ─────────────────────────────────────────────────────────────────#[test]fn the_alarm_list_is_a_clock_face_and_keeps_the_ones_that_are_switched_off() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_alarms (id, workspace_id, label, hour, minute, repeat_days, enabled, sound, created_at, updated_at)         VALUES ('alarm-late', '$WS', 'Gym', 18, 30, '[1,3,5]', 0, 1, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('alarm-early', '$WS', '', 6, 45, 'not json', 1, 0, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.alarms", &Map::new());    let alarms = answer["alarms"].as_array().expect("a list");    // Clock order, not the order they were added: the list is a clock face.    assert_eq!(alarms[0]["id"], json!("alarm-early"));    assert_eq!(alarms[1]["id"], json!("alarm-late"));    // A disabled alarm is still an alarm the person owns — the screen greys it    // and draws its switch off; filtering it here would delete it from sight.    assert_eq!(alarms[1]["enabled"], json!(false));    assert_eq!(alarms[1]["repeatDays"], json!([1, 3, 5]));    // A `repeat_days` no reader can parse is a ONE-SHOT, never a failed screen.    assert_eq!(alarms[0]["repeatDays"], json!([]));    // "" is what "the owner named nothing" looks like; the screen decides what    // that reads as.    assert_eq!(alarms[0]["label"], json!(""));    assert_eq!(alarms[0]["sound"], json!(false));}/// RULE: An alarm in the bin never rings: the schedule read the AlarmKit reconciler diffs against leaves it out, switched on or not, so restoring it is what sets it again.#[test]fn a_binned_alarm_is_not_on_the_clock_face() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_alarms (id, workspace_id, label, hour, minute, repeat_days, enabled, sound, trashed_at, created_at, updated_at)         VALUES ('alarm-set', '$WS', 'Gym', 6, 30, '[]', 1, 1, NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('alarm-binned', '$WS', 'Ferry', 7, 0, '[]', 1, 1, '2026-09-02T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-02T00:00:00.000Z')",    );    let answer = read(&client, "read.alarms", &Map::new());    let ids: Vec<&str> = answer["alarms"].as_array().expect("a list").iter().filter_map(|row| row["id"].as_str()).collect();    assert_eq!(ids, vec!["alarm-set"], "{ids:?}");}/// RULE: A goal in the bin is left out of the Goals read: it is deleted, waiting, never one of the person's intentions on screen.#[test]fn a_binned_goal_is_not_listed() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_goals (id, workspace_id, title, status, sort_order, trashed_at, created_at, updated_at)         VALUES ('goal-kept', '$WS', 'Learn the cello', 'active', 1, NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('goal-binned', '$WS', 'Run a marathon', 'active', 2, '2026-09-02T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-02T00:00:00.000Z')",    );    let answer = read(&client, "read.goals", &Map::new());    let ids: Vec<&str> = answer["goals"].as_array().expect("a list").iter().filter_map(|row| row["id"].as_str()).collect();    assert!(ids.contains(&"goal-kept") && !ids.contains(&"goal-binned"), "{ids:?}");}// ── /journal ────────────────────────────────────────────────────────────────#[test]fn the_journal_is_the_person_s_own_days_and_never_a_project_s_page() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, journal_date, project_id, archived_at, created_at, updated_at)         VALUES ('page-11th', '$WS', 'journal', NULL, 'a quiet day', '2026-09-11', NULL, NULL, '2026-09-11T00:00:00.000Z', '2026-09-11T00:00:00.000Z'),                ('page-10th', '$WS', 'journal', NULL, 'the tenth', '2026-09-10', NULL, NULL, '2026-09-10T00:00:00.000Z', '2026-09-10T00:00:00.000Z'),                ('page-project', '$WS', 'journal', NULL, 'a standup', '2026-09-11', 'project-a', NULL, '2026-09-03T00:00:00.000Z', '2026-09-03T00:00:00.000Z'),                ('page-binned', '$WS', 'journal', NULL, 'put away', '2026-09-09', NULL, '2026-09-05T00:00:00.000Z', '2026-09-09T00:00:00.000Z', '2026-09-09T00:00:00.000Z'),                ('a-note', '$WS', 'note', 'Not a page', 'a note', NULL, NULL, NULL, '2026-09-02T00:00:00.000Z', '2026-09-02T00:00:00.000Z')",    );    // The clock and the zone: the read counts the streak from the phone's    // moment, in the workspace's zone — this file has recorded none, so the    // device's name is the fallback, exactly as the calendar's reads do it.    let pages = read(        &client,        "read.journal",        &args(&[            // 2026-09-11T12:00:00Z            ("nowMs", json!(1_789_128_000_000_i64)),            ("timezone", json!("UTC")),        ]),    );    let ids: Vec<&str> = pages["pages"]        .as_array()        .expect("a list")        .iter()        .filter_map(|page| page["id"].as_str())        .collect();    // Newest DAY first — the order of the days described, never the order they    // were edited in.    // The file's own two pages (the 4th and the 5th) sit under these.    assert_eq!(&ids[..2], &["page-11th", "page-10th"]);    // A project's entry is the same kind in the same file. Showing it here    // would light the streak and head Recent with a page that is not in this    // person's journal.    assert!(!ids.contains(&"page-project"));    assert!(!ids.contains(&"page-binned"));    assert!(!ids.contains(&"a-note"));    // The body travels WHOLE: the first line the list shows is derived on the    // device, and the same body feeds the editor.    assert_eq!(pages["pages"][0]["body"], json!("a quiet day"));    // AND THE STREAK, ANSWERED HERE RATHER THAN ON THE PHONE. The Swift copy    // of this figure is gone (4i); a screen re-deriving it would be the second    // implementation that once made two surfaces disagree about one day.    // The 11th and the 10th are written and the 9th is binned, so the run is    // two — and the project's page on the 11th must not extend it.    assert_eq!(pages["writtenToday"], json!(true));    assert_eq!(pages["streak"], json!(2));    // Each row carries the crate's own verdict, so the list that draws    // "written pages" asks `body` no second question.    assert_eq!(pages["pages"][0]["written"], json!(true));}#[test]fn a_blank_page_opened_today_is_a_day_opened_not_a_day_written() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_notes (id, workspace_id, kind, title, body, journal_date, project_id, archived_at, created_at, updated_at)         VALUES ('page-today', '$WS', 'journal', NULL, '   ', '2026-09-11', NULL, NULL, '2026-09-11T00:00:00.000Z', '2026-09-11T00:00:00.000Z')",    );    let answer = read(        &client,        "read.journal",        &args(&[            ("nowMs", json!(1_789_128_000_000_i64)),            ("timezone", json!("UTC")),        ]),    );    assert_eq!(answer["pages"][0]["written"], json!(false));    assert_eq!(answer["writtenToday"], json!(false));    assert_eq!(answer["streak"], json!(0));}// ── /calendar ───────────────────────────────────────────────────────────────#[test]fn the_day_draws_a_series_occurrence_the_master_never_starts_on() {    let (_dir, client) = attached();    calendared(&client);    // A weekly event anchored a fortnight earlier. Its occurrence on the 4th is    // the whole reason the candidate query has no lower bound on `starts_at`.    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, rrule, created_at, updated_at)         VALUES ('ev-weekly', 'cal-1', 'Swim', '2026-08-21T06:00:00.000Z', '2026-08-21T07:00:00.000Z', 0, 'FREQ=WEEKLY',                 '2026-08-21T00:00:00.000Z', '2026-08-21T00:00:00.000Z')",    );    let answer = read(&client, "read.day", &day_window());    let drawn = answer["occurrences"].as_array().expect("a list");    assert_eq!(drawn.len(), 1, "{drawn:?}");    assert_eq!(drawn[0]["startsAt"], json!("2026-09-04T06:00:00.000Z"));    assert_eq!(drawn[0]["occurrenceAt"], json!("2026-09-04T06:00:00.000Z"));    assert_eq!(drawn[0]["event"]["title"], json!("Swim"));}#[test]fn a_trashed_exception_still_claims_the_instant_it_was_moved_off() {    // The expansion's rule, reached through this read: an exception's    // `original_starts_at` claims its instant even when the exception is in the    // bin — a trashed exception is on its way OUT of Google, not on its way    // back into the series. Without this the master re-draws the occurrence it    // gave up and the person sees an appointment they cancelled.    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, rrule, created_at, updated_at)         VALUES ('ev-weekly', 'cal-1', 'Swim', '2026-08-21T06:00:00.000Z', '2026-08-21T07:00:00.000Z', 0, 'FREQ=WEEKLY',                 '2026-08-21T00:00:00.000Z', '2026-08-21T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, series_id, original_starts_at, trashed_at, gcal_id, created_at, updated_at)         VALUES ('ev-moved', 'cal-1', 'Swim', '2026-09-04T09:00:00.000Z', '2026-09-04T10:00:00.000Z', 0,                 'ev-weekly', '2026-09-04T06:00:00.000Z', '2026-09-05T00:00:00.000Z', 'g-moved',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.day", &day_window());    assert!(        answer["occurrences"].as_array().expect("a list").is_empty(),        "the cancelled occurrence came back: {}",        answer["occurrences"]    );}// RULE: The day's invite strip is the same set Home counts (`asked_of_you::INVITE_SQL`): someone else's unanswered events, never the owner's own, never one in the bin.#[test]fn the_invite_strip_is_rows_not_occurrences_and_leaves_the_bin_out() {    // An invitation is answered ONCE for the whole series — `my_response` is a    // column on the row — so the strip never expands. Which is exactly why the    // bin has to be filtered in the QUERY here: there is no expansion to hide a    // trashed row from.    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, my_response, organizer_is_self, trashed_at, created_at, updated_at)         VALUES ('ev-asking', 'cal-1', 'Standup', '2026-09-10T09:00:00.000Z', '2026-09-10T09:15:00.000Z', 0, 'needs_action', 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-binned', 'cal-1', 'Cancelled', '2026-09-11T09:00:00.000Z', '2026-09-11T09:15:00.000Z', 0, 'needs_action', 0, '2026-09-05T00:00:00.000Z',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-answered', 'cal-1', 'Answered', '2026-09-12T09:00:00.000Z', '2026-09-12T09:15:00.000Z', 0, 'accepted', 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-own', 'cal-1', 'My own', '2026-09-13T09:00:00.000Z', '2026-09-13T09:15:00.000Z', 0, 'needs_action', 1, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let mut window = day_window();    window.insert("invitesFrom".to_string(), json!("2026-09-04T00:00:00.000Z"));    let answer = read(&client, "read.day", &window);    let ids: Vec<&str> = answer["invites"]        .as_array()        .expect("a list")        .iter()        .filter_map(|event| event["id"].as_str())        .collect();    assert_eq!(ids, vec!["ev-asking"]);}#[test]fn the_day_s_todos_are_the_ones_due_in_its_window_and_never_a_dropped_one() {    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at)         VALUES ('todo-today', '$WS', 'Post the form', 'open', '2026-09-04T15:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-dropped', '$WS', 'Never mind', 'dropped', '2026-09-04T16:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-undated', '$WS', 'Someday', 'open', NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-tomorrow', '$WS', 'Later', 'open', '2026-09-05T09:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.day", &day_window());    let ids: Vec<&str> = answer["todos"]        .as_array()        .expect("a list")        .iter()        .filter_map(|todo| todo["id"].as_str())        .collect();    // A dropped todo must not come back onto a day; a todo with no date is on    // no day at all.    assert_eq!(ids, vec!["todo-today"]);}/// RULE: A todo is on the day it is next due, as its list reads it: a snooze past the day takes it off the day whatever its due date says, a snooze landing in the day brings it on at the snooze, and a lapsed snooze leaves the due date to decide — Today never holds a coming todo (290 walk).#[test]fn a_snoozed_todo_stands_on_the_day_it_comes_back_never_on_the_day_it_left() {    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, snoozed_until, created_at, updated_at)         VALUES ('snoozed-away', '$WS', 'Moved to tomorrow', 'open', '2026-09-04T10:00:00.000Z', '2026-09-05T09:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('snoozed-here', '$WS', 'Back this afternoon', 'open', '2026-09-02T10:00:00.000Z', '2026-09-04T14:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('snooze-lapsed', '$WS', 'Due today', 'open', '2026-09-04T11:00:00.000Z', '2026-09-03T08:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.day", &day_window());    let rows: Vec<(&str, &str)> = answer["todos"]        .as_array()        .expect("a list")        .iter()        .map(|todo| (todo["id"].as_str().unwrap_or(""), todo["dueAt"].as_str().unwrap_or("")))        .collect();    assert_eq!(rows, vec![("snooze-lapsed", "2026-09-04T11:00:00.000Z"), ("snoozed-here", "2026-09-04T14:00:00.000Z")]);}/// RULE: Today, Calendar and Todos read every instant in the phone's zone; a database's news zone cannot shift a clock or put tomorrow under Today.#[test]fn fixed_offset_households_share_clock_times_and_day_boundaries() {    for (zone, from, to, late_today, tomorrow, expected) in [        ("Asia/Kolkata", "2026-09-03T18:30:00.000Z", "2026-09-04T18:29:59.999Z", "2026-09-04T18:00:00.000Z", "2026-09-04T19:30:00.000Z", "2:30 pm"),        ("Etc/GMT+7", "2026-09-04T07:00:00.000Z", "2026-09-05T06:59:59.999Z", "2026-09-05T06:30:00.000Z", "2026-09-05T08:00:00.000Z", "2:00 am"),    ] {        // These households stay at +05:30 and -07:00, with no DST. News        // deliberately belongs to +07:00, reproducing the 90-minute drift.        let (_dir, client) = attached();        calendared(&client);        sql(&client, "UPDATE cotton_news_settings SET timezone = 'Asia/Bangkok'");        for (id, at) in [("same-instant", "2026-09-04T09:00:00.000Z"), ("late-today", late_today), ("tomorrow", tomorrow)] {            sql(&client, &format!("INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, created_at, updated_at)                VALUES ('{id}', 'cal-1', 'Appointment', '{at}', '{at}', 0, '{at}', '{at}')"));            sql(&client, &format!("INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at)                VALUES ('{id}', '$WS', 'Rent', 'open', '{at}', '{at}', '{at}')"));        }        let window = args(&[("from", json!(from)), ("to", json!(to)), ("timezone", json!(zone))]);        for method in ["read.day", "read.month"] {            let answer = read(&client, method, &window);            let events = answer["occurrences"].as_array().unwrap();            let todos = answer["todos"].as_array().unwrap();            assert_eq!(events.iter().map(|e| e["eventId"].as_str().unwrap()).collect::<Vec<_>>(), ["same-instant", "late-today"]);            assert_eq!(todos.iter().map(|t| t["id"].as_str().unwrap()).collect::<Vec<_>>(), ["same-instant", "late-today"]);            assert_eq!(events[0]["line"], expected);            assert_eq!(todos[0]["line"], expected);            // This late row is still today in the phone's zone; at +07:00            // the IST fixture used to say tomorrow's 1:00 am under Today.            assert_eq!(events[1]["line"], "11:30 pm");            assert_eq!(todos[1]["line"], "11:30 pm");            assert_eq!(answer["timezone"], zone);            for (table, column) in [("event", "starts_at"), ("todo", "due_at")] {                let definition = cotton_core::definitions::builtin_table_definitions().iter().find(|d| d.id == table).unwrap();                let data = json!({column: "2026-09-04T09:00:00.000Z"}).as_object().unwrap().clone();                let words = cotton_core::records::page::fact_words(definition, definition.column(column).unwrap(), &data[column], &data, Some(zone), None, cotton_core::records::page::Words::shipped()).unwrap();                assert!(words.ends_with(expected), "{table}: {words}");            }        }    }}/// RULE: Timed day rows share one clock spelling; date-only todos and all-day events read their definition's untimed words and sort at the day's start, so the joined feed keeps time order.#[test]fn each_row_of_the_day_says_its_time_or_its_definitions_untimed_words() {    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, rrule, created_at, updated_at)         VALUES ('ev-lunch', 'cal-1', 'Lunch', '2026-09-04T14:30:00.000Z', '2026-09-04T15:30:00.000Z', 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-holiday', 'cal-1', 'Holiday', '2026-09-04T00:00:00.000Z', '2026-09-05T00:00:00.000Z', 1, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at)         VALUES ('todo-nine', '$WS', 'Call the bank', 'open', '2026-09-04T09:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-day', '$WS', 'Post the form', 'open', '2026-09-04T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.day", &day_window());    let mut rows: Vec<(String, Value, String)> = Vec::new();    for occurrence in answer["occurrences"].as_array().expect("a list") {        rows.push((occurrence["event"]["title"].as_str().unwrap_or("").to_string(), occurrence["line"].clone(),                   occurrence["sortAt"].as_str().expect("a sort instant").to_string()));    }    for todo in answer["todos"].as_array().expect("a list") {        rows.push((todo["title"].as_str().unwrap_or("").to_string(), todo["line"].clone(),                   todo["sortAt"].as_str().expect("a sort instant").to_string()));    }    rows.sort_by(|a, b| a.2.cmp(&b.2));    let said: Vec<(&str, &Value)> = rows.iter().map(|(title, line, _)| (title.as_str(), line)).collect();    assert_eq!(said[2..], [("Call the bank", &json!("9:00 am")), ("Lunch", &json!("2:30 pm"))], "{said:?}");    let mut leading: Vec<(&str, &Value)> = said[..2].to_vec();    leading.sort_by_key(|(title, _)| *title);    assert_eq!(leading, [("Holiday", &json!("all day")), ("Post the form", &json!("due today"))], "{said:?}");}/// RULE: A Today slip over a table no tool draws (an event when Calendar is not installed) says the typed/// refusal as its line — "No tool draws this table." — never nothing, and a drawn table's rows keep their own/// words (architect, 21 Oct 2026, found by peoplenav's walk on a synthetic household).#[test]fn a_day_row_over_a_table_no_tool_draws_says_so() {    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, rrule, created_at, updated_at)         VALUES ('ev-lunch', 'cal-1', 'Lunch', '2026-09-04T14:30:00.000Z', '2026-09-04T15:30:00.000Z', 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-holiday', 'cal-1', 'Holiday', '2026-09-04T00:00:00.000Z', '2026-09-05T00:00:00.000Z', 1, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at)         VALUES ('todo-day', '$WS', 'Post the form', 'open', '2026-09-04T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(&client, "DELETE FROM cotton_table_definitions WHERE id = 'event'");    let answer = read(&client, "read.day", &day_window());    let occurrences = answer["occurrences"].as_array().expect("a list");    assert_eq!(occurrences.len(), 2);    for occurrence in occurrences {        assert_eq!(occurrence["line"], json!(cotton_core::definitions::no_tool_draws_this_table(&[])), "{occurrence}");        assert!(occurrence["sortAt"].is_string(), "it still sorts into the day");    }    assert_eq!(answer["todos"][0]["line"], json!("due today"), "a drawn table keeps its own words");}#[test]fn a_window_this_core_cannot_compute_is_refused_rather_than_guessed() {    // `dayWindow` is built with the DEVICE's local midnight. This core has no    // clock and no locale, and a window it invented would be a different day    // from the one the person is looking at.    let (_dir, client) = attached();    calendared(&client);    let reason = refuse(&client, "read.day", &Map::new());    assert!(reason.contains("`from`"), "{reason}");}/// RULE (27 Oct 2026): an event is the database's, never its calendar's. The/// object keeps no calendars, so a copy holds none, and its day, its month and/// its invitations draw every event it holds: one naming no calendar, one/// naming a calendar the copy never holds, and an invitation of either.#[test]fn a_file_with_no_calendar_draws_every_event_it_holds() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_news_settings (workspace_id, timezone, created_at, updated_at)         VALUES ('$WS', 'UTC', '2026-08-01T00:00:00.000Z', '2026-08-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, organizer_is_self, my_response, created_at, updated_at)         VALUES ('ev-google', NULL, 'From Google', '2026-09-04T09:00:00.000Z', '2026-09-04T10:00:00.000Z', 0, 1, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-imported', 'a-calendar-never-held', 'Imported', '2026-09-04T11:00:00.000Z', '2026-09-04T12:00:00.000Z', 0, 1, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-invite', 'a-calendar-never-held', 'Asked', '2026-09-06T11:00:00.000Z', '2026-09-06T12:00:00.000Z', 0, 0, 'needs_action',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let titles = |answer: &Value, key: &str| -> Vec<String> {        answer[key]            .as_array()            .expect("a list")            .iter()            .filter_map(|slot| slot["event"]["title"].as_str().or(slot["title"].as_str()).map(str::to_string))            .collect()    };    let day = read(&client, "read.day", &day_window());    assert_eq!(titles(&day, "occurrences"), ["From Google", "Imported"]);    assert_eq!(titles(&day, "invites"), ["Asked"]);    assert!(day.get("calendar").is_none(), "the day names no calendar of its own");    let month = read(        &client,        "read.month",        &args(&[("timezone", json!("UTC")), ("from", json!("2026-08-31T00:00:00.000Z")), ("to", json!("2026-10-04T23:59:59.999Z"))]),    );    assert_eq!(titles(&month, "occurrences"), ["From Google", "Imported", "Asked"]);    let event = read(&client, "read.event", &args(&[("id", json!("ev-imported"))]));    assert_eq!(event["event"]["title"], json!("Imported"));    assert_eq!(event["calendarName"], Value::Null, "a calendar the copy does not hold has no name here");}#[test]fn the_phone_zone_wins_and_a_missing_phone_zone_refuses() {    let (_dir, client) = attached();    calendared(&client);    let mut window = day_window();    window.insert("timezone".to_string(), json!("Asia/Kolkata"));    assert_eq!(read(&client, "read.day", &window)["timezone"], json!("Asia/Kolkata"));    window.remove("timezone");    let reason = refuse(&client, "read.day", &window);    assert!(reason.contains("timezone"), "{reason}");    window.insert("timezone".to_string(), json!("Not/AZone"));    assert!(refuse(&client, "read.day", &window).contains("not a known time zone"));}// ── /calendar/month ─────────────────────────────────────────────────────────#[test]fn the_month_draws_a_spanning_occurrence_once_on_the_day_it_begins() {    // The grid says "something begins here", never "this day is covered" — and    // it carries a title and a start, because a cell opens a DAY and never an    // event.    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, created_at, updated_at)         VALUES ('ev-trip', 'cal-1', 'Chennai', '2026-09-09T23:00:00.000Z', '2026-09-11T22:59:59.999Z', 1,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(        &client,        "read.month",        &args(&[            ("timezone", json!("UTC")),            ("from", json!("2026-08-31T00:00:00.000Z")),            ("to", json!("2026-10-04T23:59:59.999Z")),        ]),    );    let drawn = answer["occurrences"].as_array().expect("a list");    assert_eq!(drawn.len(), 1, "{drawn:?}");    assert_eq!(drawn[0]["event"]["title"], json!("Chennai"));    assert_eq!(drawn[0]["event"]["allDay"], json!(true));    assert_eq!(drawn[0]["startsAt"], json!("2026-09-09T23:00:00.000Z"));}#[test]fn the_month_answers_the_day_s_own_occurrence_so_a_selected_day_s_row_can_open_it() {    // The rows under the grid open an EVENT, so the month carries what the day    // carries — the id, the instant in the series, where, and the projects —    // and the two reads can never draw the same occurrence two ways.    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, location, starts_at, ends_at, all_day, created_at, updated_at)         VALUES ('ev-lunch', 'cal-1', 'Invented lunch', 'Nowhere Street', '2026-09-04T11:30:00.000Z',                 '2026-09-04T12:30:00.000Z', 0, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let month = read(&client, "read.month", &day_window());    let day = read(&client, "read.day", &day_window());    assert_eq!(month["occurrences"], day["occurrences"]);    let slot = &month["occurrences"][0];    assert_eq!(slot["eventId"], json!("ev-lunch"));    assert_eq!(slot["occurrenceAt"], json!("2026-09-04T11:30:00.000Z"));    assert_eq!(slot["event"]["location"], json!("Nowhere Street"));    assert_eq!(slot["projects"], json!([]), "an unfiled event answers none, never a missing key");}#[test]fn an_occurrence_wears_its_own_projects_first_and_else_its_series_masters() {    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, created_at, updated_at)         VALUES ('project-ev-a', '$WS', 'invented-a', 'Invented A', 'active',                 '2026-08-01T00:00:00.000Z', '2026-08-01T00:00:00.000Z'),                ('project-ev-b', '$WS', 'invented-b', 'Invented B', 'active',                 '2026-08-02T00:00:00.000Z', '2026-08-02T00:00:00.000Z')",    );    // A daily series, and one moved occurrence of it with no links of its own;    // and a plain event filed in both projects, linked newest-project first.    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, rrule, series_id, original_starts_at, created_at, updated_at)         VALUES ('ev-daily', 'cal-1', 'Invented standup', '2026-09-01T09:00:00.000Z', '2026-09-01T09:15:00.000Z', 0,                 'FREQ=DAILY', NULL, NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-moved', 'cal-1', 'Invented standup', '2026-09-04T10:00:00.000Z', '2026-09-04T10:15:00.000Z', 0,                 NULL, 'ev-daily', '2026-09-04T09:00:00.000Z', '2026-09-03T00:00:00.000Z', '2026-09-03T00:00:00.000Z'),                ('ev-both', 'cal-1', 'Invented review', '2026-09-04T15:00:00.000Z', '2026-09-04T16:00:00.000Z', 0,                 NULL, NULL, NULL, '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id,                                           applied_by, created_at, updated_at)         VALUES ('plink-series', '$WS', 'project-ev-b', 'event', 'ev-daily', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-both-b', '$WS', 'project-ev-b', 'event', 'ev-both', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-both-a', '$WS', 'project-ev-a', 'event', 'ev-both', 'user',                 '2026-09-02T00:00:00.000Z', '2026-09-02T00:00:00.000Z')",    );    let answer = read(&client, "read.day", &day_window());    let slugs = |event_id: &str| -> Vec<String> {        answer["occurrences"]            .as_array()            .expect("a list")            .iter()            .find(|slot| slot["eventId"] == event_id)            .unwrap_or_else(|| panic!("{event_id} is drawn"))["projects"]            .as_array()            .expect("a list")            .iter()            .filter_map(|project| project["slug"].as_str().map(str::to_string))            .collect()    };    assert_eq!(slugs("ev-moved"), vec!["invented-b"], "the exception inherits its master's");    assert_eq!(        slugs("ev-both"),        vec!["invented-a", "invented-b"],        "the project's own age orders them, never the link's"    );}// ── /calendar/event/[id] ────────────────────────────────────────────────────#[test]fn one_event_comes_back_with_its_guests_and_the_people_they_might_be() {    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, notes, gcal_id, sync_state, created_at, updated_at)         VALUES ('ev-1', 'cal-1', 'Coffee', '2026-09-04T09:00:00.000Z', '2026-09-04T09:30:00.000Z', 0, 'the usual place',                 'g-1', 'synced', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_event_attendees (id, event_id, email, display_name, response, created_at, updated_at)         VALUES ('att-1', 'ev-1', 'someone@example.invalid', 'Someone', 'needs_action',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at)         VALUES ('per-1', '$WS', 'Someone',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    // An email is a handle row since v90.    sql(        &client,        "INSERT INTO cotton_person_handles (id, workspace_id, person_id, kind, value, normalised,                                            source, created_at, updated_at)         VALUES ('handle-per-1-email', '$WS', 'per-1', 'email', 'someone@example.invalid',                 'someone@example.invalid', 'manual',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.event", &args(&[("id", json!("ev-1"))]));    assert_eq!(answer["event"]["title"], json!("Coffee"));    assert_eq!(answer["event"]["syncState"], json!("synced"));    assert_eq!(answer["calendarName"], json!("Personal"));    assert_eq!(answer["attendees"][0]["displayName"], json!("Someone"));    // The whole address book comes back — the file's own people included — so    // the guest is matched here rather than by a lookup per row.    let matched = answer["people"]        .as_array()        .expect("a list")        .iter()        .find(|person| person["id"] == json!("per-1"))        .expect("the person the guest is");    assert_eq!(matched["emails"], json!(["someone@example.invalid"]));}#[test]fn an_event_that_is_gone_is_null_and_one_in_the_bin_is_still_answered() {    // `null` rather than a refusal: a stale link draws "This event isn't here    // any more", and an error would make it draw a crash. A TRASHED event comes    // back WITH its `trashedAt` — the screen decides, exactly as the app's    // does, because folding that in here would take the deleted-and-still-    // syncing state off the screen that has to explain it.    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, trashed_at, gcal_id, created_at, updated_at)         VALUES ('ev-binned', 'cal-1', 'Gone', '2026-09-04T09:00:00.000Z', '2026-09-04T09:30:00.000Z', 0,                 '2026-09-05T00:00:00.000Z', 'g-2', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let gone = read(&client, "read.event", &args(&[("id", json!("ev-absent"))]));    assert_eq!(gone["event"], Value::Null);    let binned = read(&client, "read.event", &args(&[("id", json!("ev-binned"))]));    assert_eq!(binned["event"]["trashedAt"], json!("2026-09-05T00:00:00.000Z"));}// ── /thoughts ───────────────────────────────────────────────────────────────#[test]fn the_chat_reads_the_five_columns_the_assistant_s_tool_does_not() {    // `list_thoughts` reads none of these, and each one is a different thing    // the chat draws: the confidence separates a CORRECTION from a hand-filing    // of an abstention, the proposal IS the pending outcome, the sweep note    // REPLACES the filed caption, and the audio is what makes a spoken capture    // look spoken.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, audio_url, captured_at, route_status,                                         route_reason, route_confidence, routed_records, route_proposal,                                         sweep_note, created_at, updated_at)         VALUES ('cap-spoken', '$WS', 'call amma', 'media://take-1', '2026-09-04T10:00:00.000Z', 'corrected',                 'confident', '0.91', '[{\"kind\":\"todo\",\"id\":\"todo-1\"}]', NULL,                 'refiled by the sweep', '2026-09-04T10:00:00.000Z', '2026-09-04T10:00:00.000Z')",    );    let answer = read(&client, "read.thoughts", &Map::new());    let row = &answer["thoughts"][0];    assert_eq!(row["id"], json!("cap-spoken"));    assert_eq!(row["audioUrl"], json!("media://take-1"));    assert_eq!(row["routeConfidence"], json!(0.91));    assert_eq!(row["sweepNote"], json!("refiled by the sweep"));    assert_eq!(row["routeReason"], json!("confident"));    // And the tool it used to be bound to answers none of them.    let tool = client        .read_tool("list_thoughts", &Map::new())        .expect("the tool still runs");    let listed = tool["thoughts"].as_array().cloned().unwrap_or_default();    for entry in listed {        assert!(entry.get("audioUrl").is_none(), "{entry}");        assert!(entry.get("routeConfidence").is_none(), "{entry}");        assert!(entry.get("routeProposal").is_none(), "{entry}");    }}#[test]fn the_ledger_carries_each_thought_s_pictures_in_the_note_s_own_row_shape() {    // A bug report is one thought with a screenshot. The phone draws it with    // the reader it already has for a note's pictures, so the row shape is    // `get_record`'s — and a picture since removed still answers, as missing.    let (_dir, client) = attached();    let sha_a = "a".repeat(64);    let sha_b = "b".repeat(64);    sql(        &client,        "INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, captured_at, route_status, created_at, updated_at)         VALUES ('cap-shot', '$WS', 'the day list jumps', '2026-09-27T10:00:00.000Z', 'pending',                 '2026-09-27T10:00:00.000Z', '2026-09-27T10:00:00.000Z'),                ('cap-bare', '$WS', 'no picture on this one', '2026-09-27T09:00:00.000Z', 'pending',                 '2026-09-27T09:00:00.000Z', '2026-09-27T09:00:00.000Z')",    );    sql(        &client,        &format!(            "INSERT INTO cotton_photos (id, workspace_id, key, sha256, content_type, size_bytes, width, height, caption, taken_at, created_at, updated_at)             VALUES ('photo:{sha_a}', '$WS', 'ws/photos/{sha_a}.png', '{sha_a}', 'image/png', 2048, 1179, 2556, 'the screenshot',                     '2026-09-27T10:00:00.000Z', '2026-09-27T10:00:00.000Z', '2026-09-27T10:00:00.000Z')"        ),    );    sql(        &client,        &format!(            "INSERT INTO cotton_thought_attachments (id, workspace_id, thought_id, record_kind, record_id, position, caption, created_at, updated_at)             VALUES ('att-1', '$WS', 'cap-shot', 'photo', 'photo:{sha_b}', 0, NULL, '2026-09-27T10:00:00.000Z', '2026-09-27T10:00:00.000Z'),                    ('att-2', '$WS', 'cap-shot', 'photo', 'photo:{sha_a}', 1, 'where it jumps', '2026-09-27T10:00:00.000Z', '2026-09-27T10:00:00.000Z')"        ),    );    let answer = read(&client, "read.thoughts", &Map::new());    let shot = &answer["thoughts"][0];    assert_eq!(shot["id"], json!("cap-shot"));    let pictures = shot["attachments"].as_array().expect("a list");    assert_eq!(pictures.len(), 2);    // The one whose photo row is gone: the reference stands and says so.    assert_eq!(pictures[0]["id"], json!(format!("photo:{sha_b}")));    assert_eq!(pictures[0]["position"], json!(0));    assert_eq!(pictures[0]["missing"], json!(true));    assert_eq!(pictures[0]["key"], Value::Null);    // The one that is there: the key `read.mediaPath` takes, both captions.    assert_eq!(pictures[1]["id"], json!(format!("photo:{sha_a}")));    assert_eq!(pictures[1]["position"], json!(1));    assert_eq!(pictures[1]["missing"], json!(false));    assert_eq!(pictures[1]["key"], json!(format!("ws/photos/{sha_a}.png")));    assert_eq!(pictures[1]["caption"], json!("where it jumps"));    assert_eq!(pictures[1]["recordCaption"], json!("the screenshot"));    assert_eq!(pictures[1]["width"], json!(1179));    assert_eq!(pictures[1]["contentType"], json!("image/png"));    // A thought with none answers an empty list, never an absent key.    assert_eq!(answer["thoughts"][1]["id"], json!("cap-bare"));    assert_eq!(answer["thoughts"][1]["attachments"], json!([]));}#[test]fn a_filed_chip_learns_its_date_and_a_person_note_learns_whose_it_is() {    // Without `personId` a person-note chip must not navigate at all: falling    // back to the note's own id pushes a person screen under the wrong id. And    // a record since deleted simply does not come back — the chip falls to the    // bare kind, which is not an error.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at)         VALUES ('todo-filed', '$WS', 'Post the form', 'open', '2026-09-10T09:00:00.000Z',                 '2026-09-04T00:00:00.000Z', '2026-09-04T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_person_notes (id, person_id, body, noted_at, created_at)         VALUES ('pn-1', 'person-a', 'a synthetic line', '2026-09-04T00:00:00.000Z', '2026-09-04T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, captured_at, route_status,                                         routed_records, created_at, updated_at)         VALUES ('cap-filed', '$WS', 'two things', '2026-09-04T10:00:00.000Z', 'routed',                 '[{\"kind\":\"todo\",\"id\":\"todo-filed\"},{\"kind\":\"person_note\",\"id\":\"pn-1\"},{\"kind\":\"todo\",\"id\":\"todo-gone\"}]',                 '2026-09-04T10:00:00.000Z', '2026-09-04T10:00:00.000Z'),                ('cap-dismissed', '$WS', 'never mind', '2026-09-03T10:00:00.000Z', 'dismissed',                 '[{\"kind\":\"todo\",\"id\":\"todo-dismissed-only\"}]',                 '2026-09-03T10:00:00.000Z', '2026-09-03T10:00:00.000Z')",    );    // The record the dismissed capture points at is REAL, so its absence from    // the facts is dismissal doing the work rather than a deleted row.    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, created_at, updated_at)         VALUES ('todo-dismissed-only', '$WS', 'Never mind', 'open', '2026-09-11T09:00:00.000Z',                 '2026-09-03T00:00:00.000Z', '2026-09-03T00:00:00.000Z')",    );    let facts = read(&client, "read.thoughts", &Map::new())["routedFacts"].clone();    assert_eq!(facts["todo-filed"]["dateIso"], json!("2026-09-10T09:00:00.000Z"));    assert_eq!(facts["pn-1"]["personId"], json!("person-a"));    assert_eq!(facts.get("todo-gone"), None);    // The dismissed capture's OWN reference contributes nothing. It has to    // point at a record no other capture names, or the assertion passes on the    // filed capture's reference and says nothing at all about dismissal.    assert_eq!(facts.get("todo-dismissed-only"), None);}#[test]fn the_ledger_is_every_capture_including_the_ones_that_were_dismissed() {    // `list_thoughts` filters to open captures by default and caps at 100. The    // chat is the person's own transcript of everything they ever said.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_inbox_items (id, workspace_id, raw_text, captured_at, route_status, created_at, updated_at)         VALUES ('cap-dismissed', '$WS', 'never mind', '2026-09-03T10:00:00.000Z', 'dismissed',                 '2026-09-03T10:00:00.000Z', '2026-09-03T10:00:00.000Z'),                ('cap-newest', '$WS', 'the latest', '2026-09-05T10:00:00.000Z', 'pending',                 '2026-09-05T10:00:00.000Z', '2026-09-05T10:00:00.000Z')",    );    let answer = read(&client, "read.thoughts", &Map::new());    let ids: Vec<&str> = answer["thoughts"]        .as_array()        .expect("a list")        .iter()        .filter_map(|row| row["id"].as_str())        .collect();    // Newest first, and the dismissed one is in the transcript.    assert_eq!(ids, vec!["cap-newest", "cap-dismissed"]);}// ── /locations ──────────────────────────────────────────────────────────────#[test]fn a_place_put_away_leaves_the_list_and_the_map_and_its_links_are_counted_both_ways() {    // `archived_at IS NULL` is the soft archive: without it every place    // somebody put away comes back to both surfaces. And the link count is the    // two-direction one — an edge may name the place at either end, and one    // side alone under-counts.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_locations (id, workspace_id, name, address, lat, lng, note, created_at, updated_at, archived_at)         VALUES ('loc-cafe', '$WS', 'A cafe', 'Nowhere Street', 1.5, 2.5, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', NULL),                ('loc-nopin', '$WS', 'Beyond the map', NULL, NULL, NULL, 'the one with the gate',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', NULL),                ('loc-gone', '$WS', 'Closed down', NULL, NULL, NULL, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-05T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_links (id, workspace_id, from_kind, from_id, to_kind, to_id, created_at)         VALUES ('lnk-1', '$WS', 'todo', 'todo-x', 'location', 'loc-cafe', '2026-09-01T00:00:00.000Z'),                ('lnk-2', '$WS', 'location', 'loc-cafe', 'person', 'person-a', '2026-09-02T00:00:00.000Z')",    );    let answer = read(&client, "read.locations", &Map::new());    let places = answer["locations"].as_array().expect("a list");    let ids: Vec<&str> = places.iter().filter_map(|place| place["id"].as_str()).collect();    // Name order, which is the rendered order — there is no client re-sort.    assert_eq!(ids, vec!["loc-cafe", "loc-nopin"]);    assert_eq!(places[0]["linkCount"], json!(2));    // A place nothing names says nothing, rather than a zero the row has to    // decide how to draw.    assert_eq!(places[1]["linkCount"], json!(0));    // The pin, and the pin's absence.    assert!(places[0]["lat"].is_number());    assert_eq!(places[1]["lat"], Value::Null);}#[test]fn each_place_says_when_it_was_last_written() {    // The list's "Recent" rows are the places touched most lately, so the read    // carries each row's own `updated_at` — not its creation.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_locations (id, workspace_id, name, created_at, updated_at)         VALUES ('loc-old', '$WS', 'Old haunt', '2026-01-01T00:00:00.000Z', '2026-09-10T08:30:00.000Z')",    );    let answer = read(&client, "read.locations", &Map::new());    assert_eq!(answer["locations"][0]["updatedAt"], json!("2026-09-10T08:30:00.000Z"));}// ── /goals ──────────────────────────────────────────────────────────────────#[test]fn every_goal_comes_back_in_one_read_whatever_became_of_it() {    // ONE read, not two: the screen draws the live goals and the "Behind you"    // section from the same list, and splitting it would mean two answers that    // can disagree about a goal the owner just achieved. So there is no status    // filter here at all.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_goals (id, workspace_id, title, why, target_date, status, achieved_at, sort_order, created_at, updated_at)         VALUES ('goal-second', '$WS', 'Learn to swim', 'the sea is right there', '2026-12-01', 'active', NULL, 2048,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('goal-first', '$WS', 'Ship Cotton', NULL, NULL, 'paused', NULL, 1024,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('goal-done', '$WS', 'Read ten books', NULL, NULL, 'achieved', '2026-08-20T00:00:00.000Z', 512,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('goal-let-go', '$WS', 'Never mind', NULL, NULL, 'dropped', NULL, 4096,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.goals", &Map::new());    let ids: Vec<&str> = answer["goals"]        .as_array()        .expect("a list")        .iter()        .filter_map(|goal| goal["id"].as_str())        .collect();    // The hand order, which is what makes two goals at one position resolve the    // same way on every device — the screen does the live/finished partition.    assert_eq!(        ids,        vec!["goal-done", "goal-first", "goal-second", "goal-let-go"]    );    assert_eq!(answer["goals"][0]["achievedAt"], json!("2026-08-20T00:00:00.000Z"));    // `why` travels even though this screen never draws it — the detail screen    // does, and it is one column.    assert_eq!(answer["goals"][2]["why"], json!("the sea is right there"));}// ── /people/import ──────────────────────────────────────────────────────────#[test]fn the_import_screen_learns_which_cards_are_taken_and_never_counts_an_archived_person() {    // The set of `device_contact_id`s IS "already in People" and the linked    // count. An archived person must not appear in it twice over: they are out    // of the directory, and offering their card as taken would make them    // unreachable.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_people (id, workspace_id, full_name, device_contact_id, device_contact_snapshot, birth_month, birth_day, archived_at, created_at, updated_at)         VALUES ('per-linked', '$WS', 'A Linked Person', 'device-contact-1', '{\"v\":1}', 4, 2, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('per-archived', '$WS', 'An Archived Person', 'device-contact-2', NULL, NULL, NULL, '2026-09-05T00:00:00.000Z',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('per-manual', '$WS', 'Typed By Hand', NULL, NULL, NULL, NULL, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.peopleImport", &Map::new());    let linked = answer["linked"].as_array().expect("a list");    assert_eq!(linked.len(), 1, "{linked:?}");    assert_eq!(linked[0]["deviceContactId"], json!("device-contact-1"));    assert_eq!(answer["linkedCount"], json!(1));    // The mirror's planning fields ride along — a second read for them would be    // a second answer to who is linked.    assert_eq!(linked[0]["deviceContactSnapshot"], json!({ "v": 1 }));    // Month and day are one fact; the year is separately optional, because iOS    // says "a birthday with no year" and means it.    assert_eq!(linked[0]["birthday"], json!({ "month": 4, "day": 2, "year": Value::Null }));}// RULE (B1, 6 Nov 2026): a linked person whose birthday came whole from the object — the month, day and year empty on a signed-in copy — reads with that birthday, year or none, so the contacts mirror never takes it for a birthday removed; the phone's own month and day win where set.#[test]fn the_import_screen_reads_a_birthday_the_object_keeps_whole() {    use cotton_store::schema::package_shape::{add_served, served_column};    let (_dir, client) = attached();    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");    sql(        &client,        "INSERT INTO cotton_people (id, workspace_id, full_name, device_contact_id, birth_month, birth_day, birthday, created_at, updated_at)         VALUES ('per-a', '$WS', 'A Whole Birthday', 'device-contact-1', NULL, NULL, '1988-11-20',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('per-b', '$WS', 'B No Year', 'device-contact-2', NULL, NULL, '--03-02',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('per-c', '$WS', 'C Both Forms', 'device-contact-3', 4, 2, '1988-11-20',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('per-d', '$WS', 'D None', 'device-contact-4', NULL, NULL, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.peopleImport", &Map::new());    let birthdays: Vec<&Value> = answer["linked"].as_array().expect("a list").iter().map(|person| &person["birthday"]).collect();    assert_eq!(        birthdays,        [            &json!({ "month": 11, "day": 20, "year": 1988 }),            &json!({ "month": 3, "day": 2, "year": Value::Null }),            &json!({ "month": 4, "day": 2, "year": Value::Null }),            &Value::Null,        ],        "{answer}"    );}// ── /todos, /todos/done, /todos/dropped ─────────────────────────────────────/// Three todos of our own, so the lists have something the seed does not/// already decide: one done, one dropped, one still open with a due date.fn shelved(client: &ClientController) {    sql(        client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, due_at, priority, completed_at, created_at, updated_at)         VALUES ('todo-open', '$WS', 'Still open', 'open', '2026-09-08T09:00:00.000Z', 2, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-done', '$WS', 'Finished', 'done', '2026-09-07T09:00:00.000Z', 0, '2026-09-07T10:00:00.000Z',                 '2026-09-01T00:00:00.000Z', '2026-09-07T10:00:00.000Z'),                ('todo-old-drop', '$WS', 'Let go first', 'dropped', NULL, 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-02T00:00:00.000Z'),                ('todo-new-drop', '$WS', 'Let go later', 'dropped', NULL, 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-06T00:00:00.000Z')",    );}#[test]fn the_pool_carries_the_done_ones_and_never_a_dropped_one() {    // ONE read draws three screens: `/todos` filters the pool to what is open,    // `/todos/done` to what is finished, and both are the same list — a done    // todo is still a todo. A DROPPED one is not: it was let go, and it lives    // on the third screen alone.    let (_dir, client) = attached();    shelved(&client);    let answer = read(&client, "read.todos", &Map::new());    let ids: Vec<&str> = answer["todos"]        .as_array()        .expect("a list")        .iter()        .map(|todo| todo["id"].as_str().expect("an id"))        .collect();    assert!(ids.contains(&"todo-open"), "{ids:?}");    assert!(ids.contains(&"todo-done"), "{ids:?}");    assert!(!ids.contains(&"todo-old-drop"), "{ids:?}");    // Dated before undated, and earliest first — the app's own order, which a    // plain `ORDER BY due_at` would invert on SQLite (NULL sorts first).    let dated: Vec<&str> = ids        .iter()        .copied()        .take_while(|id| *id != "todo-b" && *id != "todo-c")        .collect();    assert_eq!(dated, vec!["todo-done", "todo-open", "todo-a"], "{ids:?}");}#[test]fn the_dropped_shelf_reads_newest_first_because_nothing_records_when_it_was_let_go() {    // There is no `dropped_at` column, so `updated_at` IS the moment — which is    // why this read answers it and `list_todos` cannot draw this screen.    let (_dir, client) = attached();    shelved(&client);    let answer = read(&client, "read.todos", &Map::new());    let dropped: Vec<&str> = answer["dropped"]        .as_array()        .expect("a list")        .iter()        .map(|todo| todo["id"].as_str().expect("an id"))        .collect();    assert_eq!(dropped, vec!["todo-new-drop", "todo-old-drop"]);    assert_eq!(answer["dropped"][0]["updatedAt"], json!("2026-09-06T00:00:00.000Z"));}// ── /todos/todo/[id] ────────────────────────────────────────────────────────#[test]fn the_detail_screen_gets_the_raw_priority_and_the_rule_it_repeats_by() {    // `get_record` answers `priority: "high"` and `repeating: true`; this    // screen toggles the NUMBER and reshapes the SERIES, so it needs both in    // the shapes the writer takes.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_todo_recurrences (id, workspace_id, title, notes, priority, rrule, dtstart, paused, materialized_until, created_at, updated_at)         VALUES ('rec-1', '$WS', 'Water the plants', 'The ones on the sill', 2, 'FREQ=WEEKLY;BYDAY=MO', '2026-09-07T08:00:00.000Z', 0, '2026-09-21T08:00:00.000Z',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, priority, recurrence_id, occurrence_at, source_inbox_id, created_at, updated_at)         VALUES ('todo-rec', '$WS', 'Water the plants', 'open', 2, 'rec-1', '2026-09-14T08:00:00.000Z', 'capture-1',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.todo", &args(&[("id", json!("todo-rec"))]));    assert_eq!(answer["todo"]["priority"], json!(2));    assert_eq!(answer["todo"]["recurrenceId"], json!("rec-1"));    // The capture trail: this todo came from something the owner sent in.    assert_eq!(answer["todo"]["sourceInboxId"], json!("capture-1"));    assert_eq!(answer["recurrence"]["rrule"], json!("FREQ=WEEKLY;BYDAY=MO"));    assert_eq!(answer["recurrence"]["paused"], json!(false));    assert_eq!(answer["recurrence"]["materializedUntil"], json!("2026-09-21T08:00:00.000Z"));}#[test]fn a_todo_that_repeats_by_nothing_and_a_todo_that_is_not_there_both_answer_null() {    // Two absences, one shape. The rule is `null` because this todo carries no    // `recurrence_id` — the only way a template can be missing, since the    // file's foreign key means a todo cannot point at a rule that is not there.    let (_dir, client) = attached();    let answer = read(&client, "read.todo", &args(&[("id", json!("todo-a"))]));    assert_eq!(answer["todo"]["id"], json!("todo-a"));    assert_eq!(answer["todo"]["recurrenceId"], Value::Null);    assert_eq!(answer["recurrence"], Value::Null);    // A todo that is not there at all answers `null` too: a stale link draws    // "this isn't here any more", never an error screen.    let gone = read(&client, "read.todo", &args(&[("id", json!("todo-absent"))]));    assert_eq!(gone["todo"], Value::Null);    assert_eq!(gone["recurrence"], Value::Null);    // No id at all IS a caller's mistake, and says which argument it wants.    let refused = refuse(&client, "read.todo", &Map::new());    assert!(refused.contains("todo"), "{refused}");}// ── the two-branch reads' key sets ──────────────────────────────────────────/// Every key a read answers, sorted.////// SORTED rather than in insertion order: Swift's decoder does not care what/// order the keys arrive in, so order is not the contract and pinning it would/// only make the guard red for a reason nobody has to fix.fn keys(value: &Value) -> Vec<String> {    let mut names: Vec<String> = value        .as_object()        .expect("an object")        .keys()        .cloned()        .collect();    names.sort();    names}#[test]fn a_reads_gone_branch_answers_the_same_keys_as_its_found_branch() {    // THE RULE, and why it is a test rather than a habit. Swift's synthesized    // `Decodable` calls `decode` — NOT `decodeIfPresent` — for a non-optional    // stored property, so a default written beside the property is never    // reached on an absent key: the decode THROWS. A read whose "this is gone"    // branch is one key short therefore does not draw "gone"; it draws the load    // ERROR, with a Try again that can never succeed, which is the worst    // possible answer to a stale deep link. `read.person` shipped exactly that    // (`faceSuggestionPhotos`), which is what this test exists to catch.    let (_dir, client) = attached();    calendared(&client);    // /calendar and /calendar/month: a file with NO calendar, against the same    // read in one that holds a calendar — the same keys either way.    let (_bare_dir, bare) = attached();    // The device's own zone, since a calendar-less file has recorded none and    // `expansion_zone` refuses rather than flooring to UTC.    let bare_window = args(&[        ("from", json!("2026-09-04T00:00:00.000Z")),        ("to", json!("2026-09-04T23:59:59.999Z")),        ("timezone", json!("UTC")),    ]);    for name in ["read.day", "read.month"] {        let gone = read(&bare, name, &bare_window);        let found = read(&client, name, &day_window());        assert_eq!(keys(&gone), keys(&found), "{name}");    }    // /calendar/event: an id nobody has, against a real event.    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day,                                    created_at, updated_at)         VALUES ('ev-keys', 'cal-1', 'Something', '2026-09-04T09:00:00.000Z',                 '2026-09-04T10:00:00.000Z', 0, '2026-08-01T00:00:00.000Z',                 '2026-08-01T00:00:00.000Z')",    );    let gone = read(&client, "read.event", &args(&[("id", json!("ev-absent"))]));    let found = read(&client, "read.event", &args(&[("id", json!("ev-keys"))]));    assert_eq!(gone["event"], Value::Null);    assert_eq!(keys(&gone), keys(&found));    // /todos/todo/[id]: the same shape one table over.    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-keys', '$WS', 'Something', 'open', '2026-08-01T00:00:00.000Z',                 '2026-08-01T00:00:00.000Z')",    );    let gone = read(&client, "read.todo", &args(&[("id", json!("todo-absent"))]));    let found = read(&client, "read.todo", &args(&[("id", json!("todo-keys"))]));    assert_eq!(gone["todo"], Value::Null);    assert_eq!(keys(&gone), keys(&found));}// ── the clauses a WHERE carries, each with a row it has to leave out ────────//// A read's exclusion is only proved by a row it excludes. Every test above// seeds what it expects to see; these seed what must NOT come back, which is// the half a port drops silently — a dropped clause answers MORE rows, and a// test that only checks the rows it wanted still passes./// A second workspace, with one row of each kind that read is scoped by.////// `cotton_workspaces` is a real FK target for these tables, so the workspace/// row goes in first. Every value synthetic/// ([nothing-real-ever-goes-in-cotton-s-public-tree]).fn a_second_workspace(client: &ClientController) {    sql(        client,        "INSERT INTO cotton_workspaces (id, name, owner_user_id, created_at)         VALUES ('ws-other', 'Somebody else', 'user-other', '2026-09-01T00:00:00.000Z')",    );}#[test]fn every_workspace_scoped_read_leaves_another_workspaces_rows_out() {    // The clause these all carry, proved by a row on the other side of it.    // Nothing in this tree seeded a foreign workspace before, so every    // `workspace_id = ?` in the day surface was untested against the one thing    // it exists to stop.    let (_dir, client) = attached();    a_second_workspace(&client);    sql(        &client,        "INSERT INTO cotton_alarms (id, workspace_id, label, hour, minute, repeat_days, enabled,                                    sound, created_at, updated_at)         VALUES ('alarm-mine', '$WS', 'Mine', 6, 30, '[]', 1, 1,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('alarm-theirs', 'ws-other', 'Theirs', 5, 0, '[]', 1, 1,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-mine', '$WS', 'Mine', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-theirs', 'ws-other', 'Theirs', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    // /alarms — the list had no exclusion test of any kind.    let alarms = read(&client, "read.alarms", &Map::new());    let ids: Vec<&str> = alarms["alarms"]        .as_array()        .expect("a list")        .iter()        .filter_map(|row| row["id"].as_str())        .collect();    assert_eq!(ids, vec!["alarm-mine"], "{ids:?}");    // /todos — the pool. The fixture already seeds three of this workspace's    // own todos, so what is asserted is that the foreign one is absent and the    // local one is not.    let pool = read(&client, "read.todos", &Map::new());    let ids: Vec<&str> = pool["todos"]        .as_array()        .expect("a list")        .iter()        .filter_map(|row| row["id"].as_str())        .collect();    assert!(ids.contains(&"todo-mine"), "{ids:?}");    assert!(!ids.contains(&"todo-theirs"), "{ids:?}");    // /todos/todo/[id] — the detail read is NARROWER than its `selectById`    // original on purpose, and this is the clause that makes it so: an id from    // another workspace answers "gone", not that workspace's row.    let theirs = read(&client, "read.todo", &args(&[("id", json!("todo-theirs"))]));    assert_eq!(theirs["todo"], Value::Null);    let mine = read(&client, "read.todo", &args(&[("id", json!("todo-mine"))]));    assert_eq!(mine["todo"]["id"], json!("todo-mine"));}#[test]fn the_month_leaves_out_the_bin_and_everything_past_the_window_and_keeps_every_calendar() {    // One event and one assertion proved the grid drew something; these rows    // prove it draws only what it should. A trashed master and an event    // outside the month are absent; an event naming a second calendar is the    // database's like any other, and is drawn (27 Oct 2026).    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_collections (id, workspace_id, kind, name, is_default, created_at)         VALUES ('cal-2', '$WS', 'calendar', 'Second', 0, '2026-08-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, trashed_at, created_at, updated_at)         VALUES ('ev-drawn', 'cal-1', 'Drawn', '2026-09-10T09:00:00.000Z', '2026-09-10T10:00:00.000Z', 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-binned', 'cal-1', 'Binned', '2026-09-11T09:00:00.000Z', '2026-09-11T10:00:00.000Z', 0,                 '2026-09-05T00:00:00.000Z', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-elsewhere', 'cal-2', 'Elsewhere', '2026-09-12T09:00:00.000Z', '2026-09-12T10:00:00.000Z', 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('ev-later', 'cal-1', 'Later', '2026-11-02T09:00:00.000Z', '2026-11-02T10:00:00.000Z', 0, NULL,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(        &client,        "read.month",        &args(&[            ("timezone", json!("UTC")),            ("from", json!("2026-08-31T00:00:00.000Z")),            ("to", json!("2026-10-04T23:59:59.999Z")),        ]),    );    let titles: Vec<&str> = answer["occurrences"]        .as_array()        .expect("a list")        .iter()        .filter_map(|slot| slot["event"]["title"].as_str())        .collect();    assert_eq!(titles, vec!["Drawn", "Elsewhere"], "{titles:?}");}#[test]fn the_event_screens_address_book_leaves_out_a_person_put_away() {    // The guest-matching list is `archived_at IS NULL`: somebody archived is    // out of the DIRECTORY, and offering them as the person a guest might be    // would bring them back through the editor's autocomplete. The fixture    // already holds `person-archived`; this is the assertion that reads it.    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, created_at, updated_at)         VALUES ('ev-guests', 'cal-1', 'Coffee', '2026-09-04T09:00:00.000Z', '2026-09-04T09:30:00.000Z', 0,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.event", &args(&[("id", json!("ev-guests"))]));    let named: Vec<&str> = answer["people"]        .as_array()        .expect("a list")        .iter()        .filter_map(|person| person["id"].as_str())        .collect();    assert!(named.contains(&"person-a"), "{named:?}");    assert!(!named.contains(&"person-archived"), "{named:?}");}#[test]fn the_chats_project_vocabulary_can_still_name_a_project_that_was_retired() {    // A VOCABULARY, not an offer: its one job is turning the id a router    // proposal already carries into a name. `memoriesService.listProjects` has    // no status filter, and adding one made a proposal naming a since-archived    // project draw the bare uuid. The fixture already holds `project-old`.    let (_dir, client) = attached();    let answer = read(&client, "read.thoughts", &Map::new());    let listed: Vec<&str> = answer["projects"]        .as_array()        .expect("a list")        .iter()        .filter_map(|project| project["id"].as_str())        .collect();    assert!(listed.contains(&"project-a"), "{listed:?}");    assert!(listed.contains(&"project-old"), "{listed:?}");    // The status rides along so a CALLER can narrow what the read deliberately    // does not: a picker offering somewhere to file a thought wants the    // active ones, so the caller needs both halves in one hand.    let status_of = |wanted: &str| -> String {        answer["projects"]            .as_array()            .expect("a list")            .iter()            .find(|project| project["id"].as_str() == Some(wanted))            .and_then(|project| project["status"].as_str())            .expect("a status")            .to_string()    };    assert_eq!(status_of("project-a"), "active");    assert_eq!(status_of("project-old"), "archived");    // And the SLUG, which is the other half of the same key: `link_to_project`    // takes a slug while the app holds the project by id, so a list answering    // only one of the two leaves a `#` chip remembered and unsettleable. All    // four fields, on every row, archived included.    for project in answer["projects"].as_array().expect("a list") {        let row = project.as_object().expect("an object");        let mut keys: Vec<&str> = row.keys().map(String::as_str).collect();        keys.sort();        assert_eq!(keys, vec!["id", "name", "slug", "status"], "{row:?}");    }    let slug_of = |wanted: &str| -> String {        answer["projects"]            .as_array()            .expect("a list")            .iter()            .find(|project| project["id"].as_str() == Some(wanted))            .and_then(|project| project["slug"].as_str())            .expect("a slug")            .to_string()    };    assert_eq!(slug_of("project-a"), "alpaca-work");    assert_eq!(slug_of("project-old"), "alpaca-old");}// ── /todos narrowed to a project ────────────────────────────────────────────#[test]fn a_project_narrows_both_lists_to_its_own_todos() {    // The INTERSECTION `narrowToScope` computes: the link edge says a todo    // belongs to the project, the pool says what state it is in, and the screen    // needs both.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-in', '$WS', 'In the project', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-out', '$WS', 'Not in it', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-in-dropped', '$WS', 'Let go', 'dropped',                 '2026-09-01T00:00:00.000Z', '2026-09-02T00:00:00.000Z'),                ('todo-out-dropped', '$WS', 'Let go elsewhere', 'dropped',                 '2026-09-01T00:00:00.000Z', '2026-09-02T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id,                                           applied_by, created_at, updated_at)         VALUES ('plink-1', '$WS', 'project-a', 'todo', 'todo-in', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-2', '$WS', 'project-a', 'todo', 'todo-in-dropped', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    // The unnarrowed pool holds these plus the fixture's own three.    let whole = read(&client, "read.todos", &Map::new());    assert_eq!(whole["todos"].as_array().expect("a list").len(), 5);    assert_eq!(whole["dropped"].as_array().expect("a list").len(), 2);    let scoped = read(&client, "read.todos", &args(&[("project", json!("project-a"))]));    let open: Vec<&str> = scoped["todos"]        .as_array()        .expect("a list")        .iter()        .filter_map(|row| row["id"].as_str())        .collect();    assert_eq!(open, vec!["todo-in"], "{open:?}");    // Done and Dropped are opened FROM the project's timeline and stay inside    // it — `donePath(projectId)` / `droppedPath(projectId)`.    let dropped: Vec<&str> = scoped["dropped"]        .as_array()        .expect("a list")        .iter()        .filter_map(|row| row["id"].as_str())        .collect();    assert_eq!(dropped, vec!["todo-in-dropped"], "{dropped:?}");}#[test]fn the_project_argument_takes_a_slug_as_well_as_an_id() {    // The two screens that reach this read carry different things and neither    // side can convert: `/todos/done?project=<id>` carries an id, while    // `/projects/[slug]/todos` has only the slug —    // and the roster the phone holds comes from `list_projects`, whose    // `project_out` never writes an id. Both must narrow to the same list.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-in', '$WS', 'In the project', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-out', '$WS', 'Not in it', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id,                                           applied_by, created_at, updated_at)         VALUES ('plink-1', '$WS', 'project-a', 'todo', 'todo-in', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    // `project-a` is the id; `alpaca-work` is its slug.    for named in ["project-a", "alpaca-work"] {        let scoped = read(&client, "read.todos", &args(&[("project", json!(named))]));        let open: Vec<&str> = scoped["todos"]            .as_array()            .expect("a list")            .iter()            .filter_map(|row| row["id"].as_str())            .collect();        assert_eq!(open, vec!["todo-in"], "{named}: {open:?}");        // The title the scoped screen draws, off the same lookup — the roster        // read cannot supply it, because `project_out` writes no id to match.        assert_eq!(scoped["projectName"], json!("Alpaca Work"), "{named}");    }}#[test]fn a_project_that_resolves_to_nothing_narrows_to_nothing_never_to_everything() {    // `EMPTY_SCOPE`, and it is a privacy-shaped rule rather than a nicety: the    // fallback would be every todo in the database sitting under one project's    // title, which is this repo's banned silent fallback wearing its worst    // face — a wrong answer that looks like a right one.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-loose', '$WS', 'Belongs to nobody', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-loose-dropped', '$WS', 'Also nobody', 'dropped',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    // A project with no todo members, and a project that is not in the file at    // all: both are "named but unread", and both answer nothing.    for project in ["project-a", "project-absent"] {        let scoped = read(&client, "read.todos", &args(&[("project", json!(project))]));        assert_eq!(scoped["todos"], json!([]), "{project}");        assert_eq!(scoped["dropped"], json!([]), "{project}");    }    // The name follows what RESOLVED, not what narrowed: a real project with no    // todos keeps its title over its two empty lists, and one that is not there    // has no title to draw. Both keys are present either way.    let empty = read(&client, "read.todos", &args(&[("project", json!("project-a"))]));    assert_eq!(empty["projectName"], json!("Alpaca Work"));    let absent = read(        &client,        "read.todos",        &args(&[("project", json!("project-absent"))]),    );    assert!(absent.as_object().expect("an object").contains_key("projectName"));    assert_eq!(absent["projectName"], Value::Null);    // And a blank argument is NO narrowing, not an empty project — the whole    // pool, which is the tool's own screen.    let blank = read(&client, "read.todos", &args(&[("project", json!("  "))]));    // No narrowing was asked for, so there is no title — the same null as the    // unresolvable case, over the OPPOSITE rows.    assert_eq!(blank["projectName"], Value::Null);    let open: Vec<&str> = blank["todos"]        .as_array()        .expect("a list")        .iter()        .filter_map(|row| row["id"].as_str())        .collect();    assert!(open.contains(&"todo-loose"), "{open:?}");    assert_eq!(blank["dropped"].as_array().expect("a list").len(), 1);}// ── the Projects… sheet's two keys, on every detail read ────────────────────/// The project ids one read says a record belongs to.fn linked_projects(answer: &Value) -> Vec<&str> {    answer["projectLinks"]        .as_array()        .expect("a list")        .iter()        .filter_map(|link| link["projectId"].as_str())        .collect()}#[test]fn a_membership_carries_its_note_and_an_unwritten_one_is_null_not_empty() {    // The sheet shows the note stored on the MEMBERSHIP and commits an edit on    // blur. Read empty, every edit is a fresh write over what was there — and    // the same three screens share these rows, so one column is three screens.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-noted', '$WS', 'Noted', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-bare', '$WS', 'Bare', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id,                                           note, applied_by, created_at, updated_at)         VALUES ('plink-noted', '$WS', 'project-a', 'todo', 'todo-noted', 'why this is here',                 'user', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-bare', '$WS', 'project-a', 'todo', 'todo-bare', NULL,                 'user', '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let noted = read(&client, "read.todo", &args(&[("id", json!("todo-noted"))]));    assert_eq!(noted["projectLinks"][0]["note"], json!("why this is here"));    // Never written is NULL, not "": an empty string is a note somebody typed    // and cleared, which is a different fact.    let bare = read(&client, "read.todo", &args(&[("id", json!("todo-bare"))]));    let link = bare["projectLinks"][0].as_object().expect("a link");    assert!(link.contains_key("note"));    assert_eq!(link["note"], Value::Null);}#[test]fn every_detail_read_answers_the_roster_and_this_records_own_memberships() {    // The sheet is KIND-AGNOSTIC and was live on one page out of five, because    // `read.person` was the only read that carried these two keys. They are the    // same two shapes everywhere, so the Swift decodes one type on all of them.    //    // ARCHIVED PROJECTS ARE IN THE ROSTER, which is `read.person`'s reason    // kept: the chips draw only the active ones, but the sheet has to be able    // to unlink from a project that has since been retired.    let (_dir, client) = attached();    calendared(&client);    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-linked', '$WS', 'Linked', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_events (id, collection_id, title, starts_at, ends_at, all_day, created_at, updated_at)         VALUES ('ev-linked', 'cal-1', 'Linked', '2026-09-04T09:00:00.000Z', '2026-09-04T10:00:00.000Z', 0,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_goals (id, workspace_id, title, status, sort_order, created_at, updated_at)         VALUES ('goal-linked', '$WS', 'Linked', 'active', 1024,                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_locations (id, workspace_id, name, address, lat, lng, note, created_at, updated_at)         VALUES ('loc-linked', '$WS', 'A cafe', 'Nowhere Street', 1.5, 2.5, 'the one with the gate',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id,                                           applied_by, created_at, updated_at)         VALUES ('plink-todo', '$WS', 'project-a', 'todo', 'todo-linked', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-event', '$WS', 'project-a', 'event', 'ev-linked', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-goal', '$WS', 'project-old', 'goal', 'goal-linked', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-place', '$WS', 'project-a', 'location', 'loc-linked', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-elsewhere', '$WS', 'project-a', 'todo', 'todo-a', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    for (name, key, id, expected) in [        ("read.todo", "id", "todo-linked", "project-a"),        ("read.event", "id", "ev-linked", "project-a"),        ("read.goal", "id", "goal-linked", "project-old"),        ("read.location", "id", "loc-linked", "project-a"),    ] {        let answer = read(&client, name, &args(&[(key, json!(id))]));        // The ROSTER is every project, retired ones included.        let roster: Vec<&str> = answer["projects"]            .as_array()            .expect("a list")            .iter()            .filter_map(|project| project["id"].as_str())            .collect();        assert!(roster.contains(&"project-a"), "{name}: {roster:?}");        assert!(roster.contains(&"project-old"), "{name}: {roster:?}");        // The MEMBERSHIPS are this record's alone — never another record's of        // the same kind, and never another kind's under the same id.        assert_eq!(linked_projects(&answer), vec![expected], "{name}");    }}#[test]fn a_record_that_is_gone_still_answers_both_project_keys() {    // Same rule as every other gone branch: the key SET does not change, or the    // decode throws and the "gone" screen becomes a load failure.    let (_dir, client) = attached();    calendared(&client);    for (name, id) in [        ("read.todo", "todo-absent"),        ("read.event", "ev-absent"),        ("read.goal", "goal-absent"),        ("read.location", "loc-absent"),    ] {        let answer = read(&client, name, &args(&[("id", json!(id))]));        assert_eq!(answer["projects"], json!([]), "{name}");        assert_eq!(answer["projectLinks"], json!([]), "{name}");    }}#[test]fn the_place_page_answers_the_row_get_record_answered_under_the_same_names() {    // `read.location` is split out of `read.record` so the sheet's two keys can    // land without widening an assistant's tool. The ROW is unchanged — the    // same seven values `LOCATION_COLUMNS` carries, under the same key names    // including `created_at`'s snake case — so the screen's decoder needs    // nothing but the two additions.    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_locations (id, workspace_id, name, address, lat, lng, note, created_at, updated_at)         VALUES ('loc-one', '$WS', 'A cafe', 'Nowhere Street', 1.5, 2.5, 'the one with the gate',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let place = read(&client, "read.location", &args(&[("id", json!("loc-one"))]))["location"].clone();    assert_eq!(place["id"], json!("loc-one"));    assert_eq!(place["name"], json!("A cafe"));    assert_eq!(place["address"], json!("Nowhere Street"));    assert_eq!(place["note"], json!("the one with the gate"));    assert_eq!(place["lat"], json!(1.5));    assert_eq!(place["lng"], json!(2.5));    assert_eq!(place["created_at"], json!("2026-09-01T00:00:00.000Z"));    assert_eq!(place.as_object().expect("an object").len(), 7);    // And it is workspace-scoped, where `get_record` reached the row by id    // through `ReadDb`'s own stamp — the same narrowing `read.todo` makes.    a_second_workspace(&client);    sql(        &client,        "INSERT INTO cotton_locations (id, workspace_id, name, created_at, updated_at)         VALUES ('loc-theirs', 'ws-other', 'Somewhere else',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let theirs = read(&client, "read.location", &args(&[("id", json!("loc-theirs"))]));    assert_eq!(theirs["location"], Value::Null);}// ── no label, and the card's project chips ──────────────────────────────────/// RULE: A todo read answers no label, even for a row an older build labelled — todos lost labels on 5 Oct 2026 and groups do that job; a label still answered would be a second way to sort the same todos.#[test]fn a_todo_read_answers_no_label() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, label, status, created_at, updated_at)         VALUES ('todo-worded', '$WS', 'Renew the invented passport before the trip', 'Renew passport', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.todos", &Map::new());    let todo = answer["todos"]        .as_array()        .expect("a list")        .iter()        .find(|todo| todo["id"] == "todo-worded")        .cloned()        .expect("the todo is listed");    assert_eq!(todo["title"], "Renew the invented passport before the trip");    assert!(todo.get("label").is_none(), "{todo}");    let single = read(&client, "read.todo", &args(&[("id", json!("todo-worded"))]));    assert!(single["todo"].get("label").is_none(), "{single}");}#[test]fn the_list_answers_each_todo_s_projects_in_one_read_and_an_unlinked_one_answers_none() {    let (_dir, client) = attached();    sql(        &client,        "INSERT INTO cotton_memory_projects (id, workspace_id, slug, name, status, created_at, updated_at)         VALUES ('project-x', '$WS', 'invented-x', 'Invented X', 'active',                 '2026-08-01T00:00:00.000Z', '2026-08-01T00:00:00.000Z'),                ('project-y', '$WS', 'invented-y', 'Invented Y', 'archived',                 '2026-08-02T00:00:00.000Z', '2026-08-02T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_todos (id, workspace_id, title, status, created_at, updated_at)         VALUES ('todo-two', '$WS', 'In two projects', 'open',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('todo-none', '$WS', 'In no project', 'open',                 '2026-09-01T00:00:01.000Z', '2026-09-01T00:00:01.000Z'),                ('todo-gone', '$WS', 'Dropped, and in one', 'dropped',                 '2026-09-01T00:00:02.000Z', '2026-09-02T00:00:00.000Z')",    );    sql(        &client,        "INSERT INTO cotton_project_links (id, workspace_id, project_id, record_kind, record_id,                                           applied_by, created_at, updated_at)         VALUES ('plink-x', '$WS', 'project-x', 'todo', 'todo-two', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-y', '$WS', 'project-y', 'todo', 'todo-two', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z'),                ('plink-gone', '$WS', 'project-x', 'todo', 'todo-gone', 'user',                 '2026-09-01T00:00:00.000Z', '2026-09-01T00:00:00.000Z')",    );    let answer = read(&client, "read.todos", &Map::new());    let find = |list: &str, id: &str| -> Value {        answer[list]            .as_array()            .expect("a list")            .iter()            .find(|todo| todo["id"] == id)            .cloned()            .expect("the todo is listed")    };    // In the projects' own order, archived included — the chip is drawn from    // the active ones on the device, but an unlink from a retired project has    // to stay possible, the single read's reason.    assert_eq!(        find("todos", "todo-two")["projects"],        json!([            { "id": "project-x", "slug": "invented-x", "name": "Invented X" },            { "id": "project-y", "slug": "invented-y", "name": "Invented Y" },        ])    );    assert_eq!(find("todos", "todo-none")["projects"], json!([]), "a list, never a missing key");    assert_eq!(        find("dropped", "todo-gone")["projects"],        json!([{ "id": "project-x", "slug": "invented-x", "name": "Invented X" }]),        "the dropped list carries its chips too"    );    // Narrowing to a project changes WHICH todos answer, not what each one    // says about its projects.    let scoped = read(&client, "read.todos", &args(&[("project", json!("invented-x"))]));    let open: Vec<&str> = scoped["todos"]        .as_array()        .expect("a list")        .iter()        .filter_map(|row| row["id"].as_str())        .collect();    assert_eq!(open, vec!["todo-two"]);    assert_eq!(        scoped["todos"][0]["projects"].as_array().expect("a list").len(),        2    );}/// Seconds are deliberately ignored: a due time of 00:00:30 is a DATE, not an/// appointment, and drawing an hour for it would be the app inventing an hour/// the person never stated.#[test]fn only_an_hour_or_a_minute_states_a_clock_time() {    use super::has_clock_time;    let ms = |at: &str| cotton_store::protocol::js::parse_date_ms(at).expect("an instant");    let ist = "Asia/Kolkata";    assert!(!has_clock_time(ms("2026-08-08T00:00:00.000+05:30"), ist).expect("readable"));    assert!(!has_clock_time(ms("2026-08-08T00:00:30.000+05:30"), ist).expect("readable"));    assert!(has_clock_time(ms("2026-08-08T00:01:00.000+05:30"), ist).expect("readable"));    assert!(has_clock_time(ms("2026-08-08T09:00:00.000+05:30"), ist).expect("readable"));}