Cotton code
1840 lines · 88.5 KB · RustRaw
//! Cotton Days on the phone: every `days.*` method `assets/design/days///! CONTRACT.md` names, over this device's own copy (signed out too; a write//! queues for the object like any other). What a day is, is decided in//! `cotton_rules::days`; this module reads the rows, hands them over, and//! carries out the acts. The phone draws what these answer.//!//! Sources: events (the person's own and Google's), to-dos, and birthdays//! from People. Nothing else in this version.use std::collections::{HashMap, HashSet};use cotton_core::cotton_rules::days::{    day_of_key,    layout::{self, Item, Kind, Place, Whose},    marks, when,    words::{self, fill, Words},};use cotton_core::cotton_rules::js::parse_date_ms;use cotton_core::rules::reminders::{event_lead, NO_ALERT};use cotton_core::cotton_rules::moment_split::{join_moment, split_moment, MomentSplit};use cotton_core::cotton_rules::zoned_clock::{    civil_from_days, day_key, day_number, days_in_month, instant_from_zoned, local_day, yearly_in_year, zoned_parts, ZonedParts,};use cotton_store::driver::Row;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::update_row;use cotton_tools::mcp::handlers::records_1::engine_shim::{materialize_template, RecurrenceTemplate, RECURRENCE_TEMPLATE_COLUMNS};use cotton_tools::mcp::handlers::records_1::{events, todos};use crate::handle::CottonHandle;use crate::methods::MethodError;use super::days_people::Heard;pub const METHODS: [&str; 28] = [    "days.export",    "days.google",    "days.google_keep",    "days.send_to_google",    "days.invitations",    "days.answer",    "days.people_find",    "days.tell",    "days.google_disconnect",    "days.span",    "days.groups",    "days.month",    "days.sometime",    "days.item",    "days.change",    "days.done",    "days.undone",    "days.skip",    "days.move",    "days.read_line",    "days.add",    "days.marks",    "days.marks.find",    "days.drop",    "days.bring_back",    "days.delete",    "days.show",    "days.find",];/// The most days one `days.span` answers.const MOST_DAYS: i64 = 370;/// How many marks a typed line is offered.const MARKS_OFFERED: usize = 4;pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "days.export" => {            let dir = handle.client().layout().exports_dir().join("days");            with_read(handle, method, |ctx| export::export(ctx, &dir, request))        }        "days.span" => with_read(handle, method, |ctx| span(ctx, request)),        "days.month" => with_read(handle, method, |ctx| month(ctx, request)),        "days.sometime" => with_read(handle, method, |ctx| sometime(ctx, request)),        "days.groups" => with_read(handle, method, |ctx| groups(ctx, request)),        "days.item" => {            let heard = heard_here(handle);            with_read(handle, method, |ctx| item(ctx, request, &heard))        }        "days.people_find" => super::days_people::find(&handle.client(), request),        "days.tell" => {            let heard = heard_here(handle);            with_read(handle, method, |ctx| tell(ctx, request, &heard))        }        "days.read_line" => read_line(request),        "days.marks" => Ok(json!({ "marks": marks::offered(text(request, "words").unwrap_or_default(), language(request)) })),        "days.marks.find" => {            let typed = text(request, "words").unwrap_or_default();            Ok(json!({ "marks": marks::find(typed, language(request), MARKS_OFFERED) }))        }        "days.change" => {            let heard = google_heard(handle, request)?;            with_write(handle, method, |ctx| change(ctx, request, &heard)).and_then(|answer| asking_leave(handle, answer, text(request, "id"), request))        }        "days.done" => with_write(handle, method, |ctx| done(ctx, request)),        "days.undone" => with_write(handle, method, |ctx| undone(ctx, request)),        "days.skip" => with_write(handle, method, |ctx| skip(ctx, request)),        "days.move" => {            let heard = google_heard(handle, request)?;            with_write(handle, method, |ctx| move_to(ctx, request, &heard)).and_then(|answer| asking_leave(handle, answer, text(request, "id"), request))        }        "days.add" => with_write(handle, method, |ctx| add(ctx, request)).and_then(|answer| {            let id = answer["id"].as_str().map(str::to_string);            asking_leave(handle, answer, id.as_deref(), request)        }),        "days.drop" => with_write(handle, method, |ctx| drop_todo(ctx, request)),        "days.bring_back" => with_write(handle, method, |ctx| bring_back(ctx, request)),        "days.delete" => {            let heard = google_heard(handle, request)?;            with_write(handle, method, |ctx| delete(ctx, request, &heard))        }        "days.show" => with_read(handle, method, |ctx| views::show(ctx, request)),        "days.find" => with_read(handle, method, |ctx| views::find(ctx, request)),        "days.google" => super::days_google::settings(handle, request),        "days.google_disconnect" => super::days_google::disconnect(handle, request),        "days.google_keep" => super::days_google::keep(handle, request),        "days.send_to_google" => super::days_push::send(handle, request),        "days.invitations" => super::days_invite::pass(handle, request),        "days.answer" => super::days_invite::answer(handle, request),        other => Err(MethodError::new("unknown_method", format!("this core does not answer `{other}`"))),    }}// ── plumbing ────────────────────────────────────────────────────────────────/// What Days has heard of Google, freshened from the object when the event a/// change names is on Google (or to go there) and the object can be reached:/// a change Google must hear is refused before anything is saved when the only/// grant cannot write (CONTRACT.md section 16). Offline, what was last heard/// stands, and the change waits to be sent./// What was last heard of Google and of the person's connected people, without asking; a phone with no server copy/// (signed out) has nothing connected and can connect nothing.fn heard_here(handle: &CottonHandle) -> Heard {    let client = handle.client();    if client.object_door().is_none() {        Heard::not_connected(&client);    }    Heard::of(&client)}fn google_heard(handle: &CottonHandle, request: &Value) -> Result<Heard, MethodError> {    let client = handle.client();    let bound = text(request, "table") == Some("event")        && text(request, "id").is_some_and(|id| {            let id = id.to_string();            with_read(handle, "days.google_bound", |ctx| {                let row = event_row(ctx, &id)?;                let master = row.as_ref().and_then(|r| r.text("series_id")).map(|s| event_row(ctx, s)).transpose()?.flatten();                let on = |r: &Row| r.text("gcal_id").is_some() || r.int("on_google").unwrap_or(0) != 0;                Ok(Value::Bool(row.as_ref().is_some_and(on) || master.as_ref().is_some_and(on) || request.get("people").is_some()))            })            .map(|v| v == Value::Bool(true))            .unwrap_or(false)        });    if bound {        match super::google::call(handle, "google.status", &json!({})) {            Ok(status) => Heard::google(&client, &status),            // No server copy (signed out): no Google can be connected, so nobody is promised Google's email (the            // emulator walk, 22 Nov 2026: signed out, the sheet said Google would invite the person).            Err(refused) if refused.code == "not_connected" => Heard::not_connected(&client),            Err(_) => {}        }    }    Ok(Heard::of(&client))}/// Whether a change Google must hear may be saved: refused with Connect when every connected grant is read-only.fn google_may_change(heard: &Heard) -> Result<(), MethodError> {    match heard.writable() {        Some(None) if heard.connected_google() => {            let mut refused = MethodError::new("google_needs_write", super::days_people::line("google.needs_write")?);            refused.details = json!({ "connect": super::days_people::connect_act(heard)? });            Err(refused)        }        Some(None) => Err(MethodError::new("google_read_only", events::GOOGLE_READ_ONLY)),        _ => Ok(()),    }}pub(super) fn with_read(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result<Value, MethodError>) -> Result<Value, MethodError> {    let mut refusal: Option<MethodError> = None;    let answer = handle.client().read_rows(label, &mut |ctx| {        body(ctx).map_err(|refused| {            let said = refused.message.clone();            refusal = Some(refused);            said        })    });    match (answer, refusal) {        (Ok(answer), _) => Ok(answer),        (Err(_), Some(refused)) => Err(refused),        (Err(why), None) => Err(MethodError::new("unreadable", why)),    }}pub(super) fn with_write(handle: &CottonHandle, label: &str, mut body: impl FnMut(&mut Ctx<'_>) -> Result<Value, MethodError>) -> Result<Value, MethodError> {    let mut refusal: Option<MethodError> = None;    let answer = handle.client().write_rows(label, &mut |ctx| {        body(ctx).map_err(|refused| {            let said = refused.message.clone();            refusal = Some(refused);            said        })    });    match (answer, refusal) {        (Ok(answer), _) => Ok(crate::authoring::own_answer(answer)),        (Err(_), Some(refused)) => Err(refused),        (Err(why), None) => Err(MethodError::new("write_refused", why)),    }}fn text<'a>(request: &'a Value, key: &str) -> Option<&'a str> {    request.get(key).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty())}fn language(request: &Value) -> &str {    text(request, "language").unwrap_or("en")}fn said(request: &Value) -> &'static Words {    words::words(language(request))}fn bad(message: impl Into<String>) -> MethodError {    MethodError::new("bad_request", message.into())}fn sql(error: impl std::fmt::Display) -> MethodError {    MethodError::new("unreadable", error.to_string())}fn tool(failure: cotton_tools::mcp::protocol::ToolFailure) -> MethodError {    let message = failure.to_string();    if message == events::GOOGLE_READ_ONLY {        return MethodError::new("google_read_only", message);    }    MethodError::new("write_refused", message)}/// Leave to notify, asked at the moment it is needed (LAUNCH.md, 22 Nov 2026): on a phone that has never asked, an/// add, change or move that gives the item a reminder (a timed event; a to-do with a time) answers/// `platform_action: request_notifications`, and Days asks the OS then. The platform says it asked/// (`device.notifications.asked`), so the one inline ask is spent once, never at a launch and never for an item that/// will not alert.fn asking_leave(handle: &CottonHandle, mut answer: Value, id: Option<&str>, request: &Value) -> Result<Value, MethodError> {    let Some(id) = id.filter(|id| !id.is_empty()) else { return Ok(answer) };    if crate::phone::device_preferences::prefs(&handle.client())?.asked_at.is_some() {        return Ok(answer);    }    let due = crate::phone::reminders::call(handle, &json!({ "args": { "timeZone": zone_arg(request)? } }))?;    if due["reminders"].as_array().into_iter().flatten().any(|reminder| reminder["recordId"] == id) {        answer["platform_action"] = Value::from("request_notifications");        // Why, before the OS asks (LAUNCH.md section 4): the phone shows this first, then the OS's own ask.        let say = |name: &str| {            cotton_core::rules::shell_lines::LineSet::shipped("days")                .and_then(|lines| lines.say(name, &[]))                .ok_or_else(|| MethodError::new("unreadable", format!("the days set says no line {name}")))        };        answer["leave"] = json!({ "title": say("leave.title")?, "body": say("leave.body")?, "go": say("leave.go")?, "notNow": say("leave.not_now")? });    }    Ok(answer)}fn zone_arg(request: &Value) -> Result<String, MethodError> {    let zone = text(request, "timezone").ok_or_else(|| bad("`timezone` is the zone the phone stands in"))?;    zoned_parts(0, zone).map_err(|error| bad(error.to_string()))?;    Ok(zone.to_string())}fn day_arg(request: &Value, name: &str) -> Result<i64, MethodError> {    let raw = text(request, name).ok_or_else(|| bad(format!("`{name}` is a day, YYYY-MM-DD")))?;    day_of_key(raw).ok_or_else(|| bad(format!("`{name}` is not a day: {raw}")))}fn rows(ctx: &Ctx<'_>, statement: &str, params: &[SqlValue]) -> Result<Vec<Row>, MethodError> {    ctx.read.driver().all(statement, params).map_err(sql)}fn ws(ctx: &Ctx<'_>) -> SqlValue {    SqlValue::Text(ctx.workspace_id.to_string())}/// Whether this copy keeps `column` on `table` (a kit column the copy adds).fn holds(ctx: &Ctx<'_>, table: &str, column: &str) -> Result<bool, MethodError> {    Ok(rows(ctx, &format!("SELECT name FROM pragma_table_info('{table}')"), &[])?        .iter()        .any(|row| row.text("name") == Some(column)))}/// `column` as a select item, or NULL under its name where this copy keeps/// no such column.fn optional(ctx: &Ctx<'_>, table: &str, column: &str) -> Result<String, MethodError> {    Ok(if holds(ctx, table, column)? { column.to_string() } else { format!("NULL AS {column}") })}/// The database's own zone, where repeats and date-only to-dos are read; the/// phone's where it has recorded none.fn database_zone(ctx: &Ctx<'_>, fallback: &str) -> Result<String, MethodError> {    let recorded = ctx        .read        .driver()        .get("SELECT timezone FROM cotton_news_settings WHERE workspace_id = ?", &[ws(ctx)])        .map_err(sql)?        .and_then(|row| row.text("timezone").map(str::to_string))        .filter(|zone| !zone.trim().is_empty() && zoned_parts(0, zone).is_ok());    Ok(recorded.unwrap_or_else(|| fallback.to_string()))}/// The instant a day starts in `zone`.fn day_start(day: i64, zone: &str) -> Result<i64, MethodError> {    let (year, month, date) = civil_from_days(day);    instant_from_zoned(ZonedParts { year, month, day: date, hour: 0, minute: 0, second: 0 }, 0, zone).map_err(|error| bad(error.to_string()))}fn iso(ms: i64) -> String {    cotton_core::cotton_rules::js::to_iso_string(ms).unwrap_or_default()}fn ms_of(raw: Option<&str>) -> Option<i64> {    raw.and_then(parse_date_ms)}// ── reading the items ───────────────────────────────────────────────────────/// What the reads share: the phone's zone, the database's, and today.struct Reading {    zone: String,    db_zone: String,    today: i64,    /// The to-dos the person ticked or unticked since the list was opened,    /// each with the day its row stood on (`None`: Sometime). Each stays    /// where it stood until the phone lets go (CONTRACT.md section 2, Keep).    keep: HashMap<String, Option<i64>>,}fn reading(ctx: &Ctx<'_>, request: &Value) -> Result<Reading, MethodError> {    let zone = zone_arg(request)?;    let db_zone = database_zone(ctx, &zone)?;    Ok(Reading { today: day_arg(request, "today")?, zone, db_zone, keep: keep_arg(request)? })}/// `keep: [ { id, day } ]`, the rows held where they stood.fn keep_arg(request: &Value) -> Result<HashMap<String, Option<i64>>, MethodError> {    let mut out = HashMap::new();    let Some(kept) = request.get("keep") else { return Ok(out) };    let kept = kept.as_array().ok_or_else(|| bad("`keep` is a list of { id, day }"))?;    for one in kept {        let id = one.get("id").and_then(Value::as_str).ok_or_else(|| bad("each of `keep` names its to-do's `id`"))?;        let day = match one.get("day") {            None | Some(Value::Null) => None,            Some(_) => Some(day_arg(one, "day")?),        };        out.insert(id.to_string(), day);    }    Ok(out)}/// Every event occurrence in the days `from..=to`, as items.fn event_items(ctx: &Ctx<'_>, at: &Reading, from: i64, to: i64) -> Result<Vec<Item>, MethodError> {    let window_from = day_start(from, &at.zone)?;    let window_to = day_start(to + 1, &at.zone)? - 1;    let to_iso = iso(window_to);    let extra = ["mark", "your_note", "alert"].iter().map(|column| optional(ctx, "cotton_events", column)).collect::<Result<Vec<_>, _>>()?.join(", ");    let found = rows(        ctx,        &format!(            "SELECT id, title, starts_at, ends_at, all_day, rrule, exdates, series_id, original_starts_at, trashed_at, gcal_id, my_response, {extra}               FROM cotton_events WHERE (starts_at <= ?1 OR original_starts_at <= ?1) ORDER BY starts_at ASC, id ASC"        ),        &[SqlValue::Text(to_iso)],    )?;    let series: Vec<cotton_core::rules::series::SeriesRow> = found        .iter()        .map(|row| cotton_core::rules::series::SeriesRow {            id: row.text("id").unwrap_or_default().to_string(),            starts_at: row.text("starts_at").unwrap_or_default().to_string(),            ends_at: row.text("ends_at").map(str::to_string),            rrule: row.text("rrule").map(str::to_string),            exdates: row.text("exdates").and_then(|raw| serde_json::from_str::<Vec<String>>(raw).ok()),            series_id: row.text("series_id").map(str::to_string),            original_starts_at: row.text("original_starts_at").map(str::to_string),            trashed_at: row.text("trashed_at").map(str::to_string),        })        .collect();    let range = cotton_core::transforms::rrule::DateRange { from: window_from, to: window_to };    let drawn = cotton_core::rules::series::expand_calendar(&series, range, &at.db_zone).map_err(sql)?;    let by_id: HashMap<&str, &Row> = found.iter().filter_map(|row| Some((row.text("id")?, row))).collect();    let mut out = Vec::new();    for (order, slot) in drawn.iter().enumerate() {        let Some(row) = by_id.get(slot.event_id.as_str()) else { continue };        if row.text("my_response") == Some("declined") {            continue;        }        let master = slot.series_id.as_deref().and_then(|id| by_id.get(id));        let mark = row.text("mark").or_else(|| master.and_then(|m| m.text("mark"))).map(str::to_string);        let Some(starts) = parse_date_ms(&slot.starts_at) else { continue };        let google = row.text("gcal_id").is_some() || master.is_some_and(|m| m.text("gcal_id").is_some());        out.push(Item {            key: format!("event:{}@{}", slot.event_id, slot.occurrence_at),            kind: Kind::Event,            whose: if google { Whose::Google } else { Whose::Yours },            words: row.text("title").unwrap_or_default().to_string(),            mark: mark.filter(|id| marks::known(id)),            done: false,            place: Place::Event { starts, ends: ms_of(slot.ends_at.as_deref()), all_day: row.int("all_day").unwrap_or(0) != 0 },            opens: json!({ "sheet": "event", "id": slot.event_id, "occurrenceAt": slot.occurrence_at }),            order: order as i64,        });    }    Ok(out)}/// One to-do as a row source: its day and minute, read in the right zone.pub(super) struct Todo {    id: String,    title: String,    status: String,    /// When it is next due: its snooze where that is ahead, else its due.    at: Option<String>,    completed_at: Option<String>,    series: Option<String>,    occurrence_at: Option<String>,    mark: Option<String>,    created_at: String,}fn todos_of(ctx: &Ctx<'_>, where_clause: &str, params: &[SqlValue]) -> Result<Vec<Todo>, MethodError> {    let mark = optional(ctx, "cotton_todos", "mark")?;    let now = iso(ctx.now.timestamp_millis());    let mut all = vec![ws(ctx), SqlValue::Text(now)];    all.extend_from_slice(params);    Ok(rows(        ctx,        &format!(            "SELECT id, title, status, completed_at, recurrence_id, occurrence_at, created_at, {mark},                    CASE WHEN snoozed_until IS NOT NULL AND snoozed_until > ?2 THEN snoozed_until ELSE due_at END AS at               FROM cotton_todos              WHERE workspace_id = ?1 AND trashed_at IS NULL {where_clause}              ORDER BY created_at ASC, id ASC"        ),        &all,    )?    .iter()    .map(|row| Todo {        id: row.text("id").unwrap_or_default().to_string(),        title: row.text("title").unwrap_or_default().to_string(),        status: row.text("status").unwrap_or("open").to_string(),        at: row.text("at").map(str::to_string),        completed_at: row.text("completed_at").map(str::to_string),        series: row.text("recurrence_id").map(str::to_string),        occurrence_at: row.text("occurrence_at").map(str::to_string),        mark: row.text("mark").map(str::to_string).filter(|id| marks::known(id)),        created_at: row.text("created_at").unwrap_or_default().to_string(),    })    .collect())}/// A due instant as a day and a minute: midnight in the database's zone is a/// day with no time (the store's contract), read as that calendar day; any/// other instant is at its clock in the phone's zone.fn due_place(at: &str, reading: &Reading) -> Result<Option<(i64, Option<i64>)>, MethodError> {    let Some(ms) = parse_date_ms(at) else { return Ok(None) };    let split = split_moment(at, &reading.db_zone).map_err(sql)?;    if split.time.is_none() {        return Ok(day_of_key(&format!("{:0>10}", split.date)).or_else(|| local_day(ms, &reading.db_zone).ok()).map(|day| (day, None)));    }    let parts = zoned_parts(ms, &reading.zone).map_err(sql)?;    Ok(Some((day_number(parts.year, parts.month, parts.day), Some(parts.hour * 60 + parts.minute))))}/// The open occurrence of each repeating to-do that stands for its series:/// its newest. A stack the old rule left draws as one row before the/// materializer collapses it (CONTRACT.md section 4).fn live_copies(todos: &[Todo], keep: &HashMap<String, Option<i64>>) -> HashSet<String> {    // A kept copy stands for its series while it is kept: the next one its    // tick made waits until the phone lets go.    let held: HashSet<&str> = todos.iter().filter(|todo| keep.contains_key(&todo.id)).filter_map(|todo| todo.series.as_deref()).collect();    let mut newest: HashMap<&str, (&str, &str)> = HashMap::new();    for todo in todos.iter().filter(|todo| todo.status == "open" && !keep.contains_key(&todo.id)) {        if let Some(series) = &todo.series {            let at = todo.occurrence_at.as_deref().unwrap_or("");            let entry = newest.entry(series.as_str()).or_insert((todo.id.as_str(), at));            if at > entry.1 {                *entry = (todo.id.as_str(), at);            }        }    }    let stand: HashSet<&str> = newest.values().map(|(id, _)| *id).collect();    todos        .iter()        .filter(|todo| {            if keep.contains_key(&todo.id) {                return true;            }            match todo.series.as_deref() {                Some(series) if todo.status == "open" => !held.contains(series) && stand.contains(todo.id.as_str()),                _ => true,            }        })        .map(|todo| todo.id.clone())        .collect()}/// Every to-do on a day in `from..=to`: an open one on the day it is due (or/// on today, `from` its day, once that day has passed), a done one on the/// day it was done.fn todo_items(ctx: &Ctx<'_>, at: &Reading, from: i64, to: i64) -> Result<Vec<Item>, MethodError> {    let found = todos_of(ctx, "AND status IN ('open', 'done')", &[])?;    let shown = live_copies(&found, &at.keep);    let mut out = Vec::new();    for (order, todo) in found.iter().enumerate() {        if !shown.contains(&todo.id) {            continue;        }        let place = match at.keep.get(&todo.id) {            // Kept in Sometime: not on a day.            Some(None) => continue,            // Kept on the day it stood on, in the place it held there: as an            // open row or a done one, whichever stood on that day.            Some(Some(kept)) => [open_place(todo, at)?, done_place(todo, at)?]                .into_iter()                .flatten()                .find(|place| matches!(place, Place::Todo { day, .. } if day == kept))                .unwrap_or(Place::Todo { day: *kept, minute: None, from: None }),            None if todo.status == "done" => {                let Some(place) = done_place(todo, at)? else { continue };                place            }            None => {                let Some(place) = open_place(todo, at)? else { continue };                place            }        };        let Place::Todo { day, .. } = place else { continue };        if day < from || day > to {            continue;        }        out.push(Item {            key: format!("todo:{}", todo.id),            kind: Kind::Todo,            whose: Whose::Yours,            words: todo.title.clone(),            mark: todo.mark.clone(),            done: todo.status == "done",            place,            opens: json!({ "sheet": "todo", "id": todo.id }),            order: order as i64,        });    }    Ok(out)}/// Where an open to-do stands: on the day it is due, or on today `from`/// that day once it has passed. `None`: no day (Sometime).fn open_place(todo: &Todo, at: &Reading) -> Result<Option<Place>, MethodError> {    let Some(due) = todo.at.as_deref() else { return Ok(None) };    let Some((day, minute)) = due_place(due, at)? else { return Ok(None) };    Ok(Some(if day < at.today { Place::Todo { day: at.today, minute: None, from: Some(day) } } else { Place::Todo { day, minute, from: None } }))}/// Where a done to-do stands: on the day it was done.fn done_place(todo: &Todo, at: &Reading) -> Result<Option<Place>, MethodError> {    let Some(done) = ms_of(todo.completed_at.as_deref()) else { return Ok(None) };    Ok(Some(Place::Todo { day: local_day(done, &at.zone).map_err(sql)?, minute: None, from: None }))}/// Every birthday on a day in `from..=to`: a person with a birth month and/// day is a row on that day every year, and opens the person.fn birthday_items(ctx: &Ctx<'_>, from: i64, to: i64, words: &Words) -> Result<Vec<Item>, MethodError> {    let whole = optional(ctx, "cotton_people", "birthday")?;    let found = rows(        ctx,        &format!(            "SELECT id, full_name, birth_month, birth_day, {whole} FROM cotton_people              WHERE workspace_id = ? AND archived_at IS NULL AND trashed_at IS NULL ORDER BY full_name ASC, id ASC"        ),        &[ws(ctx)],    )?;    let (first_year, ..) = civil_from_days(from);    let (last_year, ..) = civil_from_days(to);    let mut out = Vec::new();    for (order, person) in found.iter().enumerate() {        let parts = match (person.int("birth_month"), person.int("birth_day")) {            (Some(month), Some(day)) if (1..=12).contains(&month) && (1..=31).contains(&day) => Some((month, day)),            _ => person.text("birthday").and_then(cotton_core::cotton_rules::zoned_clock::yearly_month_day),        };        let Some((month, date)) = parts else { continue };        let name = person.text("full_name").unwrap_or_default().trim().to_string();        if name.is_empty() {            continue;        }        let id = person.text("id").unwrap_or_default().to_string();        for year in first_year..=last_year {            let (y, m, d) = yearly_in_year(month, date, year);            let day = day_number(y, m, d);            if day < from || day > to {                continue;            }            out.push(Item {                key: format!("birthday:{id}@{y}"),                kind: Kind::Birthday,                whose: Whose::Birthday,                words: fill(&words.birthday, &[("name", &name)]),                mark: Some("cake".to_string()),                done: false,                place: Place::Birthday { day },                opens: json!({ "person": id }),                order: order as i64,            });        }    }    Ok(out)}/// Every item on the days `from..=to`; with a group chosen, only that/// group's to-dos (events and birthdays have no group).fn items(ctx: &Ctx<'_>, at: &Reading, from: i64, to: i64, words: &Words, group: Option<&TodoGroup>) -> Result<Vec<Item>, MethodError> {    let Some(group) = group else {        let mut all = event_items(ctx, at, from, to)?;        all.extend(birthday_items(ctx, from, to, words)?);        all.extend(todo_items(ctx, at, from, to)?);        return Ok(all);    };    let members: HashSet<&str> = group.members.iter().map(String::as_str).collect();    Ok(todo_items(ctx, at, from, to)?        .into_iter()        .filter(|item| item.opens.get("id").and_then(Value::as_str).is_some_and(|id| members.contains(id)))        .collect())}// ── groups ──────────────────────────────────────────────────────────────────/// One to-do group as Days shows it: the person's hand-picked groups, two/// with the same name (case and spacing aside) as one, under the oldest's id./// Nothing is deleted: `ids` holds every group folded in.struct TodoGroup {    id: String,    ids: Vec<String>,    name: String,    position: f64,    /// Every member of the folded groups, in their order, once each.    members: Vec<String>,}fn name_key(name: &str) -> String {    name.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()}/// The person's to-do groups in their own order, same names folded.fn todo_groups(ctx: &Ctx<'_>) -> Result<Vec<TodoGroup>, MethodError> {    use cotton_tools::mcp::handlers::tables::groups as kept;    let mut out: Vec<TodoGroup> = Vec::new();    // live_groups answers the oldest first, so the first of a name stands.    for (id, data) in kept::live_groups(ctx.read.driver(), Some(ctx.workspace_id)).map_err(sql)? {        if data.get("table").and_then(Value::as_str) != Some("todo") || data.get("where").is_some_and(|f| !f.is_null()) {            continue;        }        let name = kept::name_of(&data).trim().to_string();        let position = data.get(kept::POSITION).and_then(Value::as_f64).unwrap_or(f64::MAX);        let members = kept::members_of(&data);        match out.iter_mut().find(|group| name_key(&group.name) == name_key(&name)) {            Some(group) => {                group.ids.push(id);                group.position = group.position.min(position);                for member in members {                    if !group.members.contains(&member) {                        group.members.push(member);                    }                }            }            None => out.push(TodoGroup { id: id.clone(), ids: vec![id], name, position, members }),        }    }    out.sort_by(|a, b| a.position.total_cmp(&b.position));    Ok(out)}/// The group a request names (`group`, either id of a fold), or none asked.fn group_arg(ctx: &Ctx<'_>, request: &Value) -> Result<Option<TodoGroup>, MethodError> {    let Some(asked) = text(request, "group") else { return Ok(None) };    todo_groups(ctx)?        .into_iter()        .find(|group| group.ids.iter().any(|id| id == asked))        .map(Some)        .ok_or_else(|| MethodError::new("not_found", "There is no such group. It may have been deleted."))}/// `days.groups {}` (CONTRACT.md section 5b): the filter's choices.fn groups(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let words = said(request);    let open: HashSet<String> = todos_of(ctx, "AND status = 'open'", &[])?.into_iter().map(|todo| todo.id).collect();    let listed: Vec<Value> = todo_groups(ctx)?        .iter()        .map(|group| json!({ "id": group.id, "name": group.name, "count": group.members.iter().filter(|id| open.contains(*id)).count() }))        .collect();    Ok(json!({ "all": words.all, "count": open.len(), "groups": listed }))}/// A to-do into `group` (the oldest of its fold) and out of every other to-do/// group; `None` takes it out of all of them.fn file_into(ctx: &mut Ctx<'_>, todo: &str, group: Option<&str>) -> Result<(), MethodError> {    use cotton_tools::mcp::handlers::tables::groups as kept;    let all = todo_groups(ctx)?;    let target = match group {        Some(asked) => Some(            all.iter()                .find(|g| g.ids.iter().any(|id| id == asked))                .ok_or_else(|| MethodError::new("not_found", "There is no such group. It may have been deleted."))?                .id                .clone(),        ),        None => None,    };    let holding: Vec<String> = kept::live_groups(ctx.read.driver(), Some(ctx.workspace_id))        .map_err(sql)?        .into_iter()        .filter(|(id, data)| all.iter().any(|g| g.ids.contains(id)) && kept::members_of(data).iter().any(|m| m == todo))        .map(|(id, _)| id)        .collect();    for id in holding.iter().filter(|id| Some(id.as_str()) != target.as_deref()) {        kept::update_group(ctx, &args(json!({ "id": id, "remove": [todo] }))).map_err(tool)?;    }    if let Some(target) = target.filter(|target| !holding.contains(target)) {        kept::update_group(ctx, &args(json!({ "id": target, "add": [todo] }))).map_err(tool)?;    }    ctx.commit().map_err(tool)}// ── the reads ───────────────────────────────────────────────────────────────/// `days.span { timezone, today, from, to }` (CONTRACT.md section 2).fn span(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let at = reading(ctx, request)?;    let (from, to) = (day_arg(request, "from")?, day_arg(request, "to")?);    if to < from || to - from + 1 > MOST_DAYS {        return Err(bad(format!("a span is one to {MOST_DAYS} days, `from` before `to`")));    }    let words = said(request);    let group = group_arg(ctx, request)?;    // What lies a span's length on either side too, so a fold at either end    // is the whole quiet run and the list knows where it ends and begins.    let (wide_from, wide_to) = (from - MOST_DAYS, to + MOST_DAYS);    let all = items(ctx, &at, wide_from, wide_to, words, group.as_ref())?;    // Every day with a row, and today, which always stands.    let mut busy: std::collections::BTreeSet<i64> =        layout::rows_by_day(&all, wide_from, wide_to, at.today, &at.zone, words).map_err(sql)?.into_iter().filter(|(_, rows)| !rows.is_empty()).map(|(day, _)| day).collect();    busy.insert(at.today);    let after = match busy.range(to + 1..).next() {        Some(day) => Some(*day),        None => far_after(ctx, &at, wide_to, group.as_ref())?,    };    let before = match busy.range(..from).next_back() {        Some(day) => Some(*day),        None => far_before(ctx, &at, wide_from, group.as_ref())?,    };    // Nothing after: the list ends on its last day with a row, or today.    let last = busy.range(..=to).next_back().copied().unwrap_or(at.today).max(at.today);    let first = busy.range(from..).next().copied().unwrap_or(at.today).min(at.today);    let end = after.is_none().then_some(last);    let begins = before.is_none().then_some(first);    let lo = begins.map_or(from, |first| from.max(first));    let hi = end.map_or(to, |last| to.min(last));    let mut days = if lo <= hi { layout::days(&all, lo, hi, at.today, &at.zone, words).map_err(sql)? } else { Vec::new() };    // A fold at either end reaches over the whole quiet run.    if let (Some(layout::Entry::Fold { fold }), Some(before)) = (days.first_mut(), before) {        if lo == from {            *fold = layout::fold_of(before + 1, day_of_key(&fold.to).unwrap_or(from), words);        }    }    if let (Some(layout::Entry::Fold { fold }), Some(after)) = (days.last_mut(), after) {        if hi == to {            *fold = layout::fold_of(day_of_key(&fold.from).unwrap_or(to), after - 1, words);        }    }    let mut answer = json!({ "today": day_key(at.today), "days": days });    if let Some(last) = end {        let line = match (&group, last > at.today) {            (None, true) => words.end_after_this.clone(),            (None, false) => words.end_after_today.clone(),            (Some(group), true) => fill(&words.end_group_after_this, &[("name", &group.name)]),            (Some(group), false) => fill(&words.end_group_after_today, &[("name", &group.name)]),        };        answer["end"] = json!({ "after": day_key(last), "words": line });    }    if let Some(first) = begins {        answer["begins"] = Value::from(day_key(first));    }    Ok(answer)}/// The first day after `beyond` that holds a one-off thing (an open to-do/// due then, an event starting then), for a quiet run longer than a span./// Repeating things always lie within a span's reach (a birthday within a/// year), so only one-off ones are asked for here.fn far_after(ctx: &Ctx<'_>, at: &Reading, beyond: i64, group: Option<&TodoGroup>) -> Result<Option<i64>, MethodError> {    let edge = iso(day_start(beyond + 1, &at.zone)?);    // Today always stands.    let mut found: Vec<i64> = if at.today > beyond { vec![at.today] } else { Vec::new() };    for todo in todos_of(ctx, "AND status = 'open' AND due_at IS NOT NULL AND due_at >= ?3", &[SqlValue::Text(edge.clone())])? {        if group.is_some_and(|group| !group.members.contains(&todo.id)) {            continue;        }        if let Some((day, _)) = todo.at.as_deref().map(|due| due_place(due, at)).transpose()?.flatten() {            if day > beyond {                found.push(day);                break;            }        }    }    if group.is_none() {        let event = ctx            .read            .driver()            .get(                "SELECT MIN(starts_at) AS at FROM cotton_events WHERE trashed_at IS NULL AND starts_at >= ? AND (my_response IS NULL OR my_response != 'declined')",                &[SqlValue::Text(edge)],            )            .map_err(sql)?;        if let Some(ms) = event.as_ref().and_then(|row| row.text("at")).and_then(parse_date_ms) {            found.push(local_day(ms, &at.zone).map_err(sql)?);        }    }    Ok(found.into_iter().filter(|day| *day > beyond).min())}/// The last day before `beyond` that holds anything: a to-do done then, a/// one-off event then, or the last occurrence of a series that has ended.fn far_before(ctx: &Ctx<'_>, at: &Reading, beyond: i64, group: Option<&TodoGroup>) -> Result<Option<i64>, MethodError> {    let edge = iso(day_start(beyond, &at.zone)?);    // Today always stands.    let mut found: Vec<i64> = if at.today < beyond { vec![at.today] } else { Vec::new() };    // An open to-do stands on its day, or on today once that has passed.    for todo in todos_of(ctx, "AND status = 'open' AND due_at IS NOT NULL AND due_at < ?3", &[SqlValue::Text(edge.clone())])? {        if group.is_some_and(|group| !group.members.contains(&todo.id)) {            continue;        }        if let Some(Place::Todo { day, .. }) = open_place(&todo, at)? {            found.push(day);        }    }    for todo in todos_of(ctx, "AND status = 'done' AND completed_at < ?3", &[SqlValue::Text(edge.clone())])? {        if group.is_some_and(|group| !group.members.contains(&todo.id)) {            continue;        }        if let Some(Place::Todo { day, .. }) = done_place(&todo, at)? {            found.push(day);        }    }    if group.is_none() {        let earliest = ctx            .read            .driver()            .get("SELECT MIN(starts_at) AS at FROM cotton_events WHERE trashed_at IS NULL AND starts_at < ?", &[SqlValue::Text(edge)])            .map_err(sql)?            .and_then(|row| row.text("at").and_then(parse_date_ms));        if let Some(earliest) = earliest {            // Every event before the edge, drawn from its first day: the            // last occurrence of each that ended before the edge.            let first = local_day(earliest, &at.zone).map_err(sql)?;            let mut day = beyond - 1;            while day >= first {                let from = (day - MOST_DAYS + 1).max(first);                let mut seen: Vec<i64> = Vec::new();                for item in event_items(ctx, at, from, day)? {                    if let Place::Event { starts, ends, .. } = item.place {                        let last = ends.filter(|ends| *ends > starts).map_or(starts, |ends| ends - 1);                        seen.push(local_day(last, &at.zone).map_err(sql)?.min(day));                    }                }                if let Some(last) = seen.into_iter().max() {                    found.push(last);                    break;                }                day = from - 1;            }        }    }    Ok(found.into_iter().filter(|day| *day < beyond).max())}/// `days.month { timezone, today, month: "2026-11" }` (CONTRACT.md section 6).fn month(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let at = reading(ctx, request)?;    let raw = text(request, "month").ok_or_else(|| bad("`month` is YYYY-MM"))?;    let first = day_of_key(&format!("{raw}-01")).ok_or_else(|| bad(format!("`month` is not a month: {raw}")))?;    let (year, number, _) = civil_from_days(first);    let last = first + days_in_month(year, number) - 1;    let words = said(request);    let group = group_arg(ctx, request)?;    let all = items(ctx, &at, first, last, words, group.as_ref())?;    let by_day = layout::rows_by_day(&all, first, last, at.today, &at.zone, words).map_err(sql)?;    let days: Vec<Value> = (first..=last)        .map(|day| {            let rows = by_day.get(&day).map(Vec::as_slice).unwrap_or_default();            let mut given: Vec<&str> = Vec::new();            for row in rows {                if let Some(id) = row.drawn().filter(|id| marks::drawn(id)) {                    if !given.contains(&id) && given.len() < 3 {                        given.push(id);                    }                }            }            let other = rows.iter().any(|row| row.drawn().is_none_or(|id| !marks::drawn(id)));            json!({ "day": day_key(day), "marks": given, "other": other, "today": day == at.today })        })        .collect();    // Blank cells before the 1st, in a week that starts on `weekStart` (1    // Monday … 7 Sunday): a date's weekday is the calendar's, never a zone's.    let week_start = request.get("weekStart").and_then(Value::as_i64).filter(|n| (1..=7).contains(n)).unwrap_or(1);    let monday_first = cotton_core::cotton_rules::days::weekday_monday_first(first) as i64;    let lead = (monday_first - (week_start - 1)).rem_euclid(7);    Ok(json!({        "month": raw,        "title": fill(&words.month_title, &[("month", &words.months[(number - 1) as usize]), ("year", &year.to_string())]),        "weekStart": week_start,        "lead": lead,        "weeks": 6,        "days": days,    }))}/// `days.sometime { group? }` (CONTRACT.md section 5): every open to-do with/// no day, all of them, under the person's to-do groups in their order, then/// "No group" last. With `group`, that group alone.fn sometime(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let words = said(request);    let chosen = group_arg(ctx, request)?;    let keep = keep_arg(request)?;    // Every open to-do with no day, and the ones ticked here since the list    // was opened, done as they now are (nothing moves at the moment a    // person acts).    let undated: Vec<Todo> = todos_of(ctx, "AND status IN ('open', 'done') AND due_at IS NULL AND snoozed_until IS NULL", &[])?        .into_iter()        .filter(|todo| todo.status == "open" || keep.get(&todo.id) == Some(&None))        .collect();    let by_id: HashMap<&str, &Todo> = undated.iter().map(|todo| (todo.id.as_str(), todo)).collect();    let row_of = |todo: &Todo| {        let done = todo.status == "done";        json!({            "key": format!("todo:{}", todo.id), "kind": "todo", "time": null, "end": null,            "mark": { "kind": "tick", "done": done }, "drawnMark": todo.mark, "words": todo.title,            "suffix": null, "done": done, "whose": "yours", "opens": { "sheet": "todo", "id": todo.id },        })    };    let group_of = |id: Value, name: &str, members: &[&Todo]| {        json!({ "id": id, "name": name, "count": members.len(), "rows": members.iter().map(|todo| row_of(todo)).collect::<Vec<_>>() })    };    let all = todo_groups(ctx)?;    if let Some(group) = chosen {        let held: Vec<&Todo> = group.members.iter().filter_map(|member| by_id.get(member.as_str()).copied()).collect();        let count = held.len();        return Ok(json!({ "groups": [group_of(Value::from(group.id.clone()), &group.name, &held)], "count": count }));    }    let mut grouped: HashSet<&str> = HashSet::new();    let mut out = Vec::new();    for group in &all {        let held: Vec<&Todo> = group.members.iter().filter_map(|member| by_id.get(member.as_str()).copied()).collect();        if held.is_empty() {            continue;        }        grouped.extend(held.iter().map(|todo| todo.id.as_str()));        out.push(group_of(Value::from(group.id.clone()), &group.name, &held));    }    let loose: Vec<&Todo> = undated.iter().filter(|todo| !grouped.contains(todo.id.as_str())).collect();    if !loose.is_empty() {        out.push(group_of(Value::Null, &words.no_group, &loose));    }    Ok(json!({ "groups": out, "count": undated.len() }))}/// One event's row, read for the sheet.pub(super) fn event_row(ctx: &Ctx<'_>, id: &str) -> Result<Option<Row>, MethodError> {    let extra = ["mark", "your_note", "alert", "guest_responses", "invited", "organizer_is_self", "on_google", "sync_state", "account", "source", "ical_uid", "my_response", "location", "exdates", "timezone", "original_starts_at", "updated_at", "gcal_etag"].iter().map(|column| optional(ctx, "cotton_events", column)).collect::<Result<Vec<_>, _>>()?.join(", ");    Ok(ctx        .read        .driver()        .get(            &format!("SELECT id, title, starts_at, ends_at, all_day, notes, rrule, series_id, gcal_id, trashed_at, {extra} FROM cotton_events WHERE id = ?"),            &[SqlValue::Text(id.to_string())],        )        .map_err(sql)?        .filter(|row| row.text("trashed_at").is_none()))}fn todo_row(ctx: &Ctx<'_>, id: &str) -> Result<Option<Todo>, MethodError> {    Ok(todos_of(ctx, "AND id = ?3", &[SqlValue::Text(id.to_string())])?.into_iter().next())}fn todo_notes(ctx: &Ctx<'_>, id: &str) -> Result<Option<String>, MethodError> {    Ok(ctx        .read        .driver()        .get("SELECT notes FROM cotton_todos WHERE id = ?", &[SqlValue::Text(id.to_string())])        .map_err(sql)?        .and_then(|row| row.text("notes").map(str::to_string)))}fn gone(words: &Words) -> MethodError {    MethodError::new("not_found", words.not_found.clone())}fn clock_of(minute: Option<i64>) -> Value {    minute.map_or(Value::Null, |minute| Value::from(layout::clock(minute)))}/// `days.item { table, id, occurrenceAt?, timezone, today }`: the one sheet.fn item(ctx: &mut Ctx<'_>, request: &Value, heard: &Heard) -> Result<Value, MethodError> {    let at = reading(ctx, request)?;    let words = said(request);    let id = text(request, "id").ok_or_else(|| bad("`id` names the item"))?;    match text(request, "table") {        Some("todo") => {            let todo = todo_row(ctx, id)?.ok_or_else(|| gone(words))?;            let place = todo.at.as_deref().map(|due| due_place(due, &at)).transpose()?.flatten();            Ok(json!({                "table": "todo", "id": todo.id, "whose": "yours", "says": words.yours_says,                "words": todo.title, "day": place.map(|(day, _)| day_key(day)), "time": clock_of(place.and_then(|(_, minute)| minute)),                "end": null, "mark": todo.mark, "note": todo_notes(ctx, id)?, "alert": null,                "done": todo.status == "done", "repeats": todo.series.is_some(),                "group": todo_groups(ctx)?.iter().find(|g| g.members.contains(&todo.id)).map(|g| json!({ "id": g.id, "name": g.name })),                "choices": day_choices(at.today, true),                "dropped": todo.status == "dropped",                "canChange": { "title": true, "time": true, "mark": true, "note": true, "alert": false, "group": true },            }))        }        Some("event") => {            let row = event_row(ctx, id)?.ok_or_else(|| gone(words))?;            let master = row.text("series_id").map(|series| event_row(ctx, series)).transpose()?.flatten();            let google = row.text("gcal_id").is_some() || master.as_ref().is_some_and(|m| m.text("gcal_id").is_some());            let starts = match text(request, "occurrenceAt") {                Some(occurrence) if row.text("series_id").is_none() && row.text("rrule").is_some() => parse_date_ms(occurrence),                _ => ms_of(row.text("starts_at")),            };            let all_day = row.int("all_day").unwrap_or(0) != 0;            let length = ms_of(row.text("ends_at")).zip(ms_of(row.text("starts_at"))).map(|(e, s)| e - s);            let minute = |ms: i64| -> Result<i64, MethodError> {                let parts = zoned_parts(ms, &at.zone).map_err(sql)?;                Ok(parts.hour * 60 + parts.minute)            };            let day = starts.map(|ms| local_day(ms, &at.zone)).transpose().map_err(sql)?;            let time = match (starts, all_day) {                (Some(ms), false) => Some(minute(ms)?),                _ => None,            };            let end = match (starts, length, all_day) {                (Some(ms), Some(length), false) if length > 0 => Some(minute(ms + length)?),                _ => None,            };            let note = if google { row.text("your_note") } else { row.text("notes") };            // A Google event is changed here and sent to Google, while a grant that can write stands (or nothing            // has been heard yet); with only a read-only grant the sheet's Save asks to connect again.            let changes_google = !google || heard.writable() != Some(None) || heard.connected_google();            let received = row.text("invited") == Some("invited") || master.as_ref().is_some_and(|m| m.text("invited") == Some("invited"));            let people = super::days_people::part(ctx, heard, &row, master.as_ref())?;            let held = super::days_people::guests(ctx, row.text("series_id").unwrap_or(id))?;            let invitation = if received { super::days_invite::part(ctx, &row, master.as_ref())? } else { Value::Null };            // An occurrence moved out of a series keeps the series' alert unless it has its own, as its reminder does.            let alert = row.int("alert").or_else(|| master.as_ref().and_then(|m| m.int("alert")));            Ok(json!({                "table": "event", "id": row.text("id"), "whose": if google { "google" } else { "yours" },                "says": if received { invitation["says"].clone() } else if google { json!(words.google_says) } else { json!(words.yours_says) },                "words": row.text("title"), "day": day.map(day_key), "time": clock_of(time), "end": clock_of(end),                "mark": row.text("mark").filter(|id| marks::known(id)), "note": note,                "alert": alert_standing(alert), "alerts": alert_choices(alert),                "done": false, "repeats": row.text("rrule").is_some() || master.is_some(),                "canChange": { "title": changes_google && !received, "time": changes_google && !received, "mark": true, "note": true, "alert": true, "people": people["canChange"] },                "choices": if !changes_google || received { json!([]) } else { day_choices(at.today, false) },                "people": people,                "deleteTells": super::days_people::delete_tells(&held, row.text("gcal_id").or_else(|| master.as_ref().and_then(|m| m.text("gcal_id"))).is_some())?,                "invitation": invitation,                "ends": match (time, all_day) {                    (Some(start), false) => ends_row(start, length.filter(|l| *l > 0).map(|l| l / 60_000))?,                    _ => Value::Null,                },            }))        }        _ => Err(bad("`table` is event or todo")),    }}/// The alert that stands on an event, as its sheet marks it (CONTRACT.md section 3): `"none"` for an event the person/// set to No alert ([`NO_ALERT`]), else the minutes before it reminds, an event with no alert stored answering the ten/// minutes it reminds at, never null: the sheet shows what the reminder will do.fn alert_standing(stored: Option<i64>) -> Value {    event_lead(stored).map_or_else(|| Value::from(ALERT_NONE), Value::from)}/// The sheet's alert choices, in order (CONTRACT.md section 3): No alert, At the start, 10, 30 and 60 minutes before,/// with a stored lead none of those name (one an assistant wrote, say 15) placed among them by its minutes, each/// `{ alert, on }` with the one that stands on. The phone labels `"none"` by `change.no_alert`, `0` by/// `change.alert_at` and the rest by `change.alert_before`, and writes the chosen `alert` back to `days.change`.fn alert_choices(stored: Option<i64>) -> Value {    let standing = event_lead(stored);    let mut minutes = vec![0, 10, 30, 60];    if let Some(lead) = standing.filter(|lead| !minutes.contains(lead)) {        minutes.push(lead);        minutes.sort_unstable();    }    let mut out = vec![json!({ "alert": ALERT_NONE, "on": standing.is_none() })];    out.extend(minutes.into_iter().map(|n| json!({ "alert": n, "on": standing == Some(n) })));    Value::from(out)}/// The lengths the ENDS row offers as chips, in minutes (CONTRACT.md section 14).const LENGTH_CHIPS: [(&str, i64); 3] = [("30m", 30), ("1h", 60), ("2h", 120)];/// A days line, by its key in the shipped set.fn days_line(name: &str, fills: &[(&str, &str)]) -> Result<String, MethodError> {    cotton_core::rules::shell_lines::LineSet::shipped("days")        .and_then(|lines| lines.say(name, fills))        .ok_or_else(|| MethodError::new("unreadable", format!("the days set says no line {name}")))}/// A length in words: "45 min", "1 hour", "2 hours", "1 hour 30 min".pub(super) fn length_words(minutes: i64) -> Result<String, MethodError> {    let (h, m) = (minutes / 60, minutes % 60);    let (hs, ms) = (h.to_string(), m.to_string());    match (h, m) {        (0, _) => days_line("change.length_min", &[("m", &ms)]),        (1, 0) => days_line("change.length_hour", &[]),        (_, 0) => days_line("change.length_hours", &[("h", &hs)]),        (1, _) => days_line("change.length_hour_min", &[("m", &ms)]),        _ => days_line("change.length_hours_min", &[("h", &hs), ("m", &ms)]),    }}/// The ENDS row of a timed event's sheet (CONTRACT.md section 14): the end/// read back with its length, and the chips, the one that stands on. `start`/// is the start's minute of the day; `length` the minutes it lasts, or none.pub(super) fn ends_row(start: i64, length: Option<i64>) -> Result<Value, MethodError> {    let says = match length {        None => days_line("change.ends_none", &[])?,        Some(length) => {            let end_minute = start + length;            let clock = layout::clock(end_minute.rem_euclid(1440));            let end = if end_minute >= 1440 { days_line("change.ends_tomorrow", &[("end", &clock)])? } else { clock };            days_line("change.ends_says", &[("end", &end), ("length", &length_words(length)?)])?        }    };    let mut choices = Vec::new();    for (chip, minutes) in LENGTH_CHIPS {        choices.push(json!({ "key": chip, "minutes": minutes, "label": days_line(&format!("change.ends_{chip}"), &[])?, "on": length == Some(minutes) }));    }    let named = length.is_some_and(|l| LENGTH_CHIPS.iter().any(|(_, m)| *m == l));    choices.push(json!({ "key": "pick", "label": days_line("change.ends_pick", &[])?, "on": length.is_some() && !named }));    choices.push(json!({ "key": "none", "label": days_line("change.ends_none", &[])?, "on": length.is_none() }));    Ok(json!({ "title": days_line("change.ends", &[])?, "says": says, "choices": choices }))}/// The word a sheet answers and writes for No alert (stored as [`NO_ALERT`]).const ALERT_NONE: &str = "none";/// The sheet's quick day row (CONTRACT.md section 3): today, tomorrow, the/// Monday of next week, and for a to-do Sometime. The phone labels each by/// its line key `move.<key>` and adds Pick a day.fn day_choices(today: i64, todo: bool) -> Value {    let monday = today + 7 - cotton_core::cotton_rules::days::weekday_monday_first(today) as i64;    let mut out = vec![        json!({ "key": "today", "day": day_key(today) }),        json!({ "key": "tomorrow", "day": day_key(today + 1) }),        json!({ "key": "next_week", "day": day_key(monday) }),    ];    if todo {        out.push(json!({ "key": "sometime", "day": null }));    }    Value::from(out)}/// `days.read_line { words, timezone, today, where, dayInView? }`: what a/// line says, for the pill (CONTRACT.md section 7).fn read_line(request: &Value) -> Result<Value, MethodError> {    let words = said(request);    let line = request.get("words").and_then(Value::as_str).unwrap_or_default();    let today = day_arg(request, "today")?;    let got = when::read(line, today, language(request));    let (day, kind) = settled(request, &got)?;    Ok(json!({        "title": got.title,        "day": day.map(day_key),        "time": clock_of(got.time),        "end": clock_of(got.end),        "kind": kind,        "pill": when::pill(day, got.time, got.end, words),        "marks": marks::find(&got.title, language(request), MARKS_OFFERED),        "said": got.said,    }))}/// The day a read line lands on, and what it makes: no day said lands on the/// day in view from Days and on no day from Sometime; a time makes an event.fn settled(request: &Value, got: &when::Understood) -> Result<(Option<i64>, &'static str), MethodError> {    let from_sometime = text(request, "where") == Some("sometime");    let day = match (got.day, got.someday, from_sometime) {        (Some(day), _, _) => Some(day),        (None, true, _) | (None, false, true) => None,        (None, false, false) => Some(match text(request, "dayInView") {            Some(_) => day_arg(request, "dayInView")?,            None => day_arg(request, "today")?,        }),    };    let kind = if got.time.is_some() && day.is_some() { "event" } else { "todo" };    Ok((day, kind))}// ── the acts ────────────────────────────────────────────────────────────────fn args(value: Value) -> Map<String, Value> {    value.as_object().cloned().unwrap_or_default()}fn mark_arg(request: &Value) -> Result<Option<Option<String>>, MethodError> {    match request.get("mark") {        None => Ok(None),        Some(Value::Null) => Ok(Some(None)),        Some(Value::String(id)) if marks::known(id) => Ok(Some(Some(id.clone()))),        Some(other) => Err(bad(format!("`mark` is a mark of the catalogue (days.marks) or null, not {other}"))),    }}fn write_columns(ctx: &mut Ctx<'_>, table: &str, id: &str, values: Map<String, Value>) -> Result<(), MethodError> {    if values.is_empty() {        return Ok(());    }    let store = if table == "todo" { "cotton_todos" } else { "cotton_events" };    for column in values.keys() {        if !holds(ctx, store, column)? {            return Err(MethodError::new("write_refused", format!("this copy keeps no {column} on {table} yet")));        }    }    update_row(ctx, store, id, values).map_err(tool)?;    ctx.commit().map_err(tool)}/// A repeating to-do's series is given what it now owes (its next, once this/// one is finished): the person's own act materialises at once.fn advance_series(ctx: &mut Ctx<'_>, series: &str, zone: &str) -> Result<(), MethodError> {    let found = ctx        .read        .driver()        .get(&format!("SELECT {} FROM cotton_todo_recurrences WHERE id = ?", RECURRENCE_TEMPLATE_COLUMNS.join(", ")), &[SqlValue::Text(series.to_string())])        .map_err(sql)?;    let Some(row) = found else { return Ok(()) };    let mut template = Map::new();    for column in RECURRENCE_TEMPLATE_COLUMNS {        let value = match column {            &"priority" => row.int(column).map(Value::from),            &"paused" => row.int(column).map(|n| Value::Bool(n != 0)),            _ => row.text(column).map(Value::from),        };        template.insert((*column).to_string(), value.unwrap_or(Value::Null));    }    materialize_template(ctx, &RecurrenceTemplate::of(&template), zone).map_err(tool)?;    Ok(())}fn todo_or_gone(ctx: &Ctx<'_>, request: &Value) -> Result<Todo, MethodError> {    let id = text(request, "id").ok_or_else(|| bad("`id` names the to-do"))?;    todo_row(ctx, id)?.ok_or_else(|| gone(said(request)))}/// `days.done { id, timezone? }`: tick a to-do; a repeating one's next is made.fn done(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let todo = todo_or_gone(ctx, request)?;    todos::complete_todo(ctx, &args(json!({ "id": todo.id }))).map_err(tool)?;    if let Some(series) = &todo.series {        let zone = database_zone(ctx, text(request, "timezone").unwrap_or("UTC"))?;        advance_series(ctx, series, &zone)?;    }    Ok(json!({ "id": todo.id, "done": true }))}/// `days.undone { id }`: untick it.fn undone(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let todo = todo_or_gone(ctx, request)?;    // A repeating one's tick made its next: the copies that tick made which    // nobody has touched since go to the bin, so the series has one live    // copy again (CONTRACT.md section 3).    if let (Some(series), Some(done_at), true) = (&todo.series, &todo.completed_at, todo.status == "done") {        let made = rows(            ctx,            "SELECT id FROM cotton_todos              WHERE recurrence_id = ?1 AND status = 'open' AND trashed_at IS NULL                AND occurrence_at > ?2 AND created_at >= ?3 AND updated_at <= created_at",            &[SqlValue::Text(series.clone()), SqlValue::Text(todo.occurrence_at.clone().unwrap_or_default()), SqlValue::Text(done_at.clone())],        )?;        let now = iso(ctx.now.timestamp_millis());        for id in made.iter().filter_map(|row| row.text("id")).map(str::to_string).collect::<Vec<_>>() {            let mut bin = Map::new();            bin.insert("trashed_at".into(), Value::from(now.clone()));            update_row(ctx, "cotton_todos", &id, bin).map_err(tool)?;        }        ctx.commit().map_err(tool)?;    }    let mut patch = Map::new();    patch.insert("status".into(), Value::from("open"));    patch.insert("completed_at".into(), Value::Null);    write_columns(ctx, "todo", &todo.id, patch)?;    Ok(json!({ "id": todo.id, "done": false }))}/// `days.skip { id }`: a repeating to-do's live copy is let go (dropped,/// never done) and its next is made; a to-do that does not repeat is refused.fn skip(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let words = said(request);    let todo = todo_or_gone(ctx, request)?;    let Some(series) = todo.series.clone() else {        return Err(MethodError::new("not_repeating", words.not_repeating.clone()));    };    let mut patch = Map::new();    patch.insert("status".into(), Value::from("dropped"));    patch.insert("completed_at".into(), Value::Null);    write_columns(ctx, "todo", &todo.id, patch)?;    let zone = database_zone(ctx, text(request, "timezone").unwrap_or("UTC"))?;    advance_series(ctx, &series, &zone)?;    Ok(json!({ "id": todo.id, "skipped": true }))}/// A series' template paused (`true`) or going again.fn pause_series(ctx: &mut Ctx<'_>, series: &str, paused: bool) -> Result<(), MethodError> {    let mut patch = Map::new();    patch.insert("paused".into(), Value::Bool(paused));    update_row(ctx, "cotton_todo_recurrences", series, patch).map_err(tool)?;    ctx.commit().map_err(tool)}/// `days.drop { id }`: the person decided not to do it. Kept, `dropped`,/// listed under Dropped; a repeating one's series stops making copies.fn drop_todo(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let todo = todo_or_gone(ctx, request)?;    let mut patch = Map::new();    patch.insert("status".into(), Value::from("dropped"));    patch.insert("completed_at".into(), Value::Null);    write_columns(ctx, "todo", &todo.id, patch)?;    if let Some(series) = &todo.series {        pause_series(ctx, series, true)?;    }    Ok(json!({ "id": todo.id, "dropped": true }))}/// `days.bring_back { id }`: a dropped to-do open again on its own day (late/// if that has passed); a repeating one's series goes on again.fn bring_back(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let todo = todo_or_gone(ctx, request)?;    let mut patch = Map::new();    patch.insert("status".into(), Value::from("open"));    patch.insert("completed_at".into(), Value::Null);    write_columns(ctx, "todo", &todo.id, patch)?;    if let Some(series) = &todo.series {        pause_series(ctx, series, false)?;    }    Ok(json!({ "id": todo.id, "dropped": false }))}/// `days.delete { table, id, occurrenceAt? }`: into the bin. A repeating/// to-do takes its series with it; one occurrence of a repeating event of/// the person's own goes alone; a Google event is refused.fn delete(ctx: &mut Ctx<'_>, request: &Value, heard: &Heard) -> Result<Value, MethodError> {    let words = said(request);    let id = text(request, "id").ok_or_else(|| bad("`id` names the item"))?.to_string();    let now = iso(ctx.now.timestamp_millis());    match text(request, "table") {        Some("todo") => {            let todo = todo_or_gone(ctx, request)?;            let mut bin = Map::new();            bin.insert("trashed_at".into(), Value::from(now.clone()));            update_row(ctx, "cotton_todos", &todo.id, bin.clone()).map_err(tool)?;            if let Some(series) = &todo.series {                pause_series(ctx, series, true)?;                if holds(ctx, "cotton_todo_recurrences", "trashed_at")? {                    update_row(ctx, "cotton_todo_recurrences", series, bin).map_err(tool)?;                }                // The series' other open copies go with it.                let open = rows(ctx, "SELECT id FROM cotton_todos WHERE recurrence_id = ? AND status = 'open' AND trashed_at IS NULL", &[SqlValue::Text(series.clone())])?;                for other in open.iter().filter_map(|row| row.text("id")).map(str::to_string).collect::<Vec<_>>() {                    let mut bin = Map::new();                    bin.insert("trashed_at".into(), Value::from(now.clone()));                    update_row(ctx, "cotton_todos", &other, bin).map_err(tool)?;                }            }            ctx.commit().map_err(tool)?;        }        Some("event") => {            let row = event_row(ctx, &id)?.ok_or_else(|| gone(words))?;            let google = google_event(ctx, &row)?;            if google {                google_may_change(heard)?;            }            let mut asked = json!({ "id": id });            if let Some(occurrence) = text(request, "occurrenceAt").filter(|_| row.text("rrule").is_some()) {                asked["occurrenceAt"] = Value::from(occurrence);                asked["scope"] = Value::from("this");            }            events::delete_event(ctx, &args(asked)).map_err(tool)?;            let told = !super::days_people::guests(ctx, &id)?.is_empty();            // A whole event Google holds goes to Google as a delete (one occurrence goes as its series' exdates).            let whole = text(request, "occurrenceAt").is_none() || row.text("rrule").is_none();            if row.text("gcal_id").is_some() || row.int("on_google").unwrap_or(0) != 0 {                let target = if whole { id.clone() } else { id.clone() };                to_google(ctx, &target)?;            }            if google || row.text("gcal_id").is_some() || told {                return Ok(json!({ "id": id, "deleted": true, "google": "waiting" }));            }        }        _ => return Err(bad("`table` is event or todo")),    }    Ok(json!({ "id": id, "deleted": true }))}/// A clock argument, `H:MM` or `HH:MM`, as minutes; `None` when absent.fn minute_arg(request: &Value, name: &str) -> Result<Option<i64>, MethodError> {    let Some(raw) = text(request, name) else { return Ok(None) };    let (h, m) = raw.split_once(':').ok_or_else(|| bad(format!("`{name}` is a clock, like 19:00")))?;    let (h, m): (i64, i64) = (h.parse().map_err(|_| bad(format!("`{name}` is a clock")))?, m.parse().map_err(|_| bad(format!("`{name}` is a clock")))?);    if !(0..24).contains(&h) || !(0..60).contains(&m) || raw.split_once(':').is_some_and(|(_, m)| m.len() != 2) {        return Err(bad(format!("`{name}` is a clock, like 19:00")));    }    Ok(Some(h * 60 + m))}/// `length`: minutes the event lasts (1 to 1439), or "none" for No end/// (CONTRACT.md section 14). `None`: not given; `Some(None)`: No end.fn length_arg(request: &Value) -> Result<Option<Option<i64>>, MethodError> {    match request.get("length") {        None => Ok(None),        Some(Value::String(word)) if word == "none" => Ok(Some(None)),        Some(value) => value.as_i64().filter(|m| (1..1440).contains(m)).map(|m| Some(Some(m))).ok_or_else(|| bad("`length` is minutes, 1 to 1439, or \"none\"")),    }}fn hhmm(minute: i64) -> String {    format!("{:02}:{:02}", minute / 60, minute % 60)}/// A to-do's due as the store keeps it: the day at local midnight in the/// database's zone, or that day at a clock in the phone's zone.fn due_iso(day: i64, minute: Option<i64>, zone: &str, db_zone: &str) -> Result<String, MethodError> {    match minute {        None => join_moment(&MomentSplit { date: day_key(day), time: None }, db_zone).map_err(sql),        Some(minute) => join_moment(&MomentSplit { date: day_key(day), time: Some(hhmm(minute)) }, zone).map_err(sql),    }}fn move_todo(ctx: &mut Ctx<'_>, request: &Value, todo: &Todo) -> Result<(), MethodError> {    let zone = zone_arg(request)?;    let db_zone = database_zone(ctx, &zone)?;    let mut patch = Map::new();    match request.get("day") {        Some(Value::Null) => {            patch.insert("due_at".into(), Value::Null);        }        Some(_) => {            let day = day_arg(request, "day")?;            // A to-do with a time keeps it when only its day is given            // (`time: null` clears it): the day changes, nothing else.            let minute = match request.get("time") {                Some(_) => minute_arg(request, "time")?,                None => {                    let at = Reading { zone: zone.clone(), db_zone: db_zone.clone(), today: day, keep: HashMap::new() };                    todo.at.as_deref().map(|due| due_place(due, &at)).transpose()?.flatten().and_then(|(_, minute)| minute)                }            };            patch.insert("due_at".into(), Value::from(due_iso(day, minute, &zone, &db_zone)?));        }        None => return Ok(()),    }    patch.insert("snoozed_until".into(), Value::Null);    write_columns(ctx, "todo", &todo.id, patch)}fn move_event(ctx: &mut Ctx<'_>, request: &Value, id: &str, heard: &Heard) -> Result<(), MethodError> {    let words = said(request);    let row = event_row(ctx, id)?.ok_or_else(|| gone(words))?;    if ["day", "time", "end", "length"].iter().all(|key| request.get(*key).is_none()) {        return Ok(());    }    if google_event(ctx, &row)? {        google_may_change(heard)?;    }    let zone = zone_arg(request)?;    let occurrence = text(request, "occurrenceAt");    let starts = match occurrence {        Some(occurrence) => parse_date_ms(occurrence),        None => ms_of(row.text("starts_at")),    }    .ok_or_else(|| bad("this event has no start to move"))?;    let length = ms_of(row.text("ends_at")).zip(ms_of(row.text("starts_at"))).map(|(e, s)| e - s);    let all_day = row.int("all_day").unwrap_or(0) != 0;    let parts = zoned_parts(starts, &zone).map_err(sql)?;    let day = match request.get("day") {        Some(_) => day_arg(request, "day")?,        None => day_number(parts.year, parts.month, parts.day),    };    let mut patch = Map::new();    patch.insert("id".into(), Value::from(id));    patch.insert("timezone".into(), Value::from(zone.clone()));    if all_day && minute_arg(request, "time")?.is_none() {        let span_days = length.map_or(0, |length| (length.max(1) - 1) / 86_400_000);        patch.insert("startsAt".into(), Value::from(day_key(day)));        patch.insert("endsAt".into(), Value::from(day_key(day + span_days)));        patch.insert("allDay".into(), Value::Bool(true));    } else {        let minute = minute_arg(request, "time")?.unwrap_or(parts.hour * 60 + parts.minute);        let start = join_moment(&MomentSplit { date: day_key(day), time: Some(hhmm(minute)) }, &zone).map_err(sql)?;        let start_ms = parse_date_ms(&start).unwrap_or(starts);        patch.insert("startsAt".into(), Value::from(start.clone()));        let end = match length_arg(request)? {            Some(Some(minutes)) => Some(iso(start_ms + minutes * 60_000)),            Some(None) => {                patch.insert("endsAt".into(), Value::Null);                None            }            None => match minute_arg(request, "end")? {            Some(end) => {                let end_day = if end <= minute { day + 1 } else { day };                Some(join_moment(&MomentSplit { date: day_key(end_day), time: Some(hhmm(end)) }, &zone).map_err(sql)?)            }            None => length.map(|length| iso(start_ms + length)),            },        };        if let Some(end) = end {            patch.insert("endsAt".into(), Value::from(end));        }        if all_day {            patch.insert("allDay".into(), Value::Bool(false));        }    }    if let Some(occurrence) = occurrence {        if row.text("rrule").is_some() {            patch.insert("occurrenceAt".into(), Value::from(occurrence));            patch.insert("scope".into(), Value::from("this"));        }    }    events::update_event_from_days(ctx, &patch).map_err(tool)?;    Ok(())}/// Whether an event (or its series) came from Google.fn google_event(ctx: &Ctx<'_>, row: &Row) -> Result<bool, MethodError> {    if row.text("gcal_id").is_some() {        return Ok(true);    }    Ok(match row.text("series_id") {        Some(series) => event_row(ctx, series)?.is_some_and(|m| m.text("gcal_id").is_some()),        None => false,    })}/// Marks an event (the series' master for an occurrence of a series Google holds) to be sent to Google by the/// send pass (CONTRACT.md section 16): `on_google` and `sync_state` pending.fn to_google(ctx: &mut Ctx<'_>, id: &str) -> Result<(), MethodError> {    let mut patch = Map::new();    patch.insert("on_google".into(), Value::Bool(true));    patch.insert("sync_state".into(), Value::from("pending"));    update_row(ctx, "cotton_events", id, patch).map_err(tool)?;    ctx.commit().map_err(tool)}/// `days.move { table, id, day, time?, occurrenceAt?, timezone }`: another/// day (a swipe, a drag). A Google event is refused (`google_read_only`).fn move_to(ctx: &mut Ctx<'_>, request: &Value, heard: &Heard) -> Result<Value, MethodError> {    let id = text(request, "id").ok_or_else(|| bad("`id` names the item"))?.to_string();    match text(request, "table") {        Some("todo") => {            let todo = todo_or_gone(ctx, request)?;            move_todo(ctx, request, &todo)?;        }        Some("event") => {            move_event(ctx, request, &id, heard)?;            let row = event_row(ctx, &id)?.ok_or_else(|| gone(said(request)))?;            if row.int("on_google").unwrap_or(0) != 0 || google_event(ctx, &row)? {                if !(text(request, "occurrenceAt").is_some() && row.text("rrule").is_some()) {                    to_google(ctx, &id)?;                }                return Ok(json!({ "id": id, "moved": true, "google": "waiting" }));            }        }        _ => return Err(bad("`table` is event or todo")),    }    Ok(json!({ "id": id, "moved": true }))}/// `days.change { table, id, title?, day?, time?, end?, mark?, note?, alert? }`.fn change(ctx: &mut Ctx<'_>, request: &Value, heard: &Heard) -> Result<Value, MethodError> {    let words = said(request);    let id = text(request, "id").ok_or_else(|| bad("`id` names the item"))?.to_string();    let mark = mark_arg(request)?;    let mut own = Map::new();    if let Some(mark) = mark {        own.insert("mark".into(), mark.map_or(Value::Null, Value::from));    }    let note = request.get("note").map(|note| match note {        Value::String(text) if !text.trim().is_empty() => Value::from(text.clone()),        _ => Value::Null,    });    // A note saved from a sheet opened on an older note (another device or the assistant changed it    // since, `note_base` the note the sheet loaded) is merged into the newer one, never put over it.    let mut merged = None;    // The base is taken as sent, empty included: a sheet opened on no note, saved after the assistant wrote one,    // keeps the assistant's note beside its own; an emptied note (null) is the empty text laid over the newer one.    let base = request.get("note_base").and_then(Value::as_str);    let mut laid = |held: Option<String>, note: Value| -> Value {        let (Some(base), Some(held)) = (base, held.filter(|held| !held.is_empty())) else { return note };        let (kept, both) = crate::phone::notes::laid_over(&held, note.as_str().unwrap_or(""), Some(base));        merged = both.or(merged);        // What an emptied note leaves is the newer words alone, without the blank line the empty text stood as.        let kept = if note.is_null() { kept.trim().to_string() } else { kept };        if kept.trim().is_empty() { Value::Null } else { Value::from(kept) }    };    let mut tells: Vec<String> = Vec::new();    let mut waiting = false;    match text(request, "table") {        Some("todo") => {            let todo = todo_or_gone(ctx, request)?;            let note = match note {                Some(note) => Some(laid(todo_notes(ctx, &todo.id)?, note)),                None => None,            };            if let Some(title) = request.get("title") {                let title = title.as_str().map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("`title` is words"))?;                own.insert("title".into(), Value::from(title));            }            if let Some(note) = note {                own.insert("notes".into(), note);            }            write_columns(ctx, "todo", &todo.id, own)?;            move_todo(ctx, request, &todo)?;            match request.get("group") {                None => {}                Some(Value::Null) => file_into(ctx, &todo.id, None)?,                Some(Value::String(group)) => file_into(ctx, &todo.id, Some(group))?,                Some(other) => return Err(bad(format!("`group` is a group's id or null, not {other}"))),            }        }        Some("event") => {            let row = event_row(ctx, &id)?.ok_or_else(|| gone(words))?;            let master = row.text("series_id").map(|series| event_row(ctx, series)).transpose()?.flatten();            let google = row.text("gcal_id").is_some() || master.as_ref().is_some_and(|m| m.text("gcal_id").is_some());            let moves = ["title", "day", "time", "end", "length"].iter().any(|key| request.get(*key).is_some());            let received = row.text("invited") == Some("invited") || master.as_ref().is_some_and(|m| m.text("invited") == Some("invited"));            let wanted = super::days_people::wanted_list(request)?;            if received && (moves || wanted.is_some()) {                return Err(MethodError::new("not_yours", super::days_people::line("people.organizer_changes")?));            }            if google && (moves || wanted.is_some()) {                google_may_change(heard)?;            }            if let Some(note) = note {                let column = if google { "your_note" } else { "notes" };                own.insert(column.into(), laid(row.text(column).map(str::to_string), note));            }            match request.get("alert") {                None => {}                // Back to the ten-minute default (what an event that never named one does).                Some(Value::Null) => {                    own.insert("alert".into(), Value::Null);                }                Some(Value::String(word)) if word == ALERT_NONE => {                    own.insert("alert".into(), Value::from(NO_ALERT));                }                Some(minutes) => {                    let most = crate::phone::reminders::MOST_LEAD_MINUTES;                    let minutes = minutes.as_i64().filter(|m| (0..=most).contains(m)).ok_or_else(|| bad(format!("`alert` is minutes before, at most {most}, \"none\" or null")))?;                    own.insert("alert".into(), Value::from(minutes));                }            }            if let Some(title) = request.get("title") {                let title = title.as_str().map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("`title` is words"))?;                own.insert("title".into(), Value::from(title));            }            let own_note_on_google = !google && request.get("note").is_some();            write_columns(ctx, "event", &id, own)?;            move_event(ctx, request, &id, heard)?;            // The people: who hears of it, and whether Google must (CONTRACT.md section 15).            let owner = row.text("series_id").filter(|_| row.text("original_starts_at").is_some()).unwrap_or(&id).to_string();            let mut to_send = false;            if let Some(wanted) = &wanted {                let held = super::days_people::guests(ctx, &owner)?;                tells = super::days_people::tells(&held, wanted, heard, moves)?;                if google {                    super::days_people::adopt_google(ctx, &owner, master.as_ref().unwrap_or(&row).text("guest_responses"))?;                }                to_send |= super::days_people::set(ctx, &owner, wanted, heard)?;            } else if moves {                let held = super::days_people::guests(ctx, &owner)?;                if held.iter().any(|g| !g.removed && !g.organizer) {                    tells.push(super::days_people::line("people.tell_change")?);                }            }            let fresh = event_row(ctx, &id)?.ok_or_else(|| gone(words))?;            let on_google = fresh.int("on_google").unwrap_or(0) != 0 || master.as_ref().is_some_and(|m| m.int("on_google").unwrap_or(0) != 0);            if to_send || (on_google && !google && (moves || own_note_on_google)) || (google && (moves || wanted.is_some())) {                // One occurrence of a series is its own row now, found by the send pass; the series is not sent again.                let one_occurrence = text(request, "occurrenceAt").is_some() && row.text("rrule").is_some() && wanted.is_none();                if !one_occurrence {                    to_google(ctx, &id)?;                }                waiting = true;            }            // Cotton guests are sent the new version by the invitations pass, which compares what each was sent.            if !waiting && super::days_people::guests(ctx, &owner)?.iter().any(|g| g.via == super::days_people::Via::Cotton) {                waiting = true;            }            let _ = fresh;        }        _ => return Err(bad("`table` is event or todo")),    }    let mut answer = json!({ "id": id, "changed": true });    if waiting {        answer["google"] = json!("waiting");    }    if !tells.is_empty() {        answer["tells"] = json!(tells);    }    if let Some(both_kept) = merged {        answer["merged"] = json!(true);        answer["both_kept"] = json!(both_kept);        let merged_line = if both_kept { "change.merged_both" } else { "change.merged" };        let said = cotton_core::rules::shell_lines::LineSet::shipped("days").and_then(|lines| lines.say(merged_line, &[]));        answer["said"] = json!(said.ok_or_else(|| MethodError::new("unreadable", format!("the days set says no line {merged_line}")))?);    }    Ok(answer)}/// `days.tell { table: "event", id, people, title?, day?, time?, end?, length? }`: what saving that list would say/// (CONTRACT.md section 15).fn tell(ctx: &mut Ctx<'_>, request: &Value, heard: &Heard) -> Result<Value, MethodError> {    let id = text(request, "id").ok_or_else(|| bad("`id` names the event"))?;    let row = event_row(ctx, id)?.ok_or_else(|| gone(said(request)))?;    // An invitation received tells nobody: its people are the organizer's (the emulator walk, 22 Nov 2026: the    // guest's own sheet said "Rose gets it in Days." of the person who invited them).    let master = row.text("series_id").map(|series| event_row(ctx, series)).transpose()?.flatten();    if row.text("invited") == Some("invited") || master.as_ref().is_some_and(|m| m.text("invited") == Some("invited")) {        return Ok(json!({ "lines": [], "blocked": null }));    }    let owner = row.text("series_id").filter(|_| row.text("original_starts_at").is_some()).unwrap_or(id).to_string();    let held = super::days_people::guests(ctx, &owner)?;    let wanted = super::days_people::wanted_list(request)?.unwrap_or_else(|| {        held.iter().filter(|g| !g.removed && !g.organizer).map(|g| super::days_people::Wanted { email: g.email.clone(), number: g.phone.clone(), name: g.name.clone() }).collect()    });    let moves = ["title", "day", "time", "end", "length"].iter().any(|key| request.get(*key).is_some());    let lines = super::days_people::tells(&held, &wanted, heard, moves)?;    let diff = super::days_people::diff(&held, &wanted, heard);    let blocked = if diff.added.iter().any(|(_, via)| *via == super::days_people::Via::None) {        json!({ "line": super::days_people::line("people.blocked")?, "connect": super::days_people::connect_act(heard)? })    } else {        Value::Null    };    Ok(json!({ "lines": lines, "blocked": blocked }))}/// `days.add { words, timezone, today, where, dayInView?, day?, time?, end?, mark? }`.fn add(ctx: &mut Ctx<'_>, request: &Value) -> Result<Value, MethodError> {    let zone = zone_arg(request)?;    let line = request.get("words").and_then(Value::as_str).unwrap_or_default();    let today = day_arg(request, "today")?;    let got = when::read(line, today, language(request));    let (mut day, _) = settled(request, &got)?;    match request.get("day") {        Some(Value::Null) => day = None,        Some(_) => day = Some(day_arg(request, "day")?),        None => {}    }    let time = match request.get("time") {        Some(Value::Null) => None,        Some(_) => minute_arg(request, "time")?,        None => got.time,    };    let end = match request.get("end") {        Some(Value::Null) => None,        Some(_) => minute_arg(request, "end")?,        None if request.get("time").is_some() => None,        None => got.end,    };    let title = if got.title.is_empty() { line.trim().to_string() } else { got.title.clone() };    if title.is_empty() {        return Err(bad("there is nothing to add"));    }    let mark = mark_arg(request)?.flatten();    let group = group_arg(ctx, request)?;    let (table, id) = match (day, time) {        // With a group chosen it is always a to-do, so it stays in view.        (Some(day), Some(start)) if group.is_none() => {            let starts = join_moment(&MomentSplit { date: day_key(day), time: Some(hhmm(start)) }, &zone).map_err(sql)?;            let finish = end.unwrap_or(start + 60);            let end_day = if finish >= 24 * 60 || finish <= start { day + 1 } else { day };            let ends = join_moment(&MomentSplit { date: day_key(end_day), time: Some(hhmm(finish % (24 * 60))) }, &zone).map_err(sql)?;            let made = events::create_event(ctx, &args(json!({ "title": title, "startsAt": starts, "endsAt": ends, "timezone": zone }))).map_err(tool)?;            ("event", made.get("id").and_then(Value::as_str).unwrap_or_default().to_string())        }        _ => {            let mut asked = json!({ "title": title });            if let Some(day) = day {                asked["dueDate"] = Value::from(day_key(day));                asked["timezone"] = Value::from(database_zone(ctx, &zone)?);                if let Some(minute) = time.filter(|_| group.is_some()) {                    asked["dueTime"] = Value::from(hhmm(minute));                    asked["timezone"] = Value::from(zone.clone());                }            }            let made = todos::create_todo(ctx, &args(asked)).map_err(tool)?;            ("todo", made.get("id").and_then(Value::as_str).unwrap_or_default().to_string())        }    };    if let Some(mark) = mark {        let mut patch = Map::new();        patch.insert("mark".into(), Value::from(mark));        write_columns(ctx, table, &id, patch)?;    }    if let Some(group) = &group {        file_into(ctx, &id, Some(&group.id))?;    }    let shown = if table == "event" || group.is_some() { time.filter(|_| day.is_some()) } else { None };    Ok(json!({ "table": table, "id": id, "day": day.map(day_key), "time": clock_of(shown) }))}#[path = "days_views.rs"]mod views;#[path = "days_export.rs"]mod export;#[cfg(test)]#[path = "days_tests.rs"]pub(crate) mod tests;#[cfg(test)]#[path = "days_three_tests.rs"]mod three_tests;#[cfg(test)]#[path = "days_ends_tests.rs"]mod ends_tests;