Cotton code
929 lines · 42.3 KB · RustRaw
//! `shell.input {op: "line"}`: a typed or spoken line read into the writes//! `{op: "commit"}` takes. The rules and the answer's shape are documented//! on `shell.input` (shell_input.rs, "## shell.input {op: line, …}").use super::{bad, closed, definition_of, definitions, dispatch, said_text, text, zone_of};use crate::handle::CottonHandle;use crate::methods::MethodError;use cotton_core::definitions::{Column, ColumnType, TableDefinition, TableRole};use cotton_core::phrase::{parse_phrase, ParsedPhrase, Understood};use cotton_core::rules::{card_actions, card_when};use cotton_core::transforms::moment_split::{self, MomentSplit};use serde_json::{json, Map, Value};use std::collections::BTreeSet;/// The verbs that act on a record already there.pub const COMMANDS: [&str; 4] = ["done", "delete", "move", "rename"];/// A title or a leftover of this many words or more asks the model.pub const ASK_WORDS: usize = 3;/// The joining word a taken piece takes with it ("buy paint for Allotment").const JOINERS: [&str; 6] = ["to", "for", "on", "at", "by", "in"];/// How many records the pick searches, and how many names one read takes.const SEARCHED: usize = 50;const NAMES_PAGE: usize = 200;#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]pub enum Piece {    Date,    Time,    Project,    Person,    Verb,}/// Where the input stands.enum At {    Board,    List { table: TableDefinition, project: Option<String>, holding: Map<String, Value> },    Page { table: TableDefinition, id: String, project: Option<String> },    Blank { table: TableDefinition, preset: Map<String, Value>, project: Option<String> },    About { table: TableDefinition, id: String },}#[derive(Default)]pub struct Names {    pub projects: Vec<(String, String)>,    pub people: Vec<(String, String)>,    pub people_table: Option<String>,}impl Names {    fn id(list: &[(String, String)], name: &str) -> Option<String> {        list.iter().find(|(held, _)| held == name).map(|(_, id)| id.clone())    }}/// One line as the parser read it.pub struct Reading {    pub text: String,    pub parsed: ParsedPhrase,    pub names: Names,}/// What one line came to.#[derive(Default)]struct Answer {    writes: Vec<Value>,    asks: Vec<Value>,    picked: Option<Value>,    refusal: Option<String>,    said: Vec<String>,    opens: Option<Value>,}impl Answer {    fn refused(line: String) -> Self {        Answer { refusal: Some(line), ..Default::default() }    }    fn write(write: Value) -> Self {        Answer { writes: vec![write], ..Default::default() }    }}fn line_of(name: &str, fills: &[(&str, &str)]) -> String {    cotton_core::rules::shell_lines::LineSet::shipped("input").and_then(|lines| lines.say(name, fills)).unwrap_or_default()}pub fn line(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let words = request["words"].as_str().map(str::trim).unwrap_or_default().to_string();    let at = at_of(handle, &request["at"])?;    let spoken = request["spoken"] == json!(true);    let chosen = text(request, "record").map(str::to_string);    let answer = if words.is_empty() { Answer::default() } else { read_line(handle, request, &at, &words, spoken, chosen)? };    let mut said = answer.said;    if let Some(refusal) = &answer.refusal {        said.insert(0, refusal.clone());    }    let mut out = json!({"words": words, "writes": answer.writes});    if !answer.asks.is_empty() {        out["asks"] = Value::Array(answer.asks);    }    if let Some(picked) = answer.picked {        out["picked"] = picked;    }    if let Some(refusal) = answer.refusal {        out["refusal"] = json!(refusal);    }    if let Some(opens) = answer.opens {        out["opens"] = opens;    }    if !said.is_empty() {        out["said"] = json!(said.join(" "));    }    Ok(out)}fn at_of(handle: &CottonHandle, at: &Value) -> Result<At, MethodError> {    let client = handle.client();    let project = |place: &Value| place["project"].as_str().filter(|id| !id.is_empty()).map(str::to_string);    let table = |place: &Value| -> Result<TableDefinition, MethodError> {        definition_of(&client, place["table"].as_str().ok_or_else(|| bad("a list or a page names its table"))?)    };    if let Some(board) = at.get("board") {        let _ = project(board);        return Ok(At::Board);    }    if let Some(list) = at.get("list") {        let holding = list["holding"].as_object().cloned().unwrap_or_default();        return Ok(At::List { table: table(list)?, project: project(list), holding });    }    if let Some(page) = at.get("page") {        return Ok(match page["id"].as_str().filter(|id| !id.is_empty()) {            Some(id) => At::Page { table: table(page)?, id: id.to_string(), project: project(page) },            None => At::Blank { table: table(page)?, preset: page["preset"].as_object().cloned().unwrap_or_default(), project: project(page) },        });    }    if let Some(about) = at.get("about") {        let id = about["id"].as_str().ok_or_else(|| bad("a thought about a record names its id"))?;        return Ok(At::About { table: table(about)?, id: id.to_string() });    }    Err(bad("a line's at is {board}, {list: {table}}, {page: {table, id?}} or {about: {table, id}}"))}fn read_line(handle: &CottonHandle, request: &Value, at: &At, words: &str, spoken: bool, chosen: Option<String>) -> Result<Answer, MethodError> {    // A thought about a record is kept as said: nothing in it is read.    if let At::About { table, id } = at {        return Ok(keep(words, Some(table), Some(id)));    }    let tables = definitions(&handle.client())?;    let mut notes = Vec::new();    let names = if needs_names(at, &tables) { read_names(handle, &tables, &mut notes) } else { Names::default() };    let zone = zone_of(&handle.client(), request);    let now = request["now"].as_str().map(str::to_string).unwrap_or_else(|| handle.client().clock().now().to_rfc3339());    let project_names: Vec<String> = names.projects.iter().map(|(name, _)| name.clone()).collect();    let people_names: Vec<String> = names.people.iter().map(|(name, _)| name.clone()).collect();    let parsed = parse_phrase(words, &now, &zone, &project_names, &people_names);    let ctx = Ctx { handle, zone: &zone, now: &now, tables: &tables, spoken, chosen };    if spoken {        let Ok(parsed) = parsed else { return Ok(keep_said(at, words, None)) };        return spoken_line(&ctx, at, Reading { text: words.to_string(), parsed, names });    }    let parsed = match parsed {        Ok(parsed) => parsed,        Err(message) => {            notes.push(line_of("read_failed_said", &[("message", &message)]));            let first = words.split_whitespace().next().map(str::to_lowercase).unwrap_or_default();            if COMMANDS.contains(&first.as_str()) {                return Ok(Answer { refusal: Some(notes.join(" ")), ..Default::default() });            }            ParsedPhrase { date: None, time: None, project: None, person: None, verb: None, remainder: words.to_string(), remainder_spans: Vec::new() }        }    };    for (field, piece) in [("date", &parsed.date), ("time", &parsed.time)] {        if piece.as_ref().is_some_and(|piece| piece.candidates.len() > 1) {            return Ok(Answer::refused(line_of("many_readings", &[("field", field)])));        }    }    let reading = Reading { text: words.to_string(), parsed, names };    let mut answer = match at {        At::Board => board(&ctx, &reading),        At::List { table, project, holding } => list(&ctx, &reading, table, project.as_deref(), holding, &mut notes)?,        At::Page { table, id, project } => page(&ctx, &reading, table, id, project.as_deref(), &mut notes)?,        At::Blank { table, preset, project } => match reading.verb().filter(|verb| COMMANDS.contains(verb)) {            Some(verb) => Answer::refused(line_of("not_made_yet", &[("kind", &table.name.to_lowercase()), ("verb", verb)])),            None => create(&ctx, &reading, table, project.as_deref(), preset),        },        At::About { .. } => unreachable!(),    };    // A record made wears its receipt alone: names unread are not said.    let unread = line_of("model.names_unread", &[]);    if !answer.writes.is_empty() {        notes.retain(|note| *note != unread);    }    answer.said.extend(notes);    Ok(answer)}struct Ctx<'a> {    handle: &'a CottonHandle,    zone: &'a str,    now: &'a str,    tables: &'a [TableDefinition],    spoken: bool,    chosen: Option<String>,}fn playing(tables: &[TableDefinition], role: TableRole) -> Option<&TableDefinition> {    tables.iter().find(|table| table.role == Some(role))}fn table_named<'a>(tables: &'a [TableDefinition], id: &str) -> Option<&'a TableDefinition> {    tables.iter().find(|table| table.id == id)}// MARK: The boardfn board(_ctx: &Ctx, reading: &Reading) -> Answer {    // A command needs a record; any other words are kept as a thought.    if let Some(verb) = reading.verb().filter(|verb| COMMANDS.contains(verb)) {        let place = playing(_ctx.tables, TableRole::Todo).map(|todo| todo.plural.clone()).unwrap_or_else(|| line_of("a_list", &[]));        return Answer::refused(line_of("verb_needs_place", &[("verb", verb), ("place", &place)]));    }    keep(&reading.text, None, None)}// MARK: A new recordfn create(ctx: &Ctx, reading: &Reading, definition: &TableDefinition, project: Option<&str>, preset: &Map<String, Value>) -> Answer {    let mut fill = reading.fill(definition, ctx.zone, ctx.now, None, &ALL_PIECES);    for (key, value) in preset {        fill.values.entry(key.clone()).or_insert_with(|| value.clone());    }    if let (Some(key), Some(project)) = (definition.project.as_deref(), project) {        if !fill.values.contains_key(key) && definition.column(key).is_some_and(|column| column.readonly != Some(true)) {            fill.values.insert(key.to_string(), json!(project));        }    }    let adding = reading.verb() == Some("add");    if adding {        fill.used.insert(Piece::Verb);    }    let mut title = reading.words_without(&fill.used);    if adding {        title = without_kind(&title, definition);    }    if title.is_empty() {        title = reading.text.clone();    }    // A title its engine reads for itself is handed the whole sentence.    if definition.column(&definition.title).is_some_and(|column| column.readonly == Some(true)) {        title = reading.text.clone();    }    match (link_column(definition), address(&title)) {        (Some(link), Some(address)) => {            fill.values.insert(link.key.clone(), json!(address));        }        _ => {            fill.values.insert(definition.title.clone(), json!(title));        }    }    Answer::write(json!({"kind": "create", "table": definition.id, "data": fill.values}))}/// The table's one required link column (a saved page's `url`).fn link_column(definition: &TableDefinition) -> Option<&Column> {    definition.columns.iter().find(|column| column.required == Some(true) && (column.column_type == ColumnType::Url || column.key == "url"))}/// The words as one absolute web address: `http(s)://host…`, no spaces.pub fn address(words: &str) -> Option<String> {    let trimmed = words.trim();    if trimmed.chars().any(char::is_whitespace) {        return None;    }    let lowered = trimmed.to_lowercase();    let rest = lowered.strip_prefix("https://").or_else(|| lowered.strip_prefix("http://"))?;    let host = rest.split(['/', '?', '#']).next().unwrap_or_default();    (!host.is_empty()).then(|| trimmed.to_string())}/// "recipe Lemon tart" on the recipes' list is "Lemon tart".pub fn without_kind(words: &str, definition: &TableDefinition) -> String {    let kind = format!("{} ", definition.name.to_lowercase());    if !words.to_lowercase().starts_with(&kind) {        return words.to_string();    }    let rest = words[kind.len()..].trim();    if rest.is_empty() { words.to_string() } else { rest.to_string() }}// MARK: A listfn list(ctx: &Ctx, reading: &Reading, definition: &TableDefinition, project: Option<&str>, holding: &Map<String, Value>, notes: &mut Vec<String>) -> Result<Answer, MethodError> {    let query = match reading.verb() {        Some("done" | "delete") => reading.words_without(&set(&[Piece::Verb])),        Some("move") => {            let mut fill = reading.fill(definition, ctx.zone, ctx.now, None, &[Piece::Date, Piece::Time, Piece::Project]);            fill.used.insert(Piece::Verb);            let mut query = reading.words_without(&fill.used);            // Spoken, "move X to Monday morning": the record is before "to".            let after = reading.words_without(&set(&[Piece::Verb]));            if ctx.spoken {                if let Some(at) = after.to_lowercase().find(" to ") {                    query = after[..at].to_string();                }            }            query        }        Some("rename") => match reading.renaming(false) {            Some((old, _)) => old,            None => return Ok(Answer::refused(line_of("say_new_name", &[]))),        },        _ => {            if !takes_capture(definition) {                return Ok(keep(&reading.text, Some(definition), None));            }            let written = definition                .capture                .as_ref()                .filter(|capture| capture.page_only != Some(true))                .and_then(|capture| table_named(ctx.tables, &capture.table))                .unwrap_or(definition);            return Ok(create(ctx, reading, written, project, holding));        }    };    let record = match pick(ctx, reading, &query, definition, project)? {        Ok(record) => record,        Err(answer) => return Ok(answer),    };    act(ctx, reading, &record, definition, false, notes)}/// Whether typing on the list adds to it: it takes adds and some column of/// it is the person's to write.fn takes_capture(definition: &TableDefinition) -> bool {    definition.add != Some(false) && (definition.capture.is_some() || definition.columns.iter().any(|column| column.readonly != Some(true)))}/// A record found on a list.pub struct Found {    pub id: String,    pub title: String,    pub data: Map<String, Value>,}/// The record the words name on the list, by this order: the person's own/// choice (`record`), the exact title (case aside, the first of several),/// the one title the words begin, the one the search answers; two or more/// with none exact asks which; none says so.fn pick(ctx: &Ctx, reading: &Reading, query: &str, definition: &TableDefinition, project: Option<&str>) -> Result<Result<Found, Answer>, MethodError> {    let plural = definition.plural.to_lowercase();    if let Some(id) = &ctx.chosen {        return Ok(match get(ctx.handle, &definition.id, id)? {            Some(data) => Ok(Found { id: id.clone(), title: said_text(data.get(&definition.title)).unwrap_or_default(), data }),            None => Err(Answer::refused(line_of("gone", &[("name", &definition.name.to_lowercase())]))),        });    }    if query.is_empty() {        return Ok(Err(Answer::refused(line_of("say_which", &[("plural", &plural), ("words", &reading.text)]))));    }    let searched = if ctx.spoken { target(query) } else { query.to_string() };    let mut asked = json!({"table": definition.id, "query": searched, "limit": SEARCHED});    if let (Some(project), Some(key)) = (project, definition.project.as_deref()) {        asked["where"] = json!({key: project});    }    let Ok(listed) = dispatch(ctx.handle, "records.list", asked) else {        return Ok(Err(Answer::refused(line_of("search_failed", &[("plural", &plural)]))));    };    let found: Vec<Found> = listed["records"]        .as_array()        .into_iter()        .flatten()        .filter_map(|row| {            let data = row["data"].as_object()?.clone();            Some(Found { id: row["id"].as_str()?.to_string(), title: said_text(data.get(&definition.title)).unwrap_or_default(), data })        })        .collect();    let candidates = rank(found, query, ctx.spoken);    Ok(match candidates.len() {        0 => Err(Answer::refused(line_of("none_matched", &[("plural", &plural), ("query", query)]))),        1 => Ok(candidates.into_iter().next().unwrap()),        _ => Err(Answer {            asks: vec![json!({                "kind": "which",                "candidates": candidates.iter().map(|found| json!({"table": definition.id, "id": found.id, "title": found.title})).collect::<Vec<_>>(),            })],            said: vec![line_of("which", &[("plural", &plural), ("query", query)])],            ..Default::default()        }),    })}/// The pick's order over what the search found: an exact title (the first/// of several) alone; else the titles the words begin; else every match./// Spoken, only an exact title (less "the"/"my") counts.pub fn rank(found: Vec<Found>, query: &str, spoken: bool) -> Vec<Found> {    let wanted = query.trim().to_lowercase();    let spoken_target = target(query);    if let Some(exact) = found.iter().position(|row| {        let title = row.title.to_lowercase();        title == wanted || (spoken && title == spoken_target)    }) {        return found.into_iter().nth(exact).into_iter().collect();    }    if spoken {        return Vec::new();    }    let prefixed: Vec<usize> = found.iter().enumerate().filter(|(_, row)| row.title.to_lowercase().starts_with(&wanted)).map(|(at, _)| at).collect();    if !prefixed.is_empty() {        return found.into_iter().enumerate().filter(|(at, _)| prefixed.contains(at)).map(|(_, row)| row).collect();    }    found}// MARK: A pagefn page(ctx: &Ctx, reading: &Reading, definition: &TableDefinition, id: &str, project: Option<&str>, notes: &mut Vec<String>) -> Result<Answer, MethodError> {    let name = definition.name.to_lowercase();    let data = match get(ctx.handle, &definition.id, id) {        Ok(Some(data)) => data,        Ok(None) => return Ok(Answer::refused(line_of("gone", &[("name", &name)]))),        Err(_) => return Ok(Answer::refused(line_of("unreadable", &[("name", &name)]))),    };    let record = Found { id: id.to_string(), title: said_text(data.get(&definition.title)).unwrap_or_default(), data };    if reading.verb().is_some_and(|verb| COMMANDS.contains(&verb)) {        return act(ctx, reading, &record, definition, true, notes);    }    match typing(definition, &record.data) {        Typing::Capture => {            let capture = definition.capture.as_ref().unwrap();            let Some(written) = table_named(ctx.tables, &capture.table) else {                return Ok(Answer::refused(line_of("nothing_addable", &[])));            };            let mut preset = Map::new();            preset.insert(capture.link.clone().unwrap_or_default(), json!(record.id));            return Ok(create(ctx, reading, written, project, &preset));        }        Typing::Append => {            let mut data = Map::new();            data.insert(definition.title.clone(), json!(reading.text));            if let Some(day) = definition.date.as_deref().and_then(|day| record.data.get(day).filter(|held| super::is_set(Some(held))).map(|held| (day, held))) {                data.insert(day.0.to_string(), day.1.clone());            }            return Ok(Answer::write(json!({"kind": "create", "table": definition.id, "data": data})));        }        Typing::Ask => return Ok(keep(&reading.text, Some(definition), Some(&record.id))),        Typing::Change => {}    }    let fill = reading.fill(definition, ctx.zone, ctx.now, Some(&record.data), &ALL_PIECES);    if fill.values.is_empty() && !fill.skipped.is_empty() {        return Ok(Answer::refused(fill.skipped.join(" ")));    }    notes.extend(fill.skipped.iter().cloned());    let mut used = fill.used.clone();    if matches!(reading.verb(), Some("add" | "remind")) {        used.insert(Piece::Verb);    }    let rest = reading.words_without(&used);    if !fill.values.is_empty() && word_count(&rest) < ASK_WORDS {        if !rest.is_empty() {            notes.push(line_of("not_used", &[("rest", &rest)]));        }        return Ok(update(definition, &record, Value::Object(fill.values)));    }    // Anything that is not a clear change is a thought on this record.    Ok(keep(&reading.text, Some(definition), Some(&record.id)))}/// What a line typed on a record's page does there.enum Typing {    Change,    Append,    Ask,    Capture,}fn typing(definition: &TableDefinition, data: &Map<String, Value>) -> Typing {    if let Some(capture) = definition.capture.as_ref().filter(|capture| capture.link.is_some()) {        let holds = match &capture.when {            None => true,            Some(when) => match &when.values {                Some(values) => data.get(&when.column).and_then(Value::as_str).is_some_and(|held| values.iter().any(|value| value == held)),                None => super::is_set(data.get(&when.column)),            },        };        return if holds { Typing::Capture } else { Typing::Ask };    }    let types_into = definition.columns.iter().any(|column| column.readonly != Some(true) && column.computed.is_none() && column.column_type != ColumnType::Bool);    if closed(definition, data) || !types_into {        return Typing::Ask;    }    if definition.append == Some(true) { Typing::Append } else { Typing::Change }}// MARK: A spoken line/// A spoken line is a command for the app or a thought, never a record: a/// leading verb whose target this place resolves runs; anything else is/// kept as a thought with where it was said.fn spoken_line(ctx: &Ctx, at: &At, reading: Reading) -> Result<Answer, MethodError> {    let words = reading.text.clone();    let several = |piece: &Option<Understood>| piece.as_ref().is_some_and(|piece| piece.candidates.len() > 1);    let Some(verb) = reading.verb().filter(|verb| COMMANDS.contains(verb) || *verb == "open").map(str::to_string) else {        return Ok(keep_said(at, &words, None));    };    if several(&reading.parsed.date) || several(&reading.parsed.time) {        return Ok(keep_said(at, &words, None));    }    // On a page, done/delete/rename act on THIS record only when the words    // name nothing else.    if let At::Page { table, id, .. } = at {        if verb != "move" && verb != "open" {            let named = if verb == "rename" { reading.renaming(false).map(|(old, _)| target(&old)) } else { Some(target(&reading.words_without(&set(&[Piece::Verb])))) };            let title = get(ctx.handle, &table.id, id).ok().flatten().and_then(|data| said_text(data.get(&table.title))).map(|title| title.to_lowercase());            match named {                Some(named) if named.is_empty() || Some(&named) == title.as_ref() => {}                _ => return Ok(keep_said(at, &words, None)),            }        }    }    let mut notes = Vec::new();    let ran = if verb == "open" {        open(ctx, at, &reading)?    } else {        match at {            At::List { table, project, holding } => Some(list(ctx, &reading, table, project.as_deref(), holding, &mut notes)?),            At::Page { table, id, project } => Some(page(ctx, &reading, table, id, project.as_deref(), &mut notes)?),            _ => None,        }    };    match ran {        Some(mut answer) if answer.asks.is_empty() && (!answer.writes.is_empty() || answer.opens.is_some()) && !is_thought(&answer) => {            let unread = line_of("model.names_unread", &[]);            answer.said.extend(notes.into_iter().filter(|note| *note != unread));            Ok(answer)        }        ran => Ok(keep_said(at, &words, ran.and_then(|ran| ran.refusal))),    }}fn is_thought(answer: &Answer) -> bool {    answer.writes.iter().any(|write| write["kind"] == "thought")}/// "open todos", "go to the Kestrel invoice": a tool by its name or plural,/// else a record of this list's or page's table by its exact title.fn open(ctx: &Ctx, at: &At, reading: &Reading) -> Result<Option<Answer>, MethodError> {    let wanted = target(&reading.words_without(&set(&[Piece::Verb])));    if wanted.is_empty() {        return Ok(None);    }    if let Some(tool) = tool_named(ctx.tables, &wanted) {        return Ok(Some(Answer { opens: Some(json!({"table": tool.id})), ..Default::default() }));    }    let shown = match at {        At::List { table, .. } | At::Page { table, .. } => table,        _ => return Ok(None),    };    let Ok(listed) = dispatch(ctx.handle, "records.list", json!({"table": shown.id, "query": wanted, "limit": SEARCHED})) else { return Ok(None) };    let found = listed["records"].as_array().into_iter().flatten().find(|row| said_text(row["data"].get(&shown.title)).map(|title| title.to_lowercase()) == Some(wanted.clone()));    Ok(found.and_then(|row| row["id"].as_str()).map(|id| Answer { opens: Some(json!({"table": shown.id, "id": id})), ..Default::default() }))}/// The tool a name or plural calls.pub fn tool_named<'a>(tables: &'a [TableDefinition], words: &str) -> Option<&'a TableDefinition> {    let wanted = target(words);    if wanted.is_empty() {        return None;    }    tables.iter().find(|table| table.name.to_lowercase() == wanted || table.plural.to_lowercase() == wanted)}/// What a spoken name names: lowercased, without "the"/"my" before it or/// punctuation around it.pub fn target(words: &str) -> String {    let mut wanted = words.trim_matches(|c: char| c.is_whitespace() || c.is_ascii_punctuation()).to_lowercase();    for article in ["the ", "my "] {        if let Some(rest) = wanted.strip_prefix(article) {            wanted = rest.trim().to_string();        }    }    wanted}/// A spoken line kept as a thought with the place it was said on.fn keep_said(at: &At, words: &str, because: Option<String>) -> Answer {    let mut answer = match at {        At::List { table, .. } | At::Blank { table, .. } => keep(words, Some(table), None),        At::Page { table, id, .. } | At::About { table, id } => keep(words, Some(table), Some(id)),        At::Board => keep(words, None, None),    };    if let Some(because) = because {        answer.said.push(because);    }    answer}// MARK: A thoughtfn keep(words: &str, definition: Option<&TableDefinition>, record: Option<&str>) -> Answer {    let mut write = json!({"kind": "thought", "words": words});    if let Some(definition) = definition {        write["table"] = json!(definition.id);        if let Some(record) = record {            write["record"] = json!(record);        }    }    let said = match (definition, record) {        (Some(definition), Some(_)) => line_of("kept.on", &[("kind", &definition.name.to_lowercase())]),        (Some(definition), None) => line_of("kept.among", &[("plural", &definition.plural)]),        (None, _) => line_of("kept.saved", &[]),    };    write["said"] = json!(said);    Answer::write(write)}// MARK: The verbs on one record/// Done, delete, move or rename on one record, list or page alike. On a/// page "rename oat milk" needs no "to" and a move's every word must be used.fn act(ctx: &Ctx, reading: &Reading, record: &Found, definition: &TableDefinition, on_page: bool, notes: &mut Vec<String>) -> Result<Answer, MethodError> {    let title = if record.title.is_empty() { definition.name.to_lowercase() } else { record.title.clone() };    let picked = json!({"table": definition.id, "id": record.id, "title": title});    let mut answer = act_on(ctx, reading, record, definition, on_page, &title, notes);    if !on_page {        answer.picked = Some(picked);    }    Ok(answer)}fn act_on(ctx: &Ctx, reading: &Reading, record: &Found, definition: &TableDefinition, on_page: bool, title: &str, notes: &mut Vec<String>) -> Answer {    if closed(definition, &record.data) {        return Answer::refused(line_of("kept_elsewhere", &[("title", title)]));    }    match reading.verb() {        Some("done") => {            let column = definition.slip.toggle.as_deref().and_then(|key| definition.column(key)).filter(|column| column.readonly != Some(true));            let Some((column, on)) = column.and_then(|column| done_value(column, definition).map(|on| (column, on))) else {                return Answer::refused(line_of("nothing_to_mark", &[("plural", &definition.plural)]));            };            if record.data.get(&column.key) == Some(&on) {                return Answer::refused(line_of("already_done", &[("title", title)]));            }            update(definition, record, json!({column.key.clone(): on}))        }        Some("delete") => {            if !card_actions::deletes(definition, &record.data) {                let deleted = line_of("deleted_word", &[]);                return Answer::refused(line_of("cannot_delete", &[("title", title), ("deleted", &deleted)]));            }            if repeats(&record.data) {                return Answer::refused(line_of("delete_repeats", &[("title", title)]));            }            Answer::write(json!({"kind": "delete", "table": definition.id, "id": record.id}))        }        Some("rename") => {            let new = reading.renaming(on_page).map(|(_, new)| new).unwrap_or_default();            if new.is_empty() {                return Answer::refused(line_of("say_new_name", &[]));            }            if definition.column(&definition.title).is_some_and(|column| column.readonly == Some(true)) {                return Answer::refused(line_of("name_fixed", &[("kind", &definition.name.to_lowercase())]));            }            update(definition, record, json!({definition.title.clone(): new}))        }        _ => {            let fill = reading.fill(definition, ctx.zone, ctx.now, Some(&record.data), &[Piece::Date, Piece::Time, Piece::Project]);            notes.extend(fill.skipped.iter().cloned());            if fill.values.is_empty() {                return Answer::refused(line_of("say_where", &[("title", title)]));            }            let mut used = fill.used.clone();            used.insert(Piece::Verb);            let unused = reading.words_without(&used);            if on_page && !unused.is_empty() {                return Answer::refused(line_of("not_moved", &[("unused", &unused)]));            }            update(definition, record, Value::Object(fill.values))        }    }}/// One update. A repeating record asks how far a change reaches: its page asks.fn update(definition: &TableDefinition, record: &Found, patch: Value) -> Answer {    if repeats(&record.data) {        if let Some(key) = patch.as_object().and_then(|patch| patch.keys().find(|key| definition.date.as_deref() == Some(key.as_str()) || key.as_str() == definition.title)) {            let label = definition.column(key).map(|column| column.name.clone().unwrap_or_else(|| column.key.clone())).unwrap_or_else(|| key.clone());            return Answer::refused(line_of("change_repeats", &[("label", &label)]));        }    }    Answer::write(json!({"kind": "update", "table": definition.id, "id": record.id, "patch": patch}))}/// Whether a record is one occurrence of a series.fn repeats(data: &Map<String, Value>) -> bool {    super::is_set(data.get("recurrence_id")) || super::is_set(data.get("rrule")) || super::is_set(data.get("series_id"))}/// What "done" writes to a toggle column: yes for a yes-no; for a choice/// the slip's first `toggle_on`, else its second choice.pub fn done_value(column: &Column, definition: &TableDefinition) -> Option<Value> {    match column.column_type {        ColumnType::Bool => Some(json!(true)),        ColumnType::Choice => {            let choices = column.choices.as_ref().filter(|choices| choices.len() >= 2)?;            Some(json!(definition.slip.toggle_on.as_ref().and_then(|on| on.first()).unwrap_or(&choices[1])))        }        _ => None,    }}// MARK: Readingconst ALL_PIECES: [Piece; 4] = [Piece::Date, Piece::Time, Piece::Project, Piece::Person];fn set(pieces: &[Piece]) -> BTreeSet<Piece> {    pieces.iter().copied().collect()}pub fn word_count(words: &str) -> usize {    words.split_whitespace().count()}/// The column values the pieces give a table, which pieces they used, and a/// line for each left out because its column may not be written.#[derive(Default)]pub struct Fill {    pub values: Map<String, Value>,    pub used: BTreeSet<Piece>,    pub skipped: Vec<String>,}impl Reading {    pub fn verb(&self) -> Option<&str> {        self.parsed.verb.as_ref().and_then(|verb| verb.candidates.first()).map(String::as_str)    }    fn understood(&self, piece: Piece) -> Option<&Understood> {        match piece {            Piece::Date => self.parsed.date.as_ref(),            Piece::Time => self.parsed.time.as_ref(),            Piece::Project => self.parsed.project.as_ref(),            Piece::Person => self.parsed.person.as_ref(),            Piece::Verb => self.parsed.verb.as_ref(),        }    }    /// The text without the pieces given, each untouched segment trimmed and    /// joined by one space, the joining word right before a taken piece    /// taken with it; the whole text when none was understood.    pub fn words_without(&self, pieces: &BTreeSet<Piece>) -> String {        let mut spans: Vec<(usize, usize)> = pieces.iter().filter_map(|piece| self.understood(*piece)).map(|piece| (piece.span.start, piece.span.end)).collect();        if spans.is_empty() {            return self.text.clone();        }        spans.sort();        let bytes = self.text.as_bytes();        let mut segments: Vec<String> = Vec::new();        let mut end = 0;        for (start, stop) in spans {            let start = start.max(end).min(bytes.len());            if end < start {                let mut words: Vec<&str> = std::str::from_utf8(&bytes[end..start]).unwrap_or_default().split_whitespace().collect();                if words.last().is_some_and(|last| JOINERS.contains(&last.to_lowercase().as_str())) {                    words.pop();                }                segments.push(words.join(" "));            }            end = stop.max(end).min(bytes.len());        }        if end < bytes.len() {            segments.push(std::str::from_utf8(&bytes[end..]).unwrap_or_default().to_string());        }        segments.iter().map(|segment| segment.trim()).filter(|segment| !segment.is_empty()).collect::<Vec<_>>().join(" ")    }    /// The old name and the new. On a list "rename X to Y", split at the    /// first " to "; none without one. On a page all after the verb is the    /// new name, less a leading "to".    pub fn renaming(&self, on_page: bool) -> Option<(String, String)> {        let verb = self.parsed.verb.as_ref()?;        let after = self.text.get(verb.span.end.min(self.text.len())..).unwrap_or_default().trim();        let lowered = after.to_lowercase();        if lowered.starts_with("to ") {            return Some((String::new(), after[3..].trim().to_string()));        }        if on_page {            return Some((String::new(), after.to_string()));        }        let at = lowered.find(" to ")?;        Some((after[..at].trim().to_string(), after[at + 4..].trim().to_string()))    }    /// The day goes to the date column; a time to the first writable time    /// column, else onto the date as an instant (the day said, else the day    /// held, else today); a day said alone on a timed date keeps its time.    /// The project and a person go to the project column and the first link    /// to the people's table. A piece with no writable column stays in the    /// words.    pub fn fill(&self, definition: &TableDefinition, zone: &str, now: &str, existing: Option<&Map<String, Value>>, pieces: &[Piece]) -> Fill {        let mut fill = Fill::default();        let is_closed = existing.is_some_and(|data| closed(definition, data));        let writable = |column: Option<&Column>, piece: Piece, fill: &mut Fill| -> Option<Column> {            let column = column?;            let open = column.readonly != Some(true) && column.computed.is_none() && !is_closed;            if !open && self.understood(piece).is_some() {                fill.skipped.push(line_of("column_fixed", &[("column", column.name.as_deref().unwrap_or(&column.key))]));            }            open.then(|| column.clone())        };        let day = pieces.contains(&Piece::Date).then(|| self.parsed.date.as_ref().and_then(|date| date.candidates.first().cloned())).flatten();        let clock = pieces.contains(&Piece::Time).then(|| self.parsed.time.as_ref().and_then(|time| time.candidates.first().cloned())).flatten();        let time_column = definition.columns.iter().find(|column| column.column_type == ColumnType::Time && column.readonly != Some(true));        let date_column = definition.date.as_deref().and_then(|key| definition.column(key)).filter(|column| column.column_type == ColumnType::Date);        if let Some(clock) = &clock {            if let Some(column) = writable(time_column, Piece::Time, &mut fill) {                fill.values.insert(column.key, json!(clock));                fill.used.insert(Piece::Time);            }        }        if day.is_some() || (clock.is_some() && time_column.is_none()) {            if let Some(column) = writable(date_column, Piece::Date, &mut fill) {                let held = existing.and_then(|data| card_when::held(data.get(&column.key), zone).ok().flatten());                let loose = if time_column.is_none() { clock.clone() } else { None };                let on = day.clone().or_else(|| held.as_ref().map(|held| held.date.clone())).unwrap_or_else(|| today_in(now, zone));                let at = loose.clone().or_else(|| if day.is_some() && time_column.is_none() { held.and_then(|held| held.time) } else { None });                let value = match at {                    Some(time) => moment_split::join_moment(&MomentSplit { date: on.clone(), time: Some(time) }, zone).map(Value::from).unwrap_or_else(|_| json!(on)),                    None => json!(on),                };                fill.values.insert(column.key, value);                if day.is_some() {                    fill.used.insert(Piece::Date);                }                if loose.is_some() {                    fill.used.insert(Piece::Time);                }            }        }        if pieces.contains(&Piece::Project) {            if let Some(id) = self.parsed.project.as_ref().and_then(|project| project.candidates.first()).and_then(|name| Names::id(&self.names.projects, name)) {                if let Some(column) = writable(definition.project.as_deref().and_then(|key| definition.column(key)), Piece::Project, &mut fill) {                    fill.values.insert(column.key, json!(id));                    fill.used.insert(Piece::Project);                }            }        }        if pieces.contains(&Piece::Person) {            if let Some(id) = self.parsed.person.as_ref().and_then(|person| person.candidates.first()).and_then(|name| Names::id(&self.names.people, name)) {                let link = definition.columns.iter().find(|column| {                    column.column_type == ColumnType::Link && column.link_to.is_some() && column.link_to == self.names.people_table && Some(column.key.as_str()) != definition.project.as_deref()                });                if let Some(column) = writable(link, Piece::Person, &mut fill) {                    fill.values.insert(column.key, json!(id));                    fill.used.insert(Piece::Person);                }            }        }        fill    }}/// Today in the zone, from the RFC 3339 clock.fn today_in(now: &str, zone: &str) -> String {    chrono::DateTime::parse_from_rfc3339(now)        .ok()        .and_then(|now| cotton_core::transforms::zoned_clock::local_day(now.timestamp_millis(), zone).ok())        .map(cotton_core::transforms::zoned_clock::day_key)        .unwrap_or_else(|| now.chars().take(10).collect())}/// Whether a table the words may be written to has a writable project/// column or a writable link to the people: only then are names read.fn needs_names(at: &At, tables: &[TableDefinition]) -> bool {    let people = playing(tables, TableRole::Person).map(|people| people.id.clone());    let captured = |table: &TableDefinition| table.capture.as_ref().and_then(|capture| table_named(tables, &capture.table)).cloned();    let candidates: Vec<TableDefinition> = match at {        At::Board | At::About { .. } => Vec::new(),        At::List { table, .. } | At::Page { table, .. } => std::iter::once(table.clone()).chain(captured(table)).collect(),        At::Blank { table, .. } => vec![table.clone()],    };    candidates.iter().any(|table| {        table.project.as_deref().and_then(|key| table.column(key)).is_some_and(|column| column.readonly != Some(true))            || table.columns.iter().any(|column| column.column_type == ColumnType::Link && column.link_to.is_some() && column.link_to == people && Some(column.key.as_str()) != table.project.as_deref() && column.readonly != Some(true))    })}/// The projects' and people's names, the first of a name winning; a read/// that fails is said and matches none.fn read_names(handle: &CottonHandle, tables: &[TableDefinition], notes: &mut Vec<String>) -> Names {    let people = playing(tables, TableRole::Person);    let read = || -> Result<Names, MethodError> {        Ok(Names {            projects: titles(handle, playing(tables, TableRole::Project))?,            people: titles(handle, people)?,            people_table: people.map(|people| people.id.clone()),        })    };    read().unwrap_or_else(|_| {        notes.push(line_of("model.names_unread", &[]));        Names::default()    })}fn titles(handle: &CottonHandle, definition: Option<&TableDefinition>) -> Result<Vec<(String, String)>, MethodError> {    let Some(definition) = definition else { return Ok(Vec::new()) };    let mut names: Vec<(String, String)> = Vec::new();    let mut page = 0u64;    loop {        let listed = dispatch(handle, "records.list", json!({"table": definition.id, "page": page, "limit": NAMES_PAGE}))?;        for row in listed["records"].as_array().into_iter().flatten() {            let (Some(id), Some(name)) = (row["id"].as_str(), said_text(row["data"].get(&definition.title))) else { continue };            if !name.trim().is_empty() && !names.iter().any(|(held, _)| *held == name) {                names.push((name, id.to_string()));            }        }        match listed["next"].as_u64() {            Some(next) if next != page => page = next,            _ => return Ok(names),        }    }}fn get(handle: &CottonHandle, table: &str, id: &str) -> Result<Option<Map<String, Value>>, MethodError> {    match dispatch(handle, "records.get", json!({"table": table, "id": id})) {        Ok(got) => Ok(got.get("data").and_then(Value::as_object).cloned().or_else(|| got["record"]["data"].as_object().cloned())),        Err(error) if error.code == "not_found" => Ok(None),        Err(error) => Err(error),    }}