Cotton code
946 lines · 54.7 KB · RustRaw
//! `shell.today {timezone?, today?, database?, board?, size?, cursor?, limit?}`//! — HOME'S PAGE, ANSWERED WHOLE (the shell boundary, 7 Nov 2026: the core//! answers what to show, a platform shell only draws). `shell.home` is the//! gate, asked every tick; this is the page, asked when it is shown and again//! when the core says so.//!//! ```json//! { "cards": [{ "id", "kind": "device|day|later|thread|part", "face", "slots",//!               "tap", "acts": [id], "record", "table"?, "database"?,//!               "opens"?, "dye"?, … the deck card's readings }],//!   "acts":  { id: { "label", "kind", "red" } },//!   "parts": { "asked": { "items": [{ "key", "count", "label", "path",//!                                     "database"?, "tiles" }],//!                         "total", "unreadable" },//!              "done": [{ "kind", "id", "label", "text", "when", "action", "path" }],//!              "notices": [{ "id", "words", "kind" }],//!              "board": [{ "id", "kind", "shown", "why": { "key", "words" } | null,//!                          "settings", … what the kind draws }] },//!   "working_on"?, "update"?, "arriving"?, "failed"?,//!   "arrangement"?, "projects", "workspace_id"?, "families", "empty", "next",//!   "today" }//! ```//!//! - **`today`** is the day key the page was read for, `YYYY-MM-DD` on the//!   ask's `timezone`'s local calendar (the ask's own `today` when it names//!   one), never a UTC stamp: the key a capture is filed under, so a shell//!   computes no day of its own.//!//! - **The deck** is the board's order: this device's own card when the board//!   names a `device` part (owner, 27 Oct 2026: "so we know if the app has//!   fully synced"); then, when it names a `today` part, today's rows (every//!   database this device holds, in time order, an event before a todo at the//!   same instant, a done todo left out), the birthdays and money due, and//!   the shown database's unread conversations; then a card for each of the//!   board's `notices`, `asked` and `done` parts that has something to say. A//!   record's card is the one its tool's deck wears (`shell.deck`'s card//!   builder, never a second fill), read in its own database; a row with no//!   record of its own to wear — an occurrence of a repeating event, whose//!   record is the series — wears the `today` face: its title, its line on the//!   day, its table's name and picture. Each day card's `opens` says what a//!   tap opens: `{table, id, page, at?, database?, path, screen, opening}`//!   (the route and kind of screen by `routes::opens`), and its `dye` the paper//!   its slip is cut from on Home's list (`blue` an event, `cream` a todo).//! - **The parts** are the bands' words: the Asked of you rows worded and//!   addressed (`rules::asked_of_you`), the Done for you receipts//!   (`rules::done_for_you`) with their one action (`shell.undo` takes an//!   `undo` back), and the notices that speak now, in the part's order.//! - **`parts.board`** is the board WHOLE, in the definition's order (the//!   size's variant where `size` names one; the kit's own Home where the//!   database holds no board row): one entry per part, so a shell draws the//!   list in order and decides nothing. `id` is the part's own id, else its//!   kind (`list#2` for a kind's second); `settings` the part resolved//!   (`board::default_of`); `shown` whether it draws, and when it does not,//!   `why`: `key` one of `quiet` (nothing to say now), `head` (an `asked` or//!   `done` placed behind the head's tag), `personal` (`recent` off the//!   person's own database), `no_device`, `magnifier` (a `search` the head's//!   icon offers), `unarranged` (`tools` before the order is read),//!   `no_table`, `no_record`, `unknown` (a newer build's kind), and `words`//!   the kit's line (`board` › `part.hidden.*`). What each kind adds://!   - `head`: `tags`; `asked` `{items, total}` and `done` `{items}`, the rows//!     its two tags count and open: the board's `asked` and `done` parts', all//!     of them where the board has no such part.//!   - `device`: `card`, this device's card id in `cards`.//!   - `today`: `cards`, the ids of the day, later and thread cards in order;//!     `quiet`, the words of a day with none; `heading`, the day's heading in//!     the kit's day words (`dates` › `heading.today`).//!   - `sync`: nothing (the line is `sync.status`'s).//!   - `notices`: `items`, the notices above its `shows` keeps, in its order.//!   - `asked`: `items`, `total`, `unreadable`, `heading` — `parts.asked`'s//!     items its `shows` keeps, in its order.//!   - `done`: `items`, `heading` — `parts.done`'s rows its `shows` keeps.//!   - `list`: `table`, `heading` (the part's, else the table's plural),//!     `count`, `ask` (the `records.list` request its `where`, `period` and//!     `limit` make), `records` (those rows, `{id, data}`, for a table's own//!     tile face), `rows` (`shell.list`'s rows over them) and `acts`. A//!     part's own static rows are kept by what each `needs` of the app//!     (`SettingsReach`), and `count` is of those kept.//!   - `figure`: `heading`, `line` — the crate's worked line//!     (`read.homeFigure`), null when it says nothing.//!   - `facts`: `source`, `record` (the shown database's id) and `facts`://!     `[{key, label, value}]`, each column the record holds, in words.//!   - `recent`: `heading`, `items` (`read.recentVisits`' visits).//!   - `search`: `face`. `about`: `source`.//!   - `tools`: `tiles`, the fan's tile keys in its order (`shell.fan`), and//!     `cards`, those tiles whole. On the `tools` board, every tool of the//!     database in the person's order, one Home holds none of saying `hidden`.//! - **A read that failed** answers its line (`failed: {why, line}`) and the//!   cards it could read; past it the core says `{phase: home, stage: today}`//!   on the client stream once [`AGAIN`]'s next step has passed (the last//!   step repeats while nothing is read), and the shell asks again. A read//!   that met a table mid-move waits on that move's own done signal instead.//! - `families`: the data families whose events mean the page reads again.//! - Paged by `cursor` over the cards; `next` is null at the end.//! - `only: "device"` answers this device's card alone (`{cards, acts}`), for//!   the card's own cadence: it moves with every sync pass.use std::sync::atomic::Ordering;use cotton_core::rules::asked_of_you::{asked_label, asked_path, AskedKey, ASKED_KEYS};use cotton_core::rules::shell_lines::{number, resolve, LineRow};use cotton_core::transforms::zoned_clock;use serde_json::{json, Map, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;const METHOD: &str = "shell.today";/// A page of the deck.pub const PAGE: usize = 50;/// The waits before each next ask after a read that failed with nothing read;/// the last repeats (architect, 16 Oct 2026: the cap of four went).pub const AGAIN: [u64; 4] = [1_000, 3_000, 10_000, 30_000];/// The stage the core raises on `{phase: home}` when the page should be asked again.pub const STAGE: &str = "today";/// The newest conversations a Home read looks through for the unread ones.const THREADS: usize = 50;/// The data families whose events mean Home reads again — the tables/// `read.home` and the day read touch.pub const FAMILIES: [&str; 10] = ["core", "memory", "projects", "documents", "todos", "calendar", "people", "messages", "money", "mood"];pub fn call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let zone = request["timezone"].as_str().or(client.time_zone()).unwrap_or("UTC").to_string();    let now_ms = client.clock().now().timestamp_millis();    let today = match request["today"].as_str() {        Some(day) => day.to_string(),        None => zoned_clock::local_day_key(now_ms, &zone).map_err(|_| bad("timezone is a named time zone"))?,    };    let shown = request["database"].as_str().filter(|id| !id.trim().is_empty()).map(str::to_string);    let board = request["board"].as_str().unwrap_or("home").to_string();    let cursor = request["cursor"].as_u64().unwrap_or(0) as usize;    let limit = request["limit"].as_u64().filter(|limit| *limit > 0).map_or(PAGE, |limit| limit as usize);    // This device's card alone, read again as the sync moves (its rows done    // of total, bytes, synced at), without reading the page.    if request["only"] == "device" {        let mut acts = Map::new();        let card = match client.self_device_id() { Some(device) => device_card(handle, &device, request, &mut acts)?, None => None };        return Ok(json!({"cards": card.into_iter().collect::<Vec<_>>(), "acts": acts}));    }    let parts = board_parts(handle, &board, request["size"].as_str(), shown.as_deref())?;    let has = |kind: &str| parts.iter().any(|part| part.kind == kind);    // The shown database and what this device holds.    let held = client.databases().map_err(|why| MethodError::new("unreadable", why))?;    let listed = crate::methods::dispatch(handle, "read.databases", &json!({})).ok();    let listed: Vec<Value> = listed.and_then(|listed| listed["databases"].as_array().cloned()).unwrap_or_default();    let shown_id = shown.clone().or_else(|| held.iter().find(|database| database.personal).map(|database| database.id.clone()));    let lines = held_lines(&client, shown.as_deref());    let arriving = shown_id.as_deref().and_then(|id| {        let row = listed.iter().find(|row| row["databaseId"] == id)?;        row.get("arrival").filter(|arrival| arrival.is_object()).map(|arrival| arrival_sentence(arrival, row["name"].as_str().unwrap_or_default(), &lines))    });    let mut acts = Map::new();    let mut cards: Vec<Value> = Vec::new();    if has("device") {        if let Some(device) = client.self_device_id() {            if let Some(card) = device_card(handle, &device, request, &mut acts)? { cards.push(card) }        }    }    // The page's read: one database's (`read.home`), never while its copy is    // still on its way — that page says it is arriving and asks nothing.    let mut failed: Option<MethodError> = None;    let home = match &arriving {        Some(_) => None,        None => match crate::methods::dispatch(handle, "read.home", &scoped(json!({}), shown.as_deref())) {            Ok(home) => Some(home),            Err(error) => { failed = Some(error); None }        },    };    if has("today") && arriving.is_none() {        match day_cards(handle, &zone, &today, shown_id.as_deref(), held.len(), request, &lines, &mut acts) {            Ok(day) => cards.extend(day),            Err(error) => { failed.get_or_insert(error); }        }        let later = later_cards(handle, &zone, shown.as_deref());        if !later.is_empty() {            acts.entry("open.opened".to_string()).or_insert_with(|| json!({"label": resolve("cards", "deck.open.opened", &lines, &[]).unwrap_or_default(), "kind": "open", "red": false}));        }        cards.extend(later);        match thread_cards(handle, shown.as_deref(), request, &mut acts) {            Ok(threads) => cards.extend(threads),            Err(error) => { failed.get_or_insert(error); }        }    }    let asked = asked_part(home.as_ref(), &lines);    let done = done_part(home.as_ref());    let working_on = home.as_ref().and_then(|home| working_line(&home["workingOn"], &lines));    let sync = client.sync_status();    let update = update_slip(&client, &sync);    let unreadable: Vec<String> = listed.iter().filter(|row| row.get("arrival").is_none_or(Value::is_null))        .filter_map(|row| Some(format!("{}: {}", row["name"].as_str().unwrap_or_default(), row["unreadable"].as_str()?)))        .collect();    let failure = failed.as_ref().map(|error| failure_words(error, &name_of(&listed, shown_id.as_deref()), &lines));    let attention = crate::methods::shell_home::call(handle, &json!({})).ok()        .and_then(|home| home["notices"].as_array().and_then(|notices| notices.iter().find(|notice| notice["kind"] == "amber" || notice["kind"] == "refusal").cloned()));    let notices = notices_part(update.as_deref(), arriving.as_deref(), &unreadable, working_on.as_deref(),        failure.as_ref().map(|failure| failure["line"].as_str().unwrap_or_default()), attention.as_ref(), &lines);    // A band's card is dealt when something it shows speaks.    for part in parts.iter().filter(|part| matches!(part.kind.as_str(), "notices" | "asked" | "done")) {        let shown = shows(std::slice::from_ref(part), &part.kind);        let holds = |key: &Value| shown.is_empty() || shown.iter().any(|shown| key.as_str().is_some_and(|key| key == shown || key.starts_with(&format!("{shown}/"))));        let speaks = match part.kind.as_str() {            "notices" => notices.iter().any(|notice| holds(&notice["id"])),            "asked" => asked["items"].as_array().is_some_and(|items| items.iter().any(|item| holds(&item["key"]))) || (failed.is_some() && home.is_none()),            _ => done.iter().any(|row| holds(&row["kind"])),        };        if speaks && !cards.iter().any(|card| card["id"] == format!("part/{}", part.kind)) {            let mut card = bare(&format!("part.{}", part.kind), json!({}), &part.kind);            card["id"] = json!(format!("part/{}", part.kind));            card["kind"] = json!("part");            cards.push(card);        }    }    let personal = shown_id.is_some() && shown_id == held.iter().find(|database| database.personal).map(|database| database.id.clone());    let ordered = ordered_parts(handle, &parts, &Said {        cards: &cards, notices: &notices, asked: &asked, done: &done, unread: failed.is_some() && home.is_none(),        arranged: home.as_ref().is_some_and(|home| !home["arrangement"].is_null()), personal,        database: shown.as_deref(), shown_id: shown_id.as_deref(), today: &today, request, lines: &lines,        board: &board, parts: &parts,    });    let count = cards.len();    let page: Vec<Value> = cards.into_iter().skip(cursor).take(limit).collect();    let next = (cursor + page.len() < count).then_some(cursor + page.len());    again(handle, failed.as_ref(), home.is_some());    Ok(json!({        "cards": page,        "acts": acts,        "count": count,        "parts": { "asked": asked, "done": done, "notices": notices, "board": ordered },        "working_on": working_on,        "update": update,        "arriving": arriving,        "failed": failure,        "arrangement": home.as_ref().map(|home| home["arrangement"].clone()),        "projects": home.as_ref().and_then(|home| home["projects"].as_array().cloned()).unwrap_or_default(),        "project_facts_missing": home.as_ref().is_some_and(|home| home["projectFactsMissing"] == true),        "workspace_id": home.as_ref().and_then(|home| home["workspace"]["id"].as_str().map(str::to_string)),        "families": FAMILIES,        "empty": resolve("board", "today.empty", &lines, &[]).unwrap_or_default(),        "next": next,        "today": today,    }))}/// `shell.undo {kind, id}` — take back what Cotton did, for a Done for you/// receipt whose action is `undo`: a filing stands as the thought again/// (`keep_as_thought`), a remembered entry is archived with the reason the/// owner reads later (`memory_archive`), a city fill's cities that still/// stand are cleared (`people.unfillCities`). `{said}`, the receipt's words.pub fn undo(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let kind = request["kind"].as_str().ok_or_else(|| bad("shell.undo takes the receipt's kind"))?;    let id = request["id"].as_str().filter(|id| !id.is_empty()).ok_or_else(|| bad("shell.undo takes the receipt's id"))?;    let scope = |value: Value| match request.get("database").filter(|database| database.is_string()) {        Some(database) => { let mut value = value; value["database"] = database.clone(); value }        None => value,    };    let client = handle.client();    let lines = held_lines(&client, request["database"].as_str());    let say = |key: &str| resolve("board", key, &lines, &[]).unwrap_or_default();    match kind {        "filed" => {            crate::methods::dispatch(handle, "write", &scope(json!({"tool": "keep_as_thought", "args": {"id": id}})))?;            Ok(json!({"said": say("done.kept_as_thought")}))        }        "remembered" => {            crate::methods::dispatch(handle, "write", &scope(json!({"tool": "memory_archive", "args": {"id": id, "reason": say("done.dropped_reason")}})))?;            Ok(json!({"said": say("done.dropped")}))        }        "cityFilled" => {            crate::methods::dispatch(handle, "people.unfillCities", &scope(json!({"at": id})))?;            Ok(json!({"said": say("done.cleared")}))        }        other => Err(bad(&format!("a {other} receipt has nothing to take back"))),    }}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", format!("{METHOD}: {why}"))}fn scoped(mut request: Value, database: Option<&str>) -> Value {    if let Some(database) = database { request["database"] = json!(database) }    request}/// The lines of the shown database (the kit's where it holds none).fn held_lines(client: &crate::shell::client::ClientController, database: Option<&str>) -> Vec<LineRow> {    let _named = client.name_database(database).ok();    client.with_file(|file| Ok(cotton_tools::presentation::line_rows(file.driver, file.workspace_id))).unwrap_or_default()}fn name_of(listed: &[Value], id: Option<&str>) -> String {    id.and_then(|id| listed.iter().find(|row| row["databaseId"] == id)).and_then(|row| row["name"].as_str()).unwrap_or_default().to_string()}/// The board's parts at this size, each resolved to its defaults.fn board_parts(handle: &CottonHandle, board: &str, size: Option<&str>, database: Option<&str>) -> Result<Vec<cotton_core::definitions::board::BoardPart>, MethodError> {    use cotton_core::definitions::board::BoardDefinition;    let served = crate::methods::dispatch(handle, "definitions.board", &scoped(json!({"id": board}), database))?;    let definition: BoardDefinition = serde_json::from_value(served["definition"].clone())        .map_err(|why| MethodError::new("unreadable", format!("{METHOD}: the {board} board: {why}")))?;    let parts = size        .and_then(|size| definition.variants.iter().find(|variant| variant.when.get("size").and_then(Value::as_str) == Some(size)))        .map_or(definition.parts.clone(), |variant| variant.parts.clone());    Ok(parts.iter().enumerate().map(|(at, part)| part.resolved(&format!("parts[{at}]"), &mut Vec::new())).collect())}fn shows(parts: &[cotton_core::definitions::board::BoardPart], kind: &str) -> Vec<String> {    parts.iter().filter(|part| part.kind == kind)        .flat_map(|part| part.settings.get("shows").and_then(Value::as_array).cloned().unwrap_or_default())        .filter_map(|word| word.as_str().map(str::to_string))        .collect()}// ── The cards ────────────────────────────────────────────────────────────/// A card no table's own card fills: its face and places, reached by nobody.fn bare(face: &str, slots: Value, record: &str) -> Value {    json!({        "id": record, "face": face, "slots": slots, "tap": {}, "acts": [], "pressing": false,        "reach": {"phones": [], "emails": [], "call": false, "message": false, "email": false},        "record": {"id": record, "data": {}},    })}/// The cards of `rows` of `table`, read in `database`, as its tool's deck wears them.fn table_cards(handle: &CottonHandle, table: &str, ids: &[String], database: Option<&str>, request: &Value, acts: &mut Map<String, Value>) -> Result<Vec<Value>, MethodError> {    if ids.is_empty() { return Ok(Vec::new()) }    let client = handle.client();    let _named = client.name_database(database).map_err(|why| MethodError::new("database_not_held", why))?;    let native = |args: &Value| crate::methods::dispatch(handle, "records.list", &crate::phone::records::in_named_database(args.clone()));    let mut asked = json!({"table": table, "ids": ids});    if let Some(zone) = request["timezone"].as_str() { asked["timezone"] = json!(zone) }    let rows = native(&asked)?["records"].as_array().cloned().unwrap_or_default();    crate::methods::shell_deck::cards_of(&client, table, rows, request, &native, acts)}/// This device's own record, as its tool's card draws it, with its sync/// facts as the phone holds them now (`device.facts`).fn device_card(handle: &CottonHandle, device: &str, request: &Value, acts: &mut Map<String, Value>) -> Result<Option<Value>, MethodError> {    let Ok(facts) = crate::methods::dispatch(handle, "device.facts", &json!({"deviceId": device})) else { return Ok(None) };    let client = handle.client();    let native = |args: &Value| crate::methods::dispatch(handle, "records.list", &crate::phone::records::in_named_database(args.clone()));    let row = json!({"id": device, "data": facts["data"]});    let mut cards = crate::methods::shell_deck::cards_of(&client, "device", vec![row], request, &native, acts)?;    Ok(cards.pop().map(|mut card| {        card["id"] = json!(format!("device/{device}"));        card["kind"] = json!("device");        card["tap"] = json!({"card": "open.in_place"});        acts.entry("open.in_place".to_string()).or_insert_with(|| json!({"label": resolve("cards", "deck.open.opened", &[], &[]), "kind": "open", "red": false}));        card    }))}/// One of today's rows, as the day read answered it.struct DayRow {    table: &'static str,    id: String,    at: Option<String>,    sort_at: String,    title: String,    line: Option<String>,    repeats: bool,    database: Option<(String, String)>,}impl DayRow {    fn card_id(&self) -> String {        let own = match self.table {            "event" => format!("event:{}:{}", self.id, self.at.as_deref().unwrap_or_default()),            _ => format!("todo:{}", self.id),        };        match &self.database { Some((id, _)) => format!("{id}/{own}"), None => own }    }    fn page(&self) -> String {        match (self.repeats, &self.at) {            (true, Some(at)) => format!("{}@{at}", self.id),            _ => self.id.clone(),        }    }}/// Today's rows, across every database this device holds once it holds more/// than one, each worn as its record's card where it has one to wear.#[allow(clippy::too_many_arguments)]fn day_cards(handle: &CottonHandle, zone: &str, today: &str, shown: Option<&str>, holding: usize, request: &Value, lines: &[LineRow], acts: &mut Map<String, Value>) -> Result<Vec<Value>, MethodError> {    let (from, to) = day_window(today, zone)?;    let mut asked = json!({"from": from, "to": to, "timezone": zone});    if holding > 1 { asked["database"] = json!(crate::phone::databases::ALL_DATABASES) }    else if let Some(shown) = shown { asked["database"] = json!(shown) }    let answer = crate::methods::dispatch(handle, "read.day", &asked)?;    let rows = day_rows(&answer, shown);    // The records to wear, by database and table.    let mut worn: Map<String, Value> = Map::new();    let mut wanted: std::collections::BTreeMap<(Option<String>, &'static str), Vec<String>> = Default::default();    for row in rows.iter().filter(|row| !row.repeats) {        wanted.entry((row.database.as_ref().map(|(id, _)| id.clone()), row.table)).or_default().push(row.id.clone());    }    for ((database, table), ids) in wanted {        let database = database.or_else(|| shown.map(str::to_string));        for card in table_cards(handle, table, &ids, database.as_deref(), request, acts).unwrap_or_default() {            let key = format!("{}|{table}|{}", database.as_deref().unwrap_or_default(), card["id"].as_str().unwrap_or_default());            worn.insert(key, card);        }    }    let names = table_names(handle, shown)?;    let tool = |table: &str| names.get(table).cloned().unwrap_or_default();    let client = handle.client();    let definitions: std::collections::HashMap<&str, Option<cotton_core::definitions::TableDefinition>> = rows.iter()        .map(|row| (row.table, crate::phone::card_actions::read_definition(&client, row.table, METHOD).ok())).collect();    let open = "open.day".to_string();    acts.entry(open.clone()).or_insert_with(|| json!({"label": resolve("cards", "deck.open.opened", lines, &[]), "kind": "open", "red": false}));    Ok(rows.iter().map(|row| {        let database = row.database.as_ref().map(|(id, _)| id.clone()).or_else(|| shown.map(str::to_string));        let key = format!("{}|{}|{}", database.as_deref().unwrap_or_default(), row.table, row.id);        let mut card = match worn.get(&key).filter(|_| !row.repeats) {            Some(card) => card.clone(),            None => bare("today", json!({"title": row.title, "line": row.line, "kind": tool(row.table),                "picture": if row.table == "event" { "calendar" } else { "todos" }}), &row.page()),        };        card["id"] = json!(format!("day/{}", row.card_id()));        card["kind"] = json!("day");        card["table"] = json!(row.table);        card["tap"]["card"] = json!(open);        // The slip's paper on Home's list: an event's blue, a todo's cream.        card["dye"] = json!(if row.table == "event" { "blue" } else { "cream" });        card["opens"] = json!({"table": row.table, "id": row.id, "page": row.page(), "at": if row.repeats { row.at.clone() } else { None }, "database": row.database.as_ref().map(|(id, _)| id)});        if let Some(definition) = definitions.get(row.table).and_then(Option::as_ref) {            let at = crate::phone::routes::opens(definition, &row.id, &Map::new(), "", &|_| None);            for key in ["path", "screen", "opening"] { card["opens"][key] = at[key].clone() }        }        if let Some((id, name)) = &row.database { card["database"] = json!({"id": id, "name": name}) }        card    }).collect())}/// The day's window in `zone`: its first instant and its last millisecond.fn day_window(today: &str, zone: &str) -> Result<(String, String), MethodError> {    let (year, month, day) = (today.get(0..4), today.get(5..7), today.get(8..10));    let (Some(year), Some(month), Some(day)) = (year.and_then(|y| y.parse().ok()), month.and_then(|m| m.parse().ok()), day.and_then(|d| d.parse().ok()))    else { return Err(bad("today is YYYY-MM-DD")) };    let start_day = zoned_clock::days_from_civil(year, month, day);    let instant = |days: i64| -> Result<i64, MethodError> {        let (year, month, day) = zoned_clock::civil_from_days(days);        zoned_clock::instant_from_zoned(zoned_clock::ZonedParts { year, month, day, hour: 0, minute: 0, second: 0 }, 0, zone)            .map_err(|_| bad("timezone is a named time zone"))    };    let iso = |ms: i64| chrono::DateTime::from_timestamp_millis(ms).map(|at| at.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)).unwrap_or_default();    Ok((iso(instant(start_day)?), iso(instant(start_day + 1)? - 1)))}/// The day read's rows: its occurrences and the todos not yet done, in time/// order — an event before a todo at the same instant, else the read's own.fn day_rows(answer: &Value, shown: Option<&str>) -> Vec<DayRow> {    let database = |row: &Value| -> Option<(String, String)> {        let id = row["databaseId"].as_str().filter(|id| !id.trim().is_empty())?;        (Some(id) != shown).then(|| (id.to_string(), row["databaseName"].as_str().unwrap_or_default().to_string()))    };    let mut rows: Vec<DayRow> = Vec::new();    for occurrence in answer["occurrences"].as_array().into_iter().flatten() {        let Some(id) = occurrence["eventId"].as_str() else { continue };        let at = occurrence["startsAt"].as_str().map(str::to_string);        rows.push(DayRow {            table: "event", id: id.to_string(), sort_at: occurrence["sortAt"].as_str().map(str::to_string).or_else(|| at.clone()).unwrap_or_default(), at,            title: occurrence["event"]["title"].as_str().unwrap_or_default().to_string(),            line: occurrence["line"].as_str().map(str::to_string),            repeats: occurrence["event"]["rrule"].as_str().is_some_and(|rule| !rule.is_empty()) && occurrence["isException"] != true,            database: database(occurrence),        });    }    for todo in answer["todos"].as_array().into_iter().flatten().filter(|todo| todo["status"] != "done") {        let Some(id) = todo["id"].as_str() else { continue };        let at = todo["dueAt"].as_str().map(str::to_string);        rows.push(DayRow {            table: "todo", id: id.to_string(), sort_at: todo["sortAt"].as_str().map(str::to_string).or_else(|| at.clone()).unwrap_or_default(), at,            title: todo["title"].as_str().unwrap_or_default().to_string(),            line: todo["line"].as_str().map(str::to_string), repeats: false, database: database(todo),        });    }    // A stable sort keeps the read's own order among equals.    rows.sort_by(|a, b| a.sort_at.cmp(&b.sort_at).then_with(|| (a.table != "event").cmp(&(b.table != "event"))));    rows}/// The birthdays coming round and the money due, each its kind's card.fn later_cards(handle: &CottonHandle, zone: &str, database: Option<&str>) -> Vec<Value> {    let ask = scoped(json!({"timezone": zone}), database);    let mut cards = Vec::new();    let mut push = |face: &str, table: &str, id: &str, slots: Value| {        let mut card = bare(face, slots, id);        card["id"] = json!(format!("later/{table}/{id}"));        card["kind"] = json!("later");        card["table"] = json!(table);        card["tap"] = json!({"card": "open.opened"});        cards.push(card);    };    if let Ok(answer) = crate::methods::dispatch(handle, "cards.birthdays", &ask) {        for one in answer["birthdays"].as_array().into_iter().flatten() {            let (Some(table), Some(id)) = (one["table"].as_str(), one["id"].as_str()) else { continue };            let mut slots = json!({"date": one["when"], "title": one["name"], "photo": one["photo"], "turns": one["turns"], "wishes": one["wishes"]});            if let Some(slots) = slots.as_object_mut() { slots.retain(|_, value| !value.is_null()) }            push("birthday", table, id, slots);        }    }    if let Ok(answer) = crate::methods::dispatch(handle, "cards.moneyDue", &ask) {        for one in answer["due"].as_array().into_iter().flatten() {            let (Some(table), Some(id)) = (one["table"].as_str(), one["id"].as_str()) else { continue };            let mut slots = json!({"date": one["when"], "title": one["title"], "amount": one["amount"]});            if let Some(slots) = slots.as_object_mut() { slots.retain(|_, value| !value.is_null()) }            push("transaction.receipt", table, id, slots);        }    }    cards}/// The table definitions `database` holds.fn definitions_in(handle: &CottonHandle, database: Option<&str>) -> Result<Vec<cotton_core::definitions::TableDefinition>, MethodError> {    let client = handle.client();    let _named = client.name_database(database).map_err(|why| MethodError::new("database_not_held", why))?;    let mut tables = Vec::new();    client.read_rows(METHOD, &mut |ctx| {        tables = cotton_tools::definitions::table_definitions(ctx).map_err(|e| e.to_string())?.definitions;        Ok(Value::Null)    }).map_err(|why| MethodError::new("unreadable", why))?;    Ok(tables)}/// Each table's own name ("Todo", "Event"), by id.fn table_names(handle: &CottonHandle, database: Option<&str>) -> Result<std::collections::HashMap<String, String>, MethodError> {    Ok(definitions_in(handle, database)?.into_iter().map(|definition| (definition.id.clone(), definition.name.clone())).collect())}/// The shown database's unread conversations: every table whose card is a/// conversation's, its newest [`THREADS`] read and those whose card's unread/// place holds the choice named for it kept.fn thread_cards(handle: &CottonHandle, database: Option<&str>, request: &Value, acts: &mut Map<String, Value>) -> Result<Vec<Value>, MethodError> {    use cotton_core::definitions::card::CardSlot;    let tables = definitions_in(handle, database)?;    let mut cards = Vec::new();    for definition in tables.iter().filter(|definition| definition.card.as_ref().is_some_and(|card| card.face.as_str() == "thread.slips")) {        let Some(unread) = definition.card.as_ref().and_then(|card| card.fields.iter().find(|field| field.slot == CardSlot::Unread)).and_then(|field| field.column.clone()) else { continue };        if !definition.column(&unread).and_then(|column| column.choices.as_ref()).is_some_and(|choices| choices.iter().any(|choice| choice.as_str() == unread)) { continue }        // The unread place is a reading of the chat, never a column a list is        // narrowed by (`Chats cannot be narrowed by "unread"`): the newest        // page is read and the unread ones kept.        let listed = crate::methods::dispatch(handle, "records.list", &scoped(json!({"table": definition.id, "limit": THREADS}), database))?;        let ids: Vec<String> = listed["records"].as_array().into_iter().flatten()            .filter(|row| row["data"][&unread] == unread.as_str())            .filter_map(|row| row["id"].as_str().map(str::to_string)).collect();        for mut card in table_cards(handle, &definition.id, &ids, database, request, acts)? {            card["id"] = json!(format!("thread/{}", card["id"].as_str().unwrap_or_default()));            card["kind"] = json!("thread");            cards.push(card);        }    }    Ok(cards)}// ── The parts ────────────────────────────────────────────────────────────/// Asked of you: the read's rows worded and addressed, in the list's order/// (`ASKED_KEYS`); a board's part draws the ones it shows.fn asked_part(home: Option<&Value>, lines: &[LineRow]) -> Value {    let rows = home.and_then(|home| home["askedOfYou"]["rows"].as_array().cloned()).unwrap_or_default();    let mut items = Vec::new();    for key in ASKED_KEYS.iter() {        for row in rows.iter().filter(|row| row["key"] == key.as_str()) {            let count = row["count"].as_u64().unwrap_or(0) as usize;            items.push(asked_item(*key, count, row, lines));        }    }    let total: u64 = items.iter().filter_map(|item| item["count"].as_u64()).sum();    json!({"items": items, "total": total, "unreadable": home.is_none()})}fn asked_item(key: AskedKey, count: usize, row: &Value, lines: &[LineRow]) -> Value {    let mut item = json!({        "key": key.as_str(), "count": count, "label": asked_label(key, count, lines), "path": asked_path(key),        "tiles": row["tiles"].as_array().cloned().unwrap_or_default(),    });    if let Some(id) = row["databaseId"].as_str() { item["database"] = json!({"id": id, "name": row["databaseName"]}) }    item}/// Done for you, newest first as read, each its age in words (the read's own/// `@day_parts`); a board's part draws the kinds it shows.fn done_part(home: Option<&Value>) -> Vec<Value> {    home.and_then(|home| home["doneForYou"].as_array().cloned()).unwrap_or_default().into_iter()        .map(|row| {            let when = row.pointer("/@day_parts/at/recent").and_then(Value::as_str).unwrap_or_default();            json!({"kind": row["kind"], "id": row["id"], "label": row["label"], "text": row["text"], "when": when, "action": row["action"], "path": row["path"]})        })        .collect()}/// "Working on 2 · Researching X · 12 min", or nothing while nothing runs.fn working_line(working: &Value, lines: &[LineRow]) -> Option<String> {    let count = working["count"].as_i64().filter(|count| *count > 0)?;    let mut parts = vec![resolve("board", if count == 1 { "working.one" } else { "working.many" }, lines, &[("n", &number(count))]).unwrap_or_default()];    if let Some(task) = working["oldestTask"].as_str() { parts.push(task.to_string()) }    if let Some(age) = working.pointer("/@day_parts/oldestQueuedAt/recent").and_then(Value::as_str).filter(|age| !age.is_empty()) {        parts.push(age.to_string())    }    Some(parts.join(" \u{00B7} "))}/// Which update slip Home draws: the phone's own update first — a phone that/// cannot exchange at all cannot know what the Mac holds — then the Mac's.fn update_slip(client: &crate::shell::client::ClientController, sync: &Value) -> Option<String> {    let schema = sync["loop"]["schema"].as_str();    let refused = client.standing_refusal().is_some_and(|refusal| refusal["code"] == "upgrade_required");    if schema == Some("phoneBehind") || refused { return Some("phone".into()) }    (schema == Some("serverBehind")).then(|| "mac".into())}/// The one calm sentence a page of a database still arriving shows.fn arrival_sentence(arrival: &Value, name: &str, lines: &[LineRow]) -> String {    let megabytes = |bytes: u64| bytes.div_ceil(1_048_576).to_string();    match (arrival["state"].as_str(), arrival["totalBytes"].as_u64()) {        (Some("arriving"), Some(total)) => resolve("databases", "arriving.sentence_of", lines, &[            ("name", name), ("written", &megabytes(arrival["bytesWritten"].as_u64().unwrap_or(0))), ("total", &megabytes(total)),        ]).unwrap_or_default(),        _ => resolve("databases", "arriving.sentence", lines, &[("name", name)]).unwrap_or_default(),    }}/// What a failed read says (`reading`'s `could_not_read.*`), filled with the/// database's name: never the error's own words.fn failure_words(error: &MethodError, database: &str, lines: &[LineRow]) -> Value {    let why = match (error.code.as_str(), error.details["why"].as_str()) {        ("could_not_read", Some(why @ ("too_long" | "mac_away" | "on_the_mac" | "moving"))) => why,        ("could_not_read", _) => "busy",        _ => "other",    };    let unnamed = resolve("record", "could_not_read.unnamed", lines, &[]).unwrap_or_default();    let database = if database.is_empty() { unnamed.as_str() } else { database };    let heard = error.details.pointer("/@day_parts/heard_at/ago").and_then(Value::as_str);    let line = match (why, heard) {        ("on_the_mac", None) => resolve("reading", "could_not_read.mac_away", lines, &[("database", database)]),        ("on_the_mac", Some(heard)) => resolve("reading", "could_not_read.on_the_mac", lines, &[("database", database), ("heard", heard), ("what", database)]),        (why, _) => resolve("reading", &format!("could_not_read.{why}"), lines, &[("database", database), ("what", database)]),    }.unwrap_or_default();    if why == "other" { tracing::warn!("{METHOD}: a read failed — {}: {}", error.code, error.message) }    json!({"why": why, "line": line, "keeps_trying": why != "other"})}/// The notices that speak now, in the kit's order (`NOTICE_KINDS`); a/// board's part draws the ones it shows, in its own.#[allow(clippy::too_many_arguments)]fn notices_part(    update: Option<&str>, arriving: Option<&str>, unreadable: &[String],    working: Option<&str>, refusal: Option<&str>, attention: Option<&Value>, lines: &[LineRow],) -> Vec<Value> {    let mut notices = Vec::new();    for kind in cotton_core::definitions::board::NOTICE_KINDS {        match *kind {            "update" => if let Some(side) = update {                notices.push(json!({"id": "update", "kind": "update", "words": resolve("board", &format!("update.sentence.{side}"), lines, &[]).unwrap_or_default(),                    "title": resolve("board", &format!("update.title.{side}"), lines, &[]).unwrap_or_default(), "label": resolve("board", &format!("update.label.{side}"), lines, &[]).unwrap_or_default(), "side": side}));            },            "arriving" => if let Some(words) = arriving { notices.push(json!({"id": "arriving", "kind": "quiet", "words": words})) },            "unreadable" => for (at, words) in unreadable.iter().enumerate() {                notices.push(json!({"id": format!("unreadable/{at}"), "kind": "amber", "words": words}));            },            "workingOn" => if let Some(words) = working { notices.push(json!({"id": "workingOn", "kind": "quiet", "words": words, "path": "/activity"})) },            "readRefusal" => if let Some(words) = refusal.filter(|words| !words.is_empty()) { notices.push(json!({"id": "readRefusal", "kind": "amber", "words": words})) },            "attention" => if let Some(notice) = attention { notices.push(json!({"id": "attention", "kind": notice["kind"], "words": notice["words"]})) },            // The serving Mac's backup is a round trip Home never waits on;            // a project is the database page's own.            _ => {}        }    }    notices}// ── The board, in order ─────────────────────────────────────────────────/// What the page has read that the board's parts draw from.struct Said<'a> {    cards: &'a [Value],    notices: &'a [Value],    asked: &'a Value,    done: &'a [Value],    /// The page's read failed with nothing read: Asked of you says so.    unread: bool,    /// The shown database's order of tools has been read.    arranged: bool,    /// The shown database is the person's own.    personal: bool,    database: Option<&'a str>,    shown_id: Option<&'a str>,    today: &'a str,    request: &'a Value,    lines: &'a [LineRow],    /// The board being answered, and all its parts.    board: &'a str,    parts: &'a [cotton_core::definitions::board::BoardPart],}/// Every part the board names, in its order, each with what it draws or the/// reason it draws nothing (`parts.board`, the module doc's shape).fn ordered_parts(handle: &CottonHandle, parts: &[cotton_core::definitions::board::BoardPart], said: &Said) -> Vec<Value> {    let mut counts: std::collections::HashMap<&str, usize> = Default::default();    parts.iter().map(|part| {        let count = counts.entry(part.kind.as_str()).or_insert(0);        *count += 1;        let id = part.settings.get("id").and_then(Value::as_str).map(str::to_string)            .unwrap_or_else(|| if *count == 1 { part.kind.clone() } else { format!("{}#{count}", part.kind) });        let mut entry = json!({"id": id, "kind": part.kind, "settings": part.settings});        let hidden = part_reading(handle, part, said, &mut entry);        entry["shown"] = json!(hidden.is_none());        entry["why"] = hidden.map_or(Value::Null, |why| json!({"key": why, "words": hidden_words(why, said.lines)}));        entry    }).collect()}/// The words a hidden part's reason is said in.fn hidden_words(why: &str, lines: &[LineRow]) -> String {    match why {        "quiet" => resolve("board", "part.hidden.quiet", lines, &[]),        "head" => resolve("board", "part.hidden.head", lines, &[]),        "personal" => resolve("board", "part.hidden.personal", lines, &[]),        "no_device" => resolve("board", "part.hidden.no_device", lines, &[]),        "magnifier" => resolve("board", "part.hidden.magnifier", lines, &[]),        "unarranged" => resolve("board", "part.hidden.unarranged", lines, &[]),        "no_table" => resolve("board", "part.hidden.no_table", lines, &[]),        "no_record" => resolve("board", "part.hidden.no_record", lines, &[]),        _ => resolve("board", "part.hidden.unknown", lines, &[]),    }.unwrap_or_default()}/// The items a part's `shows` keeps: each whose `field` is a shown word or/// under one (`unreadable/0` under `unreadable`), every item when it names/// none. `shows`' own order where `ordered`, else the items' (Done's newest first).fn kept_by_shows(part: &cotton_core::definitions::board::BoardPart, items: &[Value], field: &str, ordered: bool) -> Vec<Value> {    let shows = shows(std::slice::from_ref(part), &part.kind);    let place = |key: &str| shows.iter().position(|shown| key == shown || key.starts_with(&format!("{shown}/")));    let mut kept: Vec<Value> = items.iter().filter(|item| shows.is_empty() || item[field].as_str().is_some_and(|key| place(key).is_some())).cloned().collect();    if ordered { kept.sort_by_key(|item| item[field].as_str().and_then(place).unwrap_or(0)) }    kept}/// Fills `entry` with what `part` draws; answers why it draws nothing, if it does not.fn part_reading(handle: &CottonHandle, part: &cotton_core::definitions::board::BoardPart, said: &Said, entry: &mut Value) -> Option<&'static str> {    let setting = |key: &str| part.settings.get(key).cloned().unwrap_or(Value::Null);    let quiet = |empty: bool| empty.then_some("quiet");    match part.kind.as_str() {        "head" => {            entry["tags"] = setting("tags");            let of = |kind: &str| said.parts.iter().find(|other| other.kind == kind);            let all = said.asked["items"].as_array().map_or(&[][..], Vec::as_slice);            let asked = of("asked").map_or_else(|| all.to_vec(), |asked| kept_by_shows(asked, all, "key", true));            entry["asked"] = json!({"total": asked.iter().filter_map(|item| item["count"].as_u64()).sum::<u64>(), "items": asked});            let done = of("done").map_or_else(|| said.done.to_vec(), |done| kept_by_shows(done, said.done, "kind", false));            entry["done"] = json!({"items": done});            None        }        "device" => match said.cards.iter().find(|card| card["kind"] == "device") {            Some(card) => { entry["card"] = card["id"].clone(); None }            None => Some("no_device"),        },        "today" => {            entry["cards"] = said.cards.iter().filter(|card| matches!(card["kind"].as_str(), Some("day" | "later" | "thread"))).map(|card| card["id"].clone()).collect();            entry["quiet"] = json!(resolve("board", "today.quiet", said.lines, &[]).unwrap_or_default());            entry["heading"] = json!(resolve("dates", "heading.today", said.lines, &[]).unwrap_or_default());            None        }        "sync" => None,        "notices" => {            let items = kept_by_shows(part, said.notices, "id", true);            let empty = items.is_empty();            entry["items"] = json!(items);            quiet(empty)        }        "asked" => {            let items = kept_by_shows(part, said.asked["items"].as_array().map_or(&[][..], Vec::as_slice), "key", true);            let empty = items.is_empty();            entry["total"] = json!(items.iter().filter_map(|item| item["count"].as_u64()).sum::<u64>());            entry["items"] = json!(items);            entry["unreadable"] = json!(said.unread);            entry["heading"] = json!(resolve("board", "asked.title", said.lines, &[]).unwrap_or_default());            if setting("place") == "head" { Some("head") } else { quiet(empty && !said.unread) }        }        "done" => {            let items = kept_by_shows(part, said.done, "kind", false);            let empty = items.is_empty();            entry["items"] = json!(items);            entry["heading"] = json!(resolve("board", "notice.done_heading", said.lines, &[]).unwrap_or_default());            if setting("place") == "head" { Some("head") } else { quiet(empty) }        }        "list" => list_part(handle, part, said, entry),        "figure" => {            entry["heading"] = setting("heading");            let asked = scoped(json!({"part": part.settings, "today": said.today}), said.database);            entry["line"] = crate::methods::dispatch(handle, "read.homeFigure", &asked).map_or(Value::Null, |said| said["line"].clone());            None        }        "facts" => facts_part(handle, part, said, entry),        "about" => { entry["source"] = setting("source"); None }        "recent" => {            entry["heading"] = setting("heading");            if !said.personal { return Some("personal") }            let visits = crate::methods::dispatch(handle, "read.recentVisits", &json!({"limit": setting("limit")}));            entry["items"] = visits.map_or(json!([]), |visits| visits["visits"].clone());            None        }        "search" => {            entry["face"] = setting("face");            (setting("face") != "field").then_some("magnifier")        }        "tools" => {            // No tile's views are counted here (`tool` names none).            let fan = crate::methods::dispatch(handle, "shell.fan", &scoped(json!({"tool": "", "every": said.board == "tools"}), said.database));            let cards = fan.map_or_else(|_| Vec::new(), |fan| fan["tiles"].as_array().cloned().unwrap_or_default());            entry["tiles"] = cards.iter().map(|tile| tile["key"].clone()).collect();            entry["cards"] = json!(cards);            (!said.arranged).then_some("unarranged")        }        _ => Some("unknown"),    }}/// A `list` part: the rows its `where` and `period` keep, read as/// `records.list` reads them (`ask`, which the shell may ask again) and/// worded as `shell.list` words its rows.fn list_part(handle: &CottonHandle, part: &cotton_core::definitions::board::BoardPart, said: &Said, entry: &mut Value) -> Option<&'static str> {    let Some(table) = part.settings.get("table").and_then(Value::as_str) else { return Some("no_table") };    entry["table"] = json!(table);    let client = handle.client();    let definition = {        let _named = client.name_database(said.database).ok();        crate::phone::card_actions::read_definition(&client, table, METHOD).ok()    };    let Some(definition) = definition else { return Some("no_table") };    entry["heading"] = part.settings.get("heading").cloned().unwrap_or_else(|| json!(definition.plural));    let limit = part.settings.get("limit").and_then(Value::as_u64).unwrap_or(PAGE as u64);    let mut ask = json!({"table": table, "limit": limit, "today": said.today});    for key in ["where", "period"] { if let Some(value) = part.settings.get(key) { ask[key] = value.clone() } }    if let Some(zone) = said.request["timezone"].as_str() { ask["timezone"] = json!(zone) }    let tiled = matches!(definition.tile.face, cotton_core::definitions::TileFace::SlipList)        && !["where", "period", "rows"].iter().any(|key| part.settings.contains_key(*key));    // A part's own `rows` are the list (the Settings board's); else the table's read.    let read = match part.settings.get("rows").and_then(Value::as_array) {        Some(rows) => {            let kept = rows_reached(rows, cotton_tools::presentation::settings_reach());            Some(json!({"records": kept, "total": kept.len()}))        }        // A whole table drawn as slips shows what its tile does (`shell.list {tile}`).        None if tiled => {            let mut tile = ask.clone();            tile["tile"] = json!(true);            crate::methods::dispatch(handle, "shell.list", &scoped(tile, said.database)).ok()                .map(|tile| json!({"records": tile["records"], "total": tile["count"]}))        }        None => crate::methods::dispatch(handle, "records.list", &scoped(ask.clone(), said.database)).ok(),    };    let records = read.as_ref().and_then(|read| read["records"].as_array().cloned()).unwrap_or_default();    entry["count"] = read.as_ref().and_then(|read| read["total"].as_u64()).map_or(json!(records.len()), |total| json!(total));    entry["ask"] = ask;    let mut rows: Vec<Value> = records.into_iter().map(|row| json!({"id": row["id"], "data": row["data"]})).collect();    let listed = crate::methods::dispatch(handle, "shell.list", &scoped(json!({"table": table, "rows": rows, "limit": limit}), said.database)).ok();    // Every record the board hands the shell carries its one slip answer.    let answers: std::collections::HashMap<String, Value> = listed.iter()        .flat_map(|listed| listed["sections"].as_array().into_iter().flatten())        .flat_map(|section| section["rows"].as_array().into_iter().flatten())        .filter_map(|row| Some((row["id"].as_str()?.to_string(), row["slip"]["record"]["data"].get(crate::methods::shell_slip::SAID_KEY)?.clone())))        .collect();    for row in &mut rows {        if let Some(answer) = row["id"].as_str().and_then(|id| answers.get(id)) { row["data"][crate::methods::shell_slip::SAID_KEY] = answer.clone(); }    }    entry["records"] = json!(rows);    entry["rows"] = listed.as_ref().map_or(json!([]), |listed| {        listed["sections"].as_array().into_iter().flatten().flat_map(|section| section["rows"].as_array().cloned().unwrap_or_default()).collect()    });    if let Some(listed) = listed { entry["acts"] = listed["acts"].clone() }    None}/// A part's own static rows this app reaches: each row's `needs`, if it says one, met.fn rows_reached(rows: &[Value], reach: cotton_tools::presentation::SettingsReach) -> Vec<Value> {    rows.iter().filter(|row| row["needs"].as_str().is_none_or(|need| reach.meets(need))).cloned().collect()}/// A `facts` part: the shown database's record of the table `source`, each/// column it holds as a label and its value in words.fn facts_part(handle: &CottonHandle, part: &cotton_core::definitions::board::BoardPart, said: &Said, entry: &mut Value) -> Option<&'static str> {    let Some(source) = part.settings.get("source").and_then(Value::as_str) else { return Some("no_table") };    entry["source"] = json!(source);    let Some(id) = said.shown_id else { return Some("no_record") };    entry["record"] = json!(id);    let client = handle.client();    let definition = {        let _named = client.name_database(said.database).ok();        crate::phone::card_actions::read_definition(&client, source, METHOD).ok()    };    let Some(definition) = definition else { return Some("no_table") };    let Ok(record) = crate::methods::dispatch(handle, "records.get", &scoped(json!({"table": source, "id": id}), said.database)) else { return Some("no_record") };    let dates = cotton_core::records::page::DateWords::of_rows(said.lines);    entry["facts"] = definition.columns.iter().filter_map(|column| {        let value = record["data"].get(&column.key).filter(|value| !value.is_null())?;        if column.secret == Some(true) { return None }        let words = cotton_core::records::receipt::said_value_in(column, value, &dates)            .or_else(|| match value { Value::String(text) if !text.trim().is_empty() => Some(text.clone()), Value::Number(n) => Some(n.to_string()), _ => None })?;        Some(json!({"key": column.key, "label": column.label(), "value": words}))    }).collect();    None}/// A read that failed with nothing read: say `{phase: home, stage: today}`/// once the next wait has passed. An answer, or a read waiting on a move,/// starts the waits again.fn again(handle: &CottonHandle, failed: Option<&MethodError>, read: bool) {    let watch = handle.home();    let waits_for_move = failed.is_some_and(|error| error.details["why"] == "moving");    if read || failed.is_none() || waits_for_move {        watch.today_tries.store(0, Ordering::SeqCst);        return;    }    let tries = watch.today_tries.fetch_add(1, Ordering::SeqCst);    let wait = AGAIN[tries.min(AGAIN.len() - 1)];    let events = std::sync::Arc::clone(handle.events());    std::thread::Builder::new()        .name("cotton-today-again".into())        .spawn(move || {            std::thread::sleep(std::time::Duration::from_millis(wait));            events.emit(crate::events::EventKind::Client, json!({"phase": crate::methods::shell_home::PHASE, "stage": STAGE}));        })        .map(drop)        .unwrap_or_else(|_| tracing::warn!("{METHOD}: the ask-again thread did not start"));}#[cfg(test)]#[path = "shell_today_tests.rs"]mod tests;