Cotton code
2337 lines · 123.9 KB · RustRaw
//! Cotton Data on this phone: the screens' methods (assets/design/data/CONTRACT.md//! "The core calls each screen needs"). What is inside the database, read only.//!//! ```text//! data.welcome data.tables data.room data.rows data.row data.stored data.link//! data.about data.columns data.links data.search data.assistants data.leftovers//! data.keep data.keep.set data.you//! ```//!//! **Read only.** No method here writes a row, a definition or a setting of//! the database. The one write is this device's own choice for Keep//! everything (a file beside the layout, never the database), which//! `data_app_tests::reading_changes_nothing` proves: every method read against//! a file, the file byte for byte the same.//!//! **Where facts come from.** The definitions from the object (`GET//! /v1/definitions`, every table), else the phone's own definition rows.//! Rows from the object's pages (`/v1/data/page`, else `/v1/older` for a dated//! table; `/v1/rows` by id), each opened here with the database's key, as//! Comms opens its older mail. Counts and room from `/v1/data/tables`, said as//! "Counting…" until the object answers it. What assistants read from the//! synced `assistant_read`. Every word from `cotton_core::data` and its line set.use std::collections::{BTreeMap, HashMap};use std::sync::Mutex;use serde_json::{json, Map, Value};use cotton_core::data::{self as rules, rows, say, Group, Seal};use cotton_core::definitions::TableDefinition;use crate::methods::MethodError;use crate::shell::client::ClientController;/// Every method this module answers.pub const METHODS: [&str; 24] = [    "data.about",    "data.assistants",    "data.columns",    "data.dates",    "data.export",    "data.export.plan",    "data.keep",    "data.keep.set",    "data.keep.pause",    "data.keep.resume",    "data.keep.mobile_once",    "data.lately",    "data.leftovers",    "data.link",    "data.links",    "data.media",    "data.room",    "data.row",    "data.rows",    "data.search",    "data.stored",    "data.tables",    "data.welcome",    "data.you",];/// Answer one `data.*` method.pub fn call(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    // What is hidden in Cinemas is learnt afresh for each answer (HIDDEN, below).    let forget = || {        HIDDEN.with(|h| *h.borrow_mut() = None);        SAID.with(|said| said.set(None));    };    forget();    let answer = answer(client, method, request);    forget();    answer}fn answer(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "data.keep.pause" | "data.keep.resume" | "data.keep.mobile_once" => keep_act(client, method, request),        "data.welcome" => welcome(client, request),        "data.tables" => tables(client, request),        "data.room" => room(client),        "data.rows" => rows_of(client, request),        "data.dates" => dates(client, request),        "data.export.plan" => export_plan(client, request),        "data.export" => export(client, request),        "data.row" => row(client, request),        "data.stored" => stored(client, request),        "data.link" => link(client, request),        "data.about" => about(client, request),        "data.columns" => columns(client, request),        "data.links" => links(client, request),        "data.search" => search(client, request),        "data.assistants" => assistants(client),        "data.leftovers" => leftovers(client),        "data.lately" => lately(client, request),        "data.media" => media(client, request),        "data.keep" => keep(client, request),        "data.keep.set" => keep_set(client, request),        "data.you" => you(client),        other => Err(MethodError::new("unknown_method", format!("`{other}` is not a data method"))),    }}// ── facts ─────────────────────────────────────────────────────────────────/// One table as the object defines it: typed, and as stored (for the seal rule).#[derive(Clone)]struct Table {    def: TableDefinition,    raw: Value,}impl Table {    fn id(&self) -> &str {        &self.def.id    }    fn internal(&self) -> bool {        self.raw["internal"] == Value::Bool(true)    }}/// What the object measured of one table (`/v1/data/tables`).#[derive(Clone, Default)]struct Measure {    rows: Option<u64>,    tombstones: Option<u64>,    bytes: Option<u64>,    oldest: Option<i64>,    newest: Option<i64>,}/// The definitions, remembered a minute per database (they change only when a kit moves).fn definitions(client: &ClientController) -> Result<Vec<Table>, MethodError> {    static KEPT: Mutex<Option<(String, i64, Vec<Table>)>> = Mutex::new(None);    let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;    let now = client.now().timestamp_millis();    if let Some((db, at, tables)) = KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() {        if *db == database && now - at < 60_000 {            return Ok(tables.clone());        }    }    let raw: Vec<Value> = match get(client, "/v1/definitions") {        Ok(answer) => answer["tables"].as_array().cloned().unwrap_or_default(),        Err(_) => local_definitions(client)?,    };    let mut tables: Vec<Table> = raw.into_iter().filter_map(|raw| Some(Table { def: serde_json::from_value(raw.clone()).ok()?, raw })).collect();    tables.sort_by(|a, b| a.def.id.cmp(&b.def.id));    tables.dedup_by(|a, b| a.def.id == b.def.id);    *KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((database, now, tables.clone()));    Ok(tables)}fn local_definitions(client: &ClientController) -> Result<Vec<Value>, MethodError> {    client        .read_rows("data.definitions", &mut |ctx| {            let rows = cotton_tools::definitions::definition_rows(ctx, None).map_err(|failure| failure.to_string())?;            Ok(Value::Array(rows.into_iter().filter_map(|row| serde_json::from_str::<Value>(&row.definition).ok()).filter(|v| v["columns"].is_array()).collect()))        })        .map(|v| v.as_array().cloned().unwrap_or_default())        .map_err(|why| MethodError::new("unreadable", why))}fn table(client: &ClientController, id: &str) -> Result<Table, MethodError> {    definitions(client)?.into_iter().find(|t| t.id() == id).ok_or_else(|| refused("no_table", "refused.no_table", &[("table", id)]))}/// The object's measure, by table; empty when it has none to give (offline, or a Worker without the route yet).fn measures(client: &ClientController) -> (HashMap<String, Measure>, Value) {    let Some(answer) = measured(client) else { return (HashMap::new(), Value::Null) };    let ms = |v: &Value| v.as_i64().or_else(|| v.as_str().and_then(instant_ms));    let by = answer["tables"]        .as_array()        .into_iter()        .flatten()        .filter_map(|t| {            Some((t["table"].as_str()?.to_string(), Measure { rows: t["rows"].as_u64(), tombstones: t["tombstones"].as_u64(), bytes: t["bytes"].as_u64(), oldest: ms(&t["oldest"]), newest: ms(&t["newest"]) }))        })        .collect::<HashMap<String, Measure>>();    // A table the answer does not list holds no row: the server counts only tables with rows (`row_counts` before    // the first measure, the measure after). Said as "No rows", never "Counting…"; its room is known only once a    // measure has run (a big object's first takes hours), so until then no "0 bytes" is said beside it. An answer    // with no measure and no table at all is the server still counting (`row_counts` not ready): every table says    // Counting…, never "No rows" (the owner's find of 26 Nov: "media: No rows · 0 bytes" right after sign-in).    let mut by = by;    let measured = !answer["measured"].is_null();    let counted = measured || !by.is_empty();    if answer["tables"].is_array() && counted {        for t in definitions(client).unwrap_or_default() {            let zero = measured.then_some(0);            by.entry(t.id().to_string()).or_insert(Measure { rows: Some(0), tombstones: zero, bytes: zero, oldest: None, newest: None });        }    }    (by, answer)}/// The object's measure (`/v1/data/tables`), remembered half a minute per database (DATA iPhone 3): every screen's/// lead says a table's rows from it, and while a sync pass runs the server answers each ask in seconds. The measure/// itself moves only when the server's alarm measures again (hours apart); the copy's own counts are read fresh./// A measure that did not come is remembered too, for 15 s: a server that cannot be reached is not waited on again by/// every screen that asks in the meantime (each wait is up to the request's minute).fn measured(client: &ClientController) -> Option<Value> {    static KEPT: Mutex<Option<(String, i64, Option<Value>)>> = Mutex::new(None);    let database = client.current_database().ok()?;    let now = client.now().timestamp_millis();    if let Some((db, at, answer)) = KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner).as_ref() {        let keep = if answer.is_some() { 30_000 } else { 15_000 };        if *db == database && now - at < keep {            return answer.clone();        }    }    let answer = get(client, "/v1/data/tables").ok();    *KEPT.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((database, now, answer.clone()));    answer}fn instant_ms(text: &str) -> Option<i64> {    chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.timestamp_millis()).or_else(|| chrono::NaiveDate::parse_from_str(text.get(..10)?, "%Y-%m-%d").ok().and_then(|d| d.and_hms_opt(12, 0, 0)).map(|t| t.and_utc().timestamp_millis()))}fn get(client: &ClientController, path: &str) -> Result<Value, MethodError> {    let door = client.object_door().ok_or_else(|| refused("offline", "refused.offline", &[]))?;    door.send("GET", path, None).map_err(|why| {        tracing::warn!("data: {path} did not come ({}: {})", why.code, why.message);        // Every answer is said in the app's words: a route the server does not have yet (an older deploy), the owner        // check, or anything else. The server's own English never reaches a screen.        match why.code.as_str() {            "offline" | "not_connected" => refused("offline", "refused.offline", &[]),            "owner_only" | "token_scopes" | "forbidden" => refused(&why.code, "refused.not_owner", &[]),            code if code == "not_found" || code == "404" || why.message.contains("nothing answers") => refused("not_yet", "refused.not_yet", &[]),            code => refused(code, "refused.failed", &[]),        }    })}fn part(value: &str) -> String {    url::form_urlencoded::byte_serialize(value.as_bytes()).collect()}fn refused(code: &str, line: &str, fills: &[(&str, &str)]) -> MethodError {    MethodError::new(code, say(line, fills))}/// Opened rows of `table` from one of the object's pages, each `{ id, created_at, updated_at, data… }`.fn opened(client: &ClientController, table: &str, page: &Value) -> Result<Vec<(Map<String, Value>, Value)>, MethodError> {    let open = open_rows(client, table, page)?;    Ok(shown_of(client, table, open))}/// `rows`, less those hidden in Cinemas (a family table's): what was left out, or could not be told, is said once/// for the answer (`said_hidden`).fn shown_of(client: &ClientController, table: &str, rows: Vec<(Map<String, Value>, Value)>) -> Vec<(Map<String, Value>, Value)> {    if !FAMILY.contains(&table) {        return rows;    }    let before = rows.len();    let kept: Vec<(Map<String, Value>, Value)> = match hides_by(client, table) {        Ok(hides) => rows.into_iter().filter(|(open, _)| !hides(open)).collect(),        Err(()) => {            say_hidden(true);            return Vec::new();        }    };    if kept.len() < before {        say_hidden(false);    }    kept}// ── hidden in Cinemas ──────────────────────────────────────────────────────/// HIDE FROM SCREEN (owner, 27 Nov 2026): Data does not show a title hidden in Cinemas, nor a hidden category, by THE/// predicate's one rule (`cotton_tools::…::tables::hidden::rule`): on a phone holding the whole object, the predicate/// on its copy itself; otherwise the same rule over the object's pages of his films' tables. A row is left out when/// it is hidden or names a hidden one by a link (a play's film, a link's record, …)./// The whole set is learnt once an answer. When it cannot be (a read failing, not offline), no row of the family is/// shown and a line says why. A family table says one plain line when it leaves something out. Counts the object keeps/// (a table's rows) are said as they come: they cannot leave a row out.use cotton_tools::mcp::handlers::tables::hidden::{Hiding as HiddenSet, RuleRows};use cotton_tools::mcp::handlers::tables::hidden::FAMILY;/// Whether a row carries `key` set (a category's own flag, clear on the row).fn flag(value: Option<&Value>) -> bool {    matches!(value, Some(Value::Bool(true))) || value.and_then(Value::as_i64) == Some(1)}thread_local! {    /// The hidden set of the answer being made on this thread (Err: it could not be learnt), learnt once.    static HIDDEN: std::cell::RefCell<Option<Result<std::sync::Arc<HiddenSet>, ()>>> = const { std::cell::RefCell::new(None) };    /// What this answer says of Hidden: Some(false) something was left out, Some(true) it could not tell.    static SAID: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };}fn say_hidden(unknown: bool) {    SAID.with(|said| said.set(Some(said.get().unwrap_or(false) || unknown)));}/// The line this answer says of Hidden, if any.fn said_hidden() -> Option<String> {    SAID.with(|said| said.get()).map(|unknown| say(if unknown { "rows.hidden_unknown" } else { "rows.hidden_note" }, &[]))}/// What is hidden, learnt once an answer: Err when it cannot be.fn hidden_set(client: &ClientController) -> Result<std::sync::Arc<HiddenSet>, ()> {    if let Some(known) = HIDDEN.with(|h| h.borrow().clone()) {        return known;    }    let learnt = learn_hidden(client).map(std::sync::Arc::new);    HIDDEN.with(|h| *h.borrow_mut() = Some(learnt.clone()));    learnt}fn learn_hidden(client: &ClientController) -> Result<HiddenSet, ()> {    // A phone holding the whole object asks the predicate on its copy (binned categories too).    if hidden_here(client) {        let mut hiding = HiddenSet::default();        client            .read_rows("data.hidden", &mut |ctx| {                hiding = crate::phone::cinemas_home::hiding(ctx)?;                Ok(Value::Null)            })            .map_err(|_| ())?;        return Ok(hiding);    }    // Else every row of each family table from the object, opened (a row that does not open is None): a table this    // object does not hold, or offline, reads as none; any other failure means nothing can be told.    let mut all: HashMap<&str, Vec<(Option<Map<String, Value>>, Value)>> = HashMap::new();    for table in FAMILY.iter().filter(|t| **t != "watch") {        let rows = match every_row(client, table) {            Ok(rows) => rows,            Err(why) if ["offline", "not_yet", "no_table", "not_found"].contains(&why.code.as_str()) => Vec::new(),            Err(_) => return Err(()),        };        all.insert(table, rows);    }    let rows = |table: &str| all.get(table).map(Vec::as_slice).unwrap_or_default();    let text = |open: &Option<Map<String, Value>>, wire: &Value, key: &str| open.as_ref().and_then(|o| o.get(key)).and_then(Value::as_str).or_else(|| wire["data"][key].as_str()).unwrap_or_default().to_string();    let id_of = |wire: &Value| wire["id"].as_str().unwrap_or_default().to_string();    let hidden_flag = |open: &Option<Map<String, Value>>, wire: &Value| flag(open.as_ref().and_then(|o| o.get("hidden"))) || flag(wire["data"].get("hidden"));    let rule_rows = RuleRows {        groups: rows("record_group").iter().map(|(open, wire)| (id_of(wire), text(open, wire, "table_id"), hidden_flag(open, wire))).collect(),        members: rows("group_member").iter().map(|(open, wire)| (text(open, wire, "group"), text(open, wire, "record_id"))).collect(),        seasons: rows("film_season").iter().map(|(open, wire)| (id_of(wire), text(open, wire, "film"))).collect(),        episodes: rows("film_episode").iter().map(|(open, wire)| (id_of(wire), text(open, wire, "series"), text(open, wire, "season"))).collect(),        files: rows("fetch_file").iter().map(|(open, wire)| (id_of(wire), text(open, wire, "film"), text(open, wire, "series"), text(open, wire, "episode"), text(open, wire, "fetch"))).collect(),        // The Data app tells a play by its film or episode link (`hides`), as it reads each row.        plays: Vec::new(),    };    Ok(cotton_tools::mcp::handlers::tables::hidden::rule(&rule_rows))}/// How `table`'s opened rows are told hidden; Err when it cannot be told.fn hides_by(client: &ClientController, _table: &str) -> Result<Box<dyn Fn(&Map<String, Value>) -> bool>, ()> {    let hidden = hidden_set(client)?;    Ok(Box::new(move |open| hidden.hides(open.get("id").and_then(Value::as_str), open)))}/// Of `ids` of `table`, those not to be shown: each read and told by its own row; one that does not come or open, or/// cannot be told, is not shown.fn hidden_among(client: &ClientController, table: &str, ids: &[String]) -> std::collections::HashSet<String> {    if !FAMILY.contains(&table) || ids.is_empty() {        return Default::default();    }    let Ok(hides) = hides_by(client, table) else {        say_hidden(true);        return ids.iter().cloned().collect();    };    let mut shown = std::collections::HashSet::new();    for chunk in ids.chunks(50) {        let joined = chunk.iter().map(|id| part(id)).collect::<Vec<_>>().join(",");        let opened = get(client, &format!("/v1/rows?table={}&ids={joined}", part(table))).ok().and_then(|answer| open_rows(client, table, &answer).ok()).unwrap_or_default();        for (open, _) in opened {            if !hides(&open) {                shown.insert(open["id"].as_str().unwrap_or_default().to_string());            }        }    }    let out: std::collections::HashSet<String> = ids.iter().filter(|id| !shown.contains(*id)).cloned().collect();    if !out.is_empty() {        say_hidden(false);    }    out}/// Every row of `table` at the object, each opened (None: it did not open) beside the row as served.fn every_row(client: &ClientController, table: &str) -> Result<Vec<(Option<Map<String, Value>>, Value)>, MethodError> {    if hidden_here(client) {        if let Some(t) = definitions(client)?.into_iter().find(|t| t.id() == table) {            if let Some(local) = here(client, &t, None, None, 10_000_000, &Order::default()) {                return Ok(local["rows"].as_array().into_iter().flatten().filter_map(|row| Some((Some(row["data"].as_object()?.clone()).map(|mut open| {                    open.insert("id".into(), row["id"].clone());                    open                }), row.clone()))).collect());            }        }    }    let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;    let keys: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = client.data_keys().clone();    let sealer = cotton_client::seal::Sealer::new(database, keys);    let mut out = Vec::new();    let mut after: Option<(String, String)> = None;    for _ in 0..200 {        let mut path = format!("/v1/data/page?table={}&limit=500", part(table));        if let Some((at, id)) = &after {            path.push_str(&format!("&before={}&id={}", part(at), part(id)));        }        let answer = get(client, &path)?;        let served = answer["rows"].as_array().cloned().unwrap_or_default();        for row in &served {            let (Some(id), Some(data)) = (row["id"].as_str(), row["data"].as_object()) else { continue };            let open = sealer.open(table, id, data).ok().map(|mut open| {                open.insert("id".into(), Value::from(id));                open            });            out.push((open, row.clone()));        }        after = served.last().and_then(|r| Some((r["created_at"].as_str()?.to_string(), r["id"].as_str()?.to_string())));        if answer["more"].as_bool() != Some(true) || after.is_none() {            break;        }    }    Ok(out)}/// Every row of `page`, opened here (none left out).fn open_rows(client: &ClientController, table: &str, page: &Value) -> Result<Vec<(Map<String, Value>, Value)>, MethodError> {    let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;    let keys: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = client.data_keys().clone();    let sealer = cotton_client::seal::Sealer::new(database, keys);    let mut out = Vec::new();    for row in page["rows"].as_array().into_iter().flatten() {        let (Some(id), Some(data)) = (row["id"].as_str(), row["data"].as_object()) else { continue };        match sealer.open(table, id, data) {            Ok(mut open) => {                open.insert("id".into(), Value::from(id));                out.push((open, row.clone()));            }            // A row that does not open is left out of the page and said in the log, never drawn blank.            Err(error) => tracing::warn!("data: {table} {id} did not open ({})", error.code()),        }    }    Ok(out)}// ── this phone's own copy ──────────────────────────────────────────────────/// DATA iPhone 3 (the owner's build 2, 27 Nov 2026: with his copy's first pass running, every table he opened stood/// blank). Every read here went to the server, several round trips an answer, while the server was answering his/// pass in 2 to 10 s a request; and the phone already held 4.3 GB of it. With Keep everything holding the whole/// object, a table's rows, one row and the names its links point at come from this phone's copy first, in/// milliseconds; the server answers only what the copy does not hold (a table not here yet, rows past what has come)./// Rows on the phone are kept opened, so nothing is opened again; they come shaped as the server's wire rows/// (`{ id, data, created_at, updated_at }`), so every reader below reads them the same way.fn reads_here(client: &ClientController, t: &Table) -> bool {    !t.internal() && !rules::secret_table(t.id()) && t.def.engine.is_none() && t.def.store_table().is_none() && keeps_whole(client)}/// Rows of `t` from this phone's copy: by `ids`, or a page newest first (made, or changed) after `after`, within the/// order's range. None when the copy does not hold the table or cannot be read: the server is asked instead.fn here(client: &ClientController, t: &Table, ids: Option<&[String]>, after: Option<(&str, &str)>, limit: usize, order: &Order) -> Option<Value> {    if !reads_here(client, t) {        return None;    }    let table = t.def.rows_table().to_string();    let def = t.def.clone();    let cursor = if order.changed { "updated_at" } else { "created_at" };    let read = client.read_rows("data.here", &mut |ctx| {        use rusqlite::types::Value as Sql;        if !cotton_tools::mcp::handlers::tables::made_held(ctx, &table).map_err(|failure| failure.to_string())? {            return Ok(Value::Null);        }        let mut sql = format!("SELECT * FROM {} WHERE workspace_id = ? AND deleted_at IS NULL", cotton_tools::mcp::handlers::tables::made_table(&table));        let mut params = vec![Sql::Text(ctx.workspace_id.to_string())];        if let Some(ids) = ids {            sql.push_str(&format!(" AND id IN ({})", vec!["?"; ids.len().max(1)].join(",")));            params.extend(ids.iter().map(|id| Sql::Text(id.clone())));            if ids.is_empty() {                params.push(Sql::Null);            }        } else {            if let Some(from) = &order.from {                sql.push_str(" AND created_at >= ?");                params.push(Sql::Text(from.clone()));            }            if let Some(to) = &order.to {                sql.push_str(" AND created_at < ?");                params.push(Sql::Text(to.clone()));            }            if let Some((at, id)) = after {                sql.push_str(&format!(" AND ({cursor} < ? OR ({cursor} = ? AND id < ?))"));                params.extend([Sql::Text(at.to_string()), Sql::Text(at.to_string()), Sql::Text(id.to_string())]);            }            sql.push_str(&format!(" ORDER BY {cursor} DESC, id DESC LIMIT {}", limit + 1));        }        let found = ctx.read.driver().all(&sql, &params).map_err(|error| error.to_string())?;        let mut rows: Vec<Value> = found            .iter()            .map(|row| {                let stored = cotton_tools::mcp::handlers::tables::stored_from_row(&def, row);                json!({ "table": def.id, "id": stored.id, "data": serde_json::to_value(&stored.data).unwrap_or_else(|_| json!({})), "created_at": stored.created_at, "updated_at": stored.updated_at })            })            .collect();        let more = ids.is_none() && rows.len() > limit;        rows.truncate(if ids.is_some() { rows.len() } else { limit });        Ok(json!({ "rows": rows, "more": more, "here": true }))    });    match read {        Ok(page) if !page.is_null() => Some(page),        Ok(_) => None,        Err(why) => {            tracing::warn!("data: {} not read on this phone ({why})", t.id());            None        }    }}/// Whether the hidden set may be learnt from this phone's copy: it holds the whole object and its first sync owes none/// of Cinemas' tables. A copy still on its first pull may hold a title and not yet the category that hides it, so it/// asks the server, where every row is (doubt goes toward hidden).fn hidden_here(client: &ClientController) -> bool {    keeps_whole(client) && crate::phone::first_sync::of(client, Some(&FAMILY[..])).is_none()}/// A page of `table`'s live rows, newest first: `/v1/data/page`, else `/v1/older` by its clear date.fn page(client: &ClientController, t: &Table, after: Option<(&str, &str)>, limit: usize) -> Result<Value, MethodError> {    page_by(client, t, after, limit, &Order::default())}/// How a table's rows are asked: newest made first (the default) or recently changed, within a made range.#[derive(Default)]struct Order {    changed: bool,    from: Option<String>,    to: Option<String>,}impl Order {    fn plain(&self) -> bool {        !self.changed && self.from.is_none() && self.to.is_none()    }}fn page_by(client: &ClientController, t: &Table, after: Option<(&str, &str)>, limit: usize, order: &Order) -> Result<Value, MethodError> {    if t.internal() {        return Err(refused("internal", "refused.internal", &[]));    }    // This phone's copy first. While its first sync still owes this table, the rows past what has come are the    // server's: the last page here says there is more, and the next page, finding none here, asks the server.    if let Some(mut local) = here(client, t, None, after, limit, order) {        let owed = crate::phone::first_sync::of(client, Some(&[t.id()][..])).is_some();        if local["rows"].as_array().is_some_and(|rows| !rows.is_empty()) {            if local["more"] != Value::Bool(true) && owed {                local["more"] = Value::Bool(true);            }            return Ok(local);        }        // Nothing here and nothing owed: the table is empty, said at once, never a wait on the server.        if !owed {            return Ok(local);        }    }    let mut path = format!("/v1/data/page?table={}&limit={limit}", part(t.id()));    if order.changed {        path.push_str("&order=changed");    }    if let Some(from) = &order.from {        path.push_str(&format!("&from={}", part(from)));    }    if let Some(to) = &order.to {        path.push_str(&format!("&to={}", part(to)));    }    if let Some((at, id)) = after {        path.push_str(&format!("&before={}&id={}", part(at), part(id)));    }    match get(client, &path) {        Ok(answer) => Ok(answer),        Err(why) if why.code == "offline" => Err(why),        // An older object's /v1/older orders by made only: a sort or a range it can't keep is said, never ignored.        Err(_) if !order.plain() => Err(refused("not_yet", "refused.not_yet", &[])),        Err(_) => {            let mut older = format!("/v1/older?table={}&limit={limit}", part(t.id()));            if let Some((at, id)) = after {                older.push_str(&format!("&before={}&id={}", part(at), part(id)));            }            get(client, &older).map_err(|why| if why.code == "offline" { why } else { refused("no_order", "refused.no_order", &[]) })        }    }}/// Names of linked rows, fetched once per table and kept for this answer.struct Names<'a> {    client: &'a ClientController,    tables: &'a [Table],    kept: Mutex<HashMap<(String, String), Option<String>>>,}impl<'a> Names<'a> {    fn new(client: &'a ClientController, tables: &'a [Table]) -> Self {        Names { client, tables, kept: Mutex::new(HashMap::new()) }    }    /// Fetch the names of `ids` in `table` in one ask.    fn learn(&self, table: &str, ids: &[String]) {        let Some(t) = self.tables.iter().find(|t| t.id() == table) else { return };        let missing: Vec<&String> = {            let kept = self.kept.lock().unwrap();            ids.iter().filter(|id| !kept.contains_key(&(table.to_string(), (*id).clone()))).take(50).collect()        };        if missing.is_empty() || rules::secret_table(table) {            return;        }        let title = |answer: &Value| -> HashMap<String, String> {            opened(self.client, table, answer)                .unwrap_or_default()                .into_iter()                .map(|(row, _)| (row["id"].as_str().unwrap_or_default().to_string(), rows::sentence(&t.def, &row, &|_, _| None).title))                .collect()        };        let asked: Vec<String> = missing.iter().map(|id| (*id).clone()).collect();        let mut found: HashMap<String, String> = here(self.client, t, Some(&asked), None, asked.len(), &Order::default()).map(|local| title(&local)).unwrap_or_default();        let away: Vec<&String> = missing.iter().copied().filter(|id| !found.contains_key(*id)).collect();        if !away.is_empty() {            let joined = away.iter().map(|id| part(id)).collect::<Vec<_>>().join(",");            if let Ok(answer) = get(self.client, &format!("/v1/rows?table={}&ids={joined}", part(table))) {                found.extend(title(&answer));            }        }        let mut kept = self.kept.lock().unwrap();        for id in missing {            kept.insert((table.to_string(), id.clone()), found.get(id).cloned());        }    }    fn name(&self, table: &str, id: &str) -> Option<String> {        self.kept.lock().unwrap().get(&(table.to_string(), id.to_string())).cloned().flatten()    }}/// Learn the names every link of `rows` points at, a table at a time.fn learn_links(names: &Names<'_>, def: &TableDefinition, rows: &[&Map<String, Value>]) {    for column in def.columns.iter().filter(|c| c.column_type == cotton_core::definitions::ColumnType::Link) {        let Some(target) = &column.link_to else { continue };        let ids: Vec<String> = rows            .iter()            .flat_map(|r| match r.get(&column.key) {                Some(Value::String(s)) => vec![s.clone()],                Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).map(str::to_string).collect(),                _ => Vec::new(),            })            .collect();        names.learn(target, &ids);    }}fn apps_line(apps: &[&str]) -> String {    match apps.len() {        0 => String::new(),        1 => apps[0].to_string(),        _ => format!("{} and {}", apps[..apps.len() - 1].join(", "), apps[apps.len() - 1]),    }}/// The other apps beside a table's line: up to three named, more named two and counted, and every other app said so/// (a table each app keeps, as `media`, would list ten). The table's own page names them all.fn also_line(also: &[&str]) -> String {    if also.len() + 1 >= rules::FAMILY.len() {        say("tables.also_every", &[])    } else if also.len() > 3 {        say("tables.also_more", &[("apps", &also[..2].join(", ")), ("n", &(also.len() - 2).to_string())])    } else {        say("tables.also", &[("apps", &apps_line(also))])    }}fn row_ms(wire: &Value, key: &str) -> Option<i64> {    wire[key].as_i64().or_else(|| wire[key].as_str().and_then(instant_ms))}// ── the screens ───────────────────────────────────────────────────────────fn welcome(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let (measured, answer) = measures(client);    let rows_bytes = rows_bytes(&measured, &answer);    let free = free_bytes(client, request);    // Before the server's first measure the rows' room is not known: the whole file is the most it can be, and is said    // as that ("up to"), never as the rows' own (owner, build 1: "4.3 GB, about 144 minutes" was the whole file).    let most = rows_bytes_most(&measured, &answer);    let cost = rows_bytes.map(|b| say(if most { "welcome.keep_cost_most" } else { "welcome.keep_cost" }, &[("size", &rules::size(if most { b } else { rules::kept_bytes(b) })), ("minutes", &minutes(rules::fill_minutes(b))), ("free", &rules::size(free))]));    Ok(json!({        "title": say("welcome.title", &[]),        "lead": say("welcome.lead", &[]),        "only_looks": say("welcome.only_looks", &[]),        "keep": { "on": rows_bytes.is_some_and(|b| rules::keep_starts_on(b, free)), "title": say("keep.title", &[]), "cost_line": cost, "off_line": say("welcome.keep_off", &[]) },        "start": say("welcome.start", &[]),    }))}/// The room this phone has free: only the app side can read the number the system enforces, so the phone passes/// it as `free`; otherwise the core's own reading, else nothing.fn free_bytes(client: &ClientController, request: &Value) -> u64 {    request["free"].as_u64().or_else(|| client.disk().free_bytes(client.layout().root())).unwrap_or(0)}/// A fill's minutes as said: in minutes up to an hour and a half, in hours (rounded) beyond.fn minutes(n: u64) -> String {    if n >= 90 {        return say("say.hours", &[("n", &((n + 30) / 60).to_string())]);    }    say("say.minutes", &[("n", &n.to_string())])}/// The bytes a phone keeping everything would hold: the measured rows part, else the tables' bytes summed.fn rows_bytes(measured: &HashMap<String, Measure>, answer: &Value) -> Option<u64> {    if let Some(&rows) = parts_of(&answer["parts"]).get("rows") {        return Some(rows);    }    let sum: u64 = measured.values().filter_map(|m| m.bytes).sum();    // A small database's answer carries no room per table (it is counted as asked, not measured): its whole file is    // the most its rows can take, so Keep everything is costed on that.    (sum > 0).then_some(sum).or_else(|| answer["database"]["bytes"].as_u64().filter(|b| *b > 0))}/// Whether [`rows_bytes`] is only the most the rows can take (the whole file, before a measure), not their own room.fn rows_bytes_most(measured: &HashMap<String, Measure>, answer: &Value) -> bool {    !parts_of(&answer["parts"]).contains_key("rows") && measured.values().filter_map(|m| m.bytes).sum::<u64>() == 0}/// One table's line on the Tables list.fn table_line(t: &Table, m: Option<&Measure>, also: &[&str], now: i64) -> Value {    let rows_line = match m.and_then(|m| m.rows) {        Some(n) => rules::rows_line(n),        None => say("tables.counting", &[]),    };    let mut line = rows_line.clone();    if !also.is_empty() {        line = format!("{line} \u{b7} {}", also_line(also));    }    let _ = now;    json!({        "table": t.id(),        "rows_line": rows_line,        "line": line,        // A table with no row has no room to say: "No rows" alone, never "No rows · 0 bytes" (owner, build 1).        "room_line": m.filter(|m| m.rows != Some(0)).and_then(|m| m.bytes).map(rules::size),        "mark": matches!(rules::seal_of(&t.raw), Seal::Pending).then_some("server_reads"),        "on_phone": false,        "openable": !t.internal(),    })}fn tables(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let all = definitions(client)?;    let (measured, answer) = measures(client);    let now = client.now().timestamp_millis();    let q = request["q"].as_str().map(str::to_lowercase).filter(|q| !q.trim().is_empty());    let by = request["by"].as_str().unwrap_or("app");    let shown: Vec<&Table> = all.iter().filter(|t| q.as_ref().is_none_or(|q| t.id().contains(q.as_str()) || t.def.name.to_lowercase().contains(q.as_str()))).collect();    let mut groups: Vec<Value> = Vec::new();    let mut leftovers = (0u64, 0u64);    if by == "app" {        let mut by_group: BTreeMap<(usize, String), Vec<Value>> = BTreeMap::new();        for t in &shown {            let m = measured.get(t.id());            let (order, title, also) = match rules::group_of(t.id(), t.internal()) {                Group::App { app, also } => (rules::FAMILY.iter().position(|(l, _)| *l == app).unwrap_or(0), app.to_string(), also),                Group::Assistants { also } => (100, say("tables.assistants", &[]), also),                Group::Cotton => (200, say("tables.cotton", &[]), Vec::new()),                Group::Retired => {                    leftovers.0 += 1;                    leftovers.1 += 1;                    continue;                }                Group::Unused => {                    leftovers.0 += 1;                    continue;                }            };            by_group.entry((order, title)).or_default().push(table_line(t, m, &also, now));        }        for ((_, title), mut lines) in by_group {            lines.sort_by_key(|l| std::cmp::Reverse(l["table"].as_str().and_then(|id| measured.get(id)).and_then(|m| m.bytes).unwrap_or(0)));            groups.push(json!({ "title": title, "count_line": say("tables.count", &[("n", &lines.len().to_string())]), "tables": lines }));        }    } else {        let mut lines: Vec<(&Table, Value)> = shown.iter().map(|t| (*t, table_line(t, measured.get(t.id()), &[], now))).collect();        match by {            "biggest" => lines.sort_by_key(|(t, _)| std::cmp::Reverse(measured.get(t.id()).and_then(|m| m.bytes).unwrap_or(0))),            "lately" => lines.sort_by_key(|(t, _)| std::cmp::Reverse(measured.get(t.id()).and_then(|m| m.newest).unwrap_or(0))),            _ => lines.sort_by(|a, b| a.0.id().cmp(b.0.id())),        }        groups.push(json!({ "title": Value::Null, "tables": lines.into_iter().map(|(_, l)| l).collect::<Vec<_>>() }));    }    let database = &answer["database"];    let room = match (database["bytes"].as_u64(), database["cap"].as_u64()) {        (Some(used), Some(cap)) => json!({ "used_line": rules::size(used), "line": say("tables.room", &[("used", &rules::size(used)), ("cap", &rules::size(cap))]), "share": used as f64 / cap.max(1) as f64, "go": say("tables.room_go", &[]) }),        _ => Value::Null,    };    let left_line = say("tables.leftovers_line", &[("n", &leftovers.0.to_string())]);    let leftovers_line = if leftovers.1 > 0 { say("tables.leftovers_retired", &[("line", &left_line), ("retired", &leftovers.1.to_string())]) } else { left_line };    let any_pending = all.iter().any(|t| matches!(rules::seal_of(&t.raw), Seal::Pending));    Ok(json!({        "title": say("tables.title", &[]),        "count": all.len(),        "search": say("tables.search", &[("n", &all.len().to_string())]),        "room": room,        "chips": [            { "id": "app", "title": say("tables.by_app", &[]), "on": by == "app" },            { "id": "biggest", "title": say("tables.biggest", &[]), "on": by == "biggest" },            { "id": "lately", "title": say("tables.lately", &[]), "on": by == "lately" },            { "id": "az", "title": say("tables.az", &[]), "on": by == "az" },        ],        "groups": groups,        "leftovers": (by == "app" && leftovers.0 > 0).then(|| json!({ "title": say("tables.leftovers", &[]), "line": leftovers_line, "count": leftovers.0 })),        "foot": any_pending.then(|| say("tables.server_reads", &[])),    }))}/// The parts Where room goes names, from the server's measure of the file: `storage_summary`'s `parts`, each store table/// and index with the bytes its entries carry (apps/business/src/storage_parts.ts, `{ file, parts: [{ name, kind, of?,/// entries, bytes }], carried, overhead }`). The change log (and the act log kept to its window) is the change history;/// the `rows` table is the rows; the blind index's tables are search; `links`, and the indexes that order the rows, are/// links and order. What is left (the shell's own tables, headers and free room on pages) is the rest of the file./// ANDROID READY 1 core fault 6: this read `parts.rows`, `parts.changes` and so on, which no server answers, so on dev/// the page showed Free alone.fn parts_of(parts: &Value) -> HashMap<&'static str, u64> {    let mut by: HashMap<&'static str, u64> = HashMap::new();    for p in parts["parts"].as_array().into_iter().flatten() {        let name = p["name"].as_str().unwrap_or_default();        let index = p["kind"] == json!("index");        let table = if index { p["of"].as_str().unwrap_or(name) } else { name };        let id = match table {            "change" | "change_size" | "acts" => "changes",            "blind" | "blind_row" | "blind_rid" => "search",            "links" => "links",            "rows" if index => "links",            "rows" => "rows",            _ => continue,        };        *by.entry(id).or_default() += p["bytes"].as_u64().unwrap_or(0);    }    by}fn room(client: &ClientController) -> Result<Value, MethodError> {    let (measured, answer) = measures(client);    if answer.is_null() {        return Err(refused("offline", "refused.offline", &[]));    }    let used = answer["database"]["bytes"].as_u64().unwrap_or(0);    let cap = answer["database"]["cap"].as_u64().unwrap_or(9_500_000_000);    let parts = parts_of(&answer["parts"]);    let named = [("changes", "room.changes", "room.changes_line", true), ("rows", "room.rows", "room.rows_line", false), ("search", "room.search", "room.search_line", true), ("links", "room.links", "room.links_line", true)];    let mut list = vec![json!({ "id": "free", "name": say("room.free", &[]), "size_line": rules::size(cap.saturating_sub(used)), "line": say("room.free_line_plain", &[]), "share": cap.saturating_sub(used) as f64 / cap.max(1) as f64, "stays_on_server": false })];    let mut known = 0u64;    for (id, name, line, stays) in named {        if let Some(&bytes) = parts.get(id) {            known += bytes;            list.push(json!({ "id": id, "name": say(name, &[]), "size_line": rules::size(bytes), "line": say(line, &[]), "share": bytes as f64 / cap.max(1) as f64, "stays_on_server": stays }));        }    }    if known > 0 && used > known {        list.push(json!({ "id": "other", "name": say("room.other", &[]), "size_line": rules::size(used - known), "line": say("room.other_line", &[]), "share": (used - known) as f64 / cap.max(1) as f64, "stays_on_server": true }));    }    let mut biggest: Vec<(&String, &Measure)> = measured.iter().filter(|(_, m)| m.bytes.is_some()).collect();    biggest.sort_by_key(|(_, m)| std::cmp::Reverse(m.bytes.unwrap_or(0)));    let top = biggest.first().and_then(|(_, m)| m.bytes).unwrap_or(1).max(1);    let deleted: u64 = measured.values().filter_map(|m| m.tombstones).sum();    Ok(json!({        "title": say("room.title", &[]),        "lead": say("room.lead", &[("used", &rules::size(used)), ("cap", &rules::size(cap))]),        "parts": list,        "biggest_title": say("room.biggest", &[]),        "biggest_note": say("room.rows_only", &[]),        "biggest": biggest.iter().take(4).map(|(t, m)| json!({ "table": t, "size_line": rules::size(m.bytes.unwrap_or(0)), "share": m.bytes.unwrap_or(0) as f64 / top as f64 })).collect::<Vec<_>>(),        "deleted_line": (deleted > 0).then(|| rules::rows_line(deleted)),        "measured_line": answer["measured"]["at"].as_str().and_then(instant_ms).map(|at| say("room.measured", &[("when", &rules::ago(at, client.now().timestamp_millis()))])),    }))}fn rows_of(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let all = definitions(client)?;    let t = all.iter().find(|t| t.id() == id).cloned().ok_or_else(|| refused("no_table", "refused.no_table", &[("table", id)]))?;    let (measured, _) = measures(client);    let m = measured.get(id).cloned().unwrap_or_default();    let apps = rules::apps_of(id);    let lead = format!("{} \u{b7} {}", m.rows.map(rules::rows_line).unwrap_or_else(|| say("tables.counting", &[])), if apps.is_empty() { say("rows.used_by_none", &[]) } else { say("rows.used_by", &[("apps", &apps_line(&apps))]) });    if let Some(q) = request["q"].as_str().map(str::trim).filter(|q| q.chars().count() >= 2) {        let (found, _, _) = find_rows(client, &all, &q.to_lowercase(), Some(&t), 100);        let rows: Vec<Value> = found.into_iter().flat_map(|(_, rows)| rows).collect();        return Ok(json!({            "table": id,            "lead": lead,            "q": q,            "groups": if rows.is_empty() { json!([]) } else { json!([{ "title": rules::rows_line(rows.len() as u64), "count": rows.len(), "rows": rows }]) },            "more": false,            "hidden_note": said_hidden(),            "empty": rows.is_empty().then(|| json!({ "title": say("search.nothing", &[("q", q)]), "body": say("search.try_word", &[("word", q.split_whitespace().next().unwrap_or(q))]) })),        }));    }    let after = match (request["after"]["at"].as_str(), request["after"]["id"].as_str()) {        (Some(at), Some(rid)) => Some((at, rid)),        _ => None,    };    let limit = 50;    let order = order_of(client, request)?;    let answer = page_by(client, &t, after, limit, &order)?;    if !has_key(client) && matches!(rules::seal_of(&t.raw), Seal::Sealed { .. }) {        // A Cinemas table on a phone without the key: it cannot tell which rows are hidden, so it shows none of them        // (the reviewers' Hidden rules), not even as the server holds them, and says why.        if FAMILY.contains(&t.id()) {            let mut view = sealed_view(client, &t, &json!({ "rows": [] }), lead);            view["hidden_note"] = json!(say("rows.hidden_no_key", &[]));            return Ok(view);        }        return Ok(sealed_view(client, &t, &answer, lead));    }    let opened = opened(client, id, &answer)?;    let hidden_note = said_hidden();    let names = Names::new(client, &all);    learn_links(&names, &t.def, &opened.iter().map(|(r, _)| r).collect::<Vec<_>>());    let mut groups: Vec<(String, Vec<Value>)> = Vec::new();    let mut from_fields: Vec<String> = Vec::new();    let now = client.now().timestamp_millis();    for (open, wire) in &opened {        let s = rows::sentence(&t.def, open, &|table, rid| names.name(table, rid));        if from_fields.is_empty() {            from_fields = s.from.clone();        }        let made = row_ms(wire, if order.changed { "updated_at" } else { "created_at" });        let month = made.map(|ms| chrono::DateTime::from_timestamp_millis(ms).map(|t| t.format("%B %Y").to_string()).unwrap_or_default()).unwrap_or_default();        let line = json!({ "id": open["id"], "title": s.title, "line": s.line, "when": made.map(|ms| rules::ago(ms, now)) });        match groups.last_mut() {            Some((title, rows)) if *title == month => rows.push(line),            _ => groups.push((month, vec![line])),        }    }    let cursor = if order.changed { "updated_at" } else { "created_at" };    let last = opened.last().map(|(open, wire)| json!({ "at": wire[cursor], "id": open["id"] }));    let empty = opened.is_empty() && after.is_none();    Ok(json!({        "table": id,        "lead": lead,        "search": m.rows.map(|n| say("rows.search", &[("n", &rules::count(n))])),        "sort": if order.changed { "changed" } else { "made" },        "sort_line": say(if order.changed { "rows.sort.changed" } else { "rows.sort.made" }, &[]),        "date_line": range_line(client, request),        "groups": groups.into_iter().map(|(title, rows)| json!({ "title": title, "count": rows.len(), "rows": rows })).collect::<Vec<_>>(),        "more": answer["more"].as_bool().unwrap_or(false),        "after": last,        "foot": (!from_fields.is_empty()).then(|| say("rows.foot", &[("fields", &from_fields.join(", "))])),        "hidden_note": hidden_note,        "empty": empty.then(|| json!({            "title": say("rows.empty_title", &[]),            "body": match apps.first() { Some(app) => say("rows.empty_body", &[("app", app), ("columns", &t.def.columns.len().to_string())]), None => say("rows.empty_body_none", &[("columns", &t.def.columns.len().to_string())]) },            "act": say("rows.see_columns", &[]),        })),    }))}/// A day the phone passes (`2026-11-25`) or an instant, as the instant the Worker compares: a day starts at its UTC/// midnight, and a `to` day is kept whole (it ends at the next midnight).fn instant_of(text: &str, end: bool) -> Option<String> {    if let Ok(day) = chrono::NaiveDate::parse_from_str(text, "%Y-%m-%d") {        let day = if end { day.succ_opt()? } else { day };        return Some(format!("{}T00:00:00.000Z", day.format("%Y-%m-%d")));    }    chrono::DateTime::parse_from_rfc3339(text).ok().map(|t| t.with_timezone(&chrono::Utc).format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string())}/// `data.rows`' `sort` and made range. Only when made and last changed can be ordered by the server: every other/// column may be sealed, so a sort by title is refused in words rather than drawn unsorted.fn order_of(_client: &ClientController, request: &Value) -> Result<Order, MethodError> {    let changed = match request["sort"].as_str() {        None | Some("made") => false,        Some("changed") => true,        Some(_) => return Err(refused("no_sort", "refused.no_sort", &[])),    };    if request["date"].as_str().is_some_and(|d| d != "made") {        return Err(refused("no_sort", "refused.no_date", &[]));    }    let at = |key: &str, end: bool| -> Result<Option<String>, MethodError> {        match request[key].as_str() {            None => Ok(None),            Some(text) => instant_of(text, end).map(Some).ok_or_else(|| MethodError::new("bad_request", format!("{key} is a day (2026-11-25) or an instant"))),        }    };    Ok(Order { changed, from: at("from", false)?, to: at("to", true)? })}/// What the made range says: Any time, This month, a year, or the picked days.fn range_line(client: &ClientController, request: &Value) -> String {    let (from, to) = (request["from"].as_str(), request["to"].as_str());    let Some(from) = from else {        return match to {            None => say("rows.any_time", &[]),            Some(to) => say("rows.until", &[("to", to)]),        };    };    let today = client.now().date_naive();    let month = today.format("%Y-%m-01").to_string();    match to {        None if from == month => say("rows.this_month", &[]),        Some(to) if from.ends_with("-01-01") && to.len() == 10 && to.ends_with("-12-31") && from[..4] == to[..4] => from[..4].to_string(),        None => say("rows.since", &[("from", from)]),        Some(to) => say("rows.range", &[("from", from), ("to", to)]),    }}/// `data.dates { table }`: Sort and dates' sheet. The sorts the server can keep, the one date column it can filter/// (made: every other date may be sealed), the rows per year as bars, and the ranges the phone passes back to/// `data.rows` as they are.fn dates(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let all = definitions(client)?;    let t = all.iter().find(|t| t.id() == id).cloned().ok_or_else(|| refused("no_table", "refused.no_table", &[("table", id)]))?;    if t.internal() {        return Err(refused("internal", "refused.internal", &[]));    }    let years: Vec<Value> = get(client, &format!("/v1/data/years?table={}", part(id))).map_err(|why| if why.code == "offline" { why } else { refused("not_yet", "refused.not_yet", &[]) })?["years"]        .as_array()        .cloned()        .unwrap_or_default();    let most = years.iter().filter_map(|y| y["rows"].as_u64()).max().unwrap_or(0);    let today = client.now().date_naive();    let month = today.format("%Y-%m-01").to_string();    let mut ranges = vec![json!({ "id": "any", "title": say("rows.any_time", &[]) }), json!({ "id": "month", "title": say("rows.this_month", &[]), "from": month })];    for y in &years {        if let Some(year) = y["year"].as_u64() {            ranges.push(json!({ "id": year.to_string(), "title": year.to_string(), "from": format!("{year}-01-01"), "to": format!("{year}-12-31") }));        }    }    ranges.push(json!({ "id": "pick", "title": say("rows.pick", &[]), "pick": true }));    Ok(json!({        "table": id,        "title": say("rows.dates", &[]),        "sorts": [            { "id": "made", "title": say("rows.sort.made", &[]), "line": say("rows.sort.made_line", &[]), "on": request["sort"].as_str().unwrap_or("made") == "made" },            { "id": "changed", "title": say("rows.sort.changed", &[]), "on": request["sort"].as_str() == Some("changed") },        ],        "sorts_line": say("rows.sorts_line", &[]),        "which_date": say("rows.which_date", &[]),        "columns": [{ "id": "made", "title": say("rows.made", &[]), "on": true }],        "years": years.iter().map(|y| {            let rows = y["rows"].as_u64().unwrap_or(0);            json!({ "year": y["year"], "rows": rows, "rows_line": rules::rows_line(rows), "share": if most == 0 { 0.0 } else { rows as f64 / most as f64 } })        }).collect::<Vec<_>>(),        "ranges": ranges,        "now": range_line(client, request),        // The sheet's button: how many rows the range set shows, where the year bars or the table's measure say it.        "show": shown_rows(client, id, request, &years).map(|n| say("rows.show", &[("n", &rules::count(n))])),    }))}/// How many rows a range shows, where it can be known without asking: Any time is the table's measure, a whole year/// its bar; a month or picked days are not counted ahead.fn shown_rows(client: &ClientController, table: &str, request: &Value, years: &[Value]) -> Option<u64> {    match (request["from"].as_str(), request["to"].as_str()) {        (None, None) => measures(client).0.get(table).and_then(|m| m.rows),        (Some(from), Some(to)) if from.len() == 10 && from.ends_with("-01-01") && to.ends_with("-12-31") && from[..4] == to[..4] => {            years.iter().find(|y| y["year"].as_u64().map(|n| n.to_string()).as_deref() == Some(&from[..4])).and_then(|y| y["rows"].as_u64())        }        _ => None,    }}/// A table Export may write: not internal, not a Secrets table, opened on this phone.fn exportable(client: &ClientController, request: &Value) -> Result<Table, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let t = table(client, id)?;    if t.internal() {        return Err(refused("internal", "refused.internal", &[]));    }    if rules::secret_table(id) {        return Err(refused("secret", "export.never", &[]));    }    if !has_key(client) && matches!(rules::seal_of(&t.raw), Seal::Sealed { .. }) {        return Err(refused("no_key", "locked.no_key", &[]));    }    Ok(t)}/// `data.export.plan { table }`: Export's sheet, before anything is written. Spreadsheet or For developers, each with/// about its size (the table's measured room: an opened row is about the size it is sealed), and that the file is not/// sealed, said before the button.fn export_plan(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let t = exportable(client, request)?;    let (measured, _) = measures(client);    let m = measured.get(t.id()).cloned().unwrap_or_default();    let size = m.bytes.map(|b| say("export.about", &[("size", &rules::size(b))]));    Ok(json!({        "table": t.id(),        "title": say("export.title", &[("table", t.id())]),        "lead": m.rows.map(|n| say("export.lead", &[("rows", &rules::rows_line(n))])),        "options": [            { "as": "csv", "title": say("export.csv", &[]), "size_line": size },            { "as": "json", "title": say("export.json", &[]), "size_line": size },        ],        "not_sealed": say("export.not_sealed", &[]),        "not_sealed_line": say("export.not_sealed_line", &[]),        "make": say("export.make", &[]),        "never_line": say("export.never", &[]),    }))}/// A value as one spreadsheet cell: text as it is, anything else as its JSON.fn csv_cell(value: &Value) -> String {    let text = match value {        Value::Null => String::new(),        Value::String(s) => s.clone(),        other => other.to_string(),    };    if text.contains([',', '"', '\n', '\r']) {        format!("\"{}\"", text.replace('"', "\"\""))    } else {        text    }}/// `data.export { table, as: csv | json }`: every live row of the table, opened, as one file under the phone's/// exports folder, for the share sheet. Only one Data export is kept there: an earlier one is removed first. Files and/// photos are listed by their key, never included. Refuses whole if a page fails, rather than write part of a table.fn export(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let t = exportable(client, request)?;    let csv = match request["as"].as_str() {        Some("csv") => true,        Some("json") => false,        _ => return Err(MethodError::new("bad_request", "as is csv or json")),    };    let mut rows: Vec<(Map<String, Value>, Value)> = Vec::new();    let mut after: Option<(String, String)> = None;    loop {        let answer = page(client, &t, after.as_ref().map(|(a, b)| (a.as_str(), b.as_str())), 500)?;        let got = open_rows(client, t.id(), &answer)?;        let served = answer["rows"].as_array().map_or(0, Vec::len);        if served > got.len() {            // A row that would not open: an export leaving it out would be a file that says less than the table holds.            return Err(refused("failed", "refused.failed", &[]));        }        after = got.last().and_then(|(open, wire)| Some((wire["created_at"].as_str()?.to_string(), open["id"].as_str()?.to_string())));        // A row hidden in Cinemas is not in the file either (HIDDEN).        rows.extend(shown_of(client, t.id(), got));        if answer["more"].as_bool() != Some(true) || after.is_none() {            break;        }    }    let columns: Vec<String> = t.def.columns.iter().map(|c| c.key.clone()).collect();    let body = if csv {        let mut out = String::new();        let head: Vec<String> = ["id", "created_at", "updated_at"].iter().map(|s| s.to_string()).chain(columns.iter().cloned()).collect();        out.push_str(&head.iter().map(|h| csv_cell(&Value::from(h.as_str()))).collect::<Vec<_>>().join(","));        out.push_str("\r\n");        for (open, wire) in &rows {            let cells: Vec<String> = [&open["id"], &wire["created_at"], &wire["updated_at"]].into_iter().cloned().chain(columns.iter().map(|c| open.get(c).cloned().unwrap_or(Value::Null))).map(|v| csv_cell(&v)).collect();            out.push_str(&cells.join(","));            out.push_str("\r\n");        }        out.into_bytes()    } else {        let items: Vec<Value> = rows            .iter()            .map(|(open, wire)| {                let mut item = Map::new();                item.insert("id".into(), open["id"].clone());                item.insert("created_at".into(), wire["created_at"].clone());                item.insert("updated_at".into(), wire["updated_at"].clone());                for c in &columns {                    if let Some(v) = open.get(c) {                        item.insert(c.clone(), v.clone());                    }                }                Value::Object(item)            })            .collect();        serde_json::to_vec_pretty(&json!({ "table": t.id(), "exported_at": client.now().to_rfc3339(), "columns": columns, "rows": items })).unwrap_or_default()    };    let dir = client.layout().exports_dir();    std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("io", e.to_string()))?;    let name = format!("cotton-data-{}-{}.{}", t.id(), client.now().format("%Y-%m-%d"), if csv { "csv" } else { "json" });    for entry in std::fs::read_dir(&dir).into_iter().flatten().flatten() {        let old = entry.file_name();        if old.to_str().is_some_and(|o| o.starts_with("cotton-data-") && o != name) {            // not a copy: an earlier export.            let _ = std::fs::remove_file(entry.path());        }    }    let path = dir.join(&name);    // not a copy: Data's own files (an export, the kept choice).    std::fs::write(&path, &body).map_err(|e| MethodError::new("io", e.to_string()))?;    Ok(json!({        "table": t.id(),        "path": path.display().to_string(),        "name": name,        "rows": rows.len(),        "size_line": rules::size(body.len() as u64),        "line": say("export.made", &[("rows", &rules::rows_line(rows.len() as u64)), ("size", &rules::size(body.len() as u64))]),        "not_sealed_line": say("export.not_sealed_line", &[]),    }))}/// One row of a table, opened: from `/v1/rows`.fn one_row(client: &ClientController, t: &Table, rid: &str) -> Result<(Map<String, Value>, Value), MethodError> {    if t.internal() {        return Err(refused("internal", "refused.internal", &[]));    }    let ids = [rid.to_string()];    let answer = match here(client, t, Some(&ids), None, 1, &Order::default()) {        Some(local) if local["rows"].as_array().is_some_and(|rows| !rows.is_empty()) => local,        _ => get(client, &format!("/v1/rows?table={}&ids={}", part(t.id()), part(rid)))?,    };    opened(client, t.id(), &answer)?.into_iter().find(|(r, _)| r["id"].as_str() == Some(rid)).ok_or_else(|| refused("no_row", "refused.no_row", &[]))}fn clear_of(t: &Table) -> Vec<String> {    match rules::seal_of(&t.raw) {        Seal::Sealed { clear } => clear,        _ => t.def.columns.iter().map(|c| c.key.clone()).collect(),    }}fn row(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let rid = request["id"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the row"))?;    let all = definitions(client)?;    let t = all.iter().find(|t| t.id() == id).cloned().ok_or_else(|| refused("no_table", "refused.no_table", &[("table", id)]))?;    // A phone without the key sees one sealed row as the server holds it: facts only, never a word of what is sealed.    if !has_key(client) && matches!(rules::seal_of(&t.raw), Seal::Sealed { .. }) && !t.internal() {        // One row of a Cinemas table, by its id, without the key: it could be a hidden title's; not shown.        if FAMILY.contains(&t.id()) {            return Err(refused("no_row", "refused.no_row", &[]));        }        let answer = get(client, &format!("/v1/rows?table={}&ids={}", part(t.id()), part(rid)))?;        let wire = answer["rows"].as_array().into_iter().flatten().find(|r| r["id"].as_str() == Some(rid)).cloned().ok_or_else(|| refused("no_row", "refused.no_row", &[]))?;        return Ok(sealed_row(&t, rid, &wire));    }    let (open, wire) = one_row(client, &t, rid)?;    let names = Names::new(client, &all);    learn_links(&names, &t.def, &[&open]);    let name = |table: &str, rid: &str| names.name(table, rid);    let s = rows::sentence(&t.def, &open, &name);    let fields = rows::fields(&t.def, &open, &clear_of(&t), &name);    let now = client.now().timestamp_millis();    let made = row_ms(&wire, "created_at").map(rules::day).unwrap_or_default();    let changed = row_ms(&wire, "updated_at").filter(|u| row_ms(&wire, "created_at").is_none_or(|c| u - c > 60_000)).map(|u| rules::ago(u, now));    let lead = match changed {        Some(changed) => say("row.lead_changed", &[("table", id), ("made", &made), ("changed", &changed)]),        None => say("row.lead", &[("table", id), ("made", &made)]),    };    let points = points_here(client, &all, &t, rid);    let apps = rules::apps_of(id);    let mut trail: Vec<Value> = request["trail"].as_array().cloned().unwrap_or_default();    trail.push(json!({ "table": id, "id": rid, "name": s.title }));    Ok(json!({        "table": id,        "id": rid,        "title": s.title,        "lead": lead,        "trail": trail,        "fields": fields,        "points_here": points,        "points_title": say("row.points_here", &[]),        "several_note": t.def.columns.iter().any(|c| c.column_type == cotton_core::definitions::ColumnType::Link && c.multiple == Some(true)).then(|| say("row.several_not_counted", &[])),        "stored": say("row.stored", &[]),        "foot": match apps.first() { Some(app) => say("row.read_only", &[("app", app)]), None => say("row.read_only_none", &[]) },    }))}/// The rows that point at this one (`/v1/data/points`), each group named and its rows said; empty without the route.fn points_here(client: &ClientController, all: &[Table], _t: &Table, rid: &str) -> Vec<Value> {    let Ok(answer) = get(client, &format!("/v1/data/points?table={}&id={}", part(_t.id()), part(rid))) else { return Vec::new() };    let names = Names::new(client, all);    let mut out = Vec::new();    for group in answer["points"].as_array().into_iter().flatten() {        let (Some(table), Some(column)) = (group["table"].as_str(), group["column"].as_str()) else { continue };        let mut ids: Vec<String> = group["ids"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();        // A row hidden in Cinemas is not said to point here (HIDDEN); its count is left out with it.        let mut count = group["count"].clone();        if FAMILY.contains(&table) {            let shut = hidden_among(client, table, &ids);            if !shut.is_empty() {                ids.retain(|id| !shut.contains(id));                count = count.as_u64().map(|n| json!(n.saturating_sub(shut.len() as u64))).unwrap_or(count);            }            if ids.is_empty() {                continue;            }        }        names.learn(table, &ids);        out.push(json!({            "table": table,            "column": column,            "through_line": say("row.through", &[("column", column)]),            "count": count,            "rows": ids.iter().map(|id| json!({ "table": table, "id": id, "title": names.name(table, id).unwrap_or_else(|| id.clone()) })).collect::<Vec<_>>(),        }));    }    out}fn stored(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let rid = request["id"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the row"))?;    let t = table(client, id)?;    let (open, _) = one_row(client, &t, rid)?;    Ok(json!({ "fields": rows::stored(&t.def, &open).into_iter().map(|(column, stored)| json!({ "column": column, "stored": stored })).collect::<Vec<_>>(), "plain": say("row.plain", &[]) }))}fn link(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let rid = request["id"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the row"))?;    let column = request["column"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the column"))?;    let t = table(client, id)?;    let (open, _) = one_row(client, &t, rid)?;    let address = open.get(column).and_then(Value::as_str).ok_or_else(|| refused("no_row", "refused.no_row", &[]))?.trim().to_string();    let title = rows::sentence(&t.def, &open, &|_, _| None).title;    let site = url::Url::parse(&address).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_default();    Ok(json!({        "title": say("link.title", &[]),        "from_line": say("link.from", &[("column", column), ("row", &title)]),        "address": address,        "site": site,        "open": say("link.open", &[]),        "copy": say("link.copy", &[]),        "copied": say("link.copied", &[]),        "note": say("link.note", &[]),    }))}fn about(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let t = table(client, id)?;    let (measured, _) = measures(client);    let m = measured.get(id).cloned().unwrap_or_default();    let mut facts = Vec::new();    match rules::seal_of(&t.raw) {        Seal::Sealed { clear } => {            let line = if clear.is_empty() { say("info.sealed_line", &[]) } else { say("info.sealed_clear", &[("n", &clear.len().to_string()), ("fields", &clear.join(", "))]) };            facts.push(json!({ "icon": "lock", "title": say("info.sealed", &[]), "line": line, "clear": clear }));        }        Seal::Open => facts.push(json!({ "icon": "open", "title": say("info.open", &[]), "line": say("info.open_line", &[]) })),        Seal::Pending => facts.push(json!({ "icon": "open", "title": say("info.pending", &[]), "line": say("info.pending_line", &[]) })),    }    let apps = rules::apps_of(id);    facts.push(if apps.is_empty() {        json!({ "icon": "app", "title": say("info.used_by_none", &[]), "line": Value::Null })    } else {        json!({ "icon": "app", "title": say("info.used_by", &[("apps", &apps_line(&apps))]), "line": say("info.used_line", &[("apps", apps[0])]) })    });    facts.push(assistant_fact(client, id));    facts.push(json!({ "icon": "phone", "title": say("info.on_phone_none", &[]), "line": say("info.on_phone_none_line", &[]) }));    if let Some(n) = m.tombstones.filter(|n| *n > 0) {        facts.push(json!({ "icon": "clock", "title": say("info.deleted", &[("n", &rules::count(n))]), "line": say("info.deleted_line", &[]) }));    }    let lead = match (m.rows, m.bytes, m.oldest, m.newest) {        (Some(0), _, _, _) => say("info.lead_empty", &[]),        (Some(rows), Some(bytes), Some(oldest), Some(newest)) => say("info.lead", &[("rows", &rules::rows_line(rows)), ("room", &rules::size(bytes)), ("oldest", &rules::day(oldest)), ("newest", &rules::ago(newest, client.now().timestamp_millis()))]),        (Some(rows), _, _, _) => rules::rows_line(rows),        _ => say("tables.counting", &[]),    };    let link_count = t.def.columns.iter().filter(|c| c.link_to.is_some()).count();    let mut rows = vec![        json!({ "id": "columns", "title": say("info.columns", &[]), "value_line": t.def.columns.len().to_string() }),        json!({ "id": "links", "title": say("info.links", &[]), "value_line": link_count.to_string() }),    ];    // Export, only where it may be made (not a Secrets table, opened on this phone): data.export.plan.    if exportable(client, request).is_ok() {        rows.push(json!({ "id": "export", "title": say("info.export", &[]), "method": "data.export.plan" }));    }    Ok(json!({        "table": id,        "title": say("info.title", &[("table", id)]),        "lead": lead,        "facts": facts,        "rows": rows,        "foot": say("info.foot", &[]),    }))}/// Which assistants may read a table, and when one last did (from the synced read log).fn assistant_fact(client: &ClientController, table: &str) -> Value {    if rules::secret_table(table) {        return json!({ "icon": "assistant", "title": say("info.never", &[]), "line": say("info.never_line", &[]) });    }    let reads = read_log(client);    let mine: Vec<&Value> = reads.iter().filter(|r| list_of(&r["tables"]).iter().any(|t| t == table)).collect();    let Some(last) = mine.first() else {        return json!({ "icon": "assistant", "title": say("info.assistants_none", &[]), "line": say("info.assistants_none_line", &[]) });    };    let mut who: Vec<String> = mine.iter().filter_map(|r| r["client"].as_str().map(str::to_string)).collect();    who.dedup();    let when = row_ms(last, "read_at").map(|ms| rules::ago(ms, client.now().timestamp_millis())).unwrap_or_default();    let rows = last["rows"].as_u64().unwrap_or(0);    json!({ "icon": "assistant", "title": say("info.assistants", &[("who", &apps_line(&who.iter().map(String::as_str).collect::<Vec<_>>()))]), "line": say("info.assistants_line", &[("when", &when), ("rows", &rules::rows_line(rows))]), "act": "assistants" })}fn list_of(value: &Value) -> Vec<String> {    let value = match value {        Value::String(text) => serde_json::from_str(text).unwrap_or(Value::Null),        other => other.clone(),    };    value.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()}/// The synced read log, newest first.fn read_log(client: &ClientController) -> Vec<Value> {    let Ok((_, file)) = crate::phone::unlock::copy(client) else { return Vec::new() };    let mut rows = crate::phone::unlock::rows(&file, crate::phone::unlock::READS).unwrap_or_default();    rows.sort_by_key(|r| std::cmp::Reverse(row_ms(r, "read_at").unwrap_or(0)));    rows}fn columns(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let t = table(client, id)?;    let seal = rules::seal_of(&t.raw);    let clear = match &seal {        Seal::Sealed { clear } => clear.clone(),        _ => Vec::new(),    };    let n = t.def.columns.len().to_string();    let list: Vec<Value> = t        .def        .columns        .iter()        .map(|c| {            let ty = match (&c.link_to, &c.choices) {                (Some(target), _) => say("columns.link_to", &[("table", target)]),                (_, Some(choices)) => say("columns.choice_of", &[("n", &choices.len().to_string())]),                _ => {                    let f = rows::field(&t.def, c, &Map::new(), false, &|_, _| None);                    let mut chars = f.type_line.chars();                    chars.next().map(|first| first.to_uppercase().collect::<String>() + chars.as_str()).unwrap_or_default()                }            };            json!({ "name": c.key, "type_line": ty, "clear": clear.contains(&c.key), "link": c.link_to })        })        .collect();    Ok(json!({        "title": say("info.columns", &[]),        "lead": if matches!(seal, Seal::Sealed { .. }) { say("columns.lead", &[("n", &n)]) } else { say("columns.lead_open", &[("n", &n)]) },        "clear_word": say("columns.clear", &[]),        "columns": list,    }))}fn links(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let all = definitions(client)?;    let t = all.iter().find(|t| t.id() == id).ok_or_else(|| refused("no_table", "refused.no_table", &[("table", id)]))?;    let out: Vec<Value> = t        .def        .columns        .iter()        .filter_map(|c| {            let target = c.link_to.as_ref()?;            let several = c.multiple == Some(true);            let through = if target == id { say("links.itself", &[("column", &c.key)]) } else if several { say("links.several", &[("column", &c.key)]) } else { say("links.through", &[("column", &c.key)]) };            Some(json!({ "table": target, "column": c.key, "through_line": through, "counted": !several, "count_line": several.then(|| say("links.not_counted", &[])) }))        })        .collect();    let inward: Vec<Value> = all        .iter()        .flat_map(|other| {            other.def.columns.iter().filter(|c| c.link_to.as_deref() == Some(id)).map(move |c| {                let several = c.multiple == Some(true);                json!({ "table": other.id(), "column": c.key, "through_line": if several { say("links.several", &[("column", &c.key)]) } else { say("links.through", &[("column", &c.key)]) }, "counted": !several, "count_line": several.then(|| say("links.not_counted", &[])) })            })        })        .collect();    // Two steps away: what the neighbours themselves point at, named once.    let mut two: Vec<String> = Vec::new();    for n in out.iter().chain(inward.iter()).filter_map(|v| v["table"].as_str()) {        if let Some(nt) = all.iter().find(|t| t.id() == n) {            for c in nt.def.columns.iter().filter_map(|c| c.link_to.clone()) {                if c != id && c != n && !two.contains(&c) && !out.iter().chain(inward.iter()).any(|v| v["table"] == json!(c)) {                    two.push(c);                }            }        }    }    Ok(json!({        "table": id,        "title": say("links.title", &[("table", id)]),        "lead": say("links.lead", &[]),        "out_title": say("links.out", &[]),        "in_title": say("links.in", &[]),        "out": out,        "in": inward,        "two_steps_line": (!two.is_empty()).then(|| say("links.two_steps", &[("line", &two.into_iter().take(6).collect::<Vec<_>>().join(", "))])),        "none": (t.def.columns.iter().all(|c| c.link_to.is_none()) && all.iter().all(|o| o.def.columns.iter().all(|c| c.link_to.as_deref() != Some(id)))).then(|| say("links.none", &[("table", id)])),    }))}/// Rows holding `q`: this phone's copy first (every word, letter by letter: `records.search`), then, for sealed tables/// the copy does not hold whole, the server's blind index (whole words: `seal.search`). With Keep everything keeping,/// the copy is the whole database and the server is not asked. `only` searches one table. The secret tables are/// never searched. Answers the hits by table, and how many tables each side searched.fn find_rows(client: &ClientController, all: &[Table], q: &str, only: Option<&Table>, per_table: usize) -> (Vec<(String, Vec<Value>)>, usize, usize) {    let (mut found, here, there) = find_rows_all(client, all, q, only, per_table);    // A row hidden in Cinemas is never found (HIDDEN): this phone's copy and the blind index both hold it.    for (table, rows) in found.iter_mut() {        let ids: Vec<String> = rows.iter().filter_map(|r| r["id"].as_str().map(str::to_string)).collect();        let shut = hidden_among(client, table, &ids);        rows.retain(|r| !r["id"].as_str().is_some_and(|id| shut.contains(id)));    }    found.retain(|(_, rows)| !rows.is_empty());    (found, here, there)}fn find_rows_all(client: &ClientController, all: &[Table], q: &str, only: Option<&Table>, per_table: usize) -> (Vec<(String, Vec<Value>)>, usize, usize) {    let searchable = |t: &&Table| !rules::secret_table(t.id()) && !t.internal();    let tables: Vec<&Table> = match only {        Some(t) => vec![t].into_iter().filter(searchable).collect(),        None => all.iter().filter(searchable).collect(),    };    let mut found: Vec<(String, Vec<Value>)> = Vec::new();    let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();    let mut add = |table: &str, id: &str, title: String, line: String, found: &mut Vec<(String, Vec<Value>)>| {        if !seen.insert((table.to_string(), id.to_string())) {            return;        }        let row = json!({ "table": table, "id": id, "title": title, "line": line });        match found.iter_mut().find(|(t, _)| t == table) {            Some((_, rows)) if rows.len() < per_table => rows.push(row),            Some(_) => {}            None => found.push((table.to_string(), vec![row])),        }    };    let kinds: Vec<&str> = tables.iter().map(|t| t.id()).collect();    let mut ask = json!({ "query": q, "limit": per_table.min(50) });    if only.is_some() {        ask["kinds"] = json!(kinds);    }    if let Ok(answer) = super::records::call(client, "records.search", &ask) {        for hit in answer["records"].as_array().or(answer["results"].as_array()).into_iter().flatten() {            let table = hit["table"].as_str().or(hit["kind"].as_str()).unwrap_or_default();            let Some(id) = hit["id"].as_str() else { continue };            if !kinds.contains(&table) {                continue;            }            add(table, id, hit["title"].as_str().unwrap_or(id).to_string(), hit["snippet"].as_str().unwrap_or_default().to_string(), &mut found);        }    }    let whole = holds_whole(client);    let here = if whole { tables.len() } else { tables.iter().filter(|t| !matches!(rules::seal_of(&t.raw), Seal::Sealed { .. })).count() };    if whole || !has_key(client) {        return (found, here, 0);    }    let (measured, _) = measures(client);    let mut beyond: Vec<&&Table> = tables.iter().filter(|t| matches!(rules::seal_of(&t.raw), Seal::Sealed { .. })).collect();    beyond.sort_by_key(|t| std::cmp::Reverse(measured.get(t.id()).and_then(|m| m.rows).unwrap_or(0)));    if only.is_none() {        beyond.retain(|t| measured.get(t.id()).and_then(|m| m.rows).unwrap_or(1) > 0);        beyond.truncate(BLIND_TABLES);    }    let there = beyond.len();    // Each table's blind ask is its own round trip to the server: asked side by side, so a search across everything    // takes about as long as its slowest table, not the sum (17 s for ten tables, one after another, on dev).    let Ok(database) = client.current_database() else { return (found, here, there) };    let asks: Vec<(&Table, cotton_core::definitions::seal::SealSpec)> = beyond        .into_iter()        .filter_map(|t| {            // The table's own seal block, else the shipped definition's, else the default rule's, as the object seals            // it: a definition table is not in the compiled storage map `seal.search` reads.            let shipped = cotton_core::kit::shipped_table(t.id()).and_then(|d| serde_json::to_value(d).ok());            let spec = cotton_client::seal::spec_of_definition(&t.raw)                .ok()                .flatten()                .or_else(|| shipped.as_ref().and_then(|d| cotton_client::seal::spec_of_definition(d).ok().flatten()))                .or_else(|| cotton_core::seal::rule::default_seal(shipped.as_ref().unwrap_or(&t.raw)))?;            (!spec.blind.is_empty()).then_some((*t, spec))        })        .collect();    let hits: Vec<(String, String, String, String)> = std::thread::scope(|scope| {        let running: Vec<_> = asks            .iter()            .map(|(t, spec)| {                let database = database.clone();                scope.spawn(move || {                    let keys: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = client.data_keys().clone();                    let sealer = cotton_client::seal::Sealer::new(database, keys);                    let date = t.raw["date"].as_str().map(str::to_string);                    let mut ask = |path: &str| get(client, path).map_err(|why| format!("{}: {}", why.code, why.message));                    let Ok(blind) = cotton_client::seal::search::search_beyond(&sealer, t.id(), spec, date.as_deref(), q, per_table, &|_| false, &mut ask) else { return Vec::new() };                    blind                        .hits                        .into_iter()                        .map(|hit| {                            let mut open = hit.row;                            open.entry("id").or_insert(json!(hit.id));                            let s = rows::sentence(&t.def, &open, &|_, _| None);                            (t.id().to_string(), hit.id, s.title, s.line)                        })                        .collect::<Vec<_>>()                })            })            .collect();        running.into_iter().flat_map(|r| r.join().unwrap_or_default()).collect()    });    for (table, id, title, line) in hits {        add(&table, &id, title, line, &mut found);    }    (found, here, there)}/// How many sealed tables a search across everything asks the server's blind index about, the biggest first.const BLIND_TABLES: usize = 12;/// Whether this phone's copy is the whole database: Keep everything chosen and started (its whole copy begun).pub(crate) fn keeps_whole(client: &ClientController) -> bool {    let choice = keep_choice(client);    choice["on"] == Value::Bool(true) && choice["started"] == Value::Bool(true)}/// Whether this phone's copy holds the whole database now: Keep everything kept, and its whole copy's first pull ended./// While the fill runs, or waits for room or for Carry on, the copy holds only part of it (ANDROID READY 1 core fault 5:/// search said it had searched every table on this phone, and asked the server nothing, at 20%). A copy that cannot be/// read is taken as not whole, so the server is asked.pub(crate) fn holds_whole(client: &ClientController) -> bool {    keeps_whole(client) && !whole_fill_underway(client)}/// Whether the whole copy's first pull has not ended (its cursor still on the pull from the start, or none yet).fn whole_fill_underway(client: &ClientController) -> bool {    let cursor = cotton_client::transport::object::CURSOR_KEY;    client        .with_file(|file| file.driver.get("SELECT hlc_seen FROM _cursors WHERE author_device_id = ?", &[rusqlite::types::Value::Text(cursor.to_string())]).map_err(|error| error.to_string()).map(|row| row.and_then(|row| row.text("hlc_seen").map(str::to_string))))        .map(|held| cotton_client::transport::object::first_pull_underway(&held.into_iter().map(|held| (cursor.to_string(), held)).collect()))        .unwrap_or(true)}/// How many table names, and how many column names, one search shows.const NAMES_SHOWN: usize = 30;/// `names` cut to the first [NAMES_SHOWN]: how many there were, and the line saying how many more match.pub(crate) fn capped(names: &mut Vec<Value>) -> (usize, Option<String>) {    let all = names.len();    names.truncate(NAMES_SHOWN);    (all, (all > NAMES_SHOWN).then(|| say("search.more", &[("n", &rules::count((all - NAMES_SHOWN) as u64))])))}fn search(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let q = request["q"].as_str().unwrap_or_default().trim().to_lowercase();    let all = definitions(client)?;    if q.is_empty() {        return Ok(json!({ "title": say("search.title", &[]), "placeholder": say("search.placeholder", &[]), "groups": [], "tables": [], "columns": [] }));    }    let mut tables: Vec<Value> = all.iter().filter(|t| t.id().contains(&q) || t.def.name.to_lowercase().contains(&q)).map(|t| json!({ "table": t.id(), "line": t.def.name })).collect();    let mut columns: Vec<Value> = all.iter().flat_map(|t| t.def.columns.iter().filter(|c| c.key.contains(&q)).map(move |c| json!({ "table": t.id(), "column": c.key }))).collect();    // One letter names hundreds of tables and thousands of columns (Data walk, 26 Nov 2026: "l" froze the phone drawing    // them): the first NAMES_SHOWN of each, the count of all, and a line saying more match.    let (table_count, tables_more) = capped(&mut tables);    let (column_count, columns_more) = capped(&mut columns);    let (found, here, there) = if q.chars().count() >= 2 { find_rows(client, &all, &q, None, 5) } else { (Vec::new(), 0, 0) };    let row_count: usize = found.iter().map(|(_, r)| r.len()).sum();    let row_groups: Vec<Value> = found        .iter()        .map(|(table, rows)| json!({ "table": table, "title": all.iter().find(|t| t.id() == table).map(|t| t.def.name.clone()).unwrap_or_else(|| table.clone()), "rows": rows }))        .collect();    let nothing = tables.is_empty() && columns.is_empty() && row_count == 0;    Ok(json!({        "hidden_note": said_hidden(),        "title": say("search.title", &[]),        "chips": [            { "id": "everything", "title": say("search.everything", &[]) },            { "id": "rows", "title": say("search.rows", &[]) },            { "id": "tables", "title": say("search.tables", &[]) },            { "id": "columns", "title": say("search.columns", &[]) },        ],        "groups": row_groups,        "found_line": (row_count > 0).then(|| say("search.found", &[("rows", &rules::rows_line(row_count as u64)), ("tables", &say("tables.count", &[("n", &found.len().to_string())]))])),        "tables": tables,        "tables_count": table_count,        "tables_more": tables_more,        "columns": columns,        "columns_count": column_count,        "columns_more": columns_more,        "searched_line": format!("{} {}", if there == 0 { say("search.searched_phone", &[("n", &here.to_string())]) } else { say("search.searched_split", &[("here", &here.to_string()), ("there", &there.to_string())]) }, say("search.secrets_left_out", &[])),        "nothing": nothing.then(|| json!({ "title": say("search.nothing", &[("q", &q)]), "names": say("search.try_names", &[]) })),    }))}fn assistants(client: &ClientController) -> Result<Value, MethodError> {    let reads = read_log(client);    let now = client.now().timestamp_millis();    let mut by: Vec<(String, Vec<&Value>)> = Vec::new();    for r in &reads {        let who = r["client"].as_str().unwrap_or("?").to_string();        match by.iter_mut().find(|(w, _)| *w == who) {            Some((_, list)) => list.push(r),            None => by.push((who, vec![r])),        }    }    let bands: Vec<Value> = by        .iter()        .map(|(who, list)| {            let items: Vec<Value> = list                .iter()                .take(5)                .map(|r| {                    let rows = r["rows"].as_u64().unwrap_or(0);                    let wrote = r["wrote"].as_bool() == Some(true) || r["wrote"].as_i64() == Some(1);                    let verb = if wrote { say("assistants.wrote_rows", &[("n", &rows.to_string())]) } else { say("assistants.read_rows", &[("n", &rows.to_string())]) };                    let tool = r["tool"].as_str().unwrap_or_default();                    json!({ "table": list_of(&r["tables"]).join(", "), "line": if tool.is_empty() { verb } else { format!("{verb} \u{b7} {tool}") }, "when": row_ms(r, "read_at").map(|ms| rules::ago(ms, now)) })                })                .collect();            json!({ "name": who, "items": items, "more_line": (list.len() > 5).then(|| say("assistants.more", &[("n", &(list.len() - 5).to_string())])) })        })        .collect();    Ok(json!({        "title": say("assistants.title", &[]),        "lead": say("assistants.lead", &[]),        "assistants": bands,        "none": reads.is_empty().then(|| say("assistants.none", &[])),        "never_title": say("assistants.never_title", &[]),        "never_line": say("assistants.never", &[]),        "gap_line": say("assistants.gap", &[]),    }))}fn leftovers(client: &ClientController) -> Result<Value, MethodError> {    let all = definitions(client)?;    let (measured, _) = measures(client);    let now = client.now().timestamp_millis();    let line = |t: &Table| {        let m = measured.get(t.id());        json!({            "table": t.id(),            "line": match (m.and_then(|m| m.rows), m.and_then(|m| m.newest)) {                (Some(rows), Some(newest)) => say("leftovers.last_written", &[("rows", &rules::rows_line(rows)), ("when", &rules::ago(newest, now))]),                (Some(rows), None) => rules::rows_line(rows),                _ => say("tables.counting", &[]),            },            "room_line": m.and_then(|m| m.bytes).map(rules::size),        })    };    let unused: Vec<Value> = all.iter().filter(|t| rules::group_of(t.id(), t.internal()) == Group::Unused).map(line).collect();    let retired: Vec<&Table> = all.iter().filter(|t| rules::group_of(t.id(), t.internal()) == Group::Retired).collect();    let retired_rows: u64 = retired.iter().filter_map(|t| measured.get(t.id()).and_then(|m| m.rows)).sum();    let unused_bytes: u64 = all.iter().filter(|t| rules::group_of(t.id(), t.internal()) == Group::Unused).filter_map(|t| measured.get(t.id()).and_then(|m| m.bytes)).sum();    let dangling: Vec<Value> = get(client, "/v1/data/leftovers")        .ok()        .and_then(|a| a["dangling"].as_array().cloned())        .unwrap_or_default()        .iter()        .filter_map(|d| {            let n = d["count"].as_u64()?;            Some(json!({ "line": say("leftovers.dangling_item", &[("n", &n.to_string()), ("table", d["table"].as_str()?), ("target", d["target"].as_str()?)]), "through_line": say("row.through", &[("column", d["column"].as_str()?)]), "table": d["table"], "column": d["column"] }))        })        .collect();    let nothing = unused.is_empty() && retired.is_empty() && dangling.is_empty();    Ok(json!({        "title": say("leftovers.title", &[]),        "lead": say("leftovers.lead", &[]),        "unused": (!unused.is_empty()).then(|| json!({ "title": say("leftovers.unused", &[]), "line": say("leftovers.unused_line", &[("tables", &say("tables.count", &[("n", &unused.len().to_string())])), ("room", &rules::size(unused_bytes))]), "tables": unused })),        "retired": (!retired.is_empty()).then(|| json!({ "title": say("leftovers.retired", &[]), "line": say("leftovers.retired_line", &[("rows", &rules::count(retired_rows))]), "tables": retired.iter().map(|t| line(t)).collect::<Vec<_>>() })),        "dangling": (!dangling.is_empty()).then(|| json!({ "title": say("leftovers.dangling", &[]), "items": dangling })),        "foot": say("leftovers.foot", &[]),        "none": nothing.then(|| say("leftovers.none", &[])),    }))}/// Whether this phone holds the database's key, so it can open sealed rows.fn has_key(client: &ClientController) -> bool {    let Ok(database) = client.current_database() else { return false };    let keys: std::sync::Arc<dyn cotton_client::seal::DataKeyStore> = client.data_keys().clone();    cotton_client::seal::Sealer::new(database, keys).has_key()}/// The marks a sealed row carries that are not fields.const SEAL_MARKS: [&str; 6] = ["sealed_enc", "dek_enc", "seal_v", "blind", "arrival", "patches"];/// A table's rows as the server holds them, for a phone without the key: when each was made, its clear fields, what/// it points at, its padded size. Never a word of what is sealed.fn sealed_view(client: &ClientController, t: &Table, page: &Value, lead: String) -> Value {    let links: HashMap<&str, &str> = t.def.columns.iter().filter_map(|c| Some((c.key.as_str(), c.link_to.as_deref()?))).collect();    let rows: Vec<Value> = page["rows"]        .as_array()        .into_iter()        .flatten()        .filter_map(|wire| {            let data = wire["data"].as_object()?;            let made = row_ms(wire, "created_at").map(rules::day).unwrap_or_default();            let mut clear = Vec::new();            let mut points = Vec::new();            for (key, value) in data {                if SEAL_MARKS.contains(&key.as_str()) || value.is_null() {                    continue;                }                match links.get(key.as_str()) {                    Some(target) => points.push(say("locked.links_to", &[("table", target)])),                    None => clear.push(format!("{key} {}", rows::stored_text(value))),                }            }            let size = data.get("sealed_enc").and_then(Value::as_str).map(|b| (b.len() as u64 * 3) / 4).unwrap_or(0);            Some(json!({                "id": wire["id"],                "made_line": say("locked.made", &[("date", &made)]),                "clear_line": clear.join(" \u{b7} "),                "points_line": points.join(", "),                "size_line": rules::size(size),            }))        })        .collect();    let _ = client;    json!({        "table": t.id(),        "lead": lead,        "sealed_view": true,        "locked": {            "title": say("locked.title", &[]),            "line": say("locked.line", &[]),            "sizes": say("locked.sizes", &[]),            "unlock": say("locked.unlock", &[]),            "no_key_line": say("locked.no_key", &[]),            "acts": [                { "id": "approve", "title": say("missing.approve", &[]) },                { "id": "recovery", "title": say("missing.recovery", &[]) },            ],        },        "rows": rows,        "groups": [],        "more": page["more"].as_bool().unwrap_or(false),    })}/// One sealed row for a phone without the key (data.html "Sealed row, key missing"): the table, the row, when it was/// made and last changed, its version, its clear fields, what it points at, the sealed part's padded size and how many/// scrambled words it keeps for search, each a fact the server holds; then the ways in. Never a word of what is sealed.fn sealed_row(t: &Table, rid: &str, wire: &Value) -> Value {    let links: HashMap<&str, &str> = t.def.columns.iter().filter_map(|c| Some((c.key.as_str(), c.link_to.as_deref()?))).collect();    let empty = Map::new();    let data = wire["data"].as_object().unwrap_or(&empty);    let mut clear = Vec::new();    let mut points = Vec::new();    for (key, value) in data {        if SEAL_MARKS.contains(&key.as_str()) || value.is_null() {            continue;        }        match links.get(key.as_str()) {            Some(target) => points.push(say("locked.links_to", &[("table", target)])),            None => clear.push(format!("{key} {}", rows::stored_text(value))),        }    }    let size = data.get("sealed_enc").and_then(Value::as_str).map(|b| (b.len() as u64 * 3) / 4).unwrap_or(0);    let words = wire.get("blind").or_else(|| data.get("blind")).and_then(Value::as_array).map_or(0, Vec::len);    let fact = |label: &str, value: String| json!({ "label": say(label, &[]), "value": value });    let mut facts = vec![fact("missing.table", t.id().to_string()), fact("missing.row", rid.to_string())];    if let Some(made) = row_ms(wire, "created_at") {        facts.push(fact("missing.made", rules::day(made)));    }    if let Some(changed) = row_ms(wire, "updated_at").filter(|u| row_ms(wire, "created_at").is_none_or(|c| u - c > 60_000)) {        facts.push(fact("missing.changed", rules::day(changed)));    }    if let Some(version) = wire["version"].as_i64() {        facts.push(fact("missing.version", version.to_string()));    }    if !clear.is_empty() {        facts.push(fact("missing.clear", clear.join("\n")));    }    if !points.is_empty() {        facts.push(fact("missing.points", points.join(", ")));    }    if size > 0 {        facts.push(fact("missing.sealed_part", say("missing.sealed_size", &[("size", &rules::size(size))])));    }    if words > 0 {        let n = words.to_string();        facts.push(fact("missing.for_search", say(if words == 1 { "missing.words.one" } else { "missing.words.other" }, &[("n", &n)])));    }    json!({        "table": t.id(),        "id": rid,        "sealed_view": true,        "title": say("locked.title", &[]),        "band": { "title": say("missing.title", &[]), "line": say("missing.line", &[]) },        "facts": facts,        "acts": [            { "id": "approve", "title": say("missing.approve", &[]) },            { "id": "recovery", "title": say("missing.recovery", &[]) },        ],    })}/// What changed lately: the change log's heads (`/v1/data/changes`), a run of one writer's same kind of change to one/// table said as one line with its count, grouped by day. Never a value: the log's heads hold none./// The tables a device writes its own state to, in the person's name: their writes are said as Cotton itself.const DEVICE_STATE: &[&str] = &["device"];fn lately(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let mut path = String::from("/v1/data/changes?limit=300");    if let Some(who) = request["who"].as_str().filter(|w| ["you", "apps", "assistants"].contains(w)) {        path.push_str(&format!("&who={who}"));    }    if let Some(table) = request["table"].as_str() {        path.push_str(&format!("&table={}", part(table)));    }    if let Some(before) = request["before"].as_str().or(request["before"].as_i64().map(|_| "")).filter(|b| !b.is_empty()) {        path.push_str(&format!("&before={}", part(before)));    }    let answer = get(client, &path).map_err(|why| if why.code == "offline" { refused("offline", "lately.offline", &[]) } else { why })?;    let now = client.now().timestamp_millis();    let today = chrono::DateTime::from_timestamp_millis(now).map(|t| t.date_naive());    let mut days: Vec<(String, u64, Vec<Value>)> = Vec::new();    let mut run: Option<(String, String, String, String, u64, i64)> = None; // (day, who, kind, table, n, at)    let flush = |run: &mut Option<(String, String, String, String, u64, i64)>, days: &mut Vec<(String, u64, Vec<Value>)>| {        let Some((day, who, kind, table, n, at)) = run.take() else { return };        let line_key = match kind.as_str() {            "insert" | "create" | "import" => "lately.added",            "delete" => "lately.deleted",            _ => "lately.changed",        };        let line = say(line_key, &[("n", &rules::count(n)), ("who", &who), ("table", &table)]);        let when = chrono::DateTime::from_timestamp_millis(at).map(|t| t.format("%-H:%M").to_string()).unwrap_or_default();        let item = json!({ "line": line, "table": table, "when": when, "count": n });        match days.last_mut() {            Some((d, total, items)) if *d == day => {                *total += n;                items.push(item);            }            _ => days.push((day, n, vec![item])),        }    };    let chip_you = request["who"].as_str() == Some("you");    for c in answer["changes"].as_array().into_iter().flatten() {        let at = row_ms(c, "at").unwrap_or(0);        let date = chrono::DateTime::from_timestamp_millis(at).map(|t| t.date_naive());        let day = match (date, today) {            (Some(d), Some(t)) if d == t => say("lately.today", &[]),            (Some(d), Some(t)) if (t - d).num_days() == 1 => say("lately.yesterday", &[]),            (Some(d), _) => d.format("%-d %B").to_string(),            _ => String::new(),        };        // A machine's write (a migration, sealing, a sync, a fetch: the Worker's MACHINE_WRITERS) is said as Cotton itself:        // its actor is the person it was done for, and "Walk Cinemas changed 3 rows in watch" under Apps said he did it        // (Data walk, 26 Nov 2026).        // A device's own state (each phone's row in `device`, which it writes itself every few minutes under the        // person's credential) is Cotton's own too, never the person's: "You changed 11 rows in device" said he did it        // (ANDROID READY 1 core fault 10). Under You it is left out; the server still counts it as his.        let table = c["table"].as_str().unwrap_or_default().to_string();        let devices_own = c["actor_kind"].as_str() == Some("person") && DEVICE_STATE.contains(&table.as_str());        if devices_own && chip_you {            continue;        }        let who = match c["actor_kind"].as_str() {            Some("person") if devices_own => say("lately.app_who", &[]),            Some("person") => say("lately.you_who", &[]),            Some("app") => say("lately.app_who", &[]),            _ => c["actor"].as_str().unwrap_or("?").to_string(),        };        let kind = c["kind"].as_str().unwrap_or("update").to_string();        match &mut run {            Some((d, w, k, t, n, _)) if *d == day && *w == who && *k == kind && *t == table => *n += 1,            _ => {                flush(&mut run, &mut days);                run = Some((day, who, kind, table, 1, at));            }        }    }    flush(&mut run, &mut days);    // Nothing in the 90 days kept, said for the filter chosen, never a blank page.    let chip = request["who"].as_str().filter(|w| ["you", "apps", "assistants"].contains(w)).unwrap_or("all");    let empty = days.is_empty().then(|| say(&format!("lately.empty.{chip}"), &[]));    let last = answer["changes"].as_array().and_then(|a| a.last()).map(|c| c["id"].clone());    Ok(json!({        "title": say("lately.title", &[]),        "lead": say("lately.lead", &[]),        "chips": [            { "id": "all", "title": say("lately.all", &[]) },            { "id": "you", "title": say("lately.you", &[]) },            { "id": "apps", "title": say("lately.apps", &[]) },            { "id": "assistants", "title": say("lately.assistants", &[]) },        ],        "days": days.into_iter().map(|(title, n, items)| json!({ "title": title, "count_line": say("lately.count", &[("n", &rules::count(n))]), "items": items })).collect::<Vec<_>>(),        "more": answer["more"].as_bool().unwrap_or(false),        "before": last,        "empty": empty,        "foot": say("lately.foot", &[]),    }))}/// A photo or file of a row: its name and size, where it came from, and the key the phone fetches it by/// (`media.ensure`, the existing call that brings bytes down).fn media(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let id = request["table"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the table"))?;    let rid = request["id"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the row"))?;    let column = request["column"].as_str().ok_or_else(|| MethodError::new("bad_request", "name the column"))?;    let t = table(client, id)?;    let (open, _) = one_row(client, &t, rid)?;    let c = t.def.column(column).ok_or_else(|| refused("no_row", "refused.no_row", &[]))?;    let f = rows::field(&t.def, c, &open, false, &|_, _| None);    let key = f.media.ok_or_else(|| refused("no_row", "refused.no_row", &[]))?;    let title = rows::sentence(&t.def, &open, &|_, _| None).title;    Ok(json!({        "name": f.value_line,        "key": key,        "kind": f.kind,        "size_title": say("media.size", &[]),        "from_title": say("media.from", &[]),        "from_line": say("media.from_line", &[("column", column), ("row", &title)]),        "note": say("media.note", &[]),        "offline": say("media.offline", &[]),        "close": say("media.close", &[]),    }))}// ── Keep everything: this device's own choice ─────────────────────────────fn keep_path(client: &ClientController) -> std::path::PathBuf {    client.layout().root().join(KEEP_FILE)}/// Where this device keeps its Keep everything choice, beside its copies.const KEEP_FILE: &str = "data-keep.json";/// Cotton Data's kit: the app that reads every table.pub(crate) const KIT: &str = "data";/// What Keep everything always leaves free on the phone.pub(crate) const ROOM_LEFT: u64 = 2_000_000_000;/// Keep everything's room guard for the copy's pulls: a reason while the phone has less than [`ROOM_LEFT`] free beside/// `root` ([`TEST_FREE`] in tests), none otherwise.pub(crate) fn room_guard(root: std::path::PathBuf) -> std::sync::Arc<dyn Fn() -> Option<String> + Send + Sync> {    std::sync::Arc::new(move || {        // Paused by the person (`data.keep.pause`): the pulls stop where they stand, as for room, until Carry on.        let paused = std::fs::read(root.join(KEEP_FILE)).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()).is_some_and(|c| c["paused"] == Value::Bool(true));        if paused {            return Some("paused: Keep everything is paused on this phone".to_string());        }        let free = free_at(&root)?;        (free < ROOM_LEFT).then(|| format!("room_guard: {} free, Keep everything leaves {} free", rules::size(free), rules::size(ROOM_LEFT)))    })}/// The phone's free bytes where `root` is.fn free_at(root: &std::path::Path) -> Option<u64> {    #[cfg(test)]    if let Some(free) = *TEST_FREE.lock().unwrap_or_else(|e| e.into_inner()) {        return Some(free);    }    cotton_client::media::hydrate::free_bytes_at(root)}/// The free bytes a test says the phone has (only the Keep everything tests set it).#[cfg(test)]pub(crate) static TEST_FREE: std::sync::Mutex<Option<u64>> = std::sync::Mutex::new(None);/// Whether Data's copy is the whole object on this connect. Only a choice made (Start on the first screen, or the/// switch) counts. With Wi-Fi only (the default) the whole copy starts on a connect that says `unmetered`, and once/// started it stays whole on any network: a launch on mobile data never makes the copy small again, which would drop/// the rows it filled. Switched off, it is small again.pub(crate) fn keeps_everything(root: &std::path::Path, unmetered: bool) -> bool {    let path = root.join(KEEP_FILE);    let Some(mut choice) = std::fs::read(&path).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) else { return false };    if choice["on"] != Value::Bool(true) {        return false;    }    if choice["started"] == Value::Bool(true) {        return true;    }    if choice["wifi_only"] == Value::Bool(false) || unmetered {        choice["started"] = Value::Bool(true);        // not a copy: Data's own files (an export, the kept choice).        let _ = std::fs::write(&path, serde_json::to_vec(&choice).unwrap_or_default());        return true;    }    false}fn keep_choice(client: &ClientController) -> Value {    std::fs::read(keep_path(client)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_else(|| json!({}))}fn keep(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let choice = keep_choice(client);    let (measured, answer) = measures(client);    let rows_bytes = rows_bytes(&measured, &answer);    let free = free_bytes(client, request);    let on = choice["on"].as_bool().unwrap_or_else(|| rows_bytes.is_some_and(|b| rules::keep_starts_on(b, free)));    let file = answer["database"]["bytes"].as_u64();    let started = choice["started"].as_bool() == Some(true);    let paused = choice["paused"].as_bool() == Some(true);    // While the whole copy fills: how much of the rows' room it already holds (the copy's own size, its search index    // included, against the rows' measured room), and the minutes left at the fill's rate. Done once it holds as much.    let pass = client.sync_progress().map(|progress| progress.state());    let filling = if started { fill(rows_bytes, pass.as_ref(), || copy_size(client), |pass| held_ahead(client, pass)) } else { None };    // The minutes left at this fill's own pace once it has run a while, not the first screen's estimate (owner, build    // 1: "about 144 minutes" said before a row came down).    let filling = filling.map(|(percent, left)| (percent, paced(client, &choice, percent, paused).unwrap_or(left)));    // Stopped to leave room (ANDROID READY 1 core fault 4): only a fill stops for room, so only while one is under way;    // a copy already whole keeps syncing short of room. Stopped, it offers no Pause and says no "Filling": it starts    // again by itself.    let short = free < ROOM_LEFT && filling.is_some();    let mut cost = Vec::new();    let most = rows_bytes_most(&measured, &answer);    if let Some(b) = rows_bytes {        cost.push(json!({ "name": say("keep.room", &[]), "value_line": if most { say("keep.room_most", &[("size", &rules::size(b))]) } else { rules::size(rules::kept_bytes(b)) } }));        cost.push(json!({ "name": say("keep.first", &[]), "value_line": say(if most { "keep.first_value_most" } else { "keep.first_value" }, &[("minutes", &minutes(rules::fill_minutes(b)))]) }));    }    cost.push(json!({ "name": say("keep.has", &[]), "value_line": say("keep.has_value", &[("free", &rules::size(free))]) }));    Ok(json!({        "title": say("keep.title", &[]),        "switch": say("keep.switch", &[]),        "on": on,        "wifi_only": choice["wifi_only"].as_bool().unwrap_or(true),        "costs_title": say("keep.costs", &[]),        "cost": cost,        "why_line": match (file, rows_bytes) { (Some(f), Some(r)) if !most && rules::kept_bytes(r) < f => Some(say("keep.why", &[("file", &rules::size(f)), ("rows", &rules::size(rules::kept_bytes(r)))])), _ => None },        "privacy_line": say("keep.privacy", &[]),        "how_title": say("keep.how", &[]),        "wifi": say("keep.wifi", &[]),        "wifi_line": say("keep.wifi_line", &[]),        "short_title": say("keep.short_title", &[]),        "short_line": say("keep.short", &[]),        "all_mail_line": say("keep.all_mail", &[]),        "state": match (on, started, short, filling.is_some()) { (false, ..) => "off", (true, true, _, true) if paused => "paused", (true, true, true, _) => "stopped_room", (true, true, false, true) => "filling", (true, true, false, false) => "keeping", (true, false, ..) => "waiting_wifi" },        "state_line": match (on, started, short, filling) {            (false, ..) => Value::Null,            (true, true, _, Some((percent, _))) if paused => json!(say("keep.paused_you", &[("percent", &percent.to_string())])),            (true, true, true, _) => json!(say("keep.paused", &[("free", &rules::size(free))])),            (true, true, false, Some((percent, _))) => json!(say("keep.filling_strip", &[("percent", &percent.to_string())])),            (true, true, false, None) => json!(say("keep.keeping", &[])),            (true, false, ..) => json!(say("keep.waiting", &[])),        },        "progress": filling.filter(|_| !short || paused).map(|(percent, left)| json!({ "percent": percent, "left_line": say("keep.left", &[("minutes", &minutes(left))]), "line": say("keep.filling_line", &[]) })),        // The acts the screen offers now: Pause while filling, Carry on while paused, mobile data once while waiting.        "acts": match (on, started, paused, filling.is_some()) {            (true, true, false, true) if !short => json!([{ "id": "pause", "label": say("keep.pause", &[]), "method": "data.keep.pause" }]),            (true, true, true, _) => json!([{ "id": "resume", "label": say("keep.resume", &[]), "method": "data.keep.resume" }]),            (true, false, _, _) => json!([{ "id": "mobile_once", "label": say("keep.mobile_once", &[]), "method": "data.keep.mobile_once" }]),            _ => json!([]),        },        "too_small_line": (!on && choice["on"].is_null() && rows_bytes.is_some()).then(|| say("keep.too_small", &[("free", &rules::size(free))])),    }))}/// How far the whole copy's fill stands (its percent, and the minutes left), or None once it is whole.////// The sync pass decides when it is done: a pass caught up has every row, though the copy on the phone stays smaller/// than the server's measure (its history and search index stay there), so by size alone a finished fill sat at 64%,/// "About 2 minutes left", for good (the walk of 26 Nov on a 14,100-row invented account). While a pass is counted,/// the percent is its rows done of its rows; before a pass is known, the copy's size against the rows' room.////// A pass that carries tables from their start (a first fill begun again, a table carried whole) counts only the rows/// it has carried so far: the owner's build 2, holding gigabytes, said 0% with 6 hours left (DATA iPhone 3). So the/// rows this copy already holds of the tables the pass has yet to finish (`held_rows`) count as done too.pub(crate) fn fill(    rows_bytes: Option<u64>, pass: Option<&cotton_client::transport::object::PassState>, held: impl FnOnce() -> u64,    held_rows: impl FnOnce(&cotton_client::transport::object::PassState) -> u64,) -> Option<(u64, u64)> {    let rows = rows_bytes.filter(|rows| *rows > 0)?;    match pass {        Some(pass) if pass.caught_up => None,        Some(pass) if pass.total.is_some_and(|total| total > 0) => {            let total = pass.total.unwrap_or(1) as u64;            let done = (pass.done.unwrap_or(0).max(0) as u64).saturating_add(held_rows(pass)).min(total);            // Never 100% while a page is still to come.            let part = (done as f64 / total as f64).min(0.99);            Some(((part * 100.0).floor() as u64, rules::fill_minutes(((1.0 - part) * rows as f64) as u64)))        }        _ => {            let held = held();            (held < rows).then(|| (((held as f64 / rows as f64) * 100.0).floor() as u64, rules::fill_minutes(rows - held)))        }    }}/// The minutes left at the pace this fill has kept: when it was first seen filling, and how far it stood then, are/// kept in this phone's keep file (a pause forgets them, so a fill carried on is paced from where it carried on)./// None until it has run a minute and moved: the estimate stands until then.fn paced(client: &ClientController, choice: &Value, percent: u64, paused: bool) -> Option<u64> {    let now = client.now().timestamp_millis();    // A start above where the fill stands now (the copy began again, or the start was taken from another pass: the    // seeded account's keep file said 85% while it filled at 20%) can never be paced from: it is taken again here.    let mark = (choice["began"].as_i64(), choice["began_percent"].as_u64());    let mark = match mark {        (Some(_), Some(from)) if from > percent => (None, None),        mark => mark,    };    let (Some(began), Some(from)) = mark else {        if !paused {            let mut choice = choice.clone();            choice["began"] = json!(now);            choice["began_percent"] = json!(percent);            // not a copy: Data's own files (an export, the kept choice).            let _ = std::fs::write(keep_path(client), serde_json::to_vec(&choice).unwrap_or_default());        }        return None;    };    paced_minutes(now - began, from, percent)}/// The minutes left after `ran_ms` took the fill from `from` to `percent`; None before a minute or any progress.pub(crate) fn paced_minutes(ran_ms: i64, from: u64, percent: u64) -> Option<u64> {    if ran_ms < 60_000 || percent <= from || percent >= 100 {        return None;    }    let per_percent = ran_ms as f64 / (percent - from) as f64;    Some(((100 - percent) as f64 * per_percent / 60_000.0).ceil().max(1.0) as u64)}/// Of the tables a pass has yet to finish, the rows this copy already holds that the pass has not carried yet: each/// table's rows here (counted at most every two minutes: a count reads the table's smallest index), up to what the/// pass carries of it, less what has come.fn held_ahead(client: &ClientController, pass: &cotton_client::transport::object::PassState) -> u64 {    static COUNTED: std::sync::Mutex<Option<HashMap<String, (i64, u64)>>> = std::sync::Mutex::new(None);    let ahead: Vec<(&String, &cotton_client::transport::object::TablePass)> = pass.tables.iter().filter(|(_, t)| t.done < t.rows).collect();    if ahead.is_empty() {        return 0;    }    let database = client.current_database().unwrap_or_default();    let now = client.now().timestamp_millis();    let mut counted = COUNTED.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    let counted = counted.get_or_insert_with(HashMap::new);    let stale: Vec<String> = ahead        .iter()        .map(|(table, _)| (*table).clone())        .filter(|table| counted.get(&format!("{database}/{table}")).is_none_or(|(at, _)| now - at > 120_000))        .collect();    if !stale.is_empty() {        let found = client.read_rows("data.held", &mut |ctx| {            let mut found = serde_json::Map::new();            for table in &stale {                if !cotton_tools::mcp::handlers::tables::made_held(ctx, table).map_err(|failure| failure.to_string())? {                    continue;                }                let sql = format!("SELECT count(*) AS n FROM {}", cotton_tools::mcp::handlers::tables::made_table(table));                let n = ctx.read.driver().get(&sql, &[]).map_err(|error| error.to_string())?.and_then(|row| row.int("n")).unwrap_or(0);                found.insert(table.clone(), json!(n));            }            Ok(Value::Object(found))        });        let found = found.unwrap_or(Value::Null);        for table in &stale {            counted.insert(format!("{database}/{table}"), (now, found[table].as_u64().unwrap_or(0)));        }    }    ahead        .iter()        .map(|(table, pass)| {            let here = counted.get(&format!("{database}/{table}")).map_or(0, |(_, n)| *n);            here.min(pass.rows.max(0) as u64).saturating_sub(pass.done.max(0) as u64)        })        .sum()}/// The bytes of this phone's copy of the database, its write-ahead log included.fn copy_size(client: &ClientController) -> u64 {    let Ok(database) = client.current_database() else { return 0 };    let path = client.layout().replica(&database);    let size = |p: &std::path::Path| std::fs::metadata(p).map(|m| m.len()).unwrap_or(0);    size(&path) + size(std::path::Path::new(&format!("{}-wal", path.display())))}/// This device's choice only: never a write to the database.fn keep_set(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let mut choice = keep_choice(client);    if let Some(on) = request["on"].as_bool() {        choice["on"] = Value::Bool(on);        if !on {            choice.as_object_mut().map(|c| (c.remove("started"), c.remove("began"), c.remove("began_percent")));        }    }    if let Some(wifi) = request["wifi_only"].as_bool() {        choice["wifi_only"] = Value::Bool(wifi);    }    // not a copy: Data's own files (an export, the kept choice).    std::fs::write(keep_path(client), serde_json::to_vec(&choice).unwrap_or_default()).map_err(|e| MethodError::new("io", e.to_string()))?;    keep(client, request)}/// `data.keep.pause`, `data.keep.resume`, `data.keep.mobile_once`: this device's choice only, as `data.keep.set`./// Pause stops the fill where it stands (the room guard reads it), Carry on lets it go on, and mobile data once starts/// a fill that waits for Wi-Fi now, on whatever network the phone has; once started it stays whole, as on Wi-Fi.fn keep_act(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    let mut choice = keep_choice(client);    if choice["on"] != Value::Bool(true) {        return Err(refused("keep_off", "refused.keep_off", &[]));    }    match method {        "data.keep.pause" => {            choice["paused"] = Value::Bool(true);            choice.as_object_mut().map(|c| (c.remove("began"), c.remove("began_percent")));        }        "data.keep.resume" => {            choice.as_object_mut().map(|c| c.remove("paused"));        }        _ => choice["started"] = Value::Bool(true),    }    // not a copy: Data's own files (an export, the kept choice).    std::fs::write(keep_path(client), serde_json::to_vec(&choice).unwrap_or_default()).map_err(|e| MethodError::new("io", e.to_string()))?;    // Pause and Carry on take hold at the copy's next pull (the room guard reads the file each time); mobile data once    // at the next connect, which makes the copy whole.    keep(client, request)}fn you(client: &ClientController) -> Result<Value, MethodError> {    let all = definitions(client).unwrap_or_default();    let (_, answer) = measures(client);    let keep = keep_choice(client);    let room = match (answer["database"]["bytes"].as_u64(), answer["database"]["cap"].as_u64()) {        (Some(u), Some(c)) => Some(say("tables.room", &[("used", &rules::size(u)), ("cap", &rules::size(c))])),        _ => None,    };    let left = all.iter().filter(|t| matches!(rules::group_of(t.id(), t.internal()), Group::Unused | Group::Retired)).count();    // While the phone fills, the row says how far (the owner's iPhone, 26 Nov 2026: "On" said nothing for the 26    // minutes it filled); paused, Keep's own paused line.    let kept = self::keep(client, &json!({})).ok();    let percent = kept.as_ref().and_then(|k| k["progress"]["percent"].as_u64());    let keep_line = if keep["on"].as_bool() != Some(true) {        say("you.keep_off", &[])    } else if kept.as_ref().is_some_and(|k| k["state"] == json!("stopped_room")) {        // Stopped to leave room, never "Filling, 20%" (ANDROID READY 1 core fault 4).        say("keep.stopped_title", &[])    } else if let Some(paused) = kept.as_ref().and_then(|k| k["state_line"].as_str()).filter(|_| keep["paused"].as_bool() == Some(true)) {        paused.to_string()    } else if let Some(percent) = percent {        say("you.keep_filling", &[("percent", &percent.to_string())])    } else {        say("you.keep_on", &[("size", "")]).trim_end_matches(", ").to_string()    };    Ok(json!({        "title": say("you.title", &[]),        "card": { "line": say("you.card_line", &[("tables", &all.len().to_string())]) },        "rows": [            { "id": "keep", "title": say("you.keep", &[]), "value_line": keep_line },            { "id": "assistants", "title": say("you.assistants", &[]), "value_line": Value::Null },            { "id": "leftovers", "title": say("you.leftovers", &[]), "value_line": say("tables.count", &[("n", &left.to_string())]) },            { "id": "room", "title": say("you.room", &[]), "value_line": room },            { "id": "look", "title": say("you.look", &[]), "value_line": Value::Null },        ],        "privacy_line": say("you.privacy_line", &[]),    }))}#[cfg(test)]#[path = "data_app_tests.rs"]mod tests;