Cotton code
1630 lines · 91.6 KB · RustRaw
//! What the app's screens OFFER, the generic verbs TAKE.//!//! The app draws every built-in table from the one definition the object//! serves (`crates/cotton-core/kits`): a column not//! declared `readonly` opens an editor, `archived` puts "Archive this …" in//! the page's menu, `chips` puts a row of chips above the list, `create` a//! "New …" on it. Each of those is one `update_record` or `create_record`//! from the owner's own app. This suite seeds the synthetic household and//! sends every one of them. Every value is invented//! ([nothing-real-ever-goes-in-cotton-s-public-tree]).mod support;use std::collections::BTreeSet;use cotton_core::definitions::{builtin_table_definition, Column, ColumnType, CommandKind, PickKind, TableDefinition};use cotton_store::schema::package_shape::{add_served, served_column};use cotton_tools::clock::Clock as _;use cotton_tools::synthetic::{seed_household, Plan};use serde_json::{json, Map, Value};use support::harness::{synthetic_uuid, Harness};use support::mcp::call_tool_as_owner;const PHONE: &str = "device:phone";/// The tables the app draws: the one definition of each, as the object/// serves it (`crates/cotton-core/kits`), compiled in.fn app_definitions() -> Vec<TableDefinition> {    cotton_core::definitions::builtin_table_definitions().to_vec()}fn household() -> Harness {    let h = calendar_only();    let seeded = h.with(|db| seed_household(db, &h.owner_id, &Plan::scaled(2_000), 7)).expect("a household");    // Booking verifies the seeded paper, not the harness's unrelated default    // Meridian PDF. Retain the generator's independent figures, never echo    // the booking candidate or read them back from editable statement rows.    for (id, figures) in seeded.statement_pages {        h.services.statement_visual.recording_for(&id, figures);    }    h}/// A household seeded against the wall clock (`seed_now`), as a phone's dev/// household is, the reader's clock a minute after.fn household_today() -> Harness {    let now = cotton_tools::synthetic::seed_now(chrono::Utc::now());    let h = calendar_only();    h.with(|db| cotton_tools::synthetic::seed_household_at(db, &h.owner_id, &Plan::scaled(2_000), 7, now))        .expect("a household");    h.clock.set(now + chrono::Duration::minutes(1));    h}/// A file with only its default calendar, which a provisioned file is born with.fn calendar_only() -> Harness {    let h = Harness::new();    // The phone takes this column from the object's event definition before    // offering its kind picker (3f441e61d); the engine does not own it.    add_served(&h.db, "cotton_events", &[served_column("kind", "choice", false).expect("a choice")])        .expect("the copy keeps the object's event kind");    // The file's default calendar, which a provisioned file is born with.    h.seed(&[json!({        "opId": format!("01J{:023}", 0),        "deviceId": "device:seed",        "kind": "upsert",        "table": "cotton_collections",        "rowId": synthetic_uuid("calendar"),        "patch": {            "kind": "calendar",            "name": "Personal",            "is_default": true,            "workspace_id": h.workspace_id,            "created_at": "2026-09-08T09:00:00.000Z",        },        "hlc": "1700000000000:0000:device:seed",        "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION,    })]);    h}fn owner(h: &Harness, tool: &str, args: Value) -> Result<Value, String> {    let answer = call_tool_as_owner(h, PHONE, tool, args);    if answer.is_error {        Err(answer.text)    } else {        Ok(answer.json())    }}/// The first records of a table, as the list answers them.fn first_records(h: &Harness, table: &str) -> Vec<(String, Map<String, Value>)> {    let Ok(listed) = owner(h, "list_records", json!({ "table": table, "limit": 12 })) else {        return Vec::new();    };    // A list read in sections (todos: today, the days ahead, late, done…)    // puts its closed sections last; take the head of each so a done todo's    // commands are walked too.    let mut records = listed["records"].as_array().cloned().unwrap_or_default();    for section in listed["sections"].as_array().into_iter().flatten() {        let mut args = json!({ "table": table, "limit": 3, "section": section["key"] });        if let Some(day) = section["day"].as_str() {            args["day"] = json!(day);        }        if let Ok(more) = owner(h, "list_records", args) {            records.extend(more["records"].as_array().cloned().unwrap_or_default());        }    }    records        .iter()        .filter_map(|record| {            Some((                record["id"].as_str()?.to_string(),                record["data"].as_object().cloned().unwrap_or_default(),            ))        })        .collect()}fn first_record(h: &Harness, table: &str) -> Option<(String, Map<String, Value>)> {    first_records(h, table).into_iter().next()}/// A record made the way its screen makes one — the title's words, whatever/// the definition says a record cannot go without, and the record it hangs/// under — for a table the synthetic household seeds none of.fn new_record(h: &Harness, definition: &TableDefinition) -> Option<(String, Map<String, Value>)> {    let mut sent = Map::new();    for column in &definition.columns {        let wanted = column.key == definition.title            || column.required == Some(true)            || (column.column_type == ColumnType::Link && column.key.ends_with("_id"));        if !wanted {            continue;        }        if let Some(value) = candidates(h, column, None).into_iter().next() {            sent.insert(column.key.clone(), value);        }    }    let made = owner(h, "create_record", json!({ "table": definition.id, "data": sent }))        .map_err(|sentence| eprintln!("no {} could be made: {sentence}", definition.id))        .ok()?;    Some((        made["record"]["id"].as_str()?.to_string(),        made["record"]["data"].as_object().cloned().unwrap_or_default(),    ))}/// Values a person could put in a column, none of them what it holds now. A/// column passes when the verbs take ANY of them: the guard is about whether/// the column can be written at all, not about one value's shape.fn candidates(h: &Harness, column: &Column, now: Option<&Value>) -> Vec<Value> {    let differs = |value: &Value| Some(value) != now;    // Authoring fields accept their own JSON format, rather than arbitrary    // prose. Keep the identity from the record while changing a valid value.    if column.key == "definition" {        if let Some(mut definition) = now.and_then(Value::as_str)            .and_then(|text| serde_json::from_str::<Value>(text).ok()) {            if definition.get("parts").is_some() {                definition["parts"] = json!([{"kind":"notices"}]);            } else {                definition["cap"] = json!({"colour":"red"});            }            return vec![Value::String(definition.to_string())].into_iter().filter(differs).collect();        }    }    if column.key == "currency" {        return vec![json!("EUR"), json!("USD"), json!("JPY")].into_iter().filter(differs).collect();    }    let all: Vec<Value> = match column.column_type {        ColumnType::Text | ColumnType::Longtext | ColumnType::Place => vec![            json!("Guard words"),            json!("Europe/Paris"),            json!("FREQ=WEEKLY"),            json!("https://example.com/guard"),            json!("EUR"),            json!("guard"),        ],        ColumnType::Url => vec![json!("https://example.com/guard")],        ColumnType::AccountNumber => vec![json!("12345678901234"), json!("98765432")],        ColumnType::Date => {            let hour = if column.key.contains("end") { 11 } else { 10 };            vec![                json!(format!("2031-03-04T{hour}:00:00.000Z")),                json!("2031-03-04"),            ]        }        ColumnType::Time => vec![json!("07:45")],        ColumnType::Number | ColumnType::Amount => vec![json!(3), json!(4), json!(1), json!(0)],        ColumnType::Bytes => vec![json!(0u64), json!(1u64), json!(400_000_000u64)],        ColumnType::Bool => vec![json!(true), json!(false)],        ColumnType::Choice => {            let choices = column.choices.clone().unwrap_or_default();            if column.multiple == Some(true) {                choices.iter().take(2).map(|choice| json!([choice])).collect()            } else {                choices.iter().map(|choice| json!(choice)).collect()            }        }        ColumnType::Link => column            .link_to            .as_deref()            .and_then(|table| owner(h, "list_records", json!({ "table": table, "limit": 2 })).ok())            .and_then(|listed| listed["records"].as_array().cloned())            .unwrap_or_default()            .iter()            .filter_map(|record| record["id"].as_str().map(|id| json!(id)))            .collect(),        // Bytes arrive through a picker, never as a typed value.        ColumnType::Photo | ColumnType::File => Vec::new(),    };    all.into_iter().filter(differs).collect()}/// What the screens offer and the verbs do not take yet: `table.column`, and/// whose it is. EXACT — an entry that starts passing fails the guard until it/// is taken out, and nothing may be added without a name beside it.const NOT_TAKEN_YET: &[(&str, &str)] = &[];/// Edits the engine answers by what was typed, not by whether it takes the/// column: `table.column`, and the words that say the write reached it. A/// file's password is tried, and a wrong one is told so.// An event's archive column is the bin's: the engine refuses an Archive on// purpose (architect 1650), and Delete — which asks how far it reaches — is// the way to the bin.const ANSWERED_BY_THE_ENGINE: &[(&str, &str)] = &[    ("document.unlock_password", "That password did not open this document"),    ("event.trashed_at", "An event has no Archive"),];/// Tables whose edits the app's own source takes, never the record verbs: a/// device's name and session cap are `DeviceTableSource`'s, a pull request's/// and an issue's title, body and labels their repository sources'/// (`RepoEditing`, through `repo.editPull` / `repo.editIssue` — the Swift/// suites `DeviceActionsTests` and `RepoSourcesTests` hold each to what it/// writes), a connection's kind, name, address, token and Hold/// `ConnectionTableSource`'s (a token is sealed into the vault, Hold is/// `repo.hold`), and an assistant's name, write/// access and expiry `AssistantTableSource`'s (a draft's until/// `mcpTokens.mint` makes its key; nothing writes a minted key's).const WRITTEN_BY_THE_APP: &[&str] = &["device", "pull", "issue", "connection", "assistant", "code_default"];/// RULE: Every column a built-in's screen lets a person edit, and its Archive, is taken by update_record from the owner's own app — or the definition does not offer it.#[test]fn every_edit_a_builtin_screen_offers_is_taken() {    let h = household();    let mut refused: Vec<String> = Vec::new();    let mut refused_keys: BTreeSet<String> = BTreeSet::new();    let mut walked = 0;    for definition in app_definitions() {        // A table the Rust core does not answer is drawn from the app's own        // source (Settings), not through the record verbs.        if builtin_table_definition(&definition.id).is_none()            || WRITTEN_BY_THE_APP.contains(&definition.id.as_str())        {            continue;        }        let archived = definition.archived.clone();        let mut editable: Vec<&Column> = definition            .columns            .iter()            // Swift normalizes computed columns to readonly on decode.            .filter(|column| column.readonly != Some(true) && column.computed.is_none())            .collect();        if editable.is_empty() {            continue;        }        // The archive last: an archived record takes no other edit.        editable.sort_by_key(|column| Some(&column.key) == archived.as_ref());        let mut records = first_records(&h, &definition.id);        let money = definition.id == "transaction" || definition.source.as_ref().is_some_and(|source| source.table == "transaction");        if money {            // Statement-backed facts are immutable. Exercise the same fields            // on a handmade row too, in every view over the money table.            let expected = definition.source.as_ref().and_then(|source| source.where_.as_ref())                .and_then(|filter| filter.get("status")) == Some(&json!("expected"));            let person = first_record(&h, "person").expect("a seeded person").0;            let (account, account_data) = first_record(&h, "money_account").expect("a seeded account");            let currency = account_data.get("currency").expect("the account's currency").clone();            let made = owner(&h, "create_record", json!({"table":"transaction", "data":{                "description":"An invented editable money row", "occurred_on":"2031-03-03",                "amount_minor":1000, "amount_known":true, "account_id":account, "currency":currency, "direction":"in",                "status":if expected { "expected" } else { "actual" },                "certainty":if expected { json!("fixed") } else { Value::Null },                "for_period":"2031-03", "moves_money":true, "between_us":true, "counterparty_person_id":person            }})).expect("a handmade row to exercise alongside booked facts");            records.insert(0, (made["record"]["id"].as_str().expect("id").into(),                made["record"]["data"].as_object().expect("data").clone()));        }        if records.is_empty() {            records.extend(new_record(&h, &definition));        }        if records.is_empty() {            continue;        }        let id = records[0].0.clone();        for column in editable {            // A column passes when ANY of the table's first records takes it:            // a settled question takes no answer, an open one does. The            // archive is walked on the first record alone.            let on = if Some(&column.key) == archived.as_ref() { 1 } else { records.len() };            let mut said = String::new();            let mut tried = false;            let taken = records[..on].iter().any(|(id, data)| {                // A field hidden by its declared condition offers no editor on this row.                // Native Mac Storage probes exercise Files on its visible Mac rows.                if !column.shown_on(data) { return false; }                // Match the page's readonly_when: a saved handle (or a row                // kept elsewhere) offers commands, but no field editor.                if definition.readonly_when.as_ref().and_then(|key| data.get(key)).is_some_and(|value| match value {                    Value::Null | Value::Bool(false) => false,                    Value::String(text) => !text.trim().is_empty(),                    Value::Array(items) => !items.is_empty(),                    _ => true,                }) {                    return false;                }                candidates(&h, column, data.get(&column.key)).iter().any(|value| {                    tried = true;                    let mut patch = Map::from_iter([(column.key.clone(), value.clone())]);                    if definition.id == "ai_budget" && column.key == "currency" {                        // The currency and its units per USD are one edit.                        patch.insert("usd_rate".into(), json!(0.9));                    }                    if money {                        // Money edits carry the fields that make one valid row:                        // unknown amounts have no number, expected rows have                        // certainty, and a monthly repeat has its day.                        match column.key.as_str() {                            "account_id" => {                                if let Some(account) = value.as_str() {                                    let account = self::data(&h, "money_account", account);                                    if let Some(currency) = account.get("currency") {                                        patch.insert("currency".into(), currency.clone());                                    }                                }                            }                            "between_us" if value == &json!(true) => {                                if let Some((person, _)) = first_record(&h, "person") {                                    patch.insert("counterparty_person_id".into(), json!(person));                                }                            }                            "amount_known" => {                                patch.insert("amount_minor".into(), if value == &json!(true) { json!(3) } else { Value::Null });                                if value == &json!(false) {                                    patch.insert("status".into(), json!("expected"));                                    patch.insert("certainty".into(), json!("fixed"));                                }                            }                            "currency" => {                                patch.insert("account_id".into(), Value::Null);                                patch.insert("moves_money".into(), json!(false));                            }                            "status" => {                                patch.insert("certainty".into(), if value == &json!("expected") { json!("fixed") } else { Value::Null });                                if value == &json!("actual") {                                    patch.insert("amount_known".into(), json!(true));                                    patch.insert("amount_minor".into(), json!(3));                                }                            }                            "certainty" => { patch.insert("status".into(), json!("expected")); }                            "for_period" => {                                patch.insert("for_period".into(), json!(if data.get("for_period") == Some(&json!("2031-03")) { "2031-04" } else { "2031-03" }));                            }                            "repeat" => { patch.insert("repeat_day".into(), if value == &json!("monthly") { json!(4) } else { Value::Null }); }                            "repeat_day" => { patch.insert("repeat".into(), json!("monthly")); }                            _ => {}                        }                    }                    let restore = if column.column_type == ColumnType::Choice || money {                        // A view can omit companion fields in this patch.                        // Restore their stored values from the owning row.                        let current = self::data(&h, if money { "transaction" } else { definition.id.as_str() }, id);                        Some(patch.keys().map(|key| (key.clone(), current.get(key).cloned().unwrap_or(Value::Null))).collect::<Map<String, Value>>())                    } else { None };                    match owner(                        &h,                        "update_record",                        json!({ "table": definition.id, "id": id, "patch": patch }),                    ) {                        Ok(_) => {                            // A choice goes back as it was: a project left                            // archived would hide it from the tables under it.                            if let Some(restore) = restore {                                let restored = owner(                                    &h,                                    "update_record",                                    json!({ "table": if money { "transaction" } else { definition.id.as_str() }, "id": id, "patch": restore }),                                );                                if money {                                    // Keep each view's row inside its original                                    // filter while testing the next field.                                    restored.expect("restore the Money edit through its owning table");                                }                            }                            true                        }                        Err(sentence) => {                            let key = format!("{}.{}", definition.id, column.key);                            let reached = ANSWERED_BY_THE_ENGINE                                .iter()                                .any(|(answered, words)| *answered == key && sentence.contains(words));                            said = sentence;                            reached                        }                    }                })            });            if !tried {                continue;            }            walked += 1;            if !taken {                refused_keys.insert(format!("{}.{}", definition.id, column.key));                refused.push(format!("{}.{} — {said}", definition.id, column.key));            }        }        // Back out of the archive, so a table that hangs under this record        // still finds it.        if let Some(column) = &archived {            let _ = owner(                &h,                "update_record",                json!({ "table": definition.id, "id": id, "patch": { column: null } }),            );        }    }    assert!(walked > 0, "no editable seeded column was walked");    let expected: BTreeSet<String> = NOT_TAKEN_YET.iter().map(|(key, _)| key.to_string()).collect();    assert_eq!(        refused_keys,        expected,        "the screens offer edits the verbs refuse (fix the adapter, or declare the column \         readonly in the app's definition):\n{}",        refused.join("\n")    );}fn refusal(h: &Harness, tool: &str, args: Value) -> String {    owner(h, tool, args).expect_err("the write was expected to refuse")}fn data(h: &Harness, table: &str, id: &str) -> Map<String, Value> {    let read = owner(h, "get_record_by_table", json!({ "table": table, "id": id }))        .unwrap_or_else(|sentence| panic!("{table} {id}: {sentence}"));    read["data"].as_object().cloned().unwrap_or_default()}/// Lists whose "New …" cannot make a record from words alone yet, and whose it is.const NEW_NEEDS_MORE_YET: &[(&str, &str)] =    &[        ("alarm", "ws-linux-ux1 (Alarms): a new alarm needs its time before its label"),    ];/// RULE: A built-in list that offers "New …" makes a record from the typed words alone — the words go in the table's title column, and nothing else is asked first. A built-in no tool here draws (its tool left the kit, its table stayed: Quotas, Moods, Meetings, 3 Nov 2026) is no list, so it offers no New.#[test]fn every_new_a_builtin_list_offers_makes_a_record_from_its_words() {    let h = household();    let drawn: Vec<String> = h        .with(|db| cotton_tools::definitions::table_definitions_from_driver(db, &h.workspace_id).expect("lists"))        .definitions        .into_iter()        .map(|definition| definition.id)        .collect();    let mut walked = 0;    for definition in app_definitions() {        if !drawn.contains(&definition.id) {            continue;        }        // `create` with a path opens a screen of its own (an import); one        // with an act sends its words to the object, not to create_record;        // one with doors is the doors alone, and only a door with no act,        // files or pictures of its own takes words (Passwords' New password        // is the password_new act, Bring Apple Passwords in a file).        let offered = definition.create.as_ref().is_some_and(|create| {            create.path.is_none()                && create.act.is_none()                && (create.doors.is_empty()                    || create.doors.iter().any(|door| door.act.is_none() && door.files.is_none() && door.pick.is_none()))        });        // A list whose main act is a form (Connect an assistant) opens that form, not a record from words.        let form = definition.resolved_parts().acts.main.as_deref().and_then(|id| definition.command(id)).is_some_and(|act| act.is_form());        if form {            continue;        }        if !offered || builtin_table_definition(&definition.id).is_none() {            continue;        }        // A declared create command owns its form and submission. It does        // not promise the generic title-only create this guard exercises.        if definition.commands.as_ref().is_some_and(|commands|            commands.iter().any(|command| command.kind == CommandKind::Create)) {            continue;        }        if NEW_NEEDS_MORE_YET.iter().any(|(table, _)| *table == definition.id) {            continue;        }        walked += 1;        let title = definition.title.clone();        owner(            &h,            "create_record",            json!({ "table": definition.id, "data": { title: "Guard words" } }),        )        .unwrap_or_else(|sentence| panic!("{}'s New: {sentence}", definition.id));    }    assert!(walked > 0, "no definition offers New, so this guard checked nothing");}/// RULE: "Archive this …" is a write of the definition's archive column: a day puts the record away through its engine's own verb, null brings it back, and both are recorded as a change.#[test]fn archive_this_puts_a_record_away_and_null_brings_it_back() {    let h = household();    for table in ["note", "person"] {        let (id, _) = first_record(&h, table).or_else(|| {            let made = owner(&h, "create_record", json!({ "table": table, "data": { "title": "A Guard" } })).ok()?;            Some((made["record"]["id"].as_str()?.to_string(), Map::new()))        })        .unwrap_or_else(|| panic!("no {table} to archive"));        let away = owner(            &h,            "update_record",            json!({ "table": table, "id": id, "patch": { "archived_at": "2026-10-01T09:00:00.000Z" } }),        )        .unwrap_or_else(|sentence| panic!("archive a {table}: {sentence}"));        assert!(away["record"]["data"]["archived_at"].is_string(), "{table}: {away}");        assert!(away["change"]["id"].is_string(), "{table}: {away}");        let back = owner(            &h,            "update_record",            json!({ "table": table, "id": id, "patch": { "archived_at": null } }),        )        .unwrap_or_else(|sentence| panic!("bring a {table} back: {sentence}"));        assert!(back["record"]["data"].get("archived_at").is_none(), "{table}: {back}");    }}/// RULE: A refusal the owner's own app shows names a column by the name on the page, never by its key, and never mentions the verbs; an assistant is still told the key it must write.#[test]fn a_refusal_shown_to_a_person_names_the_column_as_the_page_does() {    let h = household();    let (event, _) = first_record(&h, "event").expect("an event");    let said = [        refusal(&h, "create_record", json!({ "table": "event", "data": { "title": "Dinner" } })),        refusal(            &h,            "update_record",            json!({ "table": "event", "id": event, "patch": { "sync_state": "pending" } }),        ),    ];    assert_eq!(said[0], "Starts is required");    let keys: BTreeSet<String> = app_definitions()        .iter()        .filter(|definition| definition.id == "event")        .flat_map(|definition| definition.columns.iter().map(|column| format!("{:?}", column.key)))        .collect();    for sentence in &said {        assert!(!sentence.contains("generic verbs"), "{sentence}");        for key in &keys {            assert!(!sentence.contains(key.as_str()), "{sentence} names the column {key}");        }    }}/// Commands no seeded record is offered on, so the guard cannot run them yet: `table.command`. EXACT./// The seed's one failed meeting stopped while being turned into text, so/// Try again is run at that stage only; the other two stages send the same/// verb with the same argument shape. The seed holds no thought still waiting/// to be filed, nor one the person filed by hand, so Make a todo, Make a note,/// File to… and the two take-backs are not run here; all send `file_thought`,/// which cotton-ffi's `making_a_todo_from_a_thought_files_the_thought_and_undo_puts_both_back`/// and `filing_a_thought_into_a_picked_table_sends_the_table` run./// RULE: Every command a built-in's page offers is declared by the core's copy of the definition, verb and arguments alike, and its verb takes them on a record the command is offered on./// RULE: An act's record picks use different records from its bound references, seeding another synthetic row when needed; repeating a pickup as the drop would exercise a valid refusal instead of the offered write.#[test]fn every_command_a_builtin_page_offers_is_run() {    let h = household();    // A filing names a shared database, and the household is the personal    // one alone — so the walk files two of its chats itself, one in one    // database and one in two, for Unfile and Unfile from… to be offered on.    let chats = first_records(&h, "thread");    assert!(chats.len() >= 2, "the household seeds chats");    let stamp = cotton_tools::clock::iso(h.clock.now());    for (n, (chat, database)) in [(0, "database-one"), (1, "database-one"), (1, "database-two")].into_iter().enumerate() {        let text = |value: &str| rusqlite::types::Value::Text(value.to_string());        h.run(            "INSERT INTO cotton_msg_thread_filings (id, workspace_id, thread_id, database_id, state, filed_at, created_at, updated_at) \             VALUES (?, ?, ?, ?, 'filed', ?, ?, ?)",            &[text(&format!("filing-{n}")), text(&h.workspace_id), text(&chats[chat].0), text(database), text(&stamp), text(&stamp), text(&stamp)],        );    }    for definition in app_definitions() {        let (Some(commands), Some(core)) = (&definition.commands, builtin_table_definition(&definition.id))        else {            continue;        };        for command in commands {            let key = format!("{}.{}", definition.id, command.id);            let declared = core.commands.iter().flatten().find(|declared| declared.id == command.id);            assert_eq!(declared, Some(command), "{key}: the core's copy declares what the page offers");            let bound = |data: &Map<String, Value>, column: &str| match column {                "$id" | "$id_list" => true,                column => data.get(column).is_some_and(|value| !value.is_null()),            };            // Read again for each command: the one before may have changed            // what this one is offered on.            let offered = first_records(&h, &definition.id).into_iter().find(|(_, data)| {                command.offered_on(&Value::Object(data.clone())) && command.bindings.iter().flat_map(|bindings| bindings.0.iter()).all(|(_, column)| bound(data, column))            });            let Some((id, data)) = offered else {                continue;            };            // Going somewhere, or an app method (a device's or the serving Mac's own call), runs no engine verb.            let Some(verb) = command.verb.as_deref() else {                continue;            };            let mut args = Map::new();            for (argument, value) in command.data.iter().flat_map(|data| data.0.iter()) {                args.insert(argument.clone(), value.clone());            }            let mut bound_records = BTreeSet::new();            for (argument, column) in command.bindings.iter().flat_map(|bindings| bindings.0.iter()) {                let value = match column.as_str() {                    "$id" => json!(id),                    "$id_list" => json!([id]),                    column => data.get(column).cloned().unwrap_or(Value::Null),                };                let table = match column.as_str() {                    "$id" | "$id_list" => Some(definition.id.as_str()),                    column => definition.columns.iter().find(|field| field.key == column)                        .and_then(|field| field.link_to.as_deref()),                };                if let Some(table) = table {                    for record in value.as_array().map(Vec::as_slice).unwrap_or(std::slice::from_ref(&value)) {                        if let Some(id) = record.as_str() {                            bound_records.insert((table.to_string(), id.to_string()));                        }                    }                }                let mut keys: Vec<&str> = argument.split('.').collect();                let last = keys.pop().expect("an argument");                let mut at = &mut args;                for key in keys {                    at = at.entry(key.to_string()).or_insert_with(|| json!({})).as_object_mut().expect("an object");                }                at.insert(last.to_string(), value);            }            // A table the person picks (File into…) is sent as the command's            // `pick_table` argument: the first table any filing accepts. Left            // out, the verb refuses the missing table — run 5184's red, the            // first time the household seeded a thought to file.            if let Some(argument) = &command.pick_table {                args.insert(argument.clone(), json!("todo"));            }            // What the person picks goes in last, at its argument's path: a            // moment, or a record not already bound in this act. A ride's            // pickup and drop must differ, whether pickup is $id or a link.            if let Some(pick) = &command.pick {                let value = match pick.kind {                    PickKind::Datetime => json!("2026-10-09T12:00:00Z"),                    PickKind::Number => pick.number_value(None).unwrap_or_else(|_| json!(1)),                    PickKind::Text => json!("spent 450 on groceries at quay street grocer"),                    // A database or a file is picked only for an app method, and an app method was counted above.                    PickKind::Database | PickKind::File => unreachable!("{key}: a database or a file is picked only for an app method"),                    PickKind::Record => {                        let table = pick.table.as_deref().unwrap_or_default();                        let choices = || {                            if let Some(filter) = &pick.filter {                                // Filter before paging, with room for each bound                                // record and one choice that has not been used.                                let limit = bound_records.iter().filter(|(bound_table, _)| bound_table == table).count() + 1;                                let listed = owner(&h, "list_records", json!({"table":table,"where":filter,"limit":limit})).expect("pick choices");                                listed["records"].as_array().into_iter().flatten()                                    .filter_map(|record| record["id"].as_str().map(str::to_string)).collect::<Vec<_>>()                            } else {                                first_records(&h, table).into_iter().map(|(id, _)| id).collect()                            }                        };                        let unused = || choices().into_iter().find(|id| !bound_records.contains(&(table.to_string(), id.clone())));                        let picked = unused().or_else(|| {                            let definition = builtin_table_definition(table).unwrap_or_else(|| panic!("{key}: no {table} definition to seed"));                            new_record(&h, &definition).unwrap_or_else(|| panic!("{key}: could not seed another {table} to pick"));                            unused()                        }).unwrap_or_else(|| panic!("{key}: no unused {table} matching {:?}", pick.filter));                        json!(picked)                    }                };                let mut keys: Vec<&str> = pick.argument.split('.').collect();                let last = keys.pop().expect("an argument");                let mut at = &mut args;                for key in keys {                    at = at.entry(key.to_string()).or_insert_with(|| json!({})).as_object_mut().expect("an object");                }                at.insert(last.to_string(), value);            }            // A command runs as its page writes it: the app asks no scope            // for an act, so a write that may land on a repeating record            // carries its own (the core never guesses, and this walk never            // answers for the kit).            owner(&h, verb, Value::Object(args))                .unwrap_or_else(|sentence| panic!("{key} ({verb}): {sentence}"));        }    }    // Unseeded definitions do not invalidate this execution guard. The    // owner's test policy forbids an exact command list/count pin; every    // command actually offered above still has to run its declared verb.}/// RULE: A picture that is in an album answers that album on its own page, so the Albums heading is never empty over a picture the album itself shows.#[test]fn a_picture_in_an_album_names_its_album() {    let h = household();    let listed = owner(&h, "list_records", json!({ "table": "album_item", "limit": 200 })).expect("album pictures");    let items = listed["records"].as_array().expect("records");    assert!(!items.is_empty(), "the household seeds an album with pictures");    let mut checked = 0;    for item in items {        let (Some(album), Some(id)) = (item["data"]["album_id"].as_str(), item["data"]["record_id"].as_str()) else { continue };        let table = if id.starts_with("video") { "video" } else { "photo" };        let read = owner(&h, "get_record_by_table", json!({ "table": table, "id": id })).unwrap_or_else(|sentence| panic!("{table} {id}: {sentence}"));        let albums = read["data"]["albums"].as_array().cloned().unwrap_or_default();        assert!(albums.contains(&json!(album)), "{table} {id} is in {album} and says {albums:?}");        checked += 1;    }    assert!(checked > 0, "no album picture names its record");}/// RULE: A repeating todo says how often it comes round in words — the page's Repeats row is answered by the read, never left empty and never a stored rule.#[test]fn a_repeating_todo_says_how_often() {    let h = household();    let listed = owner(&h, "list_records", json!({ "table": "todo", "limit": 200 })).expect("the todos");    let repeating: Vec<&Value> = listed["records"].as_array().unwrap().iter().filter(|t| t["data"]["recurrence_id"].is_string()).collect();    assert!(!repeating.is_empty(), "the household seeds a repeating todo");    for todo in repeating {        assert!(todo["data"]["repeats"].as_str().is_some_and(|words| !words.trim().is_empty() && !words.contains("FREQ")), "{todo}");    }}/// RULE: An event's page is answered whole by the read — where it came from, its day, its calendar by name, each guest with their reply and the people it is with — so no row of the page is drawn from a column nothing produces.#[test]fn an_event_says_where_it_came_from_when_it_is_and_who_replied() {    let h = household();    let listed = owner(&h, "list_records", json!({ "table": "event", "limit": 200 })).expect("the events");    let events = listed["records"].as_array().expect("records");    assert!(!events.is_empty(), "the household seeds events");    let mut seen = std::collections::BTreeSet::new();    for event in events {        let data = &event["data"];        // Made in Cotton says nothing; only one from elsewhere says where.        assert!(matches!(data["source"].as_str(), None | Some("Google Calendar" | "A thought")), "{event}");        // The reply is offered only on an invitation someone else sent.        assert!(data["invited"].is_null() || data["invited"] == json!("invited"), "{event}");        // The day it is on, as a day; never words counted from today.        let day = data["day"].as_str().unwrap_or_else(|| panic!("an event says its day: {event}"));        assert!(day.len() == 10 && data["timing"].is_null(), "{event}");        for key in ["calendar_name", "guest_responses", "people"] {            if !data[key].is_null() {                seen.insert(key);            }        }        if let Some(replies) = data["guest_responses"].as_str() {            assert!(replies.lines().all(|line| line.contains(" · ")), "{replies}");        }    }    assert!(seen.contains("calendar_name"), "an event names its calendar: {seen:?}");    assert!(seen.contains("guest_responses"), "the household seeds an event with guests: {seen:?}");}/// RULE: A person's page is answered by the read — their birthday as one day, who wrote their summary, when, and what arrived since, and the channel their chat runs over — so the page draws no row from a column nothing produces.#[test]fn a_person_says_their_birthday_their_summarys_byline_and_how_they_are_messaged() {    let h = household();    let listed = owner(&h, "list_records", json!({ "table": "person", "limit": 200 })).expect("the people");    let people = listed["records"].as_array().expect("records");    let mut seen = std::collections::BTreeSet::new();    for person in people {        let data = &person["data"];        if let Some(birthday) = data["birthday"].as_str() {            let day = birthday.strip_prefix("--").map_or(birthday.len() == 10, |rest| rest.len() == 5);            assert!(day && data["birth_month"].is_number() && data["birth_day"].is_number(), "{person}");            assert_eq!(birthday.starts_with("--"), data["birth_year"].is_null(), "{person}");        } else {            assert!(data["birth_month"].is_null() || data["birth_day"].is_null(), "a known birthday is said: {person}");        }        if let Some(since) = data["summary_since"].as_str() {            assert!(since.ends_with(" since") && !data["summary_updated_at"].is_null(), "{person}");        }        for key in ["birthday", "summary_by", "summary_updated_at", "summary_since", "thread_channel"] {            if !data[key].is_null() {                seen.insert(key);            }        }    }    for key in ["birthday", "thread_channel"] {        assert!(seen.contains(key), "the household seeds a person with {key}: {seen:?}");    }    // A summary is stamped with who wrote it and when, and the notes that arrived after it are counted.    let (_, note) = first_record(&h, "person_note").expect("the household seeds a note about a person");    let id = note["person_id"].as_str().expect("the person the note is about").to_string();    h.clock.set(chrono::DateTime::parse_from_rfc3339("2020-01-01T00:00:00Z").unwrap().with_timezone(&chrono::Utc));    owner(&h, "update_record", json!({ "table": "person", "id": id, "patch": { "summary": "Sails on Sundays." } }))        .expect("the summary is taken");    let written = data(&h, "person", &id);    // The harness's phone is named by its device; the owner's own app is "user".    assert!(written["summary_by"].is_string() && written["summary_updated_at"].is_string(), "{written:?}");    let since = written["summary_since"].as_str().unwrap_or_else(|| panic!("the notes since are counted: {written:?}"));    assert!(since.ends_with(" note since") || since.ends_with(" notes since"), "{since}");}/// The device a synthetic meeting is recorded on: its author id, and the key/// its author fact names (`cotton_store::fixtures::author_device`).const RECORDER: &str = "device:synthetic-kitchen-tablet";const STRANGER: &str = "device:synthetic-unknown-recorder";/// A meeting made by `author`'s device in `status`, folded as that device's/// push — so its birth stamp names the author.fn meeting_made_by(h: &Harness, author: &str, n: u64, status: &str) -> String {    let id = synthetic_uuid(&format!("waiting-meeting-{n}"));    h.seed(&[json!({        "opId": format!("01M{n:023}"),        "deviceId": author,        "kind": "upsert",        "table": "cotton_meetings",        "rowId": id,        "patch": {            "workspace_id": h.workspace_id,            "title": "Allotment committee",            "status": status,            "failed_stage": (status == "failed").then_some("transcribe"),            "source": "recorded",            "started_at": "2026-09-10T08:00:00.000Z",            "status_changed_at": "2026-09-10T08:30:00.000Z",            "created_at": "2026-09-10T08:00:00.000Z",            "updated_at": "2026-09-10T08:30:00.000Z",        },        "hlc": format!("1757491200{n:03}:0000:{author}"),        "schemaVersion": cotton_store::schema::ddl::SCHEMA_VERSION,    })]);    id}/// The device the owner admitted under `author`'s key, by `name`. Written/// straight into the file: approving a device is a person comparing digits.fn admit_recorder(h: &Harness, author: &str, name: &str) {    let text = |value: &str| rusqlite::types::Value::Text(value.to_string());    let at = "2026-09-08T09:00:00.000Z";    h.run(        "INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, \         approved_by_device, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'self', ?, ?)",        &[            text(&format!("device-row-{author}")),            text(&h.workspace_id),            text(&cotton_store::fixtures::author_device(author)),            text(name),            text(at),            text(at),            text(at),        ],    );}/// A meeting as the list answers it.fn listed_meeting(h: &Harness, id: &str) -> Map<String, Value> {    let listed = owner(h, "list_records", json!({ "table": "meeting", "limit": 200 })).expect("the meetings");    listed["records"]        .as_array()        .expect("records")        .iter()        .find(|record| record["id"] == json!(id))        .and_then(|record| record["data"].as_object().cloned())        .unwrap_or_else(|| panic!("the list holds meeting {id}: {listed}"))}/// RULE: A made table's computed columns are answered by every read as soon as the write that moves them is made — a rollup on the record linked to, a lookup and a formula on the record written — and a write may not name one.#[test]fn a_made_tables_computed_columns_follow_its_writes() {    let h = household();    let table = |id: &str, columns: Value| {        json!({            "id": id, "name": id, "plural": format!("{id}s"), "picture": null, "builtin": false, "engine": null,            "columns": columns, "title": "name", "date": null, "project": null, "order": null,            "slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null },            "tile": { "face": "slip-list" }, "page": [{ "heading": null, "columns": ["name"] }],            "instructions": "A made table with computed columns."        })    };    let pupil = table("pupil", json!([        { "key": "name", "type": "text" },        { "key": "lessons", "type": "number", "computed": { "rollup": { "table": "lesson", "link": "pupil", "op": "count" } } },        { "key": "paid", "type": "number", "computed": { "rollup": { "table": "lesson", "link": "pupil", "op": "sum", "column": "fee", "where": { "column": "status", "values": ["paid"] } } } }    ]));    let lesson = table("lesson", json!([        { "key": "name", "type": "text" },        { "key": "pupil", "type": "link", "link_to": "pupil" },        { "key": "fee", "type": "number" },        { "key": "status", "type": "choice", "choices": ["paid", "due"] },        { "key": "pupil_name", "type": "text", "computed": { "lookup": { "through": "pupil", "column": "name" } } },        { "key": "label", "type": "text", "computed": { "formula": { "op": "join", "of": ["name", "pupil_name"] } } }    ]));    for definition in [&pupil, &lesson] {        h.run(            "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) \             VALUES (?, ?, ?, 0, '2026-10-05T00:00:00.000Z', '2026-10-05T00:00:00.000Z')",            &[                rusqlite::types::Value::Text(definition["id"].as_str().expect("an id").to_string()),                rusqlite::types::Value::Text(h.workspace_id.clone()),                rusqlite::types::Value::Text(definition.to_string()),            ],        );    }    let made = |table: &str, data: Value| -> String {        let answer = owner(&h, "create_record", json!({ "table": table, "data": data })).unwrap_or_else(|error| panic!("{table}: {error}"));        answer["record"]["id"].as_str().expect("an id").to_string()    };    let asha = made("pupil", json!({ "name": "Asha" }));    let first = made("lesson", json!({ "name": "Scales", "pupil": asha, "fee": 40, "status": "paid" }));    made("lesson", json!({ "name": "Chords", "pupil": asha, "fee": 45, "status": "due" }));    let pupil = data(&h, "pupil", &asha);    assert_eq!((pupil.get("lessons"), pupil.get("paid")), (Some(&json!(2)), Some(&json!(40))), "{pupil:?}");    let listed = owner(&h, "list_records", json!({ "table": "lesson" })).expect("the lessons");    for lesson in listed["records"].as_array().expect("records") {        assert_eq!(lesson["data"]["pupil_name"], json!("Asha"), "{lesson}");    }    owner(&h, "update_record", json!({ "table": "pupil", "id": asha, "patch": { "name": "Asha K" } })).expect("renamed");    assert_eq!(data(&h, "lesson", &first).get("label"), Some(&json!("Scales Asha K")));    owner(&h, "delete_record", json!({ "table": "lesson", "id": first })).expect("deleted");    let pupil = data(&h, "pupil", &asha);    assert_eq!((pupil.get("lessons"), pupil.get("paid")), (Some(&json!(1)), Some(&json!(0))), "{pupil:?}");    let refused = refusal(&h, "update_record", json!({ "table": "pupil", "id": asha, "patch": { "lessons": 9 } }));    assert!(refused.contains("worked out"), "{refused}");}/// A made table's definition, `extra` laid over the plain shape.fn made_table(id: &str, columns: Value, extra: Value) -> Value {    let mut table = json!({        "id": id, "name": id, "plural": format!("{id}s"), "picture": null, "builtin": false, "engine": null,        "columns": columns, "title": "name", "date": null, "project": null, "order": null,        "slip": { "title": "name", "subtitle": null, "trailing": null, "photo": null, "toggle": null },        "tile": { "face": "slip-list" }, "page": [{ "heading": null, "columns": ["name"] }],        "instructions": "A made table for a list's order and filters."    });    for (key, value) in extra.as_object().cloned().unwrap_or_default() {        table[key] = value;    }    table}fn define(h: &Harness, definition: &Value) {    h.run(        "INSERT INTO cotton_table_definitions (id, workspace_id, definition, builtin, created_at, updated_at) \         VALUES (?, ?, ?, 0, '2026-10-05T00:00:00.000Z', '2026-10-05T00:00:00.000Z')",        &[            rusqlite::types::Value::Text(definition["id"].as_str().expect("an id").to_string()),            rusqlite::types::Value::Text(h.workspace_id.clone()),            rusqlite::types::Value::Text(definition.to_string()),        ],    );}fn made_record(h: &Harness, table: &str, data: Value) -> String {    let answer = owner(h, "create_record", json!({ "table": table, "data": data })).unwrap_or_else(|error| panic!("{table}: {error}"));    answer["record"]["id"].as_str().expect("an id").to_string()}/// Pupils listed by how many lessons they have, most first (a rollup), and/// lessons that look their pupil's name and standing up (lookups) and join/// their own name to it (a formula). Answers each pupil's id by name.fn pupils_and_lessons(h: &Harness, lessons: &[(&str, usize)]) -> Vec<(String, String)> {    define(h, &made_table("pupil", json!([        { "key": "name", "type": "text" },        { "key": "active", "type": "bool" },        { "key": "lessons", "type": "number", "computed": { "rollup": { "table": "lesson", "link": "pupil", "op": "count" } } }    ]), json!({ "sort": { "column": "lessons", "descending": true } })));    define(h, &made_table("lesson", json!([        { "key": "name", "type": "text" },        { "key": "pupil", "type": "link", "link_to": "pupil" },        { "key": "pupil_name", "type": "text", "computed": { "lookup": { "through": "pupil", "column": "name" } } },        { "key": "pupil_active", "type": "bool", "computed": { "lookup": { "through": "pupil", "column": "active" } } },        { "key": "label", "type": "text", "computed": { "formula": { "op": "join", "of": ["name", "pupil_name"] } } }    ]), json!({})));    let mut pupils = Vec::new();    for (index, (name, count)) in lessons.iter().enumerate() {        let id = made_record(h, "pupil", json!({ "name": name, "active": index % 2 == 0 }));        for lesson in 0..*count {            made_record(h, "lesson", json!({ "name": format!("Lesson {lesson}"), "pupil": id }));        }        pupils.push((name.to_string(), id));    }    pupils}fn names(listed: &Value) -> Vec<String> {    listed["records"]        .as_array()        .expect("records")        .iter()        .map(|record| record["data"]["name"].as_str().unwrap_or_default().to_string())        .collect()}/// RULE: A made table's list orders by a computed column before its page is cut — the first page holds the top values of the whole table, and its total counts every record — because the values live in the device-local index the list joins.#[test]fn a_made_list_orders_by_a_computed_column_before_its_page_is_cut() {    let h = household();    // Made fewest-first, so neither the made time nor the written time is the answer.    pupils_and_lessons(&h, &[("Ivo", 0), ("Bela", 1), ("Cato", 2), ("Dara", 3), ("Esme", 4)]);    let first = owner(&h, "list_records", json!({ "table": "pupil", "limit": 2 })).expect("the first page");    assert_eq!(names(&first), ["Esme", "Dara"], "{first}");    assert_eq!(first["total"], json!(5), "{first}");    assert_eq!(first["records"][0]["data"]["lessons"], json!(4), "the values still ride on the records: {first}");    let next = first["next_page"].as_i64().expect("a next page");    let second = owner(&h, "list_records", json!({ "table": "pupil", "limit": 2, "page": next })).expect("the second page");    assert_eq!(names(&second), ["Cato", "Bela"], "{second}");}/// RULE: A made table's list filters and searches on a computed column — a rollup's count, a formula's words, a looked-up yes or no, present or not, and a looked-up name found by a search — reading the index, never the record's own data where those values are not.#[test]fn a_made_list_filters_and_searches_on_a_computed_column() {    let h = household();    let pupils = pupils_and_lessons(&h, &[("Asha", 2), ("Ravi", 1), ("Tara", 0)]);    made_record(&h, "lesson", json!({ "name": "Lesson alone" }));    let list = |args: Value| owner(&h, "list_records", args).unwrap_or_else(|error| panic!("{error}"));    let two = list(json!({ "table": "pupil", "where": { "lessons": 2 } }));    assert_eq!((names(&two), two["total"].clone()), (vec!["Asha".to_string()], json!(1)), "{two}");    let some = list(json!({ "table": "pupil", "where": { "lessons": { "values": [1, 2] } } }));    assert_eq!(names(&some), ["Asha", "Ravi"], "{some}");    let labelled = list(json!({ "table": "lesson", "where": { "label": "Lesson 0 Ravi" } }));    assert_eq!(labelled["total"], json!(1), "{labelled}");    assert_eq!(labelled["records"][0]["data"]["pupil"], json!(pupils[1].1), "{labelled}");    // Asha is active (true, kept as 1), Ravi is not (false, kept as 0).    let active = list(json!({ "table": "lesson", "where": { "pupil_active": true } }));    assert_eq!(active["total"], json!(2), "{active}");    let inactive = list(json!({ "table": "lesson", "where": { "pupil_active": false } }));    assert_eq!(inactive["total"], json!(1), "{inactive}");    let alone = list(json!({ "table": "lesson", "where": { "pupil_name": { "present": false } } }));    assert_eq!(names(&alone), ["Lesson alone"], "{alone}");    let had = list(json!({ "table": "lesson", "where": { "pupil_name": { "present": true } } }));    assert_eq!(had["total"], json!(3), "{had}");    // No lesson's own name says Asha: only the looked-up name does.    let found = list(json!({ "table": "lesson", "query": "asha" }));    assert_eq!(found["total"], json!(2), "{found}");    assert!(found["records"].as_array().expect("records").iter().all(|lesson| lesson["data"]["pupil_name"] == "Asha"), "{found}");}/// RULE: A made table's list reads in its definition's sort — the blanks last, capitals ignored, records alike in the sort column ordered by its tie the same way — so the first page is the one the app draws first.#[test]fn a_made_list_reads_in_its_definitions_sort() {    let h = household();    // A made table's id is one no kit ships (the personal kit's Library has `book`).    define(&h, &made_table("volume", json!([        { "key": "name", "type": "text" },        { "key": "author", "type": "text" }    ]), json!({ "sort": { "column": "author", "tie": "name" } })));    for (name, author) in [("Zed", json!("Alan")), ("Mid", json!("bea")), ("Blank", json!("")), ("Ant", json!("alan")), ("Absent", Value::Null)] {        let mut data = json!({ "name": name });        if !author.is_null() {            data["author"] = author;        }        made_record(&h, "volume", data);    }    let listed = owner(&h, "list_records", json!({ "table": "volume" })).expect("the volumes");    assert_eq!(names(&listed), ["Ant", "Zed", "Mid", "Absent", "Blank"], "{listed}");    // Descending: the blanks still last, the tie turned over too.    define(&h, &made_table("shelf", json!([        { "key": "name", "type": "text" },        { "key": "author", "type": "text" }    ]), json!({ "sort": { "column": "author", "descending": true, "tie": "name" } })));    for (name, author) in [("Zed", "Alan"), ("Mid", "bea"), ("Blank", ""), ("Ant", "alan")] {        made_record(&h, "shelf", json!({ "name": name, "author": author }));    }    let listed = owner(&h, "list_records", json!({ "table": "shelf" })).expect("the shelf");    assert_eq!(names(&listed), ["Mid", "Zed", "Ant", "Blank"], "{listed}");}/// RULE: A list that orders, filters or searches on a computed column while the index is stale says it is being worked out instead of answering a wrong list, because a read may not rebuild the index; the next fold rebuilds it and the list answers again.#[test]fn a_stale_index_never_answers_a_wrong_list() {    let h = household();    pupils_and_lessons(&h, &[("Ivo", 0), ("Esme", 2)]);    h.run("DELETE FROM _computed WHERE table_id = '' AND record_id = '' AND key = 'derivation'", &[]);    let refused = owner(&h, "list_records", json!({ "table": "pupil" })).expect_err("a stale index answers no ordered list");    assert_eq!(refused, "This list is being worked out \u{2014} try again in a moment.");    let refused = owner(&h, "list_records", json!({ "table": "lesson", "query": "Esme" })).expect_err("nor a search on a looked-up name");    assert!(refused.contains("being worked out"), "{refused}");    // A list that reads no computed column before its page is cut still answers.    let plain = owner(&h, "list_records", json!({ "table": "lesson", "where": { "name": "Lesson 0" } })).expect("a plain list");    assert_eq!(plain["total"], json!(1), "{plain}");    // The next write folds, the fold rebuilds the index, and the list answers.    made_record(&h, "pupil", json!({ "name": "Noor" }));    let listed = owner(&h, "list_records", json!({ "table": "pupil" })).expect("the rebuilt index answers");    assert_eq!(names(&listed)[0], "Esme", "{listed}");}/// RULE: A stale index's refusal is line `refusal.tables.being_worked_out`, never a sentence in Rust: a database that rewords it says its own words, and the app's boundary knows it as a list mid-move by the typed note the refusal leaves (`take_being_worked_out`), never by its words.#[test]fn a_stale_index_refuses_in_the_databases_own_words() {    let h = household();    pupils_and_lessons(&h, &[("Ivo", 0), ("Esme", 2)]);    let words = "Still sorting this list out, ask again shortly.";    h.run("UPDATE cotton_lines SET words = ? WHERE \"set\" = 'refusal' AND line = 'tables.being_worked_out'", &[rusqlite::types::Value::Text(words.into())]);    h.run("DELETE FROM _computed WHERE table_id = '' AND record_id = '' AND key = 'derivation'", &[]);    let _ = cotton_tools::mcp::handlers::tables::take_being_worked_out();    let refused = owner(&h, "list_records", json!({ "table": "pupil" })).expect_err("a stale index answers no ordered list");    assert_eq!(refused, words);    assert!(cotton_tools::mcp::handlers::tables::take_being_worked_out(), "the refusal left no typed note");    assert!(!cotton_tools::mcp::handlers::tables::take_being_worked_out(), "the note is taken once");    let other = owner(&h, "get_record", json!({ "table": "pupil", "id": "no-such-pupil" })).expect_err("no such pupil");    assert!(!other.is_empty());    assert!(!cotton_tools::mcp::handlers::tables::take_being_worked_out(), "another refusal is not a list mid-move");}/// RULE: An event's read answers its DAY and its start time in the reader's zone — the zone the read names, as a phone names its own — and never words counted from today, so the heading over an event and the slip under it come from one day (R5, R7).#[test]fn an_events_day_and_start_time_are_the_readers() {    let h = household();    // Wednesday 7 October, 20:07 in Berlin — already Thursday morning in Auckland.    let made = owner(        &h,        "create_record",        json!({ "table": "event", "data": { "title": "Book club", "starts_at": "2026-10-07T18:07:00.000Z", "ends_at": "2026-10-07T19:07:00.000Z" } }),    )    .expect("the event is taken");    let id = made["record"]["id"].as_str().expect("an id").to_string();    let read = |zone: &str| {        let got = owner(&h, "get_record_by_table", json!({ "table": "event", "id": id, "timezone": zone })).expect("the event");        let listed = owner(&h, "list_records", json!({ "table": "event", "ids": [id], "timezone": zone })).expect("the events");        assert_eq!(listed["records"][0]["data"], got["data"], "a list and a page say the same");        assert!(got["data"]["timing"].is_null(), "no words counted from today: {got}");        (got["data"]["day"].as_str().unwrap_or_default().to_string(), got["data"]["start_time"].as_str().unwrap_or_default().to_string())    };    assert_eq!(read("Europe/Berlin"), ("2026-10-07".to_string(), "20:07".to_string()));    assert_eq!(read("Pacific/Auckland"), ("2026-10-08".to_string(), "07:07".to_string()));    assert_eq!(read("America/Los_Angeles"), ("2026-10-07".to_string(), "11:07".to_string()));    // The clock does not move the answer: a day is a day.    h.clock.advance(chrono::Duration::days(3));    assert_eq!(read("Europe/Berlin"), ("2026-10-07".to_string(), "20:07".to_string()));    let refused = refusal(&h, "get_record_by_table", json!({ "table": "event", "id": id, "timezone": "Mars/Olympus" }));    assert!(refused.contains("timezone"), "{refused}");}/// RULE: A seeded event on the connected calendar reads sync_state "synced", source "Google Calendar" and its calendar; event's kept_by says "Kept in step with Google Calendar" on sync_state; an event made with create_record has no sync_state.#[test]fn an_event_the_calendar_connection_keeps_says_so_and_one_made_here_does_not() {    let h = household();    let kept = builtin_table_definition("event").and_then(|definition| definition.kept_by.clone()).expect("event names its keeper");    assert_eq!((kept.when.as_str(), kept.says.as_str()), ("sync_state", "Kept in step with Google Calendar"));    let synced = h        .with(|db| {            db.get(                "SELECT e.id FROM cotton_events e JOIN cotton_collections c ON c.id = e.collection_id \                 WHERE c.name = 'Work' AND e.title = 'Stand-up'",                &[],            )        })        .expect("a query")        .and_then(|row| row.text("id").map(str::to_string))        .expect("the household seeds Stand-up on its Work calendar");    let read = data(&h, "event", &synced);    assert_eq!(read.get("title"), Some(&json!("Stand-up")), "{read:?}");    assert_eq!(read.get("sync_state"), Some(&json!("synced")), "{read:?}");    assert_eq!(read.get("source"), Some(&json!("Google Calendar")), "{read:?}");    assert_eq!(read.get("calendar_name"), Some(&json!("Work")), "{read:?}");    let made = owner(        &h,        "create_record",        json!({ "table": "event", "data": { "title": "Made here", "starts_at": "2026-10-09T10:00:00Z", "ends_at": "2026-10-09T11:00:00Z" } }),    )    .expect("an event made in the app");    let id = made["record"]["id"].as_str().expect("an id").to_string();    let read = data(&h, "event", &id);    assert!(read.get("sync_state").is_none_or(Value::is_null), "an event made here says nothing of a keeper: {read:?}");    assert!(read.get("source").is_none_or(Value::is_null), "an event made here says nothing of where it came from: {read:?}");    assert!(read.get("invited").is_none_or(Value::is_null), "the owner's own event asks no reply: {read:?}");    assert!(read.get("calendar_name").is_none_or(Value::is_null), "the default calendar goes unnamed: {read:?}");}// RULE: every conversation-style table answers its seeded messages — a thread's page asks the messages' table narrowed by each link, and no such table reads empty across the household.#[test]fn every_conversation_table_answers_its_seeded_messages() {    let h = household();    let mut walked = BTreeSet::new();    for definition in app_definitions() {        let Some(layout) = definition.conversation.as_ref() else { continue };        // Email and Messages: the kit's two the core's generic list answers        // and the household seeds.        let seeded = ["thread", "email_thread"].contains(&definition.id.as_str());        if !seeded {            continue;        }        walked.insert(definition.id.clone());        let threads = first_records(&h, &definition.id);        assert!(!threads.is_empty(), "the household seeds no {}", definition.id);        let mut answered = 0;        for (id, data) in &threads {            let mut found = BTreeSet::new();            for link in &layout.links {                // A link only the app's own copy declares is answered by the                // app's adapter for that table, never by the core's list.                if builtin_table_definition(&layout.table).is_some_and(|table| table.column(link).is_none()) {                    continue;                }                let page = owner(&h, "list_records", json!({ "table": layout.table, "where": { link: id }, "limit": 200 }))                    .unwrap_or_else(|sentence| panic!("{} of {} {id}: {sentence}", layout.table, definition.id));                for record in page["records"].as_array().into_iter().flatten() {                    found.extend(record["id"].as_str().map(str::to_string));                }            }            // A thread that counts its emails answers exactly that many.            if let Some(count) = data.get("email_count").and_then(Value::as_u64) {                assert_eq!(found.len() as u64, count, "{} {id} counts {count} emails", definition.id);            }            answered += usize::from(!found.is_empty());        }        assert!(answered > 0, "no {} of the household answers a single {}", definition.id, layout.table);    }    for table in ["thread", "email_thread"] {        assert!(walked.contains(table), "{table} is no longer a conversation table");    }}// RULE: a binned email thread's page shows what was binned — its emails, as many as it counts — and Restore (the Bin's act, never the thread's own) puts the thread back in the list (architect 1030; acts ruling 13 Oct 2026).#[test]fn a_binned_thread_shows_its_emails_and_restore_brings_it_back() {    let h = household();    let binned = owner(&h, "list_records", json!({ "table": "email_thread", "where": { "binned": true }, "limit": 50 }))        .expect("the bin's threads");    let threads = binned["records"].as_array().cloned().unwrap_or_default();    assert!(!threads.is_empty(), "the household seeds no binned thread");    for thread in &threads {        let id = thread["id"].as_str().expect("an id");        let opened = owner(&h, "get_record_by_table", json!({ "table": "email_thread", "id": id }))            .unwrap_or_else(|sentence| panic!("a binned thread {id} opens: {sentence}"));        let data = opened["data"].clone();        let emails = owner(&h, "list_records", json!({ "table": "email", "where": { "thread_id": id }, "limit": 200 }))            .expect("the thread's emails");        let answered = emails["records"].as_array().map_or(0, Vec::len) as u64;        assert!(answered > 0, "binned thread {id} opens with no emails");        if let Some(count) = data["email_count"].as_u64() {            assert_eq!(answered, count, "binned thread {id} counts {count} emails");        }    }    let id = threads[0]["id"].as_str().expect("an id");    owner(&h, "restore_from_bin", json!({ "kind": "email_thread", "id": id }))        .unwrap_or_else(|sentence| panic!("Restore on {id}: {sentence}"));    let listed = owner(&h, "list_records", json!({ "table": "email_thread", "limit": 500 })).expect("the thread list");    assert!(        listed["records"].as_array().into_iter().flatten().any(|r| r["id"] == json!(id)),        "restored thread {id} is not back in the list"    );}// RULE: a conversation's delete moves it and its emails to the bin, answers "Moved <subject> to the bin" (the Bin's tile on Home, the default) with Undo; restored from the Bin it is back in Email and found by search (walk 3c SEV 1).#[test]fn a_thread_restored_from_the_bin_is_back_in_email_and_found_by_search() {    let h = household();    let definition = app_definitions().into_iter().find(|d| d.id == "email_thread").expect("email_thread.json");    // The page offers no Delete until the app runs it through the core (the    // app's own Email adapter refuses it — architect 1640 SEV 1: only what    // works is offered); the core's delete is ready for that day.    assert_eq!(definition.delete, Some(false), "a conversation's page offers a Delete the app refuses");    let listed = owner(&h, "list_records", json!({ "table": "email_thread", "limit": 50 })).expect("the thread list");    let thread = listed["records"].as_array().and_then(|rows| rows.first()).cloned().expect("a live thread");    let id = thread["id"].as_str().expect("an id").to_string();    let subject = thread["data"]["subject"].as_str().expect("a subject").to_string();    let binned = owner(&h, "delete_record", json!({ "table": "email_thread", "id": id })).expect("Delete");    // A bin receipt, worded for whether the Bin's tile is on Home (`binned_said`).    let bin_said = [true, false].map(|shown| json!(cotton_core::records::receipt::binned_said(&subject, shown)));    assert!(bin_said.contains(&binned["change"]["receipt"]["said"]), "{binned}");    assert_eq!(binned["change"]["undoable"], json!(true), "{binned}");    let change = binned["change"]["id"].as_str().expect("a change id").to_string();    owner(&h, "undo", json!({ "change_id": change })).expect("Undo");    let again = owner(&h, "get_record_by_table", json!({ "table": "email_thread", "id": id })).expect("the thread");    assert_ne!(again["data"]["binned"], json!(true), "Undo left the thread in the bin: {again}");    owner(&h, "delete_record", json!({ "table": "email_thread", "id": id })).expect("Delete again");    let back = owner(&h, "restore_from_bin", json!({ "kind": "email_thread", "id": id })).expect("Restore from the Bin");    assert_eq!(back["restored"], true, "{back}");    let listed = owner(&h, "list_records", json!({ "table": "email_thread", "limit": 500 })).expect("the thread list");    assert!(        listed["records"].as_array().into_iter().flatten().any(|r| r["id"] == json!(id)),        "a thread restored from the Bin is not back in Email"    );    let emails = owner(&h, "list_records", json!({ "table": "email", "where": { "thread_id": id }, "limit": 200 })).expect("its emails");    let emails = emails["records"].as_array().cloned().unwrap_or_default();    assert!(!emails.is_empty(), "a restored thread answers no emails");    for email in &emails {        assert!(email["data"]["trashed_at"].is_null(), "a restored thread's email is still in the bin: {email}");    }    let found = owner(&h, "search_records", json!({ "query": subject, "kinds": ["email_thread"] })).expect("search");    assert!(        found["records"].as_array().into_iter().flatten().any(|r| r["id"] == json!(id)),        "search does not find the restored thread \"{subject}\": {found}"    );}// RULE: a record restored from the Bin returns with its edited time unchanged, so it keeps its place in its list (architect 1115).#[test]fn a_note_restored_from_the_bin_keeps_its_edited_time() {    let h = household();    let made = owner(&h, "create_record", json!({ "table": "note", "data": { "title": "Shed key under the blue pot" } })).expect("a note");    let id = made["record"]["id"].as_str().expect("an id").to_string();    let edited = |h: &Harness| data(h, "note", &id).get("updated_at").cloned();    let before = edited(&h);    assert!(before.is_some(), "a note answers no updated_at");    owner(&h, "delete_record", json!({ "table": "note", "id": id })).expect("Move to bin");    owner(&h, "restore_from_bin", json!({ "kind": "note", "id": id })).expect("Restore from the Bin");    assert_eq!(edited(&h), before, "a restored note's edited time moved");}/// A value a date column answers, judged: a day ("2026-10-05"), a month/// ("2027-11"), or a moment that carries its zone. A wall clock with no zone/// ("2026-10-05T07:00:00") is a time some read formatted in a zone of its own.fn a_zoneless_clock(value: &str) -> bool {    let value = value.trim();    value.len() > 10        && value.as_bytes().get(10) == Some(&b'T')        && chrono::DateTime::parse_from_rfc3339(value).is_err()}// RULE: no read answers a date column as a wall clock with no zone — a time is an instant the phone's one formatter draws in the reader's zone, so a slip and its page never disagree (News: 7:00 am on the slip, 5:30 am on the page).#[test]fn no_read_answers_a_time_in_a_zone_of_its_own() {    let h = household();    let mut read = 0;    let mut wrong = Vec::new();    for definition in app_definitions() {        let dates: Vec<&str> = definition            .columns            .iter()            .filter(|column| column.column_type == ColumnType::Date)            .map(|column| column.key.as_str())            .collect();        if dates.is_empty() {            continue;        }        for (id, data) in first_records(&h, &definition.id) {            read += 1;            for key in &dates {                if let Some(value) = data.get(*key).and_then(Value::as_str) {                    if a_zoneless_clock(value) {                        wrong.push(format!("{}.{key} of {id}: {value}", definition.id));                    }                }            }        }    }    assert!(read > 100, "the household answered only {read} dated records");    assert!(wrong.is_empty(), "a time answered in a zone of its own:\n{}", wrong.join("\n"));}/// Every record of one section of a day-plan list, paged to its end as the/// app pages it, and the count the read says the section holds.fn whole_section(h: &Harness, table: &str, section: &str) -> (Vec<Value>, i64) {    let mut rows = Vec::new();    let mut page = 0;    loop {        let read = owner(h, "list_records", json!({ "table": table, "section": section, "page": page, "limit": 50 }))            .unwrap_or_else(|sentence| panic!("{table} {section} page {page}: {sentence}"));        let count = read["sections"].as_array().into_iter().flatten()            .find(|s| s["key"] == json!(section)).map_or(0, |s| s["count"].as_i64().unwrap_or(0));        rows.extend(read["records"].as_array().cloned().unwrap_or_default());        match read["next_page"].as_i64() {            Some(next) => page = next,            None => return (rows, count),        }        assert!(rows.len() < 20_000, "{table} {section} never ends");    }}// RULE: a repeating event stands under every day it happens in the year ahead, each a row of its own that opens the series at that time, says deletable:false and is never deleted alone; the coming count is the rows it pages to (architect, walk 1012: Swimming Tue and Thu).#[test]fn every_occurrence_of_a_repeating_event_stands_under_its_day() {    let h = household_today();    let (coming, count) = whole_section(&h, "event", "coming");    assert_eq!(coming.len() as i64, count, "the coming count is what it pages to");    let ids: BTreeSet<&str> = coming.iter().filter_map(|r| r["id"].as_str()).collect();    assert_eq!(ids.len(), coming.len(), "a listed row's id is its own");    let today = h.clock.now().date_naive();    for title in ["Swimming", "Team catch-up"] {        let days: BTreeSet<String> = coming            .iter()            .filter(|r| r["data"]["title"] == json!(title))            .filter_map(|r| r["data"]["starts_at"].as_str().map(|at| at[..10].to_string()))            .filter(|day| chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").is_ok_and(|d| (d - today).num_days() < 15))            .collect();        assert!(days.len() >= 2, "{title} stands once in the next two weeks: {days:?}");    }    let later = coming.iter().find(|r| r["id"].as_str().is_some_and(|id| id.contains('@'))).expect("a later occurrence");    let id = later["id"].as_str().unwrap();    let opened = owner(&h, "get_record_by_table", json!({ "table": "event", "id": id })).expect("an occurrence opens");    assert_eq!(opened["id"], later["id"], "{opened}");    assert_eq!(opened["data"]["starts_at"], later["data"]["starts_at"], "{opened}");    // A delete asks how far it reaches (architect 1600): without scope it is    // refused and nothing goes; "this" takes that day alone to the bin, and    // Undo brings it back; the series stays.    let series = id.split_once('@').expect("<series>@<start>").0;    let asked = owner(&h, "delete_record", json!({ "table": "event", "id": id })).expect_err("asked first");    assert!(asked.contains("only this one, or every one"), "{asked}");    let gone = owner(&h, "delete_record", json!({ "table": "event", "id": id, "scope": "this" })).expect("only this one");    let own = gone["change"]["record_id"].as_str().expect("the day's own row").to_string();    assert!(own != series && !own.contains('@'), "{gone}");    let (after, _) = whole_section(&h, "event", "coming");    assert!(after.iter().all(|r| r["id"] != later["id"] && r["id"] != json!(own)), "that day is not listed");    assert!(after.iter().any(|r| r["id"].as_str().is_some_and(|other| other.starts_with(&format!("{series}@")))), "the rest of the series is");    let bin = owner(&h, "list_bin", json!({})).expect("the bin");    assert!(bin.to_string().contains(&own), "the day waits in the bin: {bin}");    owner(&h, "undo", json!({ "change_id": gone["change"]["id"] })).expect("undo");    let (back, _) = whole_section(&h, "event", "coming");    assert!(back.iter().any(|r| r["id"] == json!(own)), "Undo brings the day back");    // An event has no Archive: writing its archive column from a later day    // (a long press's Archive) is refused, and the series stays (architect 1650).    let another = back.iter().find(|r| r["id"].as_str().is_some_and(|other| other.starts_with(&format!("{series}@")))).expect("a later day");    let archived = owner(&h, "update_record", json!({ "table": "event", "id": another["id"], "patch": { "trashed_at": "2026-10-05T12:00:00.000Z" } }))        .expect_err("no Archive");    assert!(archived.contains("no Archive"), "{archived}");    assert!(owner(&h, "get_record_by_table", json!({ "table": "event", "id": series })).is_ok_and(|s| s["data"]["trashed_at"].is_null()), "the series is not binned");}/// RULE: An edit of a repeating event says how far it reaches: without scope it is refused with the question, "this" makes that day its own event and leaves the series, "all" moves every day (walk5 SEV 1, architect 1600).#[test]fn an_edit_of_one_day_of_a_repeating_event_never_moves_the_series_silently() {    use cotton_tools::mcp::handlers::common::{iso_of_ms, parse_ms};    let h = household_today();    let (coming, _) = whole_section(&h, "event", "coming");    let later = coming.iter().find(|r| r["id"].as_str().is_some_and(|id| id.contains('@'))).expect("a later occurrence");    let day = later["id"].as_str().unwrap().to_string();    let (series, at) = day.split_once('@').expect("<series>@<start>");    let series_start = || {        owner(&h, "get_record_by_table", json!({ "table": "event", "id": series })).expect("the series")["data"]["starts_at"]            .as_str()            .and_then(parse_ms)            .expect("its start")    };    let first = series_start();    let hour_later = iso_of_ms(parse_ms(at).unwrap() + 3_600_000);    // The record names the columns whose edit asks, so the app asks first:    // on a later day and on the series' own row; a one-off names none.    let asks = json!(["title", "starts_at", "ends_at", "all_day", "location", "notes", "rrule"]);    assert_eq!(later["scope_columns"], asks, "a later day says which edits ask: {later}");    let own_row = owner(&h, "get_record_by_table", json!({ "table": "event", "id": series })).expect("the series");    assert_eq!(own_row["scope_columns"], asks, "the series' own row says so too: {own_row}");    let one_off = coming.iter().find(|r| r["data"]["rrule"].is_null()).expect("a one-off event");    assert!(one_off.get("scope_columns").is_none(), "a one-off asks nothing: {one_off}");    let asked = owner(&h, "update_record", json!({ "table": "event", "id": day, "patch": { "starts_at": hour_later } }))        .expect_err("a repeating event's edit without scope is asked");    assert!(asked.contains("only this one, or every one"), "{asked}");    assert_eq!(series_start(), first, "nothing written");    let one = owner(&h, "update_record", json!({ "table": "event", "id": day, "patch": { "starts_at": hour_later }, "scope": "this" }))        .expect("only this one");    assert_eq!(series_start(), first, "the series keeps its start: {one}");    let own = one["record"]["id"].as_str().expect("the day's own row").to_string();    assert!(!own.contains('@') && own != series, "the day is its own event: {one}");    assert_eq!(one["record"]["data"]["starts_at"].as_str().and_then(parse_ms), parse_ms(&hour_later), "{one}");    let (after, _) = whole_section(&h, "event", "coming");    assert!(after.iter().all(|r| r["id"] != json!(day)), "the old time of that day is not listed any more");    assert!(after.iter().any(|r| r["id"] == json!(own)), "the moved day is listed");    // Undo puts the day back at its time, and the day stays one event.    owner(&h, "undo", json!({ "change_id": one["change"]["id"] })).expect("undo");    let back = owner(&h, "get_record_by_table", json!({ "table": "event", "id": own })).expect("the day's row");    assert_eq!(back["data"]["starts_at"].as_str().and_then(parse_ms), parse_ms(at), "{back}");    assert!(back["data"]["rrule"].is_null(), "the day never takes the series' repeat: {back}");    assert!(back.get("scope_columns").is_none(), "a day that is its own row asks nothing: {back}");    // Every one, from a later day: the series moves by the same half hour.    let (now_listed, _) = whole_section(&h, "event", "coming");    let other = now_listed        .iter()        .find(|r| r["id"].as_str().is_some_and(|id| id.starts_with(&format!("{series}@"))))        .expect("another later day");    let other_at = other["data"]["starts_at"].as_str().and_then(parse_ms).unwrap();    owner(&h, "update_record", json!({ "table": "event", "id": other["id"], "patch": { "starts_at": iso_of_ms(other_at + 1_800_000) }, "scope": "all" }))        .expect("every one");    assert_eq!(series_start(), first + 1_800_000, "the whole series moved half an hour");}/// A household seeded today holding the LARGE seed's events (the rest small,/// to seed in seconds): the scale at which one-off events went missing.fn household_today_large_calendar() -> Harness {    let now = cotton_tools::synthetic::seed_now(chrono::Utc::now());    let h = calendar_only();    let large = Plan::named("large").expect("the large plan");    let plan = Plan { events: large.events, ..Plan::scaled(2_000) };    h.with(|db| cotton_tools::synthetic::seed_household_at(db, &h.owner_id, &plan, 7, now)).expect("a household");    h.clock.set(now + chrono::Duration::minutes(1));    h}// RULE: on the large seed's events the Calendar's coming list opens on today and holds one-off and repeating events together in time order for a reader in any zone; a day holding both shows both (walk 1225: only repeats).#[test]fn the_coming_list_holds_one_off_and_repeating_events_in_day_order() {    let h = household_today_large_calendar();    let today = h.clock.now();    // Readers on either side of the workspace's zone: the phone sends its own.    for zone in ["Europe/London", "America/Los_Angeles", "Asia/Tokyo"] {        let mut rows: Vec<(String, bool, bool)> = Vec::new();        let mut page = 0;        for _ in 0..6 {            // As the app asks: the coming section, its own page size.            let read = owner(&h, "list_records", json!({ "table": "event", "section": "coming", "page": page, "timezone": zone }))                .expect("the coming list");            for record in read["records"].as_array().into_iter().flatten() {                let id = record["id"].as_str().unwrap_or_default();                let repeats = id.contains('@') || record["data"]["rrule"].as_str().is_some_and(|rule| !rule.is_empty());                let all_day = record["data"]["all_day"] == json!(true) || record["data"]["starts_at"].as_str().is_some_and(|at| at.len() == 10);                rows.push((record["data"]["starts_at"].as_str().unwrap_or_default().to_string(), repeats, all_day));            }            match read["next_page"].as_i64() {                Some(next) => page = next,                None => break,            }        }        let instant = |at: &str| chrono::DateTime::parse_from_rfc3339(at).ok().map(|at| at.with_timezone(&chrono::Utc));        let timed: Vec<&(String, bool, bool)> = rows.iter().filter(|row| !row.2).collect();        let first = timed.first().and_then(|row| instant(&row.0)).expect("a timed event coming");        assert!(first - today < chrono::Duration::days(1), "{zone}: the list opens on {first}, not today ({today})");        for pair in timed.windows(2) {            assert!(instant(&pair[0].0) <= instant(&pair[1].0), "{zone}: out of order: {} then {}", pair[0].0, pair[1].0);        }        let ones = rows.iter().filter(|row| !row.1).count();        eprintln!("{zone}: first {} coming rows hold {ones} one-off and {} repeating", rows.len(), rows.len() - ones);        assert!(ones * 4 >= rows.len(), "{zone}: {ones} one-off of {} rows on the first pages", rows.len());        let day = |at: &str| at.get(..10).unwrap_or(at).to_string();        let mixed = timed.iter().any(|a| a.1 && timed.iter().any(|b| !b.1 && day(&a.0) == day(&b.0)));        assert!(mixed, "{zone}: no day shows a one-off beside a repeat");    }}/// What a list counts: its `total` (the Home tile's "n of m") and, read in/// sections, the sum of their counts.fn counted(h: &Harness, table: &str) -> (i64, Option<i64>) {    let listed = owner(h, "list_records", json!({ "table": table, "limit": 3 })).expect("the list reads");    let sections = listed["sections"]        .as_array()        .map(|sections| sections.iter().filter_map(|section| section["count"].as_i64()).sum());    (listed["total"].as_i64().unwrap_or(-1), sections)}// RULE: S6, the bin excluded — after a person deletes a record, every list that offers Delete counts one fewer, in its total (the Home tile's "n of m") and in its sections' counts; a binned record is never counted (walk 5a: Home read "Meetings 3 of 5" after a delete, 4 live).#[test]fn a_deleted_record_leaves_its_lists_count() {    let h = household();    let mut checked = Vec::new();    let mut wrong = Vec::new();    for definition in app_definitions() {        if definition.delete == Some(false) {            continue;        }        let table = definition.id.as_str();        let Some((id, _)) = first_records(&h, table).into_iter().find(|(id, data)| {            // A repeating series' delete takes every day it stands under; one record, one row.            !id.contains('@') && data.get("rrule").and_then(Value::as_str).is_none_or(str::is_empty)        }) else {            continue;        };        let before = counted(&h, table);        if owner(&h, "delete_record", json!({ "table": table, "id": id })).is_err() {            continue;        }        let after = counted(&h, table);        checked.push(table.to_string());        if after.0 != before.0 - 1 {            wrong.push(format!("{table}: total {} → {} after deleting {id}", before.0, after.0));        }        if let (Some(b), Some(a)) = (before.1, after.1) {            if a != b - 1 {                wrong.push(format!("{table}: sections count {b} → {a} after deleting {id}"));            }        }    }    assert!(checked.iter().any(|t| t == "todo"), "the todos list was not walked: {checked:?}");    assert!(wrong.is_empty(), "a deleted record is still counted:\n{}", wrong.join("\n"));    eprintln!("counted after a delete: {}", checked.join(", "));}// RULE: deleting "only this one" of a repeating event reaches the day the person acted on, even the day the list shows under the series' own row — never the series' first start: delete then Undo leaves as many events as before, and the receipt names that day (architect 2005, sev 1).#[test]fn deleting_one_day_of_a_series_reaches_that_day_and_undo_leaves_no_stray() {    let h = household_today();    // What the person sees: every event listed, coming and earlier — a stray    // one-off on the series' first start would be one more.    let events = |h: &Harness| whole_section(h, "event", "coming").1 + whole_section(h, "event", "earlier").1;    let (coming, _) = whole_section(&h, "event", "coming");    // The first Swimming the list shows: the series' own row standing on its next day.    let shown = coming.iter().find(|r| r["data"]["title"] == json!("Swimming")).expect("Swimming is coming");    let id = shown["id"].as_str().expect("an id").to_string();    let day = shown["data"]["starts_at"].as_str().expect("a start").to_string();    let series = id.split_once('@').map_or(id.as_str(), |(series, _)| series).to_string();    let first = data(&h, "event", &series).get("starts_at").and_then(Value::as_str).map(str::to_string);    assert_ne!(first.as_deref(), Some(day.as_str()), "the premise: the series began before the day it is shown on");    let before = events(&h);    let gone = owner(&h, "delete_record", json!({ "table": "event", "id": id, "scope": "this" })).expect("only this one");    let own = gone["change"]["record_id"].as_str().expect("the day's own row").to_string();    assert_eq!(data_or_binned(&h, &own).as_deref(), Some(day.as_str()), "the day binned is not the day acted on: {gone}");    let said = gone["change"]["receipt"]["said"].as_str().unwrap_or_default().to_string();    let named = chrono::DateTime::parse_from_rfc3339(&day).expect("a moment").format("%-d %b").to_string();    assert!(said.contains(" on ") && said.contains(&named), "the receipt names the day ({named}): {said}");    owner(&h, "undo", json!({ "change_id": gone["change"]["id"] })).expect("undo");    assert_eq!(events(&h), before, "delete then Undo lists a different number of events (a stray one-off)");}/// A row's start, live or in the bin.fn data_or_binned(h: &Harness, id: &str) -> Option<String> {    h.with(|db| db.get("SELECT starts_at FROM cotton_events WHERE id = ?", &[rusqlite::types::Value::Text(id.to_string())]).expect("a read").and_then(|row| row.text("starts_at").map(str::to_string)))}/// RULE: Between-us balances stay separate by currency; a person's euro loan and rupee borrowing never become one sum.#[test]fn the_households_money_is_in_two_currencies_and_never_summed() {    let h = household();    let person=h.with(|db| db.get("SELECT counterparty_person_id AS id FROM cotton_money_transactions WHERE between_us=1 AND counterparty_person_id IS NOT NULL GROUP BY counterparty_person_id HAVING count(DISTINCT currency)>1 LIMIT 1",&[]).unwrap().and_then(|row|row.text("id").map(str::to_string))).expect("synthetic person with two currencies");    let read = data(&h, "person", &person);    assert!(        read.get("balance").is_none_or(Value::is_null),        "currencies were added together: {read:?}"    );}