Cotton code
1486 lines · 77.3 KB · RustRaw
//! `shell.input`, `shell.draft` and an act's picks (`shell.opened {step://! pick}`) — WHAT AN INPUT WRITES, ANSWERED BY THE CORE (the shell boundary,//! 7 Nov 2026: the core answers what to show, a platform shell only draws).//! The shell keeps which tier stands, the selected part and the keyboard;//! what a tap or a commit writes is said here, and the same JSON serves a//! Kotlin shell.//!//! ## `shell.input {op: "ask", kind, …}`//!//! The editor a write stands in, and the words it opens on://!//! ```json//! { "editor": "line|page", "words", "hint"?, "title"?, "keeps_words",//!   "writes": { "kind": "column|new|act|group|tool_act|pick_words|pick_search|pick_file", … } }//! ```//!//! - `column {table, id | draft, column}`: a card's words, a longtext on the//!   whole screen (`page`), any other written type in the line; refused//!   where the shell may not write it on this record (`parts`). A title keeps//!   its words: typed away, nothing is written. A draft's title is `new`'s.//! - `new {table, draft?}`: a new card's title, under its create's label;//!   with no draft (a "+" that makes a blank card) the core begins one, and//!   the card its commit makes is where the deck lands.//! - `act {table, door?}`: the words a "+" hands an act at the person's//!   object (`create.act`, or the door's), under the create's label.//! - `group {table, id}`: a new list's name, holding the card.//! - `tool_act {tool, act, account?, group?, record?, words: {prefill, hint}}`://!   the words a tool's act asks first (a list's Rename).//! - `pick`, `pick_words` and `pick_search` are answered by the pick step//!   itself (`shell.opened {step: pick}`): its `writes`, committed with a//!   row's value; a pick asking free words, its words' ask; a record pick's//!   Search, its search's.//!//! ## `shell.input {op: "commit", writes, words, follows?}`//!//! The `writes` an ask answered, committed with the words typed://!//! ```json//! { "change"?, "record"?, "made"?, "staged"?, "said"?, "undo"?,//!   "lands"?: { "id" }, "query"?,//!   "step"?, "ran"?, "next"?, "refusal"? }//! ```//!//! `change` and `record` are the store's own write; `made` the id a new//! card's create made (`next` then asks its body on the whole screen where//! the shell says its face tags no part, `follows`); a tool act's `said` and//! `undo`; an object act's `lands` (the record its answer names under the//! act's `lands` key); a pick's answer (a row's value, or its words) its//! next `step`, or `ran` (the act's `records.command` answer) once it was//! the last, `staged` on a draft. A refusal is said in the//! core's words in `refusal`, never thrown: nothing was written. Words that//! change nothing answer `{}`.//!//! ## `shell.input {op: "line", at, words, record?, spoken?, timezone?, now?}`//!//! One typed or dictated line where the input stands, read into writes the//! shell commits as they are (`{op: "commit", writes}`, an array committed//! in order, stopping at the first refusal). `at` is `{board: {project?}}`,//! `{list: {table, view?, project?, holding?}}`, `{page: {table, id,//! project?}}`, a blank page `{page: {table, preset}}` (no id), or `{about://! {table, id}}` (a thought about a record). `record` is the id the person//! chose from a `which` ask, sent again with the same words.//!//! ```json//! { "words", "writes": [ {"kind": "create", "table", "data"}//!                      | {"kind": "update", "table", "id", "patch"}//!                      | {"kind": "delete", "table", "id"}//!                      | {"kind": "thought", "words", "table"?, "record"?, "said"} ],//!   "asks"?: [ {"kind": "which", "candidates": [{"table", "id", "title"}]} ],//!   "picked"?: {"table", "id", "title"}, "opens"?: {"table", "id"?},//!   "refusal"?, "said"? }//! ```//!//! A refusal is answered (`refusal`, said in the input's kit lines), never//! thrown, and writes nothing. Nothing is asked of a session: the session//! inbox is retired (Nov 2026). The rules://!//! - **Reading.** The words are read by the core's phrase engine//!   (`cotton_core::phrase`, what `phrase.parse` answers): a date, a time, a//!   project's or person's name, a leading verb. Projects' and people's names//!   are read only where a table the line may write has a writable project//!   column or a writable link to the people; a failed read is said, and not//!   beside a write. Words the engine refuses are kept as written and said; a//!   line opening with a command then writes nothing. A date or time with//!   more than one reading is refused before anything is written.//! - **Verbs.** done, delete, move, rename act on a record; add (and remind//!   on a page) is a plain line whose verb leaves the title; open is spoken//!   only. Where this and the Swift input differed, the engine's verb wins.//! - **Board.** A command is refused (say it on a list); any other line is//!   kept as a thought said nowhere in particular. (The Swift doc said the//!   board captures a guessed todo/event/note/person; its code kept a//!   thought, and the code is carried: no table guess runs on the board.)//! - **List.** done/delete name the record with the words after the verb;//!   move with the words the date, time and project left (spoken, the words//!   before " to "); rename X to Y splits at the first " to ", none refused.//!   No verb: a list that takes no adds keeps a thought in its tool; one//!   whose `capture` names another table (not page-only) creates there; else//!   a new record here, made with `holding`.//! - **Record pick, in order:** the chosen `record`; an exact title (case//!   aside; the first of several); the titles the words begin; every match//!   the list's search answers. One candidate is picked; two or more ask//!   `which`; none is refused. Spoken, only an exact title (less "the"///!   "my", punctuation) counts. (Swift took the search's first match where//!   no title was exact; two candidates now ask.)//! - **Page.** A command acts on this record. A page whose `capture` names a//!   `link` (where its `when` holds) creates a captured record holding this//!   one; one that `append`s creates a record on its day; a record closed to//!   edits (all its engine's, `readonly_when`) or with only yes-no columns//!   keeps a thought on it. Else the pieces fill its columns, unless//!   three words or more are left over (or nothing fills): then a thought on//!   it. A leftover under three words is said as not used.//! - **Blank page.** A command is refused (not made yet); else a create//!   with the page's preset under what the words fill.//! - **Column fill.** The day to the date column; a time to the first//!   writable time column, else onto the date as an instant (day said, else//!   held, else today); a day alone on a timed date keeps its time; the//!   project to the project column (else the switcher's on a create); a//!   person to the first link to the people's table. A piece whose column is//!   missing stays in the title; one whose column may not be written is//!   said. The joining word before a taken piece goes with it.//! - **Create.** The title is what the pieces left ("add" drops the verb and//!   a leading kind name); empty, the whole line; a read-only title gets the//!   whole line; one web address fills the table's required link column.//! - **Verbs on a record.** Closed: refused. done writes the slip's toggle//!   (yes, or the slip's first `toggle_on`, else the second choice), refused//!   when already so or none; delete follows the table's delete rule//!   (`card_actions::deletes`) and refuses an occurrence of a series; rename//!   refuses a read-only title; move writes date, time, project, refused with//!   none, and on a page refused with a word it did not use. A change to a//!   series' date or title is refused (its page asks how far).//! - **Spoken.** A command or a thought, never a record: a command runs only//!   when its target resolves here (a list's or page's record by exact//!   title, a tool by name for open); on a page done/delete/rename run only//!   when the words name this record or nothing; any other line, an//!   ambiguous day, or a command that found nothing is kept as a thought//!   with where it was said, why beside it.//!//! ## `shell.draft {table, values?, id?, stage?, timezone?, today?}`//!//! A card not yet made, kept by the core under its `id` until its create//! lands: ONE CREATE PER DRAFT. Without an `id` a draft is begun from//! `values` (an event's day today where none is given); with one, `stage`//! puts a choice on it — `{values: {column: value}}`, `{when: {date?,//! time?}}`, `{act, answers?}` or `{repeat}` — held until the create lands//! and applied after it, or applied to the made record at once. Answers//! `{id, table, values, card, staged: {acts, repeat?}, made?}`, the card//! said as `@card` says a made one's, or null where the table names none.//!//! ## `shell.opened {step: "pick", table, id | draft, act, answers?, query?, ink?, day?, count?}`//!//! An act's picks one after another: the pick now due as fan rows//! `{value, words, detail?, picture?, initials?, does: answer|count|day|search}`//! (`rest` the row the arc rests on, `nothing` what to say where there are//! none, `words` an ask where it asks free words, `table` a record pick's,//! whose rows `ink` letters narrow by `rules::ink_match`), and the `writes`//! a row's value is committed with (`shell.input`): a read, so the act runs//! only on that commit.use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;use cotton_core::definitions::card::CardSlot;use cotton_core::definitions::{Column, ColumnType, CommandPick, OrderedMap, PickKind, RecordCommand, TableDefinition};use cotton_core::rules::shell_lines::{self, LineRow};use cotton_core::rules::{card_actions, card_when, ink_match};use cotton_core::transforms::moment_split::{self, MomentSplit};use cotton_core::transforms::zoned_clock;use serde_json::{json, Map, Value};use std::collections::VecDeque;use std::sync::{Mutex, OnceLock};const METHOD: &str = "shell.input";/// How many days Pick a date offers, from today.pub const PICKED_DAYS: i64 = 120;/// How many rows a record pick offers.const PICK_ROWS: usize = 50;/// The steps a number's stepper turns by.const STEPS: [f64; 3] = [100.0, 10.0, 1.0];/// How many drafts the core keeps; an older one is let go.const KEPT_DRAFTS: usize = 32;/// The types the shell's writers write.const WRITTEN: [ColumnType; 5] = [ColumnType::Text, ColumnType::Longtext, ColumnType::Url, ColumnType::AccountNumber, ColumnType::Amount];// MARK: shell.inputpub fn call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    match request["op"].as_str() {        Some("ask") => ask(handle, request),        Some("commit") => commit(handle, request),        Some("line") => line::line(handle, request),        _ => Err(bad("shell.input takes an op: ask, commit or line")),    }}fn ask(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let rows = lines(&client);    match request["kind"].as_str() {        Some("column") => {            let column = text(request, "column").ok_or_else(|| bad("a column write names its column"))?;            let (definition, data, target) = held(handle, request)?;            let found = definition.column(column).ok_or_else(|| bad(&format!("{} has no column {column}", definition.id)))?;            if !writes_words(&definition, found, &data) {                return Err(MethodError::new("refused", format!("{column} is not written here")));            }            let title = title_column(&definition);            // A new card's title is its create's.            if let (Some(draft), true) = (target.get("draft"), title.as_deref() == Some(column)) {                return ask(handle, &json!({"kind": "new", "table": definition.id, "draft": draft}));            }            let mut writes = json!({"kind": "column", "table": definition.id, "column": column});            writes.as_object_mut().unwrap().extend(target);            if let Some(door) = text(request, "door") {                writes["door"] = json!(door);            }            let mut asked = json!({                "editor": editor_of(found.column_type),                "words": said_text(data.get(column)).unwrap_or_default(),                "title": title.as_deref().and_then(|title| said_text(data.get(title))),                "keeps_words": title.as_deref() == Some(column),                "writes": writes,            });            // An amount opens on its figures in the currency's places ("2340.50"),            // its mark beside the input and its column's name as the hint.            if found.column_type == ColumnType::Amount {                let code = currency_of(found, &data);                asked["words"] = json!(cotton_core::rules::money::print::typed_of_minor(data.get(column).and_then(Value::as_i64), digits_of(code.as_deref())));                asked["mark"] = json!(code.as_deref().and_then(|code| shell_lines::resolve("money", &format!("symbols.{code}"), &rows, &[])).or(code));                asked["hint"] = json!(found.name.clone().unwrap_or_else(|| column.to_string()));            }            Ok(asked)        }        Some("new") => {            let table = text(request, "table").ok_or_else(|| bad("a new card names its table"))?;            let definition = definition_of(&client, table)?;            let column = title_column(&definition).ok_or_else(|| bad(&format!("{table}'s card names no title")))?;            // A "+" that makes a blank card (`plus.does: blank`) asks with no draft: the core begins it here, and            // the card it makes is the one the deck stands on.            let begun = match text(request, "draft") {                Some(_) => None,                // Inside a whole (a trip's papers) the card begins in it: the whole's `where`, as the deck read                // its parts, seeds the draft with the table's own columns.                None => {                    let values: Map<String, Value> = request["where"].as_object().into_iter().flatten()                        .filter(|(key, value)| definition.column(key).is_some() && (value.is_string() || value.is_number() || value.is_boolean()))                        .map(|(key, value)| (key.clone(), value.clone()))                        .collect();                    Some(draft_call(handle, &json!({"table": table, "values": values, "timezone": request["timezone"], "today": request["today"]}))?)                }            };            let draft = match &begun {                Some(begun) => begun["id"].as_str().ok_or_else(|| bad("a begun draft names its id"))?.to_string(),                None => text(request, "draft").unwrap_or_default().to_string(),            };            let door = text(request, "door").and_then(|id| door_of(&definition, id));            let mut writes = json!({"kind": "new", "table": table, "draft": draft, "column": column});            if begun.is_some() {                writes["lands"] = json!(true);            }            if let Some(door) = door {                writes["door"] = json!(door.id);            }            Ok(json!({                "editor": "line", "words": "",                // A door's title is asked under its own word (Add a spend), else the create's.                "hint": door.map(|door| door.label.clone()).or_else(|| definition.create.as_ref().map(|create| create.label.clone())),                "keeps_words": true,                "writes": writes,            }))        }        Some("door") => {            let table = text(request, "table").ok_or_else(|| bad("a door names its table"))?;            let id = text(request, "door").ok_or_else(|| bad("a door's ask names the door"))?;            let definition = definition_of(&client, table)?;            let door = door_of(&definition, id).ok_or_else(|| bad(&format!("{table} has no door {id}")))?;            let draft = door.draft.as_ref().ok_or_else(|| bad(&format!("{table}'s door {id} writes no new record")))?;            let mut values: Map<String, Value> = draft.values.iter().map(|(key, value)| (key.clone(), value.clone())).collect();            if let Some(dated) = &draft.dated {                let zone = zone_of(&client, request);                values.insert(dated.clone(), json!(today(handle, request, &zone)?));            }            if let Some(account) = &draft.account {                let currency = values.get("currency").and_then(Value::as_str).unwrap_or("XXX").to_string();                values.insert(account.clone(), json!(crate::phone::money::usual_account(&client, &currency)?));            }            let begun = draft_call(handle, &json!({"table": table, "values": values, "timezone": request["timezone"], "today": request["today"]}))?;            let draft_id = begun["id"].as_str().ok_or_else(|| bad("a begun draft names its id"))?.to_string();            door_ask(handle, request, table, id, &draft_id, None)        }        Some("act") => {            let table = text(request, "table").ok_or_else(|| bad("an act's words name the table whose + asks them"))?;            let definition = definition_of(&client, table)?;            let create = definition.create.as_ref().ok_or_else(|| bad(&format!("{table} names no create")))?;            let (act, hint) = match text(request, "door") {                Some(door) => {                    let door = create.doors.iter().find(|found| found.id == door).ok_or_else(|| bad(&format!("{table} has no door {door}")))?;                    (door.act.clone(), door.label.clone())                }                None => (create.act.clone(), create.label.clone()),            };            let act = act.ok_or_else(|| bad(&format!("{table}'s + hands no act its words")))?;            Ok(json!({                "editor": "line", "words": "", "hint": hint, "keeps_words": false,                "writes": {"kind": "act", "table": table, "name": act.name, "argument": act.argument, "lands": act.lands},            }))        }        Some("group") => {            let table = text(request, "table").ok_or_else(|| bad("a new list names its table"))?;            let id = text(request, "id").ok_or_else(|| bad("a new list holds the card it was made from"))?;            Ok(json!({                "editor": "line", "words": "", "hint": shell_lines::resolve("lists", "group.name", &rows, &[]),                "keeps_words": false,                "writes": {"kind": "group", "table": table, "id": id},            }))        }        Some("tool_act") => {            let tool = text(request, "tool").ok_or_else(|| bad("a tool's act names its tool"))?;            let act = text(request, "act").ok_or_else(|| bad("a tool's act names its act"))?;            let words = &request["words"];            let mut writes = json!({"kind": "tool_act", "tool": tool, "act": act});            for key in ["account", "group", "record"] {                if let Some(value) = text(request, key) {                    writes[key] = json!(value);                }            }            Ok(json!({                "editor": "line", "words": words["prefill"].as_str().unwrap_or_default(), "hint": words["hint"],                "keeps_words": false, "writes": writes,            }))        }        // Account's Your people (and Send's) Add a person: a number on the phone keyboard.        Some(crate::phone::your_people::ADD_KIND) => Ok(crate::phone::your_people::add_ask()),        _ => Err(bad("shell.input's ask takes a kind: column, new, door, act, group, tool_act or people_add")),    }}/// What each column type is written in: a longtext on the whole screen, an/// amount in the amount input, every other in the line.fn editor_of(column_type: ColumnType) -> &'static str {    match column_type {        ColumnType::Longtext => "page",        ColumnType::Amount => "amount",        _ => "line",    }}/// The currency code an amount column's row holds (its `currency` column's value).fn currency_of(column: &Column, data: &Map<String, Value>) -> Option<String> {    let held = column.currency.as_deref().and_then(|key| data.get(key)).and_then(Value::as_str);    held.map(str::trim).filter(|code| !code.is_empty()).map(str::to_ascii_uppercase)}/// The places an amount in `code` is written to (two where it names none).fn digits_of(code: Option<&str>) -> u8 {    code.map_or(2, cotton_core::records::amount::digits)}fn door_of<'a>(definition: &'a TableDefinition, id: &str) -> Option<&'a cotton_core::definitions::CreateDoor> {    definition.create.as_ref()?.doors.iter().find(|door| door.id == id)}/// A draft door's next ask after `after` (none: its first): each of its/// `asks` columns in order, then the title, which makes the record.fn door_ask(handle: &CottonHandle, request: &Value, table: &str, door: &str, draft: &str, after: Option<&str>) -> Result<Value, MethodError> {    let definition = definition_of(&handle.client(), table)?;    let asks = door_of(&definition, door).and_then(|door| door.draft.as_ref()).map(|draft| draft.asks.clone()).unwrap_or_default();    let next = match after {        None => asks.first().cloned(),        Some(column) => asks.iter().position(|asked| asked == column).and_then(|at| asks.get(at + 1)).cloned(),    };    let zone = request["timezone"].clone();    match next {        Some(column) => ask(handle, &json!({"kind": "column", "table": table, "draft": draft, "column": column, "door": door, "timezone": zone})),        None => ask(handle, &json!({"kind": "new", "table": table, "draft": draft, "door": door, "timezone": zone})),    }}fn commit(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    // A line's writes, committed in order: the last one's answer, or the    // first refusal, after which nothing more is written.    if let Some(all) = request["writes"].as_array() {        let mut last = json!({});        for writes in all {            let mut one = request.clone();            one["writes"] = writes.clone();            last = commit(handle, &one)?;            if last.get("refusal").is_some() {                break;            }        }        return Ok(last);    }    let writes = &request["writes"];    let typed = request["words"].as_str().map(str::trim).unwrap_or_default().to_string();    let answer = match writes["kind"].as_str() {        Some("column") => commit_column(handle, writes, &typed, request),        Some("new") => commit_new(handle, writes, &typed, request),        Some("act") => commit_act(handle, writes, &typed, request),        Some("group") if writes.get("group").is_some() => commit_membership(handle, writes),        Some("group") => commit_group(handle, writes, &typed),        Some("face") => commit_face(handle, writes),        Some("when") => commit_when(handle, writes, request),        Some("repeat") => dispatch(handle, "cards.repeat", json!({"table": writes["table"], "id": writes["id"], "preset": writes["preset"], "timezone": request["timezone"]})),        Some("tool_act") => {            let mut asked = json!({"words": typed});            for key in ["tool", "act", "account", "group", "record"] {                if let Some(value) = writes[key].as_str() {                    asked[key] = json!(value);                }            }            dispatch(handle, "tools.act", asked).map(|ran| json!({"said": ran["said"], "undo": ran["undo"]}))        }        Some("pick_words") if typed == writes["words"].as_str().map(str::trim).unwrap_or_default() => return Ok(json!({})),        Some("pick" | "pick_words" | "pick_file") => answer_pick(handle, writes, &typed, request),        Some("pick_search") => return Ok(json!({"query": typed})),        // Added, the shell reads Your people (or the Send step) again: the person waits there until they add back.        Some(crate::phone::your_people::ADD_KIND) => crate::phone::your_people::add(&handle.client(), &json!({"number": typed})).map(|added| json!({"said": added["said"]})),        Some("business_pick") => super::shell_input_business::answer(handle, writes, &typed, request),        Some("create") => dispatch(handle, "records.create", json!({"table": writes["table"], "data": writes["data"], "timezone": request["timezone"]})),        Some("update") => dispatch(handle, "records.update", json!({"table": writes["table"], "id": writes["id"], "patch": writes["patch"]})),        // A repeating event's Bin names its scope (only this one, every one), and the day it is deleted from.        Some("delete") if writes["scope"].is_string() => dispatch(handle, "records.delete", json!({            "table": writes["table"], "id": writes["id"], "scope": writes["scope"],            "today": today(handle, request, &zone_of(&handle.client(), request))?,        })),        Some("delete") => dispatch(handle, "records.delete", json!({"table": writes["table"], "id": writes["id"]})),        Some("thought") => {            let mut kept = json!({"text": writes["words"]});            if let Some(table) = writes["table"].as_str() {                kept["saidTable"] = json!(table);                if let Some(record) = writes["record"].as_str() {                    kept["saidRecordId"] = json!(record);                }            }            dispatch(handle, "capture.create", kept).map(|mut kept| {                kept["said"] = writes["said"].clone();                kept            })        }        _ => return Err(bad("shell.input's commit takes the writes its ask answered")),    };    Ok(answer.map(clean).unwrap_or_else(|refused| json!({"refusal": refused.message})))}/// A When or Time row's write (`shell.opened`'s `writes`): the card's day/// and hour through `cards.when`, each half the row names (a null clears it)./// Where it gives the record its first reminder on a phone that has never/// asked leave to notify, the answer asks the platform to ask now/// (`request_notifications`): the one inline ask is spent at the act that/// needs it, never at a launch, and the platform records it/// (`device.notifications.asked`).fn commit_when(handle: &CottonHandle, writes: &Value, request: &Value) -> Result<Value, MethodError> {    let mut asked = json!({"table": writes["table"], "id": writes["id"], "timezone": request["timezone"]});    for half in ["date", "time"] {        if let Some(value) = writes.get(half) {            asked[half] = value.clone();        }    }    // A row naming the day and hour the card already holds (Today on a card due today) writes nothing and    // refuses nothing: the step after it still follows.    if holds_already(handle, writes, request)? {        return Ok(json!({}));    }    let mut answer = dispatch(handle, "cards.when", asked)?;    let client = handle.client();    if crate::phone::device_preferences::prefs(&client)?.asked_at.is_none() && !answer["value"].is_null() {        let zone = zone_of(&client, request);        let due = crate::phone::reminders::call(handle, &json!({"args": {"timeZone": zone}}))?;        let reminds = due["reminders"].as_array().into_iter().flatten().any(|reminder| reminder["recordId"] == writes["id"]);        if reminds {            answer["answer"] = dispatch(handle, "device.notifications.request", json!({}))?;        }    }    Ok(answer)}/// The card's date already holds each half a When row names (its day, its/// hour, or none), read in the writer's zone.fn holds_already(handle: &CottonHandle, writes: &Value, request: &Value) -> Result<bool, MethodError> {    let (definition, data, _) = held(handle, writes)?;    let Some(column) = card_actions::date_column(&definition) else { return Ok(false) };    let zone = zone_of(&handle.client(), request);    let Ok(held) = card_when::held(data.get(&column), &zone) else { return Ok(false) };    let half = |name: &str, now: Option<&str>| match writes.get(name) {        None => true,        Some(Value::Null) => now.is_none(),        Some(value) => value.as_str() == now,    };    Ok(match &held {        Some(held) => half("date", Some(held.date.as_str())) && half("time", held.time.as_deref()),        None => half("date", None) && half("time", None),    })}fn commit_column(handle: &CottonHandle, writes: &Value, typed: &str, request: &Value) -> Result<Value, MethodError> {    let column = writes["column"].as_str().ok_or_else(|| bad("a column write names its column"))?;    let (definition, data, _) = held(handle, writes)?;    let found = definition.column(column).ok_or_else(|| bad(&format!("{} has no column {column}", definition.id)))?;    // An amount is its figures read into whole minor units, refused in the money set's words when they are none.    let value = if found.column_type == ColumnType::Amount && !typed.is_empty() {        let digits = digits_of(currency_of(found, &data).as_deref());        match cotton_core::rules::money::print::minor_of_typed(typed, digits) {            Some(minor) => json!(minor),            None => {                let rows = lines(&handle.client());                let said = shell_lines::resolve("money", "editor.not_an_amount", &rows, &[("words", typed)]).unwrap_or_else(|| typed.to_string());                return Ok(json!({"refusal": said}));            }        }    } else if typed.is_empty() {        Value::Null    } else {        json!(typed)    };    let before = data.get(column).cloned().unwrap_or(Value::Null);    let keeps = title_column(&definition).as_deref() == Some(column);    let unchanged = match (&value, &before) {        (Value::String(typed), _) => said_text(Some(&before)).unwrap_or_default().trim() == typed,        _ => value == before,    };    let door = writes["door"].as_str();    if (unchanged || (typed.is_empty() && keeps)) && door.is_none() {        return Ok(json!({}));    }    let patch = json!({column: value});    match writes["draft"].as_str() {        Some(draft) => {            let staged = draft_call(handle, &json!({"id": draft, "stage": {"values": patch}, "timezone": request["timezone"]}))?;            let mut answer = json!({"staged": staged["staged"], "draft": staged});            // A door's draft asks its next column, then its title.            if let Some(door) = door {                let table = writes["table"].as_str().unwrap_or(&definition.id);                answer["next"] = door_ask(handle, request, table, door, draft, Some(column))?;            }            Ok(answer)        }        None => dispatch(handle, "records.update", json!({"table": definition.id, "id": writes["id"], "patch": patch})),    }}fn commit_new(handle: &CottonHandle, writes: &Value, typed: &str, request: &Value) -> Result<Value, MethodError> {    let id = writes["draft"].as_str().ok_or_else(|| bad("a new card is a draft's"))?;    let column = writes["column"].as_str().ok_or_else(|| bad("a new card's title column"))?;    if typed.is_empty() {        return Ok(json!({}));    }    let zone = zone_of(&handle.client(), request);    let mut made = make(handle, id, column, typed, &zone)?;    // A door's record, and a blank "+"'s, is stood on once it is made.    if writes["door"].is_string() || writes["lands"] == json!(true) {        if let Some(record) = made["made"].as_str() {            made["lands"] = json!({"id": record});        }    }    if let Some(record) = made["made"].as_str().map(str::to_string) {        if request["follows"] == json!(true) {            let table = writes["table"].as_str().unwrap_or_default();            let definition = definition_of(&handle.client(), table)?;            let body = body_column(&definition);            if let Some(body) = body {                let next = ask(handle, &json!({"op": "ask", "kind": "column", "table": table, "id": record, "column": body}));                if let Ok(next) = next {                    made["next"] = next;                }            }        }    }    Ok(made)}fn commit_act(handle: &CottonHandle, writes: &Value, typed: &str, request: &Value) -> Result<Value, MethodError> {    if typed.is_empty() {        return Ok(json!({}));    }    let name = writes["name"].as_str().ok_or_else(|| bad("an object act names itself"))?;    let argument = writes["argument"].as_str().ok_or_else(|| bad("an object act names its argument"))?;    // A password door's act is this device's (`password.new`): it seals under    // the vault, so a locked vault answers `lend` — the shell reads this    // device's vault key once (Face ID) and commits again with it.    // A page door's act is this device's too (`page.save`): a pasted link is    // kept signed out.    let answer = if let Some(method) = crate::phone::page::door_method(name) {        dispatch(handle, method, json!({argument: typed}))?    } else if let Some(method) = crate::phone::passwords::door_method(name) {        let mut asked = json!({argument: typed});        if let Some(key) = request.get("privateKey").filter(|key| key.is_string()) {            asked["privateKey"] = key.clone();        }        match dispatch(handle, method, asked) {            Ok(answer) => answer,            Err(refused) if refused.code == "vault_locked" && request.get("privateKey").is_none() => {                return Ok(json!({"refusal": refused.message, "lend": true}));            }            Err(refused) => return Err(refused),        }    } else {        dispatch(handle, "object.act", json!({"act": name, "args": {argument: typed}}))?    };    let lands = writes["lands"].as_str().and_then(|key| answer[key].as_str()).filter(|id| !id.is_empty());    let Some(id) = lands else { return Ok(json!({})) };    Ok(json!({"lands": {"table": writes["table"], "id": id}}))}fn commit_group(handle: &CottonHandle, writes: &Value, typed: &str) -> Result<Value, MethodError> {    let table = writes["table"].as_str().ok_or_else(|| bad("a new list names its table"))?;    let id = writes["id"].as_str().ok_or_else(|| bad("a new list holds a card"))?;    let line = |name: &str, fills: &[(&str, &str)]| {        shell_lines::LineSet::shipped("lists").and_then(|lines| lines.say(name, fills)).unwrap_or_default()    };    if typed.is_empty() {        return Err(MethodError::new("refused", line("list.name_empty", &[])));    }    if crate::phone::tool_acts::list_name_taken(&handle.client(), table, None, typed)? {        return Err(MethodError::new("refused", line("list.name_taken", &[("name", typed)])));    }    dispatch(handle, "groups.create", json!({"table": table, "name": typed, "records": [id]}))}/// A list of the Group step tapped (`shell.opened`'s row): the card joins/// it, or leaves the one the row said held it.fn commit_membership(handle: &CottonHandle, writes: &Value) -> Result<Value, MethodError> {    let group = writes["group"].as_str().ok_or_else(|| bad("a list's row names the list"))?;    let id = writes["id"].as_str().ok_or_else(|| bad("a list's row names the card"))?;    let change = if writes["holds"] == json!(true) { "remove" } else { "add" };    dispatch(handle, "groups.update", json!({"id": group, (change): [id]}))}/// A face chosen (the Face step's row, the hand's tap): written on the/// table's one synced row, which every deck, Home, search and the reader/// wear. The face already chosen writes nothing.fn commit_face(handle: &CottonHandle, writes: &Value) -> Result<Value, MethodError> {    let table = writes["table"].as_str().ok_or_else(|| bad("a face names its table"))?;    let face = writes["face"].as_str().ok_or_else(|| bad("a face names itself"))?;    let client = handle.client();    let definition = crate::phone::card_actions::read_definition(&client, table, "shell.input")?;    if !crate::methods::shell_deck::offers(&definition).iter().any(|offer| offer == face) {        return Err(bad(&format!("{table} does not offer the face {face}")));    }    let choices = crate::phone::face_choice::of(&client, table, "shell.input")?.ok_or_else(|| bad("this database keeps no face choices"))?;    if crate::methods::shell_deck::selected(&definition, Some(&choices.chosen)).as_deref() == Some(face) {        return Ok(json!({}));    }    // Create is an object-side upsert keyed by the table, the first choice included.    dispatch(handle, "records.create", json!({"table": choices.table.table, "data": {(choices.table.row_key.as_str()): table, "face": face}}))}// MARK: Which part writes what/// The parts a face's tap map routes on a held card (`shell.opened`'s/// `parts`), by card place: `{does, column?}` — `days` for its date,/// `statuses` where a status verb moves its state, `groups` where its table/// keeps lists, `options` where its picture chooses a column, else `viewer`,/// and where a seal or a weather glyph is drawn by its choice column;/// `line` or `page` for words the shell may write on this record. A place/// the shell writes nothing on is left out, and its tap is the card's own.pub fn parts(definition: &TableDefinition, data: &Map<String, Value>) -> Map<String, Value> {    let mut parts = Map::new();    let Some(card) = &definition.card else { return parts };    let closed = closed(definition, data);    if let Some(column) = card.corner.first().map(|fact| fact.column.clone()).and_then(|key| definition.column(&key).cloned()) {        if column.computed.is_none() && column.readonly != Some(true) && !closed {            parts.insert("date".into(), json!({"does": "days", "column": column.key}));        }    }    for field in &card.fields {        let slot = slot_name(field.slot);        if parts.contains_key(&slot) {            continue;        }        let column = field.column.as_deref().and_then(|key| definition.column(key));        let part = match field.slot {            CardSlot::Date | CardSlot::Check => None,            CardSlot::State => (!card_actions::status_commands(definition, data).is_empty())                .then(|| json!({"does": "statuses", "column": field.column})),            CardSlot::Group => definition.groups.is_some().then(|| json!({"does": "groups"})),            CardSlot::Photo => Some(match chooses(definition, field.chooses.as_deref(), data) {                Some(column) => json!({"does": "options", "column": column}),                None => json!({"does": "viewer"}),            }),            // A seal and a weather glyph are drawn by their choice: a tap            // turns the fan into its values.            CardSlot::Seal | CardSlot::Weather => {                chooses(definition, field.column.as_deref(), data).map(|column| json!({"does": "options", "column": column}))            }            CardSlot::Star => None,            _ => column.filter(|column| writes_words(definition, column, data)).map(|column| {                json!({"does": if column.column_type == ColumnType::Longtext { "page" } else { "line" }, "column": column.key})            }),        };        if let Some(part) = part {            parts.insert(slot, part);        }    }    parts}/// The choice column a tap on the picture, a seal or a weather glyph/// chooses, where the shell may write it.fn chooses(definition: &TableDefinition, key: Option<&str>, data: &Map<String, Value>) -> Option<String> {    let column = definition.column(key?)?;    let fits = column.column_type == ColumnType::Choice        && column.computed.is_none()        && column.choices.as_ref().is_some_and(|choices| !choices.is_empty())        && column.readonly != Some(true)        && !closed(definition, data);    fits.then(|| column.key.clone())}/// May the shell's writers write `column`'s words on this record: neither/// computed nor read-only, the record open to edits, of a type they write.fn writes_words(definition: &TableDefinition, column: &Column, data: &Map<String, Value>) -> bool {    column.computed.is_none() && column.readonly != Some(true) && !closed(definition, data) && WRITTEN.contains(&column.column_type)}/// Whether the whole record is closed to edits: every column its engine's,/// or its `readonly_when` column holding a value.fn closed(definition: &TableDefinition, data: &Map<String, Value>) -> bool {    (!definition.columns.is_empty() && definition.columns.iter().all(|column| column.readonly == Some(true)))        || definition.readonly_when.as_ref().is_some_and(|key| is_set(data.get(key)))}fn is_set(value: Option<&Value>) -> bool {    match value {        None | Some(Value::Null) | Some(Value::Bool(false)) => false,        Some(Value::String(text)) => !text.trim().is_empty(),        Some(Value::Array(items)) => !items.is_empty(),        Some(Value::Object(fields)) => !fields.is_empty(),        Some(_) => true,    }}pub fn title_column(definition: &TableDefinition) -> Option<String> {    definition.card.as_ref()?.fields.iter().find(|field| field.slot == CardSlot::Title)?.column.clone()}fn body_column(definition: &TableDefinition) -> Option<String> {    let key = definition.card.as_ref()?.fields.iter().find(|field| field.slot == CardSlot::Body)?.column.clone()?;    definition.column(&key).map(|column| column.key.clone())}fn slot_name(slot: CardSlot) -> String {    serde_json::to_value(slot).ok().and_then(|value| value.as_str().map(str::to_string)).unwrap_or_default()}// MARK: shell.draftstruct Draft {    table: String,    values: Map<String, Value>,    zone: String,    /// Its create is on its way: what is staged now is applied after it.    creating: bool,    made: Option<String>,    acts: Vec<(String, Vec<Value>)>,    repeat: Option<String>,    late: Map<String, Value>,}fn drafts() -> &'static Mutex<VecDeque<(String, Draft)>> {    static DRAFTS: OnceLock<Mutex<VecDeque<(String, Draft)>>> = OnceLock::new();    DRAFTS.get_or_init(|| Mutex::new(VecDeque::new()))}fn with_draft<T>(id: &str, act: impl FnOnce(&mut Draft) -> T) -> Result<T, MethodError> {    let mut kept = drafts().lock().map_err(|_| MethodError::new("unreadable", "the drafts are unreadable"))?;    let draft = kept.iter_mut().find(|(held, _)| held == id).map(|(_, draft)| draft).ok_or_else(|| bad(&format!("there is no draft {id}")))?;    Ok(act(draft))}/// What a stage puts on the draft, read off its request.enum Stage {    Values(Map<String, Value>),    When { date: Option<Option<String>>, time: Option<Option<String>> },    Act { act: String, answers: Vec<Value> },    Repeat(String),}fn stage_of(stage: &Value) -> Result<Stage, MethodError> {    if let Some(values) = stage["values"].as_object() {        return Ok(Stage::Values(values.clone()));    }    if let Some(when) = stage.get("when").filter(|when| when.is_object()) {        let half = |name: &str| -> Result<Option<Option<String>>, MethodError> {            match when.get(name) {                None => Ok(None),                Some(Value::Null) => Ok(Some(None)),                Some(Value::String(text)) => Ok(Some(Some(text.clone()))),                Some(_) => Err(bad(&format!("a when's {name} is text or null"))),            }        };        return Ok(Stage::When { date: half("date")?, time: half("time")? });    }    if let Some(act) = stage["act"].as_str() {        return Ok(Stage::Act { act: act.to_string(), answers: stage["answers"].as_array().cloned().unwrap_or_default() });    }    if let Some(preset) = stage["repeat"].as_str() {        return Ok(Stage::Repeat(preset.to_string()));    }    Err(bad("a stage is {values}, {when}, {act, answers?} or {repeat}"))}pub fn draft(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    draft_call(handle, request)}fn draft_call(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    let zone = zone_of(&client, request);    if request["blank"] == true {        return blank(handle, request, &zone);    }    let id = match text(request, "id") {        Some(id) => id.to_string(),        None => begin(handle, request, &zone)?,    };    if let Some(stage) = request.get("stage").filter(|stage| !stage.is_null()) {        let stage = stage_of(stage)?;        let made = with_draft(&id, |draft| draft.made.clone())?;        match made {            Some(record) => apply(handle, &id, &record, stage)?,            None => stage_on(handle, &id, stage)?,        }    }    said_draft(handle, &id)}/// What a blank page stands on before its first value makes the record/// (`shell.draft {table, blank: true, day?}`): an event's day.fn blank(handle: &CottonHandle, request: &Value, zone: &str) -> Result<Value, MethodError> {    let table = text(request, "table").ok_or_else(|| bad("shell.draft takes a table"))?;    let definition = definition_of(&handle.client(), table)?;    let mut values = Map::new();    let day = text(request, "day").filter(|day| chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d").is_ok());    place_event_day(handle, &definition, &mut values, day, request, zone)?;    Ok(json!({"values": values}))}/// A new event is a whole day on its day (`day`, else today) until a time/// is set: the day alone, no end and no `all_day`, which is read as a whole/// day in the writer's zone. Nothing on a table that is not an event's, or/// where the day is said already.fn place_event_day(handle: &CottonHandle, definition: &TableDefinition, values: &mut Map<String, Value>, day: Option<&str>, request: &Value, zone: &str) -> Result<(), MethodError> {    if definition.role != Some(cotton_core::definitions::TableRole::Event) {        return Ok(());    }    if let Some(column) = card_actions::date_column(definition) {        if !values.contains_key(&column) {            let day = match day {                Some(day) => day.to_string(),                None => today(handle, request, zone)?,            };            values.insert(column, json!(day));        }    }    Ok(())}/// A draft begun from `values`: an event's day is today until one is chosen,/// and so is the day a "+" holds where its table requires one/// (`create.dated` on a required column, a journal page's day): without it the/// create is refused. An optional dated column (a todo's due) stays unset.fn begin(handle: &CottonHandle, request: &Value, zone: &str) -> Result<String, MethodError> {    let table = text(request, "table").ok_or_else(|| bad("shell.draft takes a table"))?;    let mut values = match request.get("values") {        None | Some(Value::Null) => Map::new(),        Some(Value::Object(values)) => values.clone(),        Some(_) => return Err(bad("values is {column: value}")),    };    let definition = definition_of(&handle.client(), table)?;    place_event_day(handle, &definition, &mut values, None, request, zone)?;    if let Some(dated) = definition.create.as_ref().and_then(|create| create.dated.clone()) {        if !values.contains_key(&dated) && definition.column(&dated).is_some_and(|column| column.required == Some(true)) {            values.insert(dated, json!(today(handle, request, zone)?));        }    }    let id = format!("draft-{:032x}", rand::random::<u128>());    let mut kept = drafts().lock().map_err(|_| MethodError::new("unreadable", "the drafts are unreadable"))?;    kept.push_back((id.clone(), Draft { table: table.to_string(), values, zone: zone.to_string(), creating: false, made: None, acts: Vec::new(), repeat: None, late: Map::new() }));    while kept.len() > KEPT_DRAFTS {        kept.pop_front();    }    Ok(id)}/// A choice put on a draft whose record is not made yet: its values take/// it (and, while its create is on its way, it is kept for after).fn stage_on(handle: &CottonHandle, id: &str, stage: Stage) -> Result<(), MethodError> {    let (table, zone) = with_draft(id, |draft| (draft.table.clone(), draft.zone.clone()))?;    let patch = match stage {        Stage::Values(values) => values,        Stage::When { date, time } => {            let definition = definition_of(&handle.client(), &table)?;            let column = card_actions::date_column(&definition).ok_or_else(|| bad("this card has no date a person writes"))?;            let held = with_draft(id, |draft| draft.values.get(&column).cloned())?;            let value = draft_when(&definition, &column, held.as_ref(), date, time, &zone, &today_key(handle, &zone)?)?;            let mut patch = Map::new();            patch.insert(column, value);            patch        }        Stage::Act { act, answers } => return with_draft(id, |draft| draft.acts.push((act, answers))),        Stage::Repeat(preset) => return with_draft(id, |draft| draft.repeat = Some(preset)),    };    with_draft(id, |draft| {        if draft.creating {            draft.late.extend(patch.clone());        }        draft.values.extend(patch);    })}/// A draft's When, in its card's words: the half not given is kept, a day/// with no time is the bare day (an event's whole day), a time joins its day/// as the instant in `zone`; a column holding days takes no time.fn draft_when(    definition: &TableDefinition, column: &str, held: Option<&Value>, date: Option<Option<String>>, time: Option<Option<String>>,    zone: &str, today: &str,) -> Result<Value, MethodError> {    let current = card_when::held(held, zone).map_err(|error| bad(&error.to_string()))?;    let date = date.as_ref().map(|date| date.as_deref());    let time = time.as_ref().map(|time| time.as_deref());    if card_when::holds_days(definition, column) {        return card_when::written_day(current.as_ref(), date, time).map(|day| day.map_or(Value::Null, Value::from)).map_err(|error| bad(&error.to_string()));    }    let day = match (date, &current) {        (Some(None), _) => return Ok(Value::Null),        (Some(Some(day)), _) => day.to_string(),        (None, Some(current)) => current.date.clone(),        (None, None) => today.to_string(),    };    let time = match time {        None => current.and_then(|current| current.time),        Some(time) => time.map(str::to_string),    };    match time {        None if moment_split::is_calendar_day(&day) => Ok(json!(day)),        None => Err(bad(&format!("{day} is not a day"))),        Some(time) => moment_split::join_moment(&MomentSplit { date: day, time: Some(time) }, zone).map(Value::from).map_err(|error| bad(&error.to_string())),    }}/// A choice put on a draft whose record is made: written to the record now.fn apply(handle: &CottonHandle, _id: &str, record: &str, stage: Stage) -> Result<(), MethodError> {    let (table, zone) = with_draft(_id, |draft| (draft.table.clone(), draft.zone.clone()))?;    match stage {        Stage::Values(values) => {            dispatch(handle, "records.update", json!({"table": table, "id": record, "patch": values}))?;        }        Stage::When { date, time } => {            let mut asked = json!({"table": table, "id": record, "timezone": zone});            if let Some(date) = date {                asked["date"] = date.map_or(Value::Null, Value::from);            }            if let Some(time) = time {                asked["time"] = time.map_or(Value::Null, Value::from);            }            dispatch(handle, "cards.when", asked)?;        }        Stage::Act { act, answers } => {            run_act(handle, &table, record, &act, &answers)?;        }        Stage::Repeat(preset) => {            dispatch(handle, "cards.repeat", json!({"id": record, "preset": preset, "timezone": zone}))?;        }    }    Ok(())}/// The draft's record made, once: its values with the title typed, then/// every choice gathered on it written onto the record — the late values,/// the acts and the repeat chosen before or while it was made. Refused, the/// draft stands as typed, still new, and the refusal is the answer's.fn make(handle: &CottonHandle, id: &str, column: &str, typed: &str, zone: &str) -> Result<Value, MethodError> {    enum Next {        Create(String, Map<String, Value>),        Late(String, String),    }    let next = with_draft(id, |draft| {        draft.values.insert(column.to_string(), json!(typed));        match (&draft.made, draft.creating) {            (Some(record), _) => Next::Late(draft.table.clone(), record.clone()),            (None, true) => {                draft.late.insert(column.to_string(), json!(typed));                Next::Late(draft.table.clone(), String::new())            }            (None, false) => {                draft.creating = true;                Next::Create(draft.table.clone(), draft.values.clone())            }        }    })?;    let (table, values) = match next {        // ONE CREATE PER DRAFT: words committed again while its record is        // being made are a choice like any other, written onto it.        Next::Late(_, record) if record.is_empty() => return Ok(json!({"staged": true})),        Next::Late(table, record) => {            return dispatch(handle, "records.update", json!({"table": table, "id": record, "patch": {column: typed}}));        }        Next::Create(table, values) => (table, values),    };    let created = dispatch(handle, "records.create", json!({"table": table, "data": values, "timezone": zone}));    let created = match created {        Ok(created) => created,        Err(refused) => {            with_draft(id, |draft| {                draft.creating = false;                let late = std::mem::take(&mut draft.late);                draft.values.extend(late);            })?;            return Err(refused);        }    };    let record = ["/record/id", "/id", "/change/record_id", "/change/after/id"]        .iter()        .find_map(|pointer| created.pointer(pointer).and_then(Value::as_str))        .map(str::to_string)        .ok_or_else(|| MethodError::new("unreadable", "records.create answered no record"))?;    let (late, acts, repeat) = with_draft(id, |draft| {        draft.made = Some(record.clone());        draft.creating = false;        (std::mem::take(&mut draft.late), std::mem::take(&mut draft.acts), draft.repeat.take())    })?;    let mut refusals = Vec::new();    let mut answer = created;    let late: Map<String, Value> = late.into_iter().filter(|(key, _)| key != column).collect();    if !late.is_empty() {        match dispatch(handle, "records.update", json!({"table": table, "id": record, "patch": late})) {            Ok(updated) => {                answer["record"] = updated["record"].clone();            }            Err(refused) => refusals.push(refused.message),        }    }    for (act, answers) in acts {        if let Err(refused) = run_act(handle, &table, &record, &act, &answers) {            refusals.push(refused.message);        }    }    if let Some(preset) = repeat {        if let Err(refused) = dispatch(handle, "cards.repeat", json!({"id": record, "preset": preset, "timezone": zone})) {            refusals.push(refused.message);        }    }    answer["made"] = json!(record);    if let Some(first) = refusals.into_iter().next() {        answer["refusal"] = json!(first);    }    Ok(answer)}/// The draft as it stands, its card said from its values.fn said_draft(handle: &CottonHandle, id: &str) -> Result<Value, MethodError> {    let (table, values, made, acts, repeat) = with_draft(id, |draft| {        (draft.table.clone(), draft.values.clone(), draft.made.clone(), draft.acts.iter().map(|(act, _)| act.clone()).collect::<Vec<_>>(), draft.repeat.clone())    })?;    let mut said = json!({"id": "draft", "table": table, "data": values});    crate::phone::records::resolve_live_slips_on(handle, "records.get", &json!({"table": table}), &mut said)?;    let card = said["data"].get(cotton_core::records::card::CARD_KEY).cloned().unwrap_or(Value::Null);    let mut answer = json!({"id": id, "table": table, "values": values, "card": card, "staged": {"acts": acts, "repeat": repeat}});    if let Some(made) = made {        answer["made"] = json!(made);    }    Ok(answer)}/// One act run on a record with its picks' answers: a several-pick act's/// as their ordered list, a one-pick act's as its one answer.fn run_act(handle: &CottonHandle, table: &str, id: &str, act: &str, answers: &[Value]) -> Result<Value, MethodError> {    let definition = definition_of(&handle.client(), table)?;    let several = command_of(&definition, act).is_some_and(|command| command.picks.is_some());    let picked = if several { Value::Array(answers.to_vec()) } else { answers.first().cloned().unwrap_or(Value::Null) };    dispatch(handle, "records.command", json!({"table": table, "id": id, "command": act, "picked": picked}))}// MARK: The picks/// The act `id` of a definition: one of its commands, or a package act.fn command_of<'a>(definition: &'a TableDefinition, id: &str) -> Option<&'a RecordCommand> {    definition.commands.iter().flatten().chain(definition.acts.iter().flatten()).find(|command| command.id == id)}/// The picks an act asks, in order: its `picks`, or its one `pick`; an act/// that picks a table (`pick_table`) asks one pick of no kind.fn picks_of(command: &RecordCommand) -> Vec<Option<&CommandPick>> {    if let Some(picks) = command.picks.as_ref().filter(|picks| !picks.is_empty()) {        return picks.iter().map(Some).collect();    }    match (&command.pick, &command.pick_table) {        (Some(pick), _) => vec![Some(pick)],        (None, Some(_)) => vec![None],        (None, None) => Vec::new(),    }}pub fn pick(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    if !request["business"].is_null() {        return super::shell_input_business::pick(handle, request);    }    let client = handle.client();    let rows = lines(&client);    let table = text(request, "table").ok_or_else(|| bad("an act's picks name the card's table"))?;    let act = text(request, "act").ok_or_else(|| bad("the pick step takes the act that asks it"))?;    let definition = definition_of(&client, table)?;    let command = command_of(&definition, act).ok_or_else(|| bad(&format!("{table} has no act {act}")))?;    let answers = request["answers"].as_array().cloned().unwrap_or_default();    let picks = picks_of(command);    let draft = text(request, "draft");    let id = text(request, "id");    if answers.len() >= picks.len() {        return Err(bad(&format!("{act} has asked every pick: its last answer is committed (`shell.input`)")));    }    let data = match (id, draft) {        (Some(id), _) => crate::phone::card_actions::read_card(&client, &json!({"table": table, "id": id}), METHOD)?.data,        (None, Some(draft)) => with_draft(draft, |draft| draft.values.clone())?,        (None, None) => Map::new(),    };    let at = answers.len();    let current = picks[at];    let label = current.and_then(|pick| pick.label.clone()).unwrap_or_else(|| command.label.clone());    let zone = zone_of(&client, request);    let mut answering = json!({"kind": "pick", "table": table, "act": act, "answers": answers});    if let Some(id) = id {        answering["id"] = json!(id);    }    if let Some(draft) = draft {        answering["draft"] = json!(draft);    }    let mut step = json!({"kind": "pick", "label": label, "index": at, "writes": answering});    // Each row says its value alone (★, ★★, …); the question is the step's    // own `label`, said once for the tier, never under every tile.    let row = |value: &str, words: String, does: &str| json!({"value": value, "words": words, "does": does});    let found: Vec<Value> = match current {        None => {            let tables = definitions(&client)?;            cotton_core::definitions::fileable::fileable_tables(&tables, table).into_iter().map(|offered| row(&offered.id, offered.name.clone(), "answer")).collect()        }        Some(pick) => match pick.kind {            PickKind::Number => match pick.labels.as_ref().filter(|labels| !labels.is_empty()) {                Some(labels) => labelled_rows(pick, labels, &rows),                None => number_rows(pick, request["count"].as_f64(), &mut step),            },            PickKind::Datetime => {                step["moment"] = json!(true);                match text(request, "day") {                    Some(day) => half_hours(&client, &rows)                        .into_iter()                        .filter_map(|(time, words)| {                            let at = moment_split::join_moment(&MomentSplit { date: day.to_string(), time: Some(time) }, &zone).ok()?;                            Some(row(&at, words, "answer"))                        })                        .collect(),                    None => picked_days(handle, request, &rows)?                        .into_iter()                        .map(|(day, words)| json!({"value": day, "words": words, "picture": "edit-value-day", "does": "day", "day": day}))                        .collect(),                }            }            PickKind::Text => {                if let Some(column) = choice_column(&definition, pick) {                    column.choices.iter().flatten().map(|choice| row(choice, column.choice_label(choice), "answer")).collect()                } else if let Some(words) = choices_from(&definition, pick, &data) {                    words.into_iter().map(|words| row(&words, words.clone(), "answer")).collect()                } else if pick.choices_from.is_none() {                    // Free words: asked in the shell's writer, never on the fan.                    let column = words_column(&definition, pick);                    let title = title_column(&definition).and_then(|title| said_text(data.get(&title)));                    let words = column.as_ref().and_then(|column| said_text(data.get(&column.key))).unwrap_or_default();                    let mut writes = step["writes"].clone();                    writes["kind"] = json!("pick_words");                    writes["words"] = json!(words);                    step["words"] = json!({                        "editor": if column.is_some_and(|column| column.column_type == ColumnType::Longtext) { "page" } else { "line" },                        "words": words, "title": title, "hint": label, "keeps_words": false, "writes": writes,                    });                    return Ok(json!({"step": step}));                } else {                    Vec::new()                }            }            // A file from the phone's files (Give subtitles): the platform opens its own picker for `accept`, copies            // the picked file where it may read it, and commits its path as the words with `writes` (`pick_file`).            PickKind::File => {                let mut writes = step["writes"].clone();                writes["kind"] = json!("pick_file");                step["file"] = json!({ "accept": pick.accept.clone().unwrap_or_default(), "hint": label, "writes": writes });                return Ok(json!({"step": step}));            }            PickKind::Database => {                let open = client.current_database().ok();                client.databases().map_err(|why| MethodError::new("unreadable", why))?.into_iter()                    .filter(|database| !database.theirs && Some(&database.id) != open.as_ref())                    .map(|database| {                        let name = crate::phone::databases::name_of(&client, &database.id).ok().flatten().unwrap_or(database.name.clone());                        row(&database.id, name, "answer")                    })                    .collect()            }            PickKind::Record => {                let picked = pick.table.as_deref().ok_or_else(|| bad(&format!("{act}'s record pick names no table")))?;                step["table"] = json!(picked);                let query = text(request, "query").unwrap_or_default();                let ink = text(request, "ink").unwrap_or_default();                let shown = definition_of(&client, picked).ok();                let mut asked = json!({"table": picked, "limit": if ink.is_empty() { PICK_ROWS } else { cotton_core::ink::shipped().knobs.pick_rows as usize }});                let searched = if query.is_empty() { ink } else { query };                if !searched.is_empty() {                    asked["query"] = json!(searched);                }                let filter = filter_on(pick, id);                if !filter.is_empty() {                    asked["where"] = Value::Object(filter);                }                if let Some(by) = &pick.database_by {                    let database = if by == "$id" { id.map(str::to_string) } else { said_text(data.get(by)) };                    let database = database.filter(|database| !database.is_empty())                        .ok_or_else(|| MethodError::new("refused", shell_lines::resolve("definitions", "refused.no_database", &rows, &[]).unwrap_or_default()))?;                    asked["database"] = json!(database);                }                let listed = crate::methods::dispatch(handle, "records.list", &if asked.get("database").is_some() { asked } else { crate::phone::records::in_named_database(asked) })?;                let stops = ink_match::stop_words();                let people = shown.as_ref().is_some_and(|shown| shown.role == Some(cotton_core::definitions::TableRole::Person));                let records = listed["records"].as_array().cloned().unwrap_or_default();                let any = !records.is_empty();                let mut said: Vec<Value> = records.iter().filter_map(|record| {                    let id = record["id"].as_str()?;                    let name = shown.as_ref().and_then(|shown| said_text(record["data"].get(&shown.title))).filter(|name| !name.trim().is_empty())                        .or_else(|| shown.as_ref().map(|shown| shown.name.clone())).unwrap_or_else(|| id.to_string());                    if !ink_match::holds(Some(&name), ink, &stops) {                        return None;                    }                    let mut card = row(id, name.clone(), "answer");                    if people {                        let words: Vec<&str> = name.split_whitespace().collect();                        card["words"] = json!(words.first().copied().unwrap_or(&name));                        card["initials"] = json!(words.iter().take(2).filter_map(|word| word.chars().next()).collect::<String>());                    }                    Some(card)                }).collect();                if any || !query.is_empty() {                    said.push(json!({"value": "search", "words": shell_lines::resolve("editing", "command.search", &rows, &[]).unwrap_or_default(), "does": "search",                        "search": {"editor": "line", "words": query, "title": label, "hint": shell_lines::resolve("editing", "command.search", &rows, &[]), "keeps_words": false,                            "writes": {"kind": "pick_search"}}}));                }                // Letters that leave nothing leave the pick with nothing (owner, 4 Nov 2026).                if !any && query.is_empty() && ink.is_empty() {                    step["nothing"] = json!(shown.as_ref().and_then(|shown| shown.empty.as_ref().map(|empty| empty.title.clone()))                        .or_else(|| shell_lines::resolve("editing", "command.the_choices_could_not", &rows, &[])));                }                said            }        },    };    if found.is_empty() && step.get("nothing").is_none() && current.map(|pick| pick.kind) != Some(PickKind::Record) {        step["nothing"] = json!(match current.map(|pick| pick.kind) {            None => shell_lines::resolve("record", "nothing_to_make", &rows, &[]),            Some(PickKind::Database) => shell_lines::resolve("record", "no_other_database", &rows, &[]),            _ => shell_lines::resolve("editing", "command.the_choices_could_not", &rows, &[]),        });    }    step["rows"] = Value::Array(found);    Ok(json!({"step": step}))}/// One pick answered (`shell.input {op: commit, writes: {kind: pick}}`):/// the last runs the act with every answer, in the definition's order (on a/// draft it is staged for its create); else the next pick is asked.fn answer_pick(handle: &CottonHandle, writes: &Value, typed: &str, request: &Value) -> Result<Value, MethodError> {    let table = writes["table"].as_str().ok_or_else(|| bad("an act's picks name the card's table"))?;    let act = writes["act"].as_str().ok_or_else(|| bad("an act's picks name the act"))?;    let definition = definition_of(&handle.client(), table)?;    let command = command_of(&definition, act).ok_or_else(|| bad(&format!("{table} has no act {act}")))?;    let mut answers = writes["answers"].as_array().cloned().unwrap_or_default();    answers.push(json!(typed));    if answers.len() < picks_of(command).len() {        let mut asked = json!({"table": table, "act": act, "answers": answers, "timezone": request["timezone"], "today": request["today"]});        for key in ["id", "draft"] {            if let Some(value) = writes[key].as_str() {                asked[key] = json!(value);            }        }        return pick(handle, &asked);    }    if let Some(draft) = writes["draft"].as_str() {        let staged = draft_call(handle, &json!({"id": draft, "stage": {"act": act, "answers": answers}, "timezone": request["timezone"]}))?;        return Ok(json!({"staged": staged["staged"], "draft": staged}));    }    let id = writes["id"].as_str().ok_or_else(|| bad("an act runs on the card's id"))?;    Ok(json!({"ran": run_act(handle, table, id, act, &answers)?}))}/// The choice column a text pick writes (`patch.colour`), whose choices are its answers.fn choice_column<'a>(definition: &'a TableDefinition, pick: &CommandPick) -> Option<&'a Column> {    words_column(definition, pick).filter(|column| column.column_type == ColumnType::Choice && column.choices.as_ref().is_some_and(|choices| !choices.is_empty()))}/// The column a pick's words are written to, where it is one a person writes.fn words_column<'a>(definition: &'a TableDefinition, pick: &CommandPick) -> Option<&'a Column> {    let key = pick.argument.strip_prefix("patch.").unwrap_or(&pick.argument);    definition.column(key).filter(|column| column.readonly != Some(true))}/// The words a text pick offers from a read-only list column of the record.fn choices_from(definition: &TableDefinition, pick: &CommandPick, data: &Map<String, Value>) -> Option<Vec<String>> {    let key = pick.choices_from.as_deref()?;    let column = definition.column(key)?;    if column.readonly != Some(true) || column.secret == Some(true) {        return None;    }    let mut words = Vec::new();    for value in data.get(key)?.as_array()?.iter() {        let word = value.as_str().filter(|word| !word.trim().is_empty())?;        if !words.iter().any(|held: &String| held == word) {            words.push(word.to_string());        }    }    (!words.is_empty()).then_some(words)}/// A record pick's filter on the acted-on record (`$id` is its id).pub(super) fn filter_on(pick: &CommandPick, id: Option<&str>) -> Map<String, Value> {    let at = |value: &Value| match (value.as_str(), id) {        (Some(cotton_core::definitions::RECORD_ID), Some(id)) => json!(id),        _ => value.clone(),    };    pick.filter.iter().flat_map(|filter| filter.iter()).map(|(column, wanted)| {        let value = match wanted {            Value::Array(any) => Value::Array(any.iter().map(at).collect()),            value => at(value),        };        (column.clone(), value)    }).collect()}/// A number's stepper as fan rows: the count in the middle (`rest`, on/// `step`), the steps down before it and up after it, none past the pick's/// min or max, the count itself held between them. A customer's picks ask/// the same one (`shell_input_business`).pub(super) fn number_rows(pick: &CommandPick, asked: Option<f64>, step: &mut Value) -> Vec<Value> {    let number = |value: &Option<serde_json::Number>| value.as_ref().and_then(serde_json::Number::as_f64);    let (min, max) = (number(&pick.min), number(&pick.max));    let count = asked.or(number(&pick.default)).or(min).unwrap_or(0.0);    let count = count.max(min.unwrap_or(f64::NEG_INFINITY)).min(max.unwrap_or(f64::INFINITY));    let fits = |value: f64| min.is_none_or(|min| value >= min) && max.is_none_or(|max| value <= max);    let mut said: Vec<Value> = STEPS.iter().filter(|by| fits(count - **by)).map(|by| {        json!({"value": format!("down-{by}"), "words": format!("\u{2212}{}", figure(*by)), "does": "count", "count": count - by})    }).collect();    step["rest"] = json!(said.len());    said.push(json!({"value": figure(count), "words": figure(count), "does": "answer"}));    said.extend(STEPS.iter().rev().filter(|by| fits(count + **by)).map(|by| {        json!({"value": format!("up-{by}"), "words": format!("+{}", figure(*by)), "does": "count", "count": count + by})    }));    said}/// A labelled number's values, lowest first, each worded as the definition/// labels it, and Skip after them where the pick may be left.pub(super) fn labelled_rows(pick: &CommandPick, labels: &OrderedMap<String>, rows: &[LineRow]) -> Vec<Value> {    let mut values: Vec<(f64, &String, &String)> = labels.iter().filter_map(|(key, words)| key.parse::<f64>().ok().map(|value| (value, key, words))).collect();    values.sort_by(|a, b| a.0.total_cmp(&b.0));    let mut said: Vec<Value> = values.into_iter().map(|(_, key, words)| json!({"value": key, "words": words, "does": "answer"})).collect();    if pick.optional == Some(true) {        said.push(json!({"value": "", "words": shell_lines::resolve("editing", "command.skip", rows, &[]).unwrap_or_default(), "does": "answer"}));    }    said}fn figure(number: f64) -> String {    if number.fract() == 0.0 { format!("{}", number as i64) } else { format!("{number}") }}// MARK: Pick a date, Pick a time/// Every day from today for `PICKED_DAYS` days, each `(YYYY-MM-DD, "Tue 4 Nov")`.pub fn picked_days(handle: &CottonHandle, request: &Value, rows: &[LineRow]) -> Result<Vec<(String, String)>, MethodError> {    picked_days_from(today_number(&handle.client(), request)?, rows)}pub fn picked_days_from(today: i64, rows: &[LineRow]) -> Result<Vec<(String, String)>, MethodError> {    let dates = cotton_core::records::page::DateWords::of_rows(rows);    let this_year = zoned_clock::civil_from_days(today).0;    Ok((0..PICKED_DAYS).map(|offset| (zoned_clock::day_key(today + offset), dates.weekday_date(today + offset, this_year))).collect())}/// Every half hour of a day, each `(HH:MM, "9:30 am")` in the database's clock.pub fn half_hours(_client: &ClientController, rows: &[LineRow]) -> Vec<(String, String)> {    let dates = cotton_core::records::page::DateWords::of_rows(rows);    (0..48).map(|half| (format!("{:02}:{:02}", half / 2, half % 2 * 30), dates.clock(half / 2, half % 2 * 30))).collect()}/// Today as a day number: the asked `today`, else the clock's in the zone.pub fn today_number(client: &ClientController, request: &Value) -> Result<i64, MethodError> {    let zone = zone_of(client, request);    match request["today"].as_str() {        Some(day) => {            let parts: Vec<i64> = day.split('-').filter_map(|part| part.parse().ok()).collect();            match parts[..] {                [year, month, date] if cotton_core::records::is_date(day) => Ok(zoned_clock::day_number(year, month, date)),                _ => Err(bad("today is a day, YYYY-MM-DD")),            }        }        None => zoned_clock::local_day(client.clock().now().timestamp_millis(), &zone).map_err(|_| bad("timezone is a named time zone")),    }}fn today(handle: &CottonHandle, request: &Value, _zone: &str) -> Result<String, MethodError> {    Ok(zoned_clock::day_key(today_number(&handle.client(), request)?))}fn today_key(handle: &CottonHandle, zone: &str) -> Result<String, MethodError> {    today(handle, &json!({"timezone": zone}), zone)}// MARK: Reading/// The card a write is for, and how the writes name it: a made record by/// its id, a draft by its id (its values).fn held(handle: &CottonHandle, request: &Value) -> Result<(TableDefinition, Map<String, Value>, Map<String, Value>), MethodError> {    let client = handle.client();    if let Some(draft) = text(request, "draft") {        let (table, values) = with_draft(draft, |held| (held.table.clone(), held.values.clone()))?;        let mut target = Map::new();        target.insert("draft".into(), json!(draft));        return Ok((definition_of(&client, &table)?, values, target));    }    let card = crate::phone::card_actions::read_card(&client, request, METHOD)?;    let mut target = Map::new();    target.insert("id".into(), json!(card.id));    Ok((card.definition, card.data, target))}fn definition_of(client: &ClientController, table: &str) -> Result<TableDefinition, MethodError> {    crate::phone::card_actions::read_definition(client, table, METHOD)}fn definitions(client: &ClientController) -> Result<Vec<TableDefinition>, MethodError> {    let mut tables = Vec::new();    client        .read_rows(METHOD, &mut |ctx| {            tables = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?.definitions;            Ok(Value::Null)        })        .map_err(|why| MethodError::new("unreadable", why))?;    Ok(tables)}fn lines(client: &ClientController) -> Vec<LineRow> {    client.with_file(|file| Ok(cotton_tools::presentation::line_rows(file.driver, file.workspace_id))).unwrap_or_default()}fn dispatch(handle: &CottonHandle, method: &str, args: Value) -> Result<Value, MethodError> {    crate::methods::dispatch(handle, method, &crate::phone::records::in_named_database(args))}fn said_text(value: Option<&Value>) -> Option<String> {    match value? {        Value::String(text) => Some(text.clone()),        Value::Number(number) => Some(number.to_string()),        _ => None,    }}fn text<'a>(request: &'a Value, key: &str) -> Option<&'a str> {    request.get(key).and_then(Value::as_str).filter(|value| !value.is_empty())}fn zone_of(client: &ClientController, request: &Value) -> String {    request["timezone"].as_str().unwrap_or(client.time_zone().unwrap_or("UTC")).to_string()}/// An answer without the nulls an optional place left.fn clean(mut answer: Value) -> Value {    if let Some(fields) = answer.as_object_mut() {        fields.retain(|_, value| !value.is_null());    }    answer}fn bad(why: &str) -> MethodError {    MethodError::new("bad_request", why.to_string())}#[path = "shell_input_line.rs"]mod line;#[cfg(test)]#[path = "shell_input_tests.rs"]mod tests;