Cotton code
5410 lines · 239.9 KB · RustRaw
//! The generic verbs over a BUILT-IN table: reads through its definition's//! columns, writes through the tool that already writes it.//!//! READS work for every built-in, from the definition the app SHIPS — never//! from the synced row, which a device could have written anything into. A//! built-in's column keys ARE its table's column names//! (`cotton_core::definitions` holds that), and its table is the primitive//! registry's, so a read selects the shipped definition's columns that the//! store's own `TABLE_SPECS` also declares, less every sensitive column//! (`cotton_core::records::is_sensitive_column`). Every column name that//! reaches SQL is therefore a `&'static str` out of `TABLE_SPECS`.//! `note` and `journal` share `cotton_notes` and are told apart by its `kind`.//!//! Each engine's own VISIBILITY holds here too. A row with `trashed_at` (the//! bin) or `archived_at` set is answered as deleted and left out of a list. A//! message hidden by the owner (`hidden_at`) or cleared away by its thread//! (`cleared_before`) is not there at all — the same three-part rule every//! message reader applies (`chat::shared::newest_visible`). A column the store//! keeps in another shape than the definition promises is answered through its//! resolver (`cotton_core::definitions::RESOLVED_COLUMNS`: a meeting's//! recording is its one media key, and null once `audio_deleted_at` is set; a//! news edition's `quiet` and `notes` lists are their display lines).//!//! WRITES never reach a built-in's table directly. Each adapter below maps a//! record's values onto the arguments of the kind's EXISTING tool and calls it//! — one writer per table, whatever door the write came in by. A tool the//! catalogue keeps for the owner's own app stays that way here: every tool a//! write's plan will call is checked BEFORE the first one runs ([`permit`]),//! because calling a handler directly skips the dispatcher's scope check. The//! covered built-ins are todo, note, journal, goal, mood, location,//! page, alarm, transaction and thought, and the photos engine's photo, video,//! album and its views `media`, `album_item` and `duplicate`//! (`super::media_tables`), and the engine views `face`, `person_suggestion`,//! `news_topic` and `news_settings`//! (`super::engine_views`, which also reads every engine view); every//! other one answers a write with//! [`read_only`]. Columns the engine sets itself (`completed_at`,//! `archived_at`, `local_day` …) are refused on a write and left out of an//! undo, which the engine re-derives.//!//! BEYOND ITS STORED COLUMNS a built-in's read answers what its engine//! computes ([`engine_extras`]): the columns `COMPUTED_COLUMNS` declares (a//! thought's story, a news edition's figure and progress), a thought's//! `links` (the records it became), and the//! `attachments` of a table whose engine keeps pictures — the last two as keys//! beside the columns, since no column type holds a list of objects. A//! computed column or `links` is refused on every write and left out of every//! undo; `attachments` is written through the engine's own attachment write.//!//! `WHERE` on a built-in ([`narrow`]): a stored column of one value filters in//! SQL as on any table; every other column — computed, resolved, holding//! several values — only through its table's own entry in [`NARROWINGS`],//! which is the hook a table adds its own keys through. A column with neither//! is refused.//!//! A built-in that is an engine's VIEW (`cotton_core::definitions::VIEW_TABLES`)//! has no table of its own: its reads are its engine's ([`read_one`] and//! [`list`] hand them over). Every list answers how many records it holds in//! all (`Page::total`).use cotton_core::definitions::{    builtin_store_table, is_computed_column, is_device_answered_column, ColumnType,    TableDefinition, RESOLVED_COLUMNS,};use cotton_core::rules::summaries::staleness_from;use cotton_core::transforms::moment_split::split_moment;use cotton_core::records::{    self, carries_attachments, is_sensitive_column, Condition, Data, RecordError, Verb,    WhereClause, ATTACHMENTS_KEY, LINKS_KEY,};use cotton_store::schema::fts::FTS_SOURCES;use cotton_store::schema::table_specs::TABLE_SPECS;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use super::{ai_usage, day_plan, engine_views, mail_chat_writes, media_tables, shop_writes};use super::{answer, read_only, record_change, sql_err, sql_value, Archive, ListExtras, Page, Stored};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::attachments::{attachment_refs_by_owner, AttachmentOwner, NOTE};use crate::mcp::handlers::common::{    flag, insert_row, iso_of_ms, maybe_row, now_iso, parse_ms, project_slug_of, projects, rows, text, today_in,    update_row, workspace_timezone,    workspace_timezone_or_null, Valid,};use crate::mcp::handlers::records_1::{events, notes, people, todos};use crate::mcp::handlers::{documents, projects, summaries};use crate::mcp::protocol::{tool_by_name, McpScope, ToolFailure};use crate::mcp::read_db::{Filter, Order, Query, ReadDb, EXPECTED_TRANSACTIONS};// ── where a built-in lives ──────────────────────────────────────────────────/// The columns whose value, once set, means the row is out of the working/// set: the bin, and the archive.const GONE_COLUMNS: [&str; 2] = ["trashed_at", "archived_at"];/// A message the owner hid, a failed text of theirs in the bin, or one its/// thread's `cleared_before` swept away — the rule/// `chat::shared::newest_visible` applies, as one condition.pub(super) const MESSAGE_VISIBLE: &str = "hidden_at IS NULL AND trashed_at IS NULL AND NOT EXISTS (SELECT 1 FROM cotton_msg_threads \     t WHERE t.id = cotton_msg_messages.thread_id AND t.cleared_before IS NOT NULL AND \     t.cleared_before <> '' AND cotton_msg_messages.sent_at <= t.cleared_before)";struct Source {    table: &'static str,    /// `cotton_notes`' row split: `note` or `journal`.    kind: Option<String>,    /// What a read selects — every name a `TABLE_SPECS` constant.    columns: Vec<&'static str>,    /// Which of [`GONE_COLUMNS`] the table has.    gone: Vec<&'static str>,    /// Messages: the visibility rule above.    messages: bool,    updated: bool,}fn source(definition: &TableDefinition) -> Valid<Source> {    let rows = definition.rows_table();    let table = definition.store_table()        .or_else(|| cotton_core::constants::BinKind::parse(rows)            .map(|kind| cotton_core::rules::bin::bin_source(kind).table))        .ok_or_else(|| {        ToolFailure::new(format!(            "{} has no storage this build knows",            definition.plural        ))    })?;    let spec = TABLE_SPECS        .iter()        .find(|spec| spec.name == table)        .ok_or_else(|| {            ToolFailure::new(format!(                "{} has no storage this build knows",                definition.plural            ))        })?;    let has = |column: &str| spec.columns.iter().any(|(name, _)| *name == column);    let mut columns: Vec<&'static str> = Vec::new();    let extra = extra_reads(rows);    for (name, _) in spec.columns {        let wanted = *name == "id"            || matches!(*name, "created_at" | "updated_at")            || GONE_COLUMNS.contains(name)            || extra.contains(name)            || definition.column(name).is_some();        if wanted && !is_sensitive_column(name) {            columns.push(name);        }    }    Ok(Source {        table,        kind: (table == "cotton_notes").then(|| rows.to_string()),        columns,        gone: GONE_COLUMNS            .iter()            .copied()            .filter(|column| has(column))            .collect(),        messages: table == "cotton_msg_messages",        updated: has("updated_at"),    })}/// A journal day that holds words. A day emptied by Undo of its first entry/// stays as a row and is left out of the list.const JOURNAL_DAY_HAS_WORDS: &str = "trim(COALESCE(body, '')) <> ''";fn base_query(source: &Source) -> Query {    let mut query = Query::on(source.table).columns(&source.columns);    if let Some(kind) = &source.kind {        query = query.eq("kind", kind.clone());    }    if source.messages {        query = query.filter(Filter::Static(MESSAGE_VISIBLE));    }    query}/// Stable, whole-table input for the definition evaluator. Use the same/// visibility and typed Money projection as reads, before paging any rows.pub(super) fn derivation_rows(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition) -> Valid<Vec<(String, Data)>> {    derivation_rows_selected(db, workspace, definition, None, None, None)}/// A message's visibility reads its thread (MESSAGE_VISIBLE), so a change/// to another row can remove it even when its own stored inputs did not move.pub(super) fn derivation_is_row_local(definition: &TableDefinition) -> Valid<bool> {    Ok(!source(definition)?.messages)}/// The same typed projection for a row-local formula, bounded by its changed ids.pub(super) fn derivation_rows_for_ids(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition, ids: &[String]) -> Valid<Vec<(String, Data)>> {    let mut found = Vec::new();    for chunk in ids.chunks(400) {        found.extend(derivation_rows_selected(db, workspace, definition, Some(chunk), None, None)?);    }    Ok(found)}pub(super) fn derivation_rows_through_window(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition, window: &crate::mcp::handlers::money::occurrences::Window) -> Valid<Vec<(String, Data)>> {    derivation_rows_selected(db, workspace, definition, None, Some(window), None)}/// The same visibility and typed projection, restricted to this parent's link.pub(super) fn derivation_rows_linked(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition, link: &str, target: &str) -> Valid<Vec<(String, Data)>> {    derivation_rows_selected(db, workspace, definition, None, None, Some((link, target)))}fn derivation_rows_selected(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition, ids: Option<&[String]>, window: Option<&crate::mcp::handlers::money::occurrences::Window>, linked: Option<(&str, &str)>) -> Valid<Vec<(String, Data)>> {    let source = source(definition)?;    let mut query = base_query(&source);    for column in &source.gone {        query = query.filter(Filter::IsNull((*column).into()));    }    let table = definition.rows_table();    if table == "journal" {        query = query.filter(Filter::Static(JOURNAL_DAY_HAS_WORDS));    }    let id_key = if table == "device" { "device_id" } else { "id" };    if let Some(ids) = ids {        query = query.filter(Filter::In(id_key.into(), ids.iter().cloned().map(SqlValue::Text).collect()));    }    if let Some(window) = window { query = window.narrow(query).filter(Filter::Static(EXPECTED_TRANSACTIONS)); }    if let Some((link, target)) = linked {        // Nonphysical links have no stored scalar for the evaluator to gather.        if !source.columns.contains(&link) { return Ok(Vec::new()); }        query = query.eq(link, target.to_string());    }    let read = crate::mcp::read_db::ReadDb::new(db, workspace);    let rows = read.select(&query).map_err(sql_err)?;    let rows = rows.into_iter().filter_map(|mut row| {        let id = row.get(id_key)?.as_str()?.to_string();        for column in &definition.columns {            if RESOLVED_COLUMNS.contains(&(table, column.key.as_str())) {                // Resolved media and reader-specific values are not stored                // scalars. Never substitute their physical representation.                row.remove(&column.key);            } else if column.column_type == ColumnType::Bool {                if let Some(value) = row.get(&column.key).and_then(Value::as_i64) {                    row.insert(column.key.clone(), Value::Bool(value != 0));                }            } else if TEXT_LISTS.contains(&(table, column.key.as_str())) {                if let Some(value) = row.get(&column.key) {                    row.insert(column.key.clone(), Value::Array(json_list(value)));                }            }        }        row.insert("id".into(), Value::from(id.clone()));        records::project_read_data(definition, &mut row);        Some((id, row))    }).collect();    let projected = super::super::money_views::project_rows(db, workspace, table, rows).map_err(ToolFailure::new)?;    // A view evaluates over its own rows only: a running balance or a rollup    // over So far counts what So far shows.    let zone = crate::mcp::handlers::common::read_where_zone(&crate::mcp::read_db::ReadDb::new(db, workspace))?;    let viewed = super::viewed(definition)?;    Ok(projected.into_iter().filter_map(|mut row| {        let id = row.get("id")?.as_str()?.to_string();        records::project_read_data(definition, &mut row);        viewed.iter().filter(|clause| window.is_none() || !super::money_runway::varies_by_occurrence(definition,&clause.column)).all(|clause| records::holds(&row, clause, &zone)).then_some((id, row))    }).collect())}/// A grouped list's rows (`derivation_rows`' own: the source's live rows/// and a view's `where`), narrowed in SQL by `clauses` as the list narrows/// them and grouped by `column` in ONE statement: each group's value beside/// the aggregates `aggregates` composes over the SQL each column reads as/// (`figure_column`). Never a walk of the rows: Owed's heads over a book.pub(super) fn grouped(    ctx: &Ctx<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    column: &str,    aggregates: impl FnOnce(&mut dyn FnMut(&str) -> Valid<String>) -> Valid<String>,) -> Valid<Vec<(Value, cotton_store::Row)>> {    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    let source = source(definition)?;    let mut query = base_query(&source);    for gone in &source.gone {        query = query.filter(Filter::IsNull((*gone).into()));    }    if definition.rows_table() == "journal" {        query = query.filter(Filter::Static(JOURNAL_DAY_HAS_WORDS));    }    // The list's clauses repeat the view's own: each condition once.    for clause in super::viewed(definition)?.iter().chain(clauses) {        for filter in narrow(ctx, definition, &source, clause, &zone)? {            if !query.filters.contains(&filter) {                query = query.filter(filter);            }        }    }    let grouped_by = source.columns.iter().find(|name| **name == column).filter(|_| !is_computed_column(definition.rows_table(), column)        && !RESOLVED_COLUMNS.contains(&(definition.rows_table(), column)))        .ok_or_else(|| super::refuse(RecordError::CannotNarrow { plural: definition.plural.clone(), column: column.to_string() }))?;    let aggregates = aggregates(&mut |column_name: &str| figure_column(definition, &source, column_name))?;    ctx.read.grouped(&query, grouped_by, &aggregates).map_err(sql_err)}/// The SQL one column of a grouped list's figure reads as: a stored column/// itself, a computed one its kept value (`_computed`, under the/// definition's own id, as `with_computed` reads it); any other is refused.fn figure_column(definition: &TableDefinition, source: &Source, column_name: &str) -> Valid<String> {    if let Some(signed) = signed_sql(definition, source, column_name) {        return Ok(signed);    }    if definition.column(column_name).is_some_and(|column| column.computed.is_some()) {        let id = if definition.rows_table() == "device" { "device_id" } else { "id" };        return Ok(format!(            "(SELECT value FROM _computed WHERE table_id = '{}' AND record_id = {}.{id} AND key = '{}')",            definition.id.replace('\'', "''"), source.table, column_name.replace('\'', "''"),        ));    }    source        .columns        .iter()        .find(|name| **name == column_name)        .filter(|_| !is_computed_column(definition.rows_table(), column_name) && !RESOLVED_COLUMNS.contains(&(definition.rows_table(), column_name))            && definition.column(column_name).is_some_and(|column| column.multiple != Some(true)))        .map(|name| format!("{}.\"{name}\"", source.table))        .ok_or_else(|| super::refuse(RecordError::CannotNarrow { plural: definition.plural.clone(), column: column_name.to_string() }))}/// A `signed` formula over one stored number, turned over while a stored/// word holds one of its values (Owed's `owed_signed`), as SQL over the row/// itself: what `cotton_rules::computed::formula` keeps, never a lookup of/// the kept value per row. A sum of it reads the columns an index holds.fn signed_sql(definition: &TableDefinition, source: &Source, column_name: &str) -> Option<String> {    use cotton_core::definitions::computed::{Computed, FormulaOp};    let Some(Computed::Formula(formula)) = definition.column(column_name)?.computed.as_ref() else { return None };    let flip = formula.flip_when.as_ref()?;    let [of] = formula.of.as_slice() else { return None };    if formula.op != FormulaOp::Signed { return None; }    let rows = definition.rows_table();    let stored = |key: &str, types: &[ColumnType]| source.columns.contains(&key) && !is_computed_column(rows, key)        && !RESOLVED_COLUMNS.contains(&(rows, key)) && !TEXT_LISTS.contains(&(rows, key))        && definition.column(key).is_some_and(|column| column.computed.is_none() && column.multiple != Some(true) && types.contains(&column.column_type));    if !stored(of, &[ColumnType::Amount, ColumnType::Number]) || !stored(&flip.column, &[ColumnType::Choice, ColumnType::Text]) || flip.values.is_empty() {        return None;    }    let (table, of, by) = (source.table, of.as_str(), flip.column.as_str());    let values = flip.values.iter().map(|value| format!("'{}'", value.replace('\'', "''"))).collect::<Vec<_>>().join(", ");    Some(format!(        "(CASE WHEN typeof({table}.\"{of}\") IN ('integer', 'real') THEN CASE WHEN typeof({table}.\"{by}\") = 'text' AND {table}.\"{by}\" IN ({values}) THEN -{table}.\"{of}\" ELSE {table}.\"{of}\" END END)"    ))}/// A stored table’s latest live stamp, independent of its display order and/// day-plan pagination. Views without a stored stamp honestly answer none.pub(super) fn last_changed(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid<Option<String>> {    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    let Ok(source) = source(definition) else { return Ok(None) };    if !source.updated { return Ok(None) }    let mut query = base_query(&source).columns(&["updated_at"]);    for column in &source.gone {        query = query.filter(Filter::IsNull((*column).to_string()));    }    for clause in super::shown(definition, &[])? {        for filter in narrow(ctx, definition, &source, &clause, &zone)? {            query = query.filter(filter);        }    }    if definition.rows_table() == "journal" {        query = query.filter(Filter::Static(JOURNAL_DAY_HAS_WORDS));    }    if let Some(hidden) = definition.hidden.as_ref()        .filter(|_| LISTS_LEAVE_HIDDEN_OUT.contains(&definition.rows_table()))        .filter(|hidden| source.columns.contains(&hidden.column.as_str()))    {        query = query.filter(Filter::NotIn(hidden.column.clone(),            hidden.values.iter().cloned().map(SqlValue::Text).collect()));    }    let found = rows(ctx, &query.order_by("updated_at", Order::Desc).limit(1))?;    Ok(found.first().and_then(|row| text(row, "updated_at")))}/// Several-choice columns the store keeps as TEXT holding a JSON list:/// `(table, column)`. The reads answer the list the column's type holds, and/// a row brought back by undo stores the text again.const TEXT_LISTS: &[(&str, &str)] = &[("mood", "emotions")];/// A resolved column's answer — see `RESOLVED_COLUMNS`.fn resolve(    ctx: &Ctx<'_>,    definition: &TableDefinition,    key: &str,    row: &Map<String, Value>,    value: &Value,    page: &PageReads,) -> Value {    match (definition.rows_table(), key) {        // What was read off a paper, a labelled line each — never the stored        // object: the account's last digits, the amount, when it is due and        // its reference.        ("document", "facts") => {            let facts = match value {                Value::String(raw) => serde_json::from_str::<Value>(raw).unwrap_or(Value::Null),                other => other.clone(),            };            let Some(facts) = facts.as_object() else {                return Value::Null;            };            let said = |key: &str| facts.get(key).and_then(Value::as_str).map(str::trim).filter(|word| !word.is_empty());            let currency = said("currency");            // The keys the reader is asked to use come first, in a paper's            // own order; anything else it found follows under its own name.            const KNOWN: &[(&str, &str)] = &[                ("account_last4", "Account"),                ("total_minor", "Amount"),                ("opening_balance_minor", "Opening balance"),                ("closing_balance_minor", "Closing balance"),                ("due_date", "Due"),                ("expires_on", "Expires"),                ("reference", "Reference"),                ("invoice_number", "Invoice number"),                ("policy_number", "Policy number"),                ("registration_number", "Registration number"),                ("patient_name", "Patient"),            ];            let named = KNOWN.iter().map(|(key, label)| (*key, (*label).to_string()));            let found = facts.keys().filter(|key| key.as_str() != "currency" && !KNOWN.iter().any(|(known, _)| known == key)).map(|key| {                let words = key.trim_end_matches("_minor").replace('_', " ");                let mut letters = words.chars();                let label = letters.next().map_or_else(String::new, |first| first.to_uppercase().chain(letters).collect());                (key.as_str(), label)            });            let mut lines: Vec<String> = Vec::new();            for (key, label) in named.chain(found) {                let line = match facts.get(key) {                    Some(Value::Number(minor)) if key.ends_with("_minor") => minor.as_i64().map(|minor| document_amount(minor, currency)),                    Some(Value::String(day)) if key.ends_with("_date") || key.ends_with("_on") => Some(                        chrono::NaiveDate::parse_from_str(day.get(..10).unwrap_or(day), "%Y-%m-%d")                            .map_or_else(|_| day.trim().to_string(), |day| day.format("%-d %B %Y").to_string()),                    ),                    Some(Value::String(last4)) if key == "account_last4" => Some(format!("•••• {}", last4.trim())),                    Some(Value::String(words)) => Some(words.trim().to_string()),                    Some(Value::Number(number)) => Some(number.to_string()),                    Some(Value::Bool(yes)) => Some(if *yes { "Yes" } else { "No" }.to_string()),                    _ => None,                };                if let Some(line) = line.filter(|line| !line.is_empty() && !label.is_empty()) {                    lines.push(format!("{label}: {line}"));                }            }            display_lines(lines)        }        // A kit's tools by name, a line each — the text update_record takes back.        ("toolkit", "tools") => serde_json::from_value::<Vec<cotton_core::toolkits::KitTool>>(Value::Array(json_list(value)))            .map(|tools| Value::from(crate::toolkits::tool_names(&tools).join("\n")))            .unwrap_or(Value::Null),        // A kit's picture: the photo it names, never the stored object.        ("toolkit", "picture") => {            let stored = match value {                Value::String(raw) => serde_json::from_str::<Value>(raw).unwrap_or(Value::Null),                other => other.clone(),            };            match serde_json::from_value::<cotton_core::definitions::ToolPicture>(stored) {                Ok(cotton_core::definitions::ToolPicture::Photo(photo)) => Value::from(photo.photo),                _ => Value::Null,            }        }        // What the owner attached to a session message: each attachment's        // media key, a line each — an entry with no key (a pre-cutover `url`)        // is not drawable and is left out.        ("session_message", "media") => display_lines(            json_list(value)                .iter()                .filter_map(|entry| entry.get("key").and_then(Value::as_str))                .map(str::trim)                .filter(|key| !key.is_empty())                .map(str::to_string)                .collect(),        ),        ("session", "shipped") => crate::session_words::shipped_lines(value).map_or(Value::Null, Value::from),        ("message", "media" | "reactions") => match &page.chat {            Some(chat) => super::chat_views::resolve_message(ctx, key, row, chat),            None => Value::Null,        },        _ => Value::Null,    }}/// A JSON list column, stored as its text or read already parsed.fn json_list(value: &Value) -> Vec<Value> {    match value {        Value::Array(items) => items.clone(),        Value::String(raw) => match serde_json::from_str::<Value>(raw) {            Ok(Value::Array(items)) => items,            _ => Vec::new(),        },        _ => Vec::new(),    }}/// Lines a long text column answers: one per line, or null for none.fn display_lines(lines: Vec<String>) -> Value {    if lines.is_empty() {        Value::Null    } else {        Value::from(lines.join("\n"))    }}fn stored_from(    ctx: &Ctx<'_>,    definition: &TableDefinition,    source: &Source,    row: &Map<String, Value>,    page: &PageReads,) -> Valid<Stored> {    let mut data = Data::new();    for column in &definition.columns {        if !source.columns.contains(&column.key.as_str()) {            continue;        }        let value = row.get(&column.key).cloned().unwrap_or(Value::Null);        let value = if RESOLVED_COLUMNS.contains(&(definition.rows_table(), column.key.as_str())) {            resolve(ctx, definition, &column.key, row, &value, page)        } else if TEXT_LISTS.contains(&(definition.rows_table(), column.key.as_str())) {            Some(json_list(&value))                .filter(|list| !list.is_empty())                .map_or(Value::Null, Value::Array)        } else if column.column_type == cotton_core::definitions::ColumnType::Bool {            // The store keeps a yes-or-no as 0 or 1. A page reads only true            // and false, so a stored 0 answered as a number drew "Favourite —",            // a switch with no state.            match value.as_i64() {                Some(stored) => Value::Bool(stored != 0),                None => value,            }        } else {            value        };        if !value.is_null() {            data.insert(column.key.clone(), value);        }    }    engine_extras(ctx, definition, row, page, &mut data)?;    Ok(Stored {        id: text(row, if definition.rows_table() == "device" { "device_id" } else { "id" }).unwrap_or_default(),        data,        created_at: text(row, "created_at"),        updated_at: text(row, "updated_at"),        deleted_at: source.gone.iter().find_map(|column| text(row, column)),        byline: None,    })}// ── what an engine answers beyond its stored columns ────────────────────────/// Store columns a table's [`engine_extras`] read beyond its definition's —/// selected, never answered. Each name is matched against `TABLE_SPECS` by/// [`source`], so a name the store does not declare is simply not read.fn extra_reads(table: &str) -> &'static [&'static str] {    match table {        "event" => &["gcal_id", "source_inbox_id", "organizer_is_self"],        "transaction" => &["status", "occurred_on", "due_date", "for_period", "repeat", "repeat_day"],        "document" => &["mime", "decrypted_path"],        "device" => &["device_id"],        "thread" => super::chat_views::THREAD_READS,        "message" => super::chat_views::MESSAGE_READS,        "story" => &["account", "external_id"],        _ => &[],    }}/// A page's pictures, read once for every record on it: owner id → its list.type PagePictures = std::collections::HashMap<String, Vec<Value>>;/// What a page of records reads ONCE for all of them, so a read costs the/// same few queries whatever its length.#[derive(Default)]struct PageReads {    /// Story expiry is said in the known workspace calendar, never a guessed zone.    story_zone: Option<String>,    /// Every record's pictures, for a table whose engine keeps them.    pictures: Option<PagePictures>,    /// Chats and messages: names, members, reactions, quoted lines.    chat: Option<super::chat_views::ChatReads>,    /// The project each record is filed under, for a table whose project is    /// a link ([`PROJECT_LINKS`]): record id → project id.    filed: Option<std::collections::HashMap<String, String>>,    /// The mail each transaction on this page was recorded from.    record_threads: std::collections::HashMap<String, String>,    /// One record read for its page, never a list: only then is a long text    /// read off other tables answered (a meeting's transcript).    whole: bool,}/// Read what [`PageReads`] holds for `found`.fn page_reads(    ctx: &Ctx<'_>,    definition: &TableDefinition,    found: &[Map<String, Value>],) -> Valid<PageReads> {    let mut page = PageReads::default();    if definition.rows_table() == "story" {        page.story_zone = workspace_timezone_or_null(ctx)?;    }    if let Some(owner) = attachment_owner(definition) {        let ids: Vec<String> = found.iter().filter_map(|row| text(row, "id")).collect();        page.pictures = Some(attachment_refs_by_owner(ctx, owner, &ids)?);    }    if project_link_column(definition).is_some() {        let ids: Vec<String> = found.iter().filter_map(|row| text(row, "id")).collect();        page.filed = Some(filed_under(ctx, definition.rows_table(), &ids)?);    }    match definition.rows_table() {        "thread" => page.chat = Some(super::chat_views::thread_reads(ctx, found)?),        "message" => page.chat = Some(super::chat_views::message_reads(ctx, found)?),        "transaction" if !found.is_empty() => {            let ids = found.iter().filter_map(|row| text(row, "id")).map(SqlValue::Text).collect();            let query = Query::on("cotton_links")                .columns(&["from_id", "to_id"])                .eq("from_kind", "transaction".to_string())                .filter(Filter::In("from_id".into(), ids))                .eq("to_kind", "email_thread".to_string())                .filter(Filter::IsNull("to_database".into()))                .order_by("created_at", Order::Asc)                .order_by("id", Order::Asc);            for row in rows(ctx, &query)? {                if let (Some(record), Some(thread)) = (text(&row, "from_id"), text(&row, "to_id")) {                    page.record_threads.entry(record).or_insert(thread);                }            }        }        _ => {}    }    Ok(page)}/// Which engine keeps this built-in's pictures, if one does.fn attachment_owner(definition: &TableDefinition) -> Option<&'static AttachmentOwner> {    if !carries_attachments(definition) {        return None;    }    match definition.rows_table() {        "note" => Some(&NOTE),        _ => None,    }}/// Add what the engine answers beyond the stored columns to one record's/// `data`: its pictures (out of `page`, read once for every record on it), a/// thought's story and links, a picture's albums and an album's print, and a/// news edition's figure and progress.fn engine_extras(    ctx: &Ctx<'_>,    definition: &TableDefinition,    row: &Map<String, Value>,    page: &PageReads,    data: &mut Data,) -> Valid<()> {    let id = text(row, "id").unwrap_or_default();    if let Some(pictures) = page.pictures.as_ref().and_then(|pictures| pictures.get(&id)) {        if !pictures.is_empty() {            data.insert(ATTACHMENTS_KEY.to_string(), Value::Array(pictures.clone()));        }    }    if let Some(column) = project_link_column(definition) {        if let Some(project) = page.filed.as_ref().and_then(|filed| filed.get(&id)) {            data.insert(column.to_string(), Value::from(project.clone()));        }    }    match definition.rows_table() {        "todo" => todo_extras(ctx, row, data)?,        "note" => linked_people(ctx, "note", &id, data)?,        "event" => event_extras(ctx, row, data)?,        "transaction" => {            if let Some(thread) = page.record_threads.get(&id) {                data.insert("email_thread_id".into(), Value::from(thread.clone()));            }        }        "secret" => secret_extras(ctx, row, data)?,        "story" => story_extras(ctx, row, page, data),        "photo" | "video" => media_tables::picture_extras(ctx, row, data)?,        "album" => media_tables::album_extras(ctx, row, data)?,        "person_handle" => {            data.insert("kept".into(), Value::Bool(text(row, "verified_at").is_some()));        }        "call" => call_extras(ctx, row, data)?,        "person" => person_extras(ctx, row, data)?,        "document" => document_extras(ctx, definition, row, page, data)?,        "thread" => {            if let Some(chat) = &page.chat {                super::chat_views::thread_extras(ctx, row, chat, data);            }        }        "message" => {            if let Some(chat) = &page.chat {                super::chat_views::message_extras(row, chat, data);            }        }        _ => {}    }    Ok(())}/// Built-ins whose project is a LINK the projects engine keeps/// (`cotton_project_links`), never a column of their own row: `(table, the/// column its definition shows the project in)`. The reads answer the project/// the record is filed under, and a write of the column files it there —/// `link_to_project` — or takes it out, `unlink_from_project`.const PROJECT_LINKS: &[(&str, &str)] = &[    ("todo", "project"),    ("event", "project"),    ("note", "project_id"),    ("document", "projects"),    // Read only: a meeting is filed from the project's side.];fn project_link_column(definition: &TableDefinition) -> Option<&'static str> {    PROJECT_LINKS        .iter()        .find(|(table, column)| *table == definition.rows_table() && definition.column(column).is_some())        .map(|(_, column)| *column)}/// The project each of `ids` is filed under — the first it was linked to,/// among the projects this file still holds.fn filed_under(    ctx: &Ctx<'_>,    kind: &str,    ids: &[String],) -> Valid<std::collections::HashMap<String, String>> {    let mut filed = std::collections::HashMap::new();    if ids.is_empty() {        return Ok(filed);    }    let known = projects(ctx)?;    let links = Query::on("cotton_project_links")        .columns(&["project_id", "record_id", "created_at"])        .eq("record_kind", kind.to_string())        .filter(Filter::In(            "record_id".into(),            ids.iter().cloned().map(SqlValue::Text).collect(),        ))        .order_by("created_at", Order::Asc);    for link in rows(ctx, &links)? {        let (Some(project), Some(record)) = (text(&link, "project_id"), text(&link, "record_id"))        else {            continue;        };        if known.iter().any(|known| known.id == project) {            filed.entry(record).or_insert(project);        }    }    Ok(filed)}/// Every project `id` is linked to, in the order it was linked.fn linked_projects(ctx: &Ctx<'_>, kind: &str, id: &str) -> Valid<Vec<String>> {    let links = Query::on("cotton_project_links")        .columns(&["project_id", "created_at"])        .eq("record_kind", kind.to_string())        .eq("record_id", id.to_string())        .order_by("created_at", Order::Asc);    Ok(rows(ctx, &links)?        .iter()        .filter_map(|link| text(link, "project_id"))        .collect())}/// A write of a record's project column: it is filed under that project and/// no other, or — null — under none.fn file_under(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    project: &Value,) -> Valid<()> {    let wanted = match project {        Value::Null => None,        Value::String(project) => Some(project.clone()),        _ => {            return Err(ToolFailure::new(format!(                "{} are filed under one project",                definition.plural            )))        }    };    let known = projects(ctx)?;    let slug = match &wanted {        None => None,        Some(project) => Some(            project_slug_of(&known, project)                .ok_or_else(|| ToolFailure::new("That project is no longer here"))?,        ),    };    let current = linked_projects(ctx, definition.rows_table(), id)?;    let record = json!([{ "kind": definition.rows_table(), "id": id }]);    for other in current.iter().filter(|other| Some(*other) != wanted.as_ref()) {        // A link to a project this file no longer holds names no slug, and        // no read answers it either.        let Some(other) = project_slug_of(&known, other) else {            continue;        };        call(            ctx,            definition,            "unlink_from_project",            projects::write::unlink_from_project,            json!({ "project": other, "records": record }),        )?;    }    if let (Some(slug), Some(project)) = (slug, &wanted) {        if !current.contains(project) {            call(                ctx,                definition,                "link_to_project",                projects::write::link_to_project,                json!({ "project": slug, "records": record }),            )?;        }    }    Ok(())}/// The day an instant falls on in the workspace's zone, for a column that/// means a day although a writer stored the moment (a person note's day, a/// store's last order, an edition's day). None when the value will not read/// or no zone is known — the instant then stands.fn zoned_day(ctx: &Ctx<'_>, at: Option<&str>) -> Valid<Option<String>> {    let Some(ms) = at.and_then(parse_ms) else {        return Ok(None);    };    Ok(workspace_timezone_or_null(ctx)?.and_then(|zone| today_in(&zone, ms).ok()))}/// A person's birthday as one day ("1992-08-17", or "--08-17" when the year/// is not known; `ENGINE_WRITTEN_COLUMNS`), and their computed columns: what/// has arrived since their summary was written ("3 notes since"), and the channel/// their conversation runs over, so the page hands off to that app.fn person_extras(ctx: &Ctx<'_>, row: &Map<String, Value>, data: &mut Data) -> Valid<()> {    let id = text(row, "id").unwrap_or_default();    let part = |key: &str| row.get(key).and_then(Value::as_i64);    // The one rule (`cotton_core::rules::people::birthday`): the parts where    // set, else the object's whole date where the copy keeps one.    let whole = row.get("birthday").and_then(Value::as_str);    if let Some(birthday) = cotton_core::rules::people::birthday::Birthday::of(part("birth_month"), part("birth_day"), part("birth_year"), whole) {        data.insert("birthday".into(), Value::from(birthday.said()));    }    // Counted by when a note ARRIVED (`created_at`), never the day it is    // about: an import writes an old `noted_at` the summary still never saw.    if let Some(written) = text(row, "summary_updated_at").filter(|at| !at.is_empty()) {        let arrived = ctx            .read            .driver()            .get(                "SELECT COUNT(*) AS n FROM cotton_person_notes WHERE person_id = ?1 AND created_at > ?2",                &[SqlValue::Text(id.clone()), SqlValue::Text(written)],            )            .map_err(sql_err)?            .and_then(|row| row.int("n"))            .unwrap_or(0);        if let Some(since) = staleness_from(cotton_core::constants::SummaryKind::Person, arrived) {            let noun = since.noun.as_str();            let plural = if since.count == 1 { "" } else { "s" };            data.insert("summary_since".into(), Value::from(format!("{} {noun}{plural} since", since.count)));        }    }    if let Some(channel) = person_thread_channel(ctx, &id)? {        data.insert("thread_channel".into(), Value::from(channel));    }    Ok(())}/// The channel a person's conversation runs over, read off the newest message/// of their chat: the live direct chat whose contact names them, else one/// whose contact names nobody and carries one of their numbers; the freshest/// wins. A person with no chat, or a chat with no message, has none.fn person_thread_channel(ctx: &Ctx<'_>, person: &str) -> Valid<Option<String>> {    let numbers: Vec<String> = person_handle_values(ctx, person, "phone")?        .iter()        .filter_map(|phone| cotton_core::import::phone::normalize_phone(phone))        .collect();    // The contact's person, derived by who(handle) (PEOPLE BUILD 1); one naming nobody (a shared landline    // included) is found by the person's numbers.    let derived = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(ctx.read.driver()), "c");    let nobody = format!("{derived} IS NULL");    let phone_leg = if numbers.is_empty() {        String::new()    } else {        format!(" OR ({nobody} AND c.phone_e164 IN ({}))", vec!["?"; numbers.len()].join(", "))    };    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(person.to_string())];    params.extend(numbers.into_iter().map(SqlValue::Text));    Ok(ctx        .read        .driver()        .get(            &format!(                "SELECT (SELECT m.channel FROM cotton_msg_messages m \                          WHERE m.thread_id = t.id AND m.hidden_at IS NULL \                          ORDER BY m.sent_at DESC LIMIT 1) AS channel \                   FROM cotton_msg_threads t JOIN cotton_msg_contacts c ON c.id = t.contact_id \                  WHERE t.workspace_id = ? AND t.archived = 0 AND t.kind = 'dm' \                    AND ({derived} = ?{phone_leg}) \                  ORDER BY (t.last_message_at IS NULL) ASC, t.last_message_at DESC, t.id ASC LIMIT 1"            ),            &params,        )        .map_err(sql_err)?        .and_then(|row| row.text("channel").map(str::to_string))        .filter(|channel| !channel.trim().is_empty()))}/// One person's handles of one kind as written, in the page's order.fn person_handle_values(ctx: &Ctx<'_>, person: &str, kind: &str) -> Valid<Vec<String>> {    Ok(ctx        .read        .driver()        .all(            "SELECT value FROM cotton_person_handles WHERE person_id = ?1 AND kind = ?2 ORDER BY position, created_at, id",            &[SqlValue::Text(person.to_string()), SqlValue::Text(kind.to_string())],        )        .map_err(sql_err)?        .iter()        .filter_map(|row| row.text("value").map(str::to_string))        .collect())}/// A call's computed columns (`COMPUTED_COLUMNS`): who it was with — the/// person's name, else the number, else "Withheld number" — and what happened, in one word a list can/// say: incoming, outgoing, missed, no answer, cancelled, failed.pub(super) fn call_extras(ctx: &Ctx<'_>, row: &Map<String, Value>, data: &mut Data) -> Valid<()> {    let person = match text(row, "person_id") {        Some(person) => maybe_row(            ctx,            &Query::on("cotton_people").columns(&["id", "full_name", "avatar_key"]).eq("id", person),        )?,        None => None,    };    let phones = match person.as_ref().and_then(|person| text(person, "id")) {        Some(id) => person_handle_values(ctx, &id, "phone")?,        None => Vec::new(),    };    // The number as the person's page writes it ("+44 20 7946 0958"), where it is one    // of theirs: the same number, matched the way their chat is.    let handle = text(row, "handle").and_then(|handle| cotton_core::import::phone::normalize_phone(&handle));    let written = handle.and_then(|handle| {        phones            .iter()            .find(|phone| cotton_core::import::phone::normalize_phone(phone).as_deref() == Some(handle.as_str()))            .map(|phone| phone.trim().to_string())    });    if let Some(written) = written {        data.insert("handle".into(), Value::from(written));    }    // The caller's own picture, when the call is someone the owner knows.    if let Some(photo) = person.as_ref().and_then(|person| text(person, "avatar_key")) {        data.insert("photo".into(), Value::from(photo));    }    let name = person        .and_then(|person| text(&person, "full_name"))        .filter(|name| !name.trim().is_empty());    // A call that showed no number is still a call, never headed by its day.    // A number nobody is named for is said grouped with its plus    // ("+44 20 7946 0958"), never twelve bare digits.    let title = name        .or_else(|| {            text(row, "handle").filter(|handle| !handle.trim().is_empty())                .map(|handle| cotton_core::import::phone::phone_words(&handle).unwrap_or(handle))        })        .unwrap_or_else(|| "Withheld number".to_string());    data.insert("title".into(), Value::from(title));    let incoming = text(row, "direction").as_deref() != Some("out");    let label = match text(row, "outcome").as_deref() {        Some("answered") => Some(if incoming { "incoming" } else { "outgoing" }),        Some("missed") => Some(if incoming { "missed" } else { "no answer" }),        Some("cancelled") => Some("cancelled"),        Some("failed") => Some("failed"),        _ => None,    };    if let Some(label) = label {        data.insert("outcome_label".into(), Value::from(label));    }    Ok(())}/// The repeat preset as a typed key; the definition carries its words and/// the paused variants. A todo without a rule leaves the value absent./// And the people the todo is linked with, whichever way the link was made.fn todo_repeats_and_people(ctx: &Ctx<'_>, row: &Map<String, Value>, data: &mut Data) -> Valid<()> {    use cotton_core::transforms::recurrence_presets::preset_for_rrule;    if let Some(recurrence) = text(row, "recurrence_id") {        let rule = maybe_row(            ctx,            &Query::on("cotton_todo_recurrences").columns(&["rrule", "paused"]).eq("id", recurrence),        )?;        if let Some(rule) = rule {            let preset = preset_for_rrule(text(&rule, "rrule").as_deref()).as_str();            if preset != "none" {                let key = if flag(&rule, "paused") { format!("paused_{preset}") } else { preset.to_string() };                data.insert("repeats".into(), Value::from(key));            }        }    }    linked_people(ctx, "todo", &text(row, "id").unwrap_or_default(), data)}/// The people a record is linked with (`people`, a link holding several),/// whichever way round the link was made, in the order they were linked —/// left out when there are none, and never a person in another database.fn linked_people(ctx: &Ctx<'_>, kind: &str, id: &str, data: &mut Data) -> Valid<()> {    let people = linked_people_ids(ctx, kind, id)?;    if !people.is_empty() {        data.insert("people".into(), Value::Array(people.into_iter().map(Value::from).collect()));    }    Ok(())}fn linked_people_ids(ctx: &Ctx<'_>, kind: &str, id: &str) -> Valid<Vec<String>> {    Ok(ctx        .read        .driver()        .all(            "SELECT person FROM ( \               SELECT to_id AS person, created_at FROM cotton_links \                WHERE workspace_id = ?1 AND to_database IS NULL \                  AND from_kind = ?3 AND from_id = ?2 AND to_kind = 'person' \               UNION ALL \               SELECT from_id AS person, created_at FROM cotton_links \                WHERE workspace_id = ?1 AND to_database IS NULL \                  AND to_kind = ?3 AND to_id = ?2 AND from_kind = 'person' \             ) GROUP BY person ORDER BY MIN(created_at), person",            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(id.to_string()),                SqlValue::Text(kind.to_string()),            ],        )        .map_err(sql_err)?        .iter()        .filter_map(|row| row.text("person").map(str::to_string))        .collect())}/// A todo due on a day with no stated hour is stored as that day's midnight in/// the workspace's zone (the `moment_split` contract: midnight means "a day is/// enough"). A phone in another zone read that instant as the evening before —/// "+" made a todo "Due Sun, 4 Oct" and the list said "Sat, 3 Oct · 7:30 PM/// — 1 day late". So the read answers such a due as the bare day, and every/// device draws the day the person meant; a due with an hour stays an instant./// The zone is the workspace's; with none known the instant stands.fn todo_extras(ctx: &Ctx<'_>, row: &Map<String, Value>, data: &mut Data) -> Valid<()> {    todo_repeats_and_people(ctx, row, data)?;    let Some(due_at) = text(row, "due_at") else {        return Ok(());    };    let Some(zone) = workspace_timezone_or_null(ctx)? else {        return Ok(());    };    if let Ok(due) = split_moment(&due_at, &zone) {        if due.time.is_none() {            data.insert("due_at".into(), Value::from(due.date));        }    }    Ok(())}/// An all-day event is stored as the first day's midnight and the last day's/// final millisecond in the workspace's zone (`all_day_window`); read as/// instants on a phone in another zone they said "Thu, 15 Oct · 6:30 PM, All/// day". The read answers them as the days they cover, so an all-day event/// never shows a clock.fn event_extras(ctx: &Ctx<'_>, row: &Map<String, Value>, data: &mut Data) -> Valid<()> {    event_facts(ctx, row, data)?;    let Some(zone) = workspace_timezone_or_null(ctx)? else {        return Ok(());    };    if !flag(row, "all_day") {        return Ok(());    }    for key in ["starts_at", "ends_at"] {        let Some(at) = text(row, key) else { continue };        let Some(ms) = parse_ms(&at) else { continue };        if let Ok(day) = today_in(&zone, ms) {            data.insert(key.into(), Value::from(day));        }    }    Ok(())}/// What an event's page says beyond its own row: each guest and their reply/// ("Jelena · Accepted"), the people it is with — linked by hand, or a guest/// whose address is a person's — the calendar it is kept in by name, and/// where it came from.fn event_facts(ctx: &Ctx<'_>, row: &Map<String, Value>, data: &mut Data) -> Valid<()> {    let id = text(row, "id").unwrap_or_default();    // The Records thread it was added from, if it was (its link to the thread).    if let Some(thread) = crate::mcp::handlers::emails::record_fields::recorded_from(ctx, "event", &id) {        data.insert("email_thread_id".into(), Value::from(thread));    }    let guests = ctx        .read        .driver()        .all(            "SELECT email, phone, display_name, response FROM cotton_event_attendees \             WHERE event_id = ?1 ORDER BY created_at, id",            &[SqlValue::Text(id.clone())],        )        .map_err(sql_err)?;    let said = |value: Option<&str>| value.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string);    let replies: Vec<String> = guests        .iter()        .filter_map(|guest| {            let who = said(guest.text("display_name"))                .or_else(|| said(guest.text("email")))                .or_else(|| said(guest.text("phone")))?;            let reply = match guest.text("response") {                Some("accepted") => "Accepted",                Some("declined") => "Declined",                Some("tentative") => "Maybe",                _ => "No reply yet",            };            Some(format!("{who} · {reply}"))        })        .collect();    if !replies.is_empty() {        data.insert("guest_responses".into(), Value::from(replies.join("\n")));    }    let mut people = linked_people_ids(ctx, "event", &id)?;    for guest in ctx        .read        .driver()        .all(            "SELECT DISTINCT p.id AS person FROM cotton_event_attendees a \             JOIN cotton_people p ON p.workspace_id = ?1 AND p.archived_at IS NULL \              AND EXISTS (SELECT 1 FROM cotton_person_handles h WHERE h.person_id = p.id AND h.kind = 'email' AND h.normalised = lower(trim(a.email))) \             WHERE a.event_id = ?2 AND a.email IS NOT NULL AND a.email <> '' ORDER BY p.id",            &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(id.clone())],        )        .map_err(sql_err)?    {        if let Some(person) = guest.text("person") {            if !people.iter().any(|known| known == person) {                people.push(person.to_string());            }        }    }    if !people.is_empty() {        data.insert("people".into(), Value::Array(people.into_iter().map(Value::from).collect()));    }    // The default calendar goes unnamed: it is the database's own, and its    // placeholder name ("Personal") is not a word the owner chose.    if let Some(collection) = text(row, "collection_id") {        let name = maybe_row(ctx, &Query::on("cotton_collections").columns(&["name", "is_default"]).eq("id", collection))?            .filter(|calendar| !flag(calendar, "is_default"))            .and_then(|calendar| text(&calendar, "name"))            .filter(|name| !name.trim().is_empty());        if let Some(name) = name {            data.insert("calendar_name".into(), Value::from(name));        }    }    // Made in Cotton says nothing: only an event that came from elsewhere    // says where.    let source = if text(row, "gcal_id").is_some() {        Some("Google Calendar")    } else if text(row, "source_inbox_id").is_some() {        Some("A thought")    } else {        None    };    if let Some(source) = source {        data.insert("source".into(), Value::from(source));    }    // An invitation someone else sent: only then is there a reply to give.    if row.contains_key("organizer_is_self") && !flag(row, "organizer_is_self") {        data.insert("invited".into(), Value::from("invited"));    }    Ok(())}/// The day an event is on, and the time it starts, in the READER's zone —/// the zone the read names (a phone names its own), else the workspace's —/// so the heading over an event and the slip under it are drawn from one/// day. Never words counted from today: those are the screen's to say. An/// all-day event's day is the day it says, and it has no start time.pub(super) fn event_day(ctx: &Ctx<'_>, data: &Data, reader_zone: Option<&str>) -> Valid<Option<(String, Option<String>)>> {    let Some(at) = data.get("starts_at").and_then(Value::as_str) else {        return Ok(None);    };    if at.len() == 10 {        return Ok(Some((at.to_string(), None)));    }    let zone = match reader_zone {        Some(zone) => Some(zone.to_string()),        None => workspace_timezone_or_null(ctx)?,    };    let (Some(zone), Some(ms)) = (zone, parse_ms(at)) else {        return Ok(None);    };    let Ok(parts) = cotton_core::transforms::zoned_clock::zoned_parts(ms, &zone) else {        return Ok(None);    };    let Ok(day) = today_in(&zone, ms) else {        return Ok(None);    };    Ok(Some((day, Some(format!("{:02}:{:02}", parts.hour, parts.minute)))))}/// Retention is the owner's choice; expiry is the source app's clock. A/// missing original does not undo Keep, and Keep does not stop app expiry.fn story_extras(ctx: &Ctx<'_>, row: &Map<String, Value>, page: &PageReads, data: &mut Data) {    let retention = if flag(row, "kept") {        Some("Kept — stays until you remove it")    } else if text(row, "media_dropped_at").is_some_and(|at| !at.trim().is_empty()) {        Some("The picture is no longer kept")    } else {        None    };    if let Some(words) = retention {        data.insert("retention_line".into(), Value::from(words));    }    let Some(expires) = text(row, "expires_at").as_deref().and_then(parse_ms) else { return };    let now = ctx.now.timestamp_millis();    let words = if expires <= now {        "Gone".to_string()    } else {        let Some(zone) = page.story_zone.as_deref() else { return };        let day = |ms| today_in(zone, ms).ok().and_then(|day| chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").ok());        let (Some(today), Some(end)) = (day(now), day(expires)) else { return };        match (end - today).num_days() {            n if n <= 0 => "Goes today".to_string(),            1 => "Goes tomorrow".to_string(),            days => format!("Goes in {days} days"),        }    };    data.insert("expiry_line".into(), Value::from(words));}/// A password's expiry is a day, and a card's is the month and year printed/// on it. Stored as an instant (a bare day written in became UTC midnight;/// the generator stamps a clock), it drew as "Runs out Mon, 8 Nov 2027 ·/// 2:30 PM" on a phone in another zone. The read answers the day — a UTC/// midnight as the day written, anything else in the workspace's zone — and a/// card's as "YYYY-MM".fn secret_extras(ctx: &Ctx<'_>, row: &Map<String, Value>, data: &mut Data) -> Valid<()> {    let at = text(row, "expires_at");    let Some(ms) = at.as_deref().and_then(parse_ms) else {        return Ok(());    };    let written = iso_of_ms(ms);    let zoned = if ms.rem_euclid(86_400_000) == 0 {        None    } else {        zoned_day(ctx, at.as_deref())?    };    let day = zoned.unwrap_or_else(|| written.chars().take(10).collect());    let answer: String = if text(row, "kind").as_deref() == Some("card") {        day.chars().take(7).collect()    } else {        day    };    data.insert("expires_at".into(), Value::from(answer));    Ok(())}/// The calls a search finds: every word is in the caller's name (a person in/// People) or in the number. A call stores no title — its title is who it was/// with — so a LIKE over the title found nobody by name.fn call_search(ctx: &Ctx<'_>, words: &str) -> Valid<Filter> {    let mut found: Option<Vec<String>> = None;    for word in words.split_whitespace() {        let pattern = format!("%{}%", word.replace(['%', '_'], ""));        let people: Vec<SqlValue> = rows(            ctx,            &Query::on("cotton_people")                .columns(&["id"])                .filter(Filter::Like("full_name".to_string(), pattern.clone())),        )?        .iter()        .filter_map(|row| text(row, "id"))        .map(SqlValue::Text)        .collect();        let mut ids: Vec<String> = Vec::new();        for filter in [            Filter::In("person_id".to_string(), people),            Filter::Like("handle".to_string(), pattern),        ] {            ids.extend(                rows(ctx, &Query::on("cotton_call_log").columns(&["id"]).filter(filter))?                    .iter()                    .filter_map(|row| text(row, "id")),            );        }        found = Some(match found {            None => ids,            Some(before) => before.into_iter().filter(|id| ids.contains(id)).collect(),        });    }    Ok(Filter::In(        "id".to_string(),        found.unwrap_or_default().into_iter().map(SqlValue::Text).collect(),    ))}/// The statement read from a document — a bank or card statement's paper/// opens its lines. One document is read into at most one statement.fn document_extras(    ctx: &Ctx<'_>,    definition: &TableDefinition,    row: &Map<String, Value>,    page: &PageReads,    data: &mut Data,) -> Valid<()> {    let id = text(row, "id").unwrap_or_default();    let statement = maybe_row(        ctx,        &Query::on("cotton_money_statements")            .columns(&["id"])            .eq("document_id", id.clone())            .limit(1),    )?    .and_then(|row| text(&row, "id"));    if let Some(statement) = statement {        data.insert("statement_id".into(), Value::from(statement));    }    linked_people(ctx, "document", &id, data)?;    let said = |key: &str| text(row, key).filter(|value| !value.trim().is_empty());    let status = said("status");    let status = status.as_deref();    // How long the paper is, as its cover says it.    match row.get("page_count").and_then(Value::as_i64) {        Some(1) => drop(data.insert("page_line".into(), Value::from("1 p"))),        Some(pages) if pages > 1 => drop(data.insert("page_line".into(), Value::from(format!("{pages} pp")))),        _ => {}    }    // The years the paper covers, when it says both ends: "2026", "2024–2026".    let year = |key: &str| said(key).and_then(|day| day.get(..4)?.parse::<i32>().ok());    if let (Some(start), Some(end)) = (year("period_start"), year("period_end")) {        let (from, to) = (start.min(end), start.max(end));        let years = if from == to { from.to_string() } else { format!("{from}–{to}") };        data.insert("period_years".into(), Value::from(years));    }    // What is happening to it, only while that is not "ready": a paper that    // was read says nothing about having been read. Said by the database's    // `documents` lines (contract 3), read only for a paper that has a state.    let lines = cotton_core::rules::shell_lines::LineSet::of_rows(        "documents",        &crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id),    );    if let Some(state) = document_state(status, said("error_code").as_deref(), said("created_at").as_deref(), &now_iso(ctx)) {        if let Some(words) = lines.as_ref().and_then(|lines| lines.say(&state, &[])) {            data.insert("state_message".into(), Value::from(words));        }    }    // Days are said in the workspace's zone, the year only when it is not    // this one; with no zone to read, the day as stored.    let zone = workspace_timezone_or_null(ctx)?;    let local_day = |at: &str| -> Option<chrono::NaiveDate> {        let day = match (&zone, at.len() > 10, parse_ms(at)) {            (Some(zone), true, Some(ms)) => today_in(zone, ms).ok()?,            _ => at.get(..10)?.to_string(),        };        chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").ok()    };    let today = local_day(&now_iso(ctx));    let short = |at: &str| -> Option<String> {        use chrono::Datelike;        let day = local_day(at)?;        Some(match today {            Some(today) if today.year() != day.year() => day.format("%-d %b %Y").to_string(),            _ => day.format("%-d %b").to_string(),        })    };    // What kind of paper it is and its day: the kind once it was read and is    // one of the named kinds, else the file's format.    let kind = said("doc_type").filter(|kind| status == Some("ready") && kind != "other").map(|kind| {        definition            .column("doc_type")            .and_then(|column| column.labels.as_ref())            .and_then(|labels| labels.get(&kind).cloned())            .unwrap_or(kind)    });    let mut type_line: Vec<String> = kind        .or_else(|| {            // The file's format, said by the database's `documents` lines:            // an HTML page is a "Web page", never "Text".            let format = cotton_core::rules::file_format::FileFormat::of(said("mime").as_deref(), said("original_name").as_deref())?;            lines.as_ref()?.say(format.line(), &[])        })        .into_iter()        .collect();    type_line.extend(said("document_date").or_else(|| said("created_at")).and_then(|at| short(&at)));    if !type_line.is_empty() {        data.insert("type_line".into(), Value::from(type_line.join(" · ")));    }    // How it came in, and the day.    let came = match said("source").as_deref() {        Some("agent") => "Filed by an assistant",        Some("share") => "Shared into Cotton",        _ => "Added here",    };    let provenance = match said("created_at").and_then(|at| short(&at)) {        Some(day) => format!("{came} · {day}"),        None => came.to_string(),    };    data.insert("provenance".into(), Value::from(provenance));    // The words read off each page, on the paper's own page only — and never    // a locked paper's, until a copy of it has been opened.    if page.whole && !(status == Some("locked") && said("decrypted_path").is_none()) {        let pages: Vec<String> = ctx            .read            .driver()            .all(                "SELECT page, text FROM cotton_document_pages WHERE document_id = ?1 ORDER BY page",                &[SqlValue::Text(id)],            )            .map_err(sql_err)?            .iter()            .filter_map(|page| {                let words = page.text("text").map(str::trim).filter(|words| !words.is_empty())?;                Some(format!("Page {}\n{words}", page.int("page").unwrap_or(0)))            })            .collect();        if !pages.is_empty() {            data.insert("pages_text".into(), Value::from(pages.join("\n\n")));        }    }    Ok(())}/// An amount read off a paper: its currency's code, then the figure.fn document_amount(minor: i64, currency: Option<&str>) -> String {    let figure = format!("{}{}.{:02}", if minor < 0 { "−" } else { "" }, minor.unsigned_abs() / 100, minor.unsigned_abs() % 100);    match currency {        Some(code) => format!("{} {figure}", code.to_uppercase()),        None => figure,    }}/// Why a paper could not be read, as one sentence — and every one says the/// file is safe, because it is: the bytes are kept before any reading starts./// The `documents` line a paper's state is said by, or `None` once it is/// ready. A paper still `processing` an hour after it was filed says why it/// waits when the worker wrote the reason on it (`error_code`, e.g./// `model_held` while the assistant's credits are spent) instead of/// "Opening it…" for ever.pub(crate) fn document_state(status: Option<&str>, code: Option<&str>, created_at: Option<&str>, now: &str) -> Option<String> {    const FAILURES: [&str; 7] =        ["no_file", "unsupported_format", "unreadable_file", "nothing_to_read", "profile_failed", "ai_unavailable", "apply_failed"];    const WAITS: [&str; 1] = ["model_held"];    let stuck = || match (created_at.and_then(parse_ms), parse_ms(now)) {        (Some(filed), Some(now)) => now - filed > 60 * 60 * 1000,        _ => false,    };    Some(match status? {        "processing" => match code {            Some(code) if WAITS.contains(&code) && stuck() => format!("state.waiting.{code}"),            _ => "state.processing".into(),        },        "summarizing" => "state.summarizing".into(),        "locked" => "state.locked".into(),        "failed" => format!("failed.{}", code.filter(|code| FAILURES.contains(code)).unwrap_or("other")),        _ => return None,    })}/// A key a write may never carry: a column the engine computes, one only the/// device holding the fact answers, or `links`.fn computed_key(definition: &TableDefinition, key: &str) -> bool {    key == LINKS_KEY        || is_computed_column(definition.rows_table(), key)        || is_device_answered_column(definition.rows_table(), key)}// ── where ───────────────────────────────────────────────────────────────────/// A built-in's own narrowing by one column the generic path cannot filter:/// the conditions it adds to the read. The hook a table adds keys through.type Narrow = fn(&Ctx<'_>, &TableDefinition, &Condition) -> Valid<Vec<Filter>>;/// Every built-in column a `where` reaches through its engine:/// `(table, column, how)`. A table adds a key by adding a row here — the/// generic path never changes. An entry wins over the generic stored-column/// filter, so a table can also re-read a stored column its own way.pub(super) const NARROWINGS: &[(&str, &str, Narrow)] = &[    ("event", "invited", event_invited),    ("photo", "albums", media_tables::in_album),    ("video", "albums", media_tables::in_album),    ("photo", "addable_to", media_tables::addable_to),    ("photo", "people", media_tables::with_person),    ("video", "people", media_tables::with_person),    ("statement_line", "transaction_id", statement_line_transaction),    ("money_account", "is_pooled", pooled_account),    ("money_account", "kind", account_kind),    ("message", "kept", super::chat_views::kept),    ("thread", "member_people", super::chat_views::with_person),    ("thread", "channels", super::chat_views::by_channel),    ("todo", "people", linked_with_person),    ("note", "people", linked_with_person),    ("document", "people", linked_with_person),    ("event", "people", linked_with_person),];/// `where people`: a record's `people` read backwards — the records of this/// table linked with the person asked for, whichever way round the link was/// made (as [`linked_people_ids`] reads it), and for an event the ones a/// contact of theirs is a guest of (as `event_extras` reads it). A person's/// page lists and counts its todos, notes, documents and events by this.fn linked_with_person(    ctx: &Ctx<'_>,    definition: &TableDefinition,    condition: &Condition,) -> Valid<Vec<Filter>> {    // `None` is "anybody at all" (`Present`); the bool says to keep the rest.    let (people, without): (Option<Vec<String>>, bool) = match condition {        Condition::Is(value) => (Some(value.as_str().map(str::to_string).into_iter().collect()), false),        Condition::OneOf(values) => (            Some(values.iter().filter_map(|value| value.as_str().map(str::to_string)).collect()),            false,        ),        Condition::Present(present) => (None, !present),        Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"),    };    let kind = definition.rows_table();    let workspace = SqlValue::Text(ctx.workspace_id.to_string());    let mut linked: Vec<(String, String)> = Vec::new();    for row in ctx        .read        .driver()        .all(            "SELECT from_id AS record, to_id AS person FROM cotton_links \              WHERE workspace_id = ?1 AND to_database IS NULL \                AND from_kind = ?2 AND to_kind = 'person' \             UNION \             SELECT to_id AS record, from_id AS person FROM cotton_links \              WHERE workspace_id = ?1 AND to_database IS NULL \                AND to_kind = ?2 AND from_kind = 'person'",            &[workspace.clone(), SqlValue::Text(kind.to_string())],        )        .map_err(sql_err)?    {        if let (Some(record), Some(person)) = (row.text("record"), row.text("person")) {            linked.push((record.to_string(), person.to_string()));        }    }    if kind == "event" {        for row in ctx            .read            .driver()            .all(                "SELECT DISTINCT a.event_id AS record, p.id AS person FROM cotton_event_attendees a \                 JOIN cotton_people p ON p.workspace_id = ?1 AND p.archived_at IS NULL \                  AND EXISTS (SELECT 1 FROM cotton_person_handles h WHERE h.person_id = p.id AND h.kind = 'email' AND h.normalised = lower(trim(a.email))) \                 WHERE a.email IS NOT NULL AND a.email <> ''",                &[workspace],            )            .map_err(sql_err)?        {            if let (Some(record), Some(person)) = (row.text("record"), row.text("person")) {                linked.push((record.to_string(), person.to_string()));            }        }    }    let mut ids: Vec<String> = linked        .into_iter()        .filter(|(_, person)| people.as_ref().is_none_or(|wanted| wanted.contains(person)))        .map(|(record, _)| record)        .collect();    ids.sort();    ids.dedup();    let ids = ids.into_iter().map(SqlValue::Text).collect();    Ok(vec![if without { Filter::NotIn("id".into(), ids) } else { Filter::In("id".into(), ids) }])}/// The same evidence resolver that answers a statement line's transaction,/// narrowed before pagination so a transaction page keeps all its statement links.fn statement_line_transaction(    _ctx: &Ctx<'_>,    _definition: &TableDefinition,    condition: &Condition,) -> Valid<Vec<Filter>> {    // Query evidence directly: no workspace-sized id vector and no extra read    // before the list's count, ordering and pagination are applied.    let mut evidence = Query::on("cotton_money_evidence")        .columns(&["ref_id"])        .eq("kind", "statement_line".to_string())        .filter(Filter::NotNull("transaction_id".into()));    match condition {        Condition::Is(value) => evidence = evidence.filter(Filter::Eq("transaction_id".into(), sql_value(value))),        Condition::OneOf(values) => evidence = evidence.filter(Filter::In("transaction_id".into(), values.iter().map(sql_value).collect())),        Condition::Present(_) => {},        Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"),    }    Ok(vec![Filter::InQuery {        column: "id".into(),        query: Box::new(evidence),        negate: matches!(condition, Condition::Present(false)),    }])}/// Transactions store their account directly; filtering never walks removed entries.fn pooled_account(    _ctx: &Ctx<'_>,    _definition: &TableDefinition,    condition: &Condition,) -> Valid<Vec<Filter>> {    let wanted = match condition {        Condition::Is(value) => vec![value            .as_bool()            .ok_or_else(|| ToolFailure::new("Pooled needs true or false"))?],        Condition::OneOf(values) => values            .iter()            .map(|value| {                value                    .as_bool()                    .ok_or_else(|| ToolFailure::new("Pooled needs true or false"))            })            .collect::<Valid<Vec<_>>>()?,        Condition::Present(true) => return Ok(vec![]),        Condition::Present(false) => return Ok(vec![Filter::Static("0")]),        Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"),    };    Ok(if wanted.contains(&true) && wanted.contains(&false) {        vec![]    } else if wanted.contains(&true) {        vec![Filter::Static(            "COALESCE(is_pooled, kind='bank' AND subtype='bank')=1",        )]    } else if wanted.contains(&false) {        vec![Filter::Static(            "COALESCE(is_pooled, kind='bank' AND subtype='bank')=0",        )]    } else {        vec![Filter::Static("0")]    })}fn account_kind(    _ctx: &Ctx<'_>,    _definition: &TableDefinition,    condition: &Condition,) -> Valid<Vec<Filter>> {    Ok(vec![match condition {        Condition::Is(value) => Filter::Eq("subtype".into(), sql_value(value)),        Condition::OneOf(values) => {            Filter::In("subtype".into(), values.iter().map(sql_value).collect())        }        Condition::Present(true) => Filter::NotNull("subtype".into()),        Condition::Present(false) => Filter::IsNull("subtype".into()),        Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"),    }])}/// A tool figure's total over a built-in's stored rows (`tool.figures[].summary`):/// its live rows, narrowed by a `where` on stored columns and by a span of its/// `date` column (`from` inclusive, `until` exclusive, compared as written, so/// a day and an instant both order), counted or summed in ONE indexed read —/// never a walk of the rows, since Home asks it. A column an engine works out/// or narrows means nothing to a sum the file can answer, and is refused. A/// lowest or highest (`min`/`max`) is read over the evaluator's rows, where a/// running balance is.pub(super) fn figure_total(    read: &ReadDb<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    span: Option<(&str, &str)>,    op: cotton_core::definitions::SummaryOp,    column: Option<&str>,    resolved: &mut super::FigureRows,) -> Valid<super::FigureTotal> {    let zone = crate::mcp::handlers::common::read_where_zone(read)?;    use cotton_core::definitions::SummaryOp;    if let (SummaryOp::Min | SummaryOp::Max, Some(read_column)) = (op, column) {        if let Some(total) = computed_extreme(read, definition, clauses, span, op, read_column)? {            return Ok(total);        }        return rows_total(read, definition, clauses, span, op, read_column, resolved);    }    let source = source(definition)?;    // A figure over what its engine works out (an account's balance) or a    // view's computed column is not one SQL sum: add it over the rows the    // evaluator reads, with the same where and period.    let held = |wanted: &str| source.columns.contains(&wanted)        && !is_computed_column(definition.rows_table(), wanted)        && !RESOLVED_COLUMNS.contains(&(definition.rows_table(), wanted))        && definition.column(wanted).is_some_and(|column| column.computed.is_none());    if column.is_some_and(|wanted| definition.column(wanted).is_some() && !held(wanted)) {        return rows_total(read, definition, clauses, span, SummaryOp::Sum, column.unwrap_or_default(), resolved);    }    let stored = |wanted: &str| -> Valid<String> {        let column = definition.column(wanted).filter(|column| column.multiple != Some(true));        source            .columns            .iter()            .find(|name| **name == wanted)            .filter(|_| column.is_some() && !is_computed_column(definition.rows_table(), wanted)                && !RESOLVED_COLUMNS.contains(&(definition.rows_table(), wanted)))            .map(|name| (*name).to_string())            .ok_or_else(|| super::refuse(RecordError::CannotNarrow { plural: definition.plural.clone(), column: wanted.to_string() }))    };    let mut query = base_query(&source);    for column in &source.gone {        query = query.filter(Filter::IsNull((*column).to_string()));    }    for clause in clauses {        if narrowing(definition.rows_table(), &clause.column).is_some() {            return Err(super::refuse(RecordError::CannotNarrow {                plural: definition.plural.clone(),                column: clause.column.clone(),            }));        }        for filter in stored_narrowing(definition, &source, clause, &zone)? {            query = query.filter(filter);        }    }    if let Some((from, until)) = span {        let date = definition.date.as_deref().ok_or_else(|| {            ToolFailure::new(format!("{} have no date a period can keep", definition.plural))        })?;        let date = stored(date)?;        query = query            .filter(Filter::Gte(date.clone(), SqlValue::Text(from.to_string())))            .filter(Filter::Lt(date, SqlValue::Text(until.to_string())));    }    let Some(added) = column else {        return Ok(super::FigureTotal { total: read.count(&query).map_err(sql_err)?, ..Default::default() });    };    let summed = stored(added)?;    // An amount's currency: the column its definition names, read per row,    // or the code it names outright.    let currency = definition.column(added).and_then(|column| column.currency.clone());    let currency_expr = match currency.as_deref() {        Some(named) if definition.column(named).is_some() => Some(stored(named)?),        _ => None,    };    let columns = match &currency_expr {        Some(currency) => format!(            "COALESCE(SUM({summed}), 0) AS total, MIN({currency}) AS currency, COUNT(DISTINCT {currency}) AS currencies"        ),        None => format!("COALESCE(SUM({summed}), 0) AS total, NULL AS currency, 0 AS currencies"),    };    let (sql, params) = read.sub_select(&query, &columns).map_err(sql_err)?;    let row = read.driver().get(&sql, &params).map_err(sql_err)?;    let total = row.as_ref().and_then(|row| row.int("total")).unwrap_or(0);    let currencies = row.as_ref().and_then(|row| row.int("currencies")).unwrap_or(0);    let currency = match &currency_expr {        Some(_) => row.as_ref().and_then(|row| row.text("currency").map(str::to_string)),        None => currency.filter(|code| !code.trim().is_empty()),    };    Ok(super::FigureTotal { total, currency, mixed: currencies > 1, on: None })}fn narrowing(table: &str, column: &str) -> Option<Narrow> {    NARROWINGS        .iter()        .find(|(narrowed_table, narrowed_column, _)| {            *narrowed_table == table && *narrowed_column == column        })        .map(|(_, _, narrow)| *narrow)}// ── what sits under a conversation's notes ──────────────────────────────────/// A column's words, trimmed; absent or blank is `None`.fn said(data: &Data, key: &str) -> Option<String> {    data.get(key).and_then(Value::as_str).map(str::trim).filter(|words| !words.is_empty()).map(str::to_string)}/// Where each owner's session message got to (`COMPUTED_COLUMNS`' `delivery`/// and `delivered_on`): typed facts from `rules::session_delivery`, read/// against the session each is addressed to. The definition says the words.pub(super) fn session_delivery(    ctx: &Ctx<'_>,    definition: &TableDefinition,    records: &mut [super::Stored],) -> Valid<()> {    use cotton_core::rules::session_delivery::{delivery, Addressed};    if !definition.has_engine() || definition.rows_table() != "session_message" {        return Ok(());    }    let mut sessions: Vec<String> = records        .iter()        .filter(|record| said(&record.data, "from_kind").as_deref() == Some("owner"))        .filter_map(|record| said(&record.data, "to_session_id"))        .collect();    sessions.sort();    sessions.dedup();    let mut addressed = std::collections::HashMap::new();    if !sessions.is_empty() {        let query = Query::on("cotton_sessions")            .columns(&["id", "machine", "host_owned"])            .filter(Filter::In("id".into(), sessions.into_iter().map(SqlValue::Text).collect()));        for session in rows(ctx, &query)? {            let host_owned = match session.get("host_owned") {                Some(Value::Bool(ours)) => *ours,                Some(other) => other.as_i64().is_some_and(|ours| ours != 0),                None => false,            };            if let Some(id) = text(&session, "id") {                addressed.insert(id, (host_owned, text(&session, "machine")));            }        }    }    for record in records.iter_mut() {        let data = &mut record.data;        let to = said(data, "to_session_id").and_then(|session| addressed.get(&session));        let facts = delivery(            said(data, "from_kind").as_deref().unwrap_or_default(),            said(data, "status").as_deref().unwrap_or("open"),            to.map(|(host_owned, machine)| Addressed { host_owned: *host_owned, machine: machine.as_deref() }),        );        let Some(facts) = facts else { continue };        data.insert("delivery".into(), Value::from(facts.delivery.as_str()));        if let Some(machine) = facts.delivered_on {            data.insert("delivered_on".into(), Value::from(machine));        }    }    Ok(())}/// The filters one `where` entry adds to a built-in's read: its table's own/// narrowing where it has one, else a stored column of ONE value filtered in/// SQL, else the refusal — a computed or resolved column, or one holding/// several values, means nothing to a plain comparison./// The table and key come from a validated definition, and are quoted as/// literals; the physical row qualifier comes from the compiled store spec./// The built-ins' computed dates a list orders and narrows by through their/// SQL twin, as by a stored date: `(table, column)`. A person's `birthday`/// is `cotton_core::rules::people::birthday`'s one rule, said as/// `person_extras` says it — "1992-08-17", or "--08-17".const COMPUTED_DATE_SQL: &[(&str, &str)] = &[("person", "birthday")];/// A column's value as SQL, for the reads that take any column's value —/// the stored column, a definition's computed column through its cache, or a/// built-in's computed date through [`COMPUTED_DATE_SQL`]; `None` for a/// column SQL cannot read.fn date_sql(ctx: &Ctx<'_>, definition: &TableDefinition, source: &Source, column: &str) -> Valid<Option<String>> {    if let Some(sql) = computed_date_sql(ctx, definition, source, column)? {        return Ok(Some(sql));    }    if definition.column(column).is_some_and(|column| column.computed.is_some()) {        if !crate::derive::is_current(ctx.read.driver()).map_err(sql_err)? {            return Err(super::being_worked_out(ctx.db(), ctx.workspace_id));        }        return Ok(Some(cached_column(definition, source, column)));    }    let stored = source.columns.contains(&column)        && !is_computed_column(definition.rows_table(), column)        && !RESOLVED_COLUMNS.contains(&(definition.rows_table(), column));    Ok(stored.then(|| format!("\"{column}\"")))}/// A built-in's computed date as SQL ([`COMPUTED_DATE_SQL`]), else `None`./// A copy signed in to an object may also hold the date itself as a served/// column — the object keeps a person's `birthday` whole, and its pull fills/// the copy's `birthday` while the month, day and year stay empty — so the/// date is the engine's where its parts are set, else the served one:/// `cotton_core::rules::people::birthday::birthday_sql`, the SQL twin of the/// rule the record (`person_extras`), the reminders and the phone's reads/// answer by, so a `where`, a sort and every reader agree.fn computed_date_sql(ctx: &Ctx<'_>, definition: &TableDefinition, source: &Source, column: &str) -> Valid<Option<String>> {    if !COMPUTED_DATE_SQL.iter().any(|(table, key)| *table == definition.rows_table() && *key == column) {        return Ok(None);    }    let whole_held = super::served_values::holds(ctx, definition, column)?;    Ok(Some(cotton_core::rules::people::birthday::birthday_sql(&source.table, whole_held)))}/// A computed column's kept value, under the definition's own id: a view/// (Owed over the money store) keeps its values under its id, never under/// the table its rows are stored in (`with_computed` reads them the same).fn cached_column(definition: &TableDefinition, source: &Source, column: &str) -> String {    let table = definition.id.replace('\'', "''");    let name = column.replace('\'', "''");    let id = if definition.rows_table() == "device" { "device_id" } else { "id" };    format!("(SELECT value FROM _computed WHERE table_id = '{table}' AND record_id = {}.{id} AND key = '{name}')", source.table)}fn narrow(    ctx: &Ctx<'_>,    definition: &TableDefinition,    source: &Source,    clause: &WhereClause,    zone: &cotton_core::records::Zone,) -> Valid<Vec<Filter>> {    if definition.column(&clause.column).is_some_and(|column| column.computed.is_some()) {        if !crate::derive::is_current(ctx.read.driver()).map_err(sql_err)? {            return Err(super::being_worked_out(ctx.db(), ctx.workspace_id));        }        let target = cached_column(definition, source, &clause.column);        let mut params = Vec::new();        let mut sql = super::condition_sql(&target, &clause.condition, &mut params, zone);        let zero = match &clause.condition {            Condition::Is(value) if value.as_i64() == Some(0) => Some(true),            Condition::NoneOf(values) if values.len() == 1 && values[0].as_i64() == Some(0) => Some(false),            _ => None,        };        if let Some(zero) = zero {            let mixed = crate::derive::mixed_rollup_matches_zero(ctx.read.driver(),definition,&clause.column,zero).map_err(sql_err)?;            if !mixed.is_empty() {                let holes = vec!["?"; mixed.len()].join(",");                let id = if definition.rows_table() == "device" { "device_id" } else { "id" };                sql = format!("({sql}) OR {}.{id} IN ({holes})",source.table);                params.extend(mixed.into_iter().map(SqlValue::Text));            }        }        return Ok(vec![Filter::ComposedBound(sql, params)]);    }    // A built-in's computed date narrows through its SQL twin, as a stored    // date does: set or not, a value, a month.    if let Some(value) = computed_date_sql(ctx, definition, source, &clause.column)? {        let mut params = Vec::new();        let sql = super::condition_sql(&value, &clause.condition, &mut params, zone);        return Ok(vec![Filter::ComposedBound(sql, params)]);    }    if let Some(narrow) = narrowing(definition.rows_table(), &clause.column) {        // A table's own narrowing answers who IS something; "none of these"        // over an engine's reading is not a set it can name, so it is        // refused here, never ignored — and never reaches the narrowing.        if matches!(clause.condition, Condition::NoneOf(_)) {            return Err(super::refuse(RecordError::BadWhere {                column: clause.column.clone(),                reason: cotton_core::records::WhereRefusal::NoNot { plural: definition.plural.clone() },            }));        }        if matches!(clause.condition, Condition::Month(_)) {            return Err(super::refuse(RecordError::BadWhere {                column: clause.column.clone(),                reason: cotton_core::records::WhereRefusal::NoMonth { plural: definition.plural.clone() },            }));        }        if matches!(clause.condition, Condition::WithinDays(_)) {            return Err(super::refuse(RecordError::BadWhere {                column: clause.column.clone(),                reason: cotton_core::records::WhereRefusal::NoWithinDays { plural: definition.plural.clone() },            }));        }        if matches!(clause.condition, Condition::On(_)) {            return Err(super::refuse(RecordError::BadWhere {                column: clause.column.clone(),                reason: cotton_core::records::WhereRefusal::NoOn { plural: definition.plural.clone() },            }));        }        if matches!(clause.condition, Condition::Bound(_)) {            return Err(super::refuse(RecordError::BadWhere {                column: clause.column.clone(),                reason: cotton_core::records::WhereRefusal::NoBound { plural: definition.plural.clone() },            }));        }        return super::served_values::narrow_links(ctx, definition, clause, narrow);    }    // A column a person or a tool added is a real column of the engine's    // own table, narrowed like any column of its type; before the file holds    // it, every record holds nothing there.    if super::own_values::narrowable(definition, &clause.column) {        if !super::own_values::holds(ctx, definition, source.table, &clause.column)? {            let empty = matches!(clause.condition, Condition::Present(false));            return Ok(vec![Filter::Composed(if empty { "1" } else { "0" }.into())]);        }        let mut params = Vec::new();        let sql = super::condition_sql(&format!("{}.\"{}\"", source.table, clause.column), &clause.condition, &mut params, zone);        return Ok(vec![Filter::ComposedBound(sql, params)]);    }    stored_narrowing(definition, source, clause, zone)}/// The filters one `where` entry adds over a built-in's STORED column of/// one value, in SQL — or the refusal for any other column.fn stored_narrowing(definition: &TableDefinition, source: &Source, clause: &WhereClause, zone: &cotton_core::records::Zone) -> Valid<Vec<Filter>> {    let stored = source        .columns        .iter()        .find(|name| **name == clause.column)        .filter(|_| {            !RESOLVED_COLUMNS.contains(&(definition.rows_table(), clause.column.as_str()))                && !is_computed_column(definition.rows_table(), &clause.column)                && definition                    .column(&clause.column)                    .is_some_and(|column| column.multiple != Some(true))        });    let Some(column) = stored else {        return Err(super::refuse(RecordError::CannotNarrow {            plural: definition.plural.clone(),            column: clause.column.clone(),        }));    };    let column = (*column).to_string();    // A date in a month, whatever its year — any stored date column.    if let Condition::Month(month) = clause.condition {        return Ok(vec![Filter::Composed(super::yearly_dates::in_month(&format!("\"{column}\""), month))]);    }    // A date no more than so many days back — any stored date column.    if let Condition::WithinDays(days) = clause.condition {        return Ok(vec![Filter::Composed(super::within_days(&format!("\"{column}\""), days))]);    }    // A date on today, or on this day in an earlier year — any stored date column.    if let Condition::On(day) = clause.condition {        return Ok(vec![Filter::Composed(super::on_day(&format!("\"{column}\""), day, zone))]);    }    // A number no more or no less than a bound — any stored number column.    if let Condition::Bound(_) = clause.condition {        let mut params = Vec::new();        let sql = super::condition_sql(&format!("\"{column}\""), &clause.condition, &mut params, zone);        return Ok(vec![Filter::ComposedBound(sql, params)]);    }    // The native partial-index hint must be valid before values are bound.    if definition.rows_table() == "transaction" && column == "status"        && matches!(&clause.condition, Condition::Is(Value::String(value)) if value == "expected")    {        return Ok(vec![Filter::Static(EXPECTED_TRANSACTIONS)]);    }    // Connection kinds are public choice words, while the supporting table    // stores engine ids. Filter the same values that records.get exposes.    if definition.rows_table() == "connection" && column == "kind" {        let stored_kind = |value: &Value| {            value.as_str().and_then(|word| crate::connections::words::KIND_WORDS                .iter().find(|(_, public)| *public == word).map(|(stored, _)| SqlValue::Text((*stored).into())))        };        return Ok(vec![match &clause.condition {            Condition::Is(value) => Filter::In(column, stored_kind(value).into_iter().collect()),            Condition::OneOf(values) => Filter::In(column, values.iter().filter_map(stored_kind).collect()),            Condition::Present(true) => Filter::NotBlank(column),            Condition::Present(false) => Filter::Blank(column),            Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("a month, within_days and a bound are answered above"),            // A record holding nothing holds no value, so it is none of them            // never: the blank rows stay out (`Condition::NoneOf`).            Condition::NoneOf(values) => {                return Ok(vec![                    Filter::NotIn(column.clone(), values.iter().filter_map(stored_kind).collect()),                    Filter::NotBlank(column),                ])            }        }]);    }    // A SOFT reference narrows by what the row READS as (`ReadDb::select`    // shows it empty while the row it names is not present), so the list and    // the records in it never disagree: "has one" is the fragment, and a    // value matches only while that value is shown.    if cotton_store::soft_refs::parent_of(source.table, &column).is_some() {        return Ok(match &clause.condition {            Condition::Is(value) => vec![                Filter::Eq(column.clone(), sql_value(value)),                Filter::SoftNames(column),            ],            Condition::OneOf(values) => vec![                Filter::In(column.clone(), values.iter().map(sql_value).collect()),                Filter::SoftNames(column),            ],            Condition::Present(true) => vec![Filter::SoftNames(column)],            Condition::Present(false) => vec![Filter::SoftAbsent(column)],            Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("a month, within_days and a bound are answered above"),            Condition::NoneOf(values) => vec![                Filter::NotIn(column.clone(), values.iter().map(sql_value).collect()),                Filter::SoftNames(column),            ],        });    }    Ok(match &clause.condition {        Condition::Is(value) => vec![Filter::Eq(column, sql_value(value))],        Condition::OneOf(values) => vec![Filter::In(column, values.iter().map(sql_value).collect())],        Condition::Present(true) => vec![Filter::NotBlank(column)],        Condition::Present(false) => vec![Filter::Blank(column)],        Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("a month, within_days and a bound are answered above"),        Condition::NoneOf(values) => vec![            Filter::NotIn(column.clone(), values.iter().map(sql_value).collect()),            Filter::NotBlank(column),        ],    })}/// `where {standing}` on thoughts: open or filed, as `standing_of` says./// `where invited`: the events someone else organizes — the computed/// column's own test (`event_extras`), read from the stored flag. With/// `my_response: needs_action` beside it, this is the set Home counts as/// invites to answer (`asked_of_you::INVITE_SQL`), which its row opens.fn event_invited(_ctx: &Ctx<'_>, _definition: &TableDefinition, condition: &Condition) -> Valid<Vec<Filter>> {    let invited = match condition {        Condition::Is(value) => value.as_str() == Some("invited"),        Condition::OneOf(values) => values.iter().any(|value| value.as_str() == Some("invited")),        Condition::Present(present) => *present,        Condition::NoneOf(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => unreachable!("narrow refuses not, month, within_days and bounds before a table's own narrowing"),    };    Ok(vec![Filter::Static(if invited { "organizer_is_self = 0" } else { "organizer_is_self <> 0" })])}/// One built-in record — binned or archived answered as deleted, a message/// its owner hid or cleared away not answered at all.pub(super) fn read_one(    ctx: &Ctx<'_>,    definition: &TableDefinition,    id: &str,) -> Valid<Option<Stored>> {    if media_tables::is_view(definition) {        return media_tables::read_view(ctx, definition, id);    }    if super::bin_table::is_bin(definition) {        return super::bin_table::read_one(ctx, id);    }    if super::email_views::handles(definition.rows_table()) { return super::email_views::read_one(ctx,definition,id); }    if super::engine_views::handles(definition) {        return super::engine_views::read_one(ctx, definition, id);    }    if super::settings_tables::handles(definition) {        return super::settings_tables::read_one(ctx, definition, id);    }    if super::activity_tables::is_activity(definition) {        return super::activity_tables::read_one(ctx, definition, id);    }    if definition.rows_table() == "call" {        return super::call_tables::read_one(ctx,definition,id);    }    let source = source(definition)?;    let storage_id = if definition.rows_table() == "device" {        let Some(approval) = super::device_words::approval_for(ctx, id)? else { return Ok(None) };        approval    } else {        id.to_string()    };    let query = base_query(&source).eq("id", storage_id);    let Some(row) = maybe_row(ctx, &query)? else {        return Ok(None);    };    let mut page = page_reads(ctx, definition, std::slice::from_ref(&row))?;    page.whole = true;    let mut stored = stored_from(ctx, definition, &source, &row, &page)?;    super::place_values::merge(ctx, definition, std::slice::from_mut(&mut stored))?;    Ok(Some(stored))}/// Several records of a built-in by id, each as [`read_one`] answers it, in/// one read of the rows and one of what their pages read beside them:/// None where the table reads its records some other way (a view, the bin,/// a filed copy), which are then read one by one.pub(super) fn read_many(ctx: &Ctx<'_>, definition: &TableDefinition, ids: &[&str]) -> Valid<Option<Vec<Stored>>> {    if media_tables::is_view(definition) || super::bin_table::is_bin(definition)        || super::email_views::handles(definition.rows_table()) || super::engine_views::handles(definition)        || super::settings_tables::handles(definition) || super::activity_tables::is_activity(definition)        || matches!(definition.rows_table(), "call" | "device" | "thread" | "message")    {        return Ok(None);    }    let source = source(definition)?;    let mut found = Vec::new();    for chunk in ids.chunks(super::IN_CHUNK) {        let query = base_query(&source).filter(Filter::In("id".into(), chunk.iter().map(|id| SqlValue::Text(id.to_string())).collect()));        found.extend(rows(ctx, &query)?);    }    let mut page = page_reads(ctx, definition, &found)?;    page.whole = true;    let mut stored: Vec<Stored> = found.iter().map(|row| stored_from(ctx, definition, &source, row, &page)).collect::<Valid<_>>()?;    super::place_values::merge(ctx, definition, &mut stored)?;    Ok(Some(stored))}/// A grouped list read without a day plan: each group's count over the WHOLE/// narrowed list, `[{key, count}]` keyed by the group's first value/// lowercased, as the app keys a heading — so a shut "Merged" says every/// merged record, never the rows its first pages held (S6, architect 1735)./// A value no group names counts in the first group, as the list places it;/// an empty group is left out, as a day plan leaves out an empty section.fn group_sections(    ctx: &Ctx<'_>,    definition: &TableDefinition,    source: &Source,    query: &Query,) -> Valid<Option<Vec<Value>>> {    let Some(grouping) = &definition.group else { return Ok(None) };    let Some(groups) = grouping.sections.as_ref().filter(|groups| !groups.is_empty()) else {        return Ok(None);    };    let Some(column) = source.columns.iter().find(|stored| **stored == grouping.column) else {        return Ok(None);    };    let mut whole = query.clone();    whole.order.clear();    whole.limit = None;    whole.offset = None;    let mut counts = vec![0_i64; groups.len()];    for (value, n) in ctx.read.count_by(&whole, column).map_err(sql_err)? {        let at = value            .and_then(|value| groups.iter().position(|group| group.values.contains(&value)))            .unwrap_or(0);        counts[at] += n;    }    Ok(Some(        groups            .iter()            .zip(counts)            .filter(|(_, count)| *count > 0)            .filter_map(|(group, count)| {                let key = group.values.first()?.to_lowercase();                Some(json!({ "key": key, "count": count }))            })            .collect(),    ))}/// One page of a built-in's live records — and, for a list read as a day/// plan (`day_plan`), its sections counted over the whole list.#[allow(clippy::too_many_arguments)]pub(super) fn list(    ctx: &Ctx<'_>,    definition: &TableDefinition,    project: Option<&str>,    query_text: Option<&str>,    clauses: &[WhereClause],    offset: i64,    limit: i64,    view: &day_plan::View,    archived: Option<Archive<'_>>,    members: Option<&[String]>,    total: super::Total,) -> Valid<(Page, ListExtras)> {    let zone = crate::mcp::handlers::common::reading_zone(ctx, view.timezone.as_deref(), view.today.as_deref())?;    let unplanned = |page: Valid<Page>| -> Valid<(Page, ListExtras)> {        if archived.is_some() {            return Err(ToolFailure::new(format!(                "The archived {} cannot be listed yet",                definition.plural.to_lowercase()            )));        }        if view.section.is_some() && !super::email_views::handles(definition.rows_table()) {            return Err(ToolFailure::new(format!(                "{} is not read in sections; ask without section",                definition.plural            )));        }        page.map(|page| (page, ListExtras::default()))    };    // `among` is honoured by the store's own list below, read in no plan;    // a list another engine reads refuses it rather than answer every row.    let refuse_among = || ToolFailure::new(format!("{} are not read among ids", definition.plural));    if view.among.is_some() && !reads_among(definition) { return Err(refuse_among()); }    if media_tables::is_view(definition) {        return unplanned(media_tables::list_view(ctx, definition, project, query_text, clauses, offset, limit));    }    if super::bin_table::is_bin(definition) {        return unplanned(super::bin_table::list(            ctx, definition, project, query_text, clauses, offset, limit,        ));    }    if super::email_views::handles(definition.rows_table()) { return unplanned(super::email_views::list(ctx,definition,project,query_text,clauses,offset,limit,total,view)); }    if super::engine_views::handles(definition) {        return unplanned(super::engine_views::list(ctx, definition, project, query_text, clauses, offset, limit));    }    if super::settings_tables::handles(definition) {        return unplanned(super::settings_tables::list(            ctx, definition, project, query_text, clauses, offset, limit,        ));    }    if super::activity_tables::is_activity(definition) {        return unplanned(super::activity_tables::list(ctx, definition, project, query_text, clauses, offset, limit));    }    if definition.rows_table() == "call" {        return super::call_tables::list(ctx,definition,project,query_text,clauses,offset,limit,members,view);    }    let runway=archived.is_none() && super::money_runway::handles(definition);    let mut source = source(definition)?;    // An article's text is its page's, never a list's: a list of articles    // would carry every article whole.    if definition.rows_table() == "page" {        source.columns.retain(|column| *column != "text");    }    // The archive is one plain list in the table's own order, never a day plan.    let mut plan = match archived {        Some(_) => None,        None => day_plan::Plan::of(ctx, definition, &source.columns, view)?,    };    let mut query = base_query(&source);    if let Some(among) = &view.among {        // A plan reads among ids where each row's section is its own.        if runway || plan.as_ref().is_some_and(|plan| !plan.rows_own_sections()) { return Err(refuse_among()); }        query = query.filter(Filter::In("id".into(), among.iter().cloned().map(SqlValue::Text).collect()));    }    if definition.rows_table() == "device" {        let approvals = super::device_words::effective_approvals(ctx)?;        query = query.filter(Filter::In("id".into(), approvals.into_iter().map(SqlValue::Text).collect()));    }    // A day whose words were taken back holds none: it is not listed.    if definition.rows_table() == "journal" {        query = query.filter(Filter::Static(JOURNAL_DAY_HAS_WORDS));    }    for column in &source.gone {        // A status archive is the status: a record archived by it carries its        // `archived_at` (a memory's), which hides it from the list, never        // from the archive.        if archived == Some(Archive::Status) && *column == "archived_at" {            continue;        }        query = query.filter(if archived == Some(Archive::Column(*column)) {            Filter::NotNull((*column).to_string())        } else {            Filter::IsNull((*column).to_string())        });    }    query = match archived {        // A column the bin and the archive share above; else the        // engine's own: a chat's switch, a question's close.        Some(Archive::Column(column)) if !source.gone.contains(&column) => {            let stored = source.columns.iter().copied().find(|stored| *stored == column).ok_or_else(|| {                ToolFailure::new(format!("{} has no archive this build can read", definition.plural))            })?;            match definition.column(stored).map(|column| &column.column_type) {                Some(ColumnType::Bool) => query.eq(stored, 1_i64),                _ => query.filter(Filter::NotNull(stored.to_string())),            }        }        Some(Archive::Status) => query.eq("status", "archived".to_string()),        _ => query,    };    for clause in clauses {        if runway && super::money_runway::varies_by_occurrence(definition,&clause.column) { continue; }        for filter in narrow(ctx, definition, &source, clause, &zone)? {            query = query.filter(filter);        }    }    if definition.id == "transaction" && clauses.iter().any(|clause| {        clause.column == "status" && match &clause.condition {            Condition::Is(value) => value.as_str() == Some("expected"),            Condition::OneOf(values) => !values.is_empty() && values.iter().all(|value| value.as_str() == Some("expected")),            Condition::NoneOf(values) => values.iter().any(|value| value.as_str() == Some("actual"))                && !values.iter().any(|value| value.as_str() == Some("expected")),            Condition::Present(_) | Condition::Month(_) | Condition::WithinDays(_) | Condition::Bound(_) | Condition::On(_) => false,        }    }) {        query = query.filter(Filter::InQuery {            column: "id".into(),            query: Box::new(                Query::on("cotton_money_transactions")                    .columns(&["settles_transaction_id"])                    .eq("status", "actual".to_string())                    .filter(Filter::IsNull("trashed_at".into())),            ),            negate: true,        });    }    if let Some(hidden) = definition        .hidden        .as_ref()        .filter(|_| LISTS_LEAVE_HIDDEN_OUT.contains(&definition.rows_table()))        .filter(|hidden| !clauses.iter().any(|clause| clause.column == hidden.column))        .filter(|hidden| source.columns.contains(&hidden.column.as_str()))    {        query = query.filter(Filter::NotIn(            hidden.column.clone(),            hidden.values.iter().cloned().map(SqlValue::Text).collect(),        ));    }    if let Some(project) = project {        query = match &definition.project {            // A real project column filters directly …            Some(column) if project_link_column(definition).is_none() => {                query.eq(column, project.to_string())            }            // … and a built-in with none is filed through the project's links.            _ => {                let links = Query::on("cotton_project_links")                    .columns(&["record_id"])                    .eq("project_id", project.to_string())                    .eq("record_kind", definition.rows_table().to_string());                let ids: Vec<SqlValue> = rows(ctx, &links)?                    .iter()                    .filter_map(|row| text(row, "record_id"))                    .map(SqlValue::Text)                    .collect();                query.filter(Filter::In("id".into(), ids))            }        };    }    // A group's page: the list narrowed to the group's members.    if let Some(members) = members {        query = query.filter(Filter::In("id".into(), members.iter().map(|id| {            let stored=if runway {crate::mcp::handlers::money::occurrences::identity(id).map(|(stored,_)|stored).unwrap_or(id)} else {id};            SqlValue::Text(stored.to_string())        }).collect()));    }    let searched: Vec<String> = definition        .search        .iter()        .flatten()        .filter(|_| SEARCHED_BY_SUBSTRING.contains(&definition.rows_table()))        .filter(|key| source.columns.contains(&key.as_str()))        .cloned()        .collect();    if let Some(words) = query_text {        // A substring of the columns the definition searches, where the        // table reads its words that way; else the table's own search index        // where it has one; else a LIKE over the title.        if definition.rows_table() == "thread" {            // A dm stores no title: its name is its contact's.            query = query.filter(super::chat_views::thread_search(ctx, words)?);        } else if definition.rows_table() == "call" {            query = query.filter(call_search(ctx, words)?);        } else if !searched.is_empty() {            for word in words.split_whitespace() {                query = query.filter(Filter::ContainsAny(searched.clone(), word.to_string()));            }        } else if FTS_SOURCES.iter().any(|fts| fts.source == source.table) {            let tables = [source.table.to_string()];            // The list's search box is typed into: its last word is the start            // of one, so "dent" finds today's Dentist before it is finished.            let hits = cotton_store::search::search_all_typed(                ctx.read.driver(),                words,                Some(&tables[..]),                Some(10_000),            )            .map_err(sql_err)?;            let ids: Vec<SqlValue> = hits                .into_iter()                .map(|hit| SqlValue::Text(hit.row_id))                .collect();            query = query.filter(Filter::In("id".into(), ids));        } else if !source.columns.contains(&definition.title.as_str()) {            // A title the engine answers (a statement's period) is in no            // stored column to search: nothing matches, rather than SQL            // naming a column the table does not have.            query = query.filter(Filter::In("id".into(), Vec::new()));        } else {            let escaped = words.replace(['%', '_'], "");            query = query.filter(Filter::Like(                definition.title.clone(),                format!("%{}%", escaped.trim()),            ));        }    }    if runway { return super::money_runway::list(ctx,definition,query,clauses,members,offset,limit,view); }    // A repeating event's later occurrences, as rows of their own: each one    // its master's row at that time, kept only where the master passes this    // read's filters (a search, a project).    let mut later: Vec<Map<String, Value>> = Vec::new();    if let Some(plan) = plan.as_mut().filter(|plan| !plan.later().is_empty()) {        let ids: Vec<SqlValue> = plan.later().iter().map(|(id, _, _)| SqlValue::Text(id.clone())).collect();        let masters: std::collections::HashMap<String, Map<String, Value>> = rows(ctx, &query.clone().filter(Filter::In("id".into(), ids)))?            .into_iter()            .filter_map(|row| Some((text(&row, "id")?, row)))            .collect();        plan.keep_later(|id| masters.contains_key(id));        for (id, starts, ends) in plan.later() {            let mut row = masters[id].clone();            row.insert("id".into(), Value::from(format!("{id}@{starts}")));            row.insert("starts_at".into(), Value::from(starts.clone()));            row.insert("ends_at".into(), ends.clone().map_or(Value::Null, Value::from));            later.push(row);        }    }    if let Some(plan) = &plan { query = plan.select(query); }    // Each row's section alone, for a reader that keeps the plan's sections.    if view.sectioned {        let plan = plan.as_ref().filter(|plan| plan.rows_own_sections() && plan.requested_section().is_none() && later.is_empty())            .ok_or_else(|| ToolFailure::new(format!("{} are not read sectioned", definition.plural)))?;        let rows = plan.sectioned(ctx, &query)?;        let total = rows.len() as i64;        let sectioned = json!({"keys": plan.keys(), "rows": rows});        return Ok((Page { records: Vec::new(), more: false, total }, ListExtras { sectioned: Some(sectioned), ..ListExtras::default() }));    }    // Count-only and archived-count answers discard headings. Keep the same    // filtered total below without grouping the whole calendar for them.    // A day plan's sections are counted in one walk of the table, and its    // total is their sum: a second count was a second walk (295 F row 81).    let counted = match &plan {        Some(plan) if limit != 0 => Some(plan.counted(ctx, &query)?),        _ => None,    };    let sections = match (&plan, &counted) {        _ if limit == 0 => None,        (Some(plan), Some(counted)) => Some(plan.sections_of(counted)),        (Some(_), None) => None,        (None, _) if archived.is_none() => group_sections(ctx, definition, &source, &query)?,        (None, _) => None,    };    if let Some(plan) = &plan {        query = plan.narrow(query);    }    let summaries = None;    // A narrow cut read answers its rows' store values alone, uncounted    // (`cut_stored`): every column it names one the row itself holds.    let cut = view.cut && plan.is_none() && later.is_empty() && limit != 0        && !matches!(definition.rows_table(), "thread" | "message" | "device")        && view.columns.iter().flatten().all(|key| cut_reads(definition, &source, key));    let skipped = total == super::Total::Skipped && limit != 0;    let total = match (&plan, &counted) {        _ if cut || skipped => 0,        (Some(plan), Some(counted)) => plan.total_of(counted),        _ => ctx.read.count(&query).map_err(sql_err)?,    } + later.len() as i64;    if limit == 0 {        return Ok((Page { records: Vec::new(), more: false, total }, ListExtras { sections, summaries, cut_rows: None, sectioned: None }));    }    // A list split into days on one stored date reads its page off that    // date's index, a section at a time (`day_plan::Plan::indexed`).    let indexed = match (&plan, &counted) {        (Some(plan), Some(counted))            if plan.indexed()                && definition.order.is_none()                && !LISTED_FIRST_BY.iter().any(|(table, _, _)| *table == definition.rows_table()) =>        {            Some((plan, counted, query.clone()))        }        _ => None,    };    for (table, column, order) in LISTED_FIRST_BY {        if *table == definition.rows_table() {            query = query.order_by(column, *order);        }    }    // Precedence: a hand-made order; else a list read as a day plan on the    // reader's day (`day_plan`: work still to do, or a list split into days);    // else the definition's `sort` when the table stores its columns; else    // its date, newest first. `sort` wins over `date` because it is what the    // app draws (questions oldest first, papers by when they came in); the    // day plan wins over `sort` because a todo list's first page must hold    // today and the days ahead, and a calendar's must open on today. A list    // split into days (`day_grouping`) never pages by its `sort`: that orders    // the slips inside one day (a calendar's day reads earliest first) —    // ascending, page one would hold the oldest event ever.    let sort = definition.sort.as_ref().filter(|_| !sorts_within_days(definition)).filter(|sort| {        // Only a column the table itself stores can order its rows in SQL.        let stored = |key: &String| source.columns.contains(&key.as_str()) || definition.column(key).is_some_and(|column| column.computed.is_some());        stored(&sort.column) && sort.tie.as_ref().is_none_or(stored)    });    // A `next` sort orders by the day its yearly date comes round next from    // the reader's day, through the date's SQL value (`date_sql`).    let next = match definition.sort.as_ref().filter(|sort| sort.next == Some(true) && !sorts_within_days(definition)) {        Some(sort) => match date_sql(ctx, definition, &source, &sort.column)? {            Some(value) => Some((sort, value, super::yearly_dates::reader_day(ctx, view)?)),            None => None,        },        None => None,    };    query = if let Some(order) = &definition.order {        query.order_by(order, Order::Asc)    } else if let Some(plan) = &plan {        plan.order(query)    } else if let Some((sort, value, today)) = next {        let order = if sort.descending == Some(true) { Order::ComposedDesc } else { Order::Composed };        let [undated, past, day] = super::yearly_dates::next_terms(|| value.clone(), &today);        query = query.order_by(&undated, Order::Composed).order_by(&past, order).order_by(&day, order);        // Ties by the sort's own tie, else by the date itself.        match sort.tie.as_ref().map(|tie| date_sql(ctx, definition, &source, tie)).transpose()?.flatten() {            Some(tie) => query.order_by(&format!("NULLIF({tie}, '') COLLATE NOCASE"), order),            None => query.order_by(&value, order),        }    } else if let Some(sort) = sort {        // The order the definition says (`sort`): people by name, pictures        // newest first, questions oldest first. The app draws the pages as        // they come, so an order kept only in the file was never seen.        if definition.has_computed() {            if !crate::derive::is_current(ctx.read.driver()).map_err(sql_err)? {                return Err(super::being_worked_out(ctx.db(), ctx.workspace_id));            }            for (name, descending) in std::iter::once((&sort.column, sort.descending == Some(true))).chain(sort.tie.iter().map(|tie| (tie, sort.tie_descends()))) {                // A stored day, newest first, orders as the wrapped term below                // (a day folds no case; a blank sorts after every day either                // way) and reads the table's date index, never sorting every                // row to cut one page: Owed's page 20 of a book.                if descending && source.columns.contains(&name.as_str())                    && definition.column(name).is_some_and(|column| column.computed.is_none() && column.column_type == ColumnType::Date)                {                    query = query.order_by(name, Order::Desc);                    continue;                }                let value = if definition.column(name).is_some_and(|column| column.computed.is_some()) {                    cached_column(definition, &source, name)                } else { format!("\"{name}\"") };                // Blanks last, then the values in their own direction.                let order = if descending { Order::ComposedDesc } else { Order::Composed };                query = query                    .order_by(&format!("NULLIF({value}, '') IS NULL"), Order::Composed)                    .order_by(&format!("NULLIF({value}, '') COLLATE NOCASE"), order);            }            if source.updated { query = query.order_by("updated_at", Order::Desc); }            query        } else {            let order = if sort.descending == Some(true) { Order::Desc } else { Order::AscBlanksLast };            query = query.order_by(&sort.column, order);            match &sort.tie {                Some(tie) => query.order_by(tie, if sort.tie_descends() { Order::Desc } else { Order::AscBlanksLast }),                None => query,            }        }    } else if let Some(date) = definition        .date        .as_deref()        .map(|date| ordered_by(definition, date))        .filter(|date| source.columns.contains(date))    {        query.order_by(date, Order::Desc)    } else if source.updated {        query.order_by("updated_at", Order::Desc)    } else {        query    };    // With later occurrences to fold in, the stored rows are read from the    // top and the page is cut after the merge below.    let merging = !later.is_empty();    query = query        .order_by("id", Order::Asc)        .limit(if merging { offset + limit + 1 } else { limit + 1 })        .offset(if merging { 0 } else { offset });    // A light read (`columns`) selects the id, the stamps and the columns    // asked, never the rest of a wide row.    if let Some(asked) = &view.columns {        query.columns = Some(source.columns.iter().filter(|column| {            matches!(**column, "id" | "created_at" | "updated_at" | "deleted_at") || asked.iter().any(|asked| asked == *column)        }).map(|column| column.to_string()).collect());    }    if cut {        let asked = view.columns.as_deref().unwrap_or_default();        // Every column a stored one the answer says as it is stored: the        // rows are read by position straight into the answer's `[id, …]`        // arrays, no map per row (Owed's cut over a book).        if asked.iter().all(|key| definition.column(key).is_some_and(|column| column.computed.is_none()))            && cotton_core::records::reads_public_as_stored(definition)        {            query.columns = Some(std::iter::once("id".to_string()).chain(asked.iter().cloned()).collect());            let bools: Vec<bool> = asked.iter().map(|key| definition.column(key).is_some_and(|column| column.column_type == ColumnType::Bool)).collect();            let mut found: Vec<Value> = ctx.read.select_rows(&query).map_err(sql_err)?.into_iter().map(|mut row| {                for (value, bool) in row.iter_mut().skip(1).zip(&bools) {                    if let (true, Some(stored)) = (*bool, value.as_i64()) { *value = Value::Bool(stored != 0); }                }                Value::Array(row)            }).collect();            let more = found.len() as i64 > limit;            found.truncate(limit as usize);            let total = offset + found.len() as i64;            return Ok((Page { records: Vec::new(), more, total }, ListExtras { sections, summaries, cut_rows: Some(found), sectioned: None }));        }        let mut records: Vec<Stored> = rows(ctx, &query)?.iter().map(|row| cut_stored(definition, row, asked)).collect();        let more = records.len() as i64 > limit;        records.truncate(limit as usize);        let total = offset + records.len() as i64;        return Ok((Page { records, more, total }, ListExtras { sections, summaries, cut_rows: None, sectioned: None }));    }    let mut found = match indexed {        Some((plan, counted, unordered)) if !merging => plan.indexed_page(ctx, &unordered, counted, offset, limit + 1)?,        _ => rows(ctx, &query)?,    };    // A repeating event answers the occurrence it is filed at, so its slip    // stands under that day and says that clock (`day_plan`).    if let Some(plan) = &plan {        for row in found.iter_mut() {            let Some(id) = text(row, "id") else { continue };            let Some((starts, ends)) = plan.occurrence(&id).cloned() else {                continue;            };            // Standing on a later day, the row IS that day: its id names it            // (`<id>@<starts>`, as every later occurrence's does), so a            // delete or an edit of "only this one" reaches the day the person            // acted on — never the series' first start (architect 2005, sev 1).            if text(row, "starts_at").as_deref() != Some(starts.as_str()) {                row.insert("id".into(), Value::from(format!("{id}@{starts}")));            }            row.insert("starts_at".into(), Value::from(starts));            if let Some(ends) = ends {                row.insert("ends_at".into(), Value::from(ends));            }        }        if merging {            found = merge_later(plan, found, later, offset, limit);        }    }    // A light read answers its columns alone: nothing a page reads beside them.    let page = if view.columns.is_some() { PageReads::default() } else { page_reads(ctx, definition, &found)? };    let mut records: Vec<Stored> = found        .iter()        .map(|row| stored_from(ctx, definition, &source, row, &page))        .collect::<Valid<_>>()?;    let more = records.len() as i64 > limit;    records.truncate(limit as usize);    Ok((        Page {            records,            more,            total,        },        ListExtras { sections, summaries, cut_rows: None, sectioned: None },    ))}/// Whether a narrow cut reads `key` straight off the row: a column the/// table stores as it reads (or a definition's computed one, its kept value/// joined after), never one an engine answers or resolves.fn cut_reads(definition: &TableDefinition, source: &Source, key: &str) -> bool {    let rows = definition.rows_table();    let Some(column) = definition.column(key) else { return false };    if column.computed.is_some() { return true; }    source.columns.contains(&key) && !is_computed_column(rows, key)        && !RESOLVED_COLUMNS.contains(&(rows, key)) && !TEXT_LISTS.contains(&(rows, key))}/// A row of a narrow cut: its id and the columns asked, each as/// `stored_from` reads it (a yes-or-no as true or false).fn cut_stored(definition: &TableDefinition, row: &Map<String, Value>, asked: &[String]) -> Stored {    let mut data = Data::new();    for key in asked {        let Some(value) = row.get(key).filter(|value| !value.is_null()) else { continue };        let value = match (definition.column(key).map(|column| &column.column_type), value.as_i64()) {            (Some(ColumnType::Bool), Some(stored)) => Value::Bool(stored != 0),            _ => value.clone(),        };        data.insert(key.clone(), value);    }    Stored {        id: text(row, if definition.rows_table() == "device" { "device_id" } else { "id" }).unwrap_or_default(),        data,        created_at: None,        updated_at: None,        deleted_at: None,        byline: None,    }}/// The stored rows of a day plan read from the top, with a repeating event's/// later occurrences (soonest first) stood among what is coming by their/// wall clock — a stored row first on a tie — then the page `offset`,/// `limit + 1` cut from the whole.fn merge_later(    plan: &day_plan::Plan,    stored: Vec<Map<String, Value>>,    later: Vec<Map<String, Value>>,    offset: i64,    limit: i64,) -> Vec<Map<String, Value>> {    let at = |row: &Map<String, Value>| plan.coming_at(text(row, "starts_at").as_deref());    let mut merged = Vec::with_capacity(stored.len() + later.len());    let mut later = later.into_iter().peekable();    for row in stored {        // A stored row past what is coming (earlier, undated) follows them all.        let here = at(&row);        while let Some(next) = later.peek() {            let before = match (&here, at(next)) {                (Some(here), Some(there)) => there < *here,                (None, _) => true,                (Some(_), None) => false,            };            if !before {                break;            }            merged.extend(later.next());        }        merged.push(row);    }    merged.extend(later);    merged.into_iter().skip(offset as usize).take(limit as usize + 1).collect()}/// Whether a definition's `sort` orders only the slips inside one day of a/// list split by `day_grouping`, the pages coming by its `date` — for a made/// table's list as for a built-in's.pub(super) fn sorts_within_days(definition: &TableDefinition) -> bool {    definition.day_grouping.is_some() && definition.date.is_some()}/// Built-ins whose list leaves out what their definition's `hidden` names,/// unless a `where` asks for that column itself: a dismissed album is brought/// back from its own page, and never sits in the list meanwhile; a recording/// that did not work is not a meeting, and stands under its own link/// ("A recording did not work · 1", walker 604bcce6).const LISTS_LEAVE_HIDDEN_OUT: &[&str] = &["album", "meeting"];/// Built-ins whose `query` reads a SUBSTRING of the columns their definition/// `search`es, every word somewhere in one of them — a picture's caption or/// the description Cotton wrote, the words the app's own search box reads.const SEARCHED_BY_SUBSTRING: &[&str] = &["photo", "video", "transaction", "statement_line"];/// The stored column a list pages by where its date is one the read works/// out (`COMPUTED_COLUMNS`) and SQL cannot order by: `(table, date, stored)`./// A session's `active_at` is when it ended, else when it last did anything —/// and a session's last activity is its end, so `last_active_at` pages it/// the same way (`list_sessions`' own order).const DATE_ORDERED_BY: &[(&str, &str, &str)] = &[("session", "active_at", "last_active_at")];/// The column a list pages by for its `date`: the date itself, or the stored/// column [`DATE_ORDERED_BY`] names for a computed one.fn ordered_by<'a>(definition: &TableDefinition, date: &'a str) -> &'a str {    DATE_ORDERED_BY        .iter()        .find(|(table, computed, _)| *table == definition.rows_table() && *computed == date)        .map_or(date, |(_, _, stored)| stored)}/// A column a built-in's list orders by FIRST, before its own order or date:/// `(table, column, order)`. An album's state descending reads `open` before/// `kept` (and `dismissed`, when asked for, last) — a suggestion waiting for/// its answer heads the list. The guard/// `an_albums_states_sort_open_first` holds the spelling to that order.////// A pinned chat heads the chats, newest pin first (a chat never pinned has/// no `pinned_at`, and nothing sorts last descending).const LISTED_FIRST_BY: &[(&str, &str, Order)] = &[    ("album", "state", Order::Desc),    ("thread", "pinned_at", Order::Desc),    // Keep account ordering stable before applying its name ordering.    ("money_account", "kind", Order::Asc),    ("money_account", "subtype", Order::Asc),];// ── calling a kind's own tool ───────────────────────────────────────────────pub(super) type Handler = fn(&mut Ctx<'_>, &Map<String, Value>) -> ToolResult;/// Call one existing tool as its adapter's writer, keeping the catalogue's/// owner-only rule, and commit what it wrote.pub(super) fn call(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    name: &str,    handler: Handler,    args: Value,) -> ToolResult {    let owner_only = tool_by_name(name).is_some_and(|tool| tool.scope == McpScope::Owner);    if owner_only && !ctx.is_owner_app() {        return Err(ToolFailure::new(format!(            "only the owner's own app can do this to {}",            definition.plural.to_lowercase()        )));    }    let Value::Object(args) = args else {        return Err(ToolFailure::new("an adapter's arguments are an object"));    };    let out = handler(ctx, &args)?;    ctx.commit()?;    Ok(out)}pub(super) fn created_id(out: &Value) -> Valid<String> {    out.get("id")        .and_then(Value::as_str)        .map(str::to_string)        .ok_or_else(|| ToolFailure::new("the record was written but its id was not answered"))}/// A column as a person reads it on the page — the definition's own name for/// it, never the key.pub(super) fn column_label(definition: &TableDefinition, key: &str) -> String {    definition        .column(key)        .map_or_else(|| cotton_core::definitions::key_as_words(key), |column| column.label())}/// A column's name inside a sentence: its first letter small, every other/// capital the person gave it kept ("what I care about", never "what i care/// about").pub(super) fn label_in_sentence(definition: &TableDefinition, key: &str) -> String {    let label = column_label(definition, key);    let mut letters = label.chars();    match letters.next() {        // "I care" and "URL" keep their capital: only a word that is a        // capital followed by small letters is lowered.        Some(first) if letters.clone().next().is_some_and(char::is_lowercase) => {            first.to_lowercase().chain(letters).collect()        }        _ => label,    }}/// A column Cotton sets itself.pub(super) fn set_by_cotton(definition: &TableDefinition, key: &str) -> ToolFailure {    ToolFailure::new(format!(        "{} cannot set {key:?} through the generic verbs; Cotton sets it itself",        definition.plural    ))}pub(super) fn cannot_clear(definition: &TableDefinition, key: &str) -> ToolFailure {    ToolFailure::new(format!("{} cannot clear {key:?}", definition.plural))}// ── the adapters ────────────────────────────────────────────────────────────type Create = fn(&mut Ctx<'_>, &TableDefinition, &Data) -> Valid<String>;type Update = fn(&mut Ctx<'_>, &TableDefinition, &str, &Data) -> Valid<()>;type Remove = fn(&mut Ctx<'_>, &TableDefinition, &str) -> Valid<()>;/// How a delete is undone: by the engine's own tool (an archive lifted), or —/// where the delete was a retract — by [`recreate`].#[derive(Clone, Copy)]enum Restore {    Engine(Remove),    Recreate,}type Place = fn(&mut Ctx<'_>, &TableDefinition, &str, f64) -> Valid<()>;/// How one built-in is written.struct Adapter {    create: Result<Create, &'static str>,    update: Option<Update>,    delete: Result<Remove, &'static str>,    restore: Result<Restore, &'static str>,    reorder: Option<Place>,    /// Columns the engine sets itself: refused on a write, left out of an undo.    derived: &'static [&'static str],    /// Why an update the engine takes cannot be undone — its write has no    /// inverse — or `None` when it can.    final_update: Option<&'static str>,}fn adapter(id: &str) -> Option<Adapter> {    Some(match id {        "ai_budget" => Adapter {            create: Err("The AI budget is created with the database"),            update: Some(ai_usage::budget_update),            delete: Err("The AI budget cannot be deleted"),            restore: Err("The AI budget cannot be deleted"),            reorder: None,            derived: &[],            final_update: None,        },        "transaction" => Adapter {            create: Ok(transaction_create), update: Some(transaction_update), final_update: None,            delete: Ok(transaction_delete),            // Undo clears the Bin marker; the row and its evidence never leave.            restore: Ok(Restore::Engine(bin_bring_back)),            reorder: None, derived: &[],        },        "evidence" => Adapter {            create: Err("Evidence is attached to a movement with attach_evidence"),            update: None, final_update: None,            delete: Ok(evidence_remove),            // The retract is taken back: the same evidence on the same movement.            restore: Ok(Restore::Recreate),            reorder: None, derived: &[],        },        "money_account" => Adapter {            create: Err("An account is opened with create_money_account; record money as a transaction"),            update: Some(money_account_update),            delete: Err("Accounts are put away, never deleted, with update_money_account"),            restore: Err("Accounts are never deleted"),            reorder: None,            derived: &[],            final_update: None,        },        "voice_word" => Adapter {            create: Ok(super::settings_tables::voice_word_create),            update: None,            delete: Ok(super::settings_tables::voice_word_delete),            restore: Err("A removed voice word is added again as a new manual word"),            reorder: None,            derived: &["added_by", "line", "source", "use_count", "last_used_at"],            final_update: Some("Dictation rebuilds the vocabulary after it changes"),        },        "todo" => Adapter {            create: Ok(todo_create),            update: Some(todo_update),            // Into the bin like every record (owner's todo sweep, 15 Oct            // 2026); Drop stays its own act and keeps the todo listed.            delete: Ok(bin_put_away),            restore: Ok(Restore::Engine(bin_bring_back)),            reorder: None,            derived: &["completed_at", "recurrence_id"],            final_update: None,        },        "note" => Adapter {            create: Ok(note_create),            update: Some(note_update),            // Delete moves the note to the bin; Archive is its own act            // ([`archive_verbs`]).            delete: Ok(note_trash),            restore: Ok(Restore::Engine(note_untrash)),            reorder: None,            derived: &["updated_at", "published_at"],            final_update: None,        },        "journal" => Adapter {            create: Ok(journal_create),            update: Some(journal_update),            delete: Err("Journal pages are added to, never deleted"),            restore: Err("Journal pages are added to, never deleted"),            reorder: None,            derived: &[],            final_update: None,        },        "event" => Adapter {            create: Ok(event_create),            update: Some(event_update),            // Every event deleted waits in the bin, local or synced alike.            delete: Ok(event_delete),            restore: Ok(Restore::Engine(event_untrash)),            reorder: None,            derived: &["collection_id", "created_at", "sync_state"],            final_update: None,        },        "person" => Adapter {            create: Ok(person_create),            update: Some(person_update),            delete: Ok(person_archive),            restore: Ok(Restore::Engine(person_unarchive)),            reorder: None,            derived: &["birth_day", "birth_month", "birth_year", "emails", "phones"],            final_update: None,        },        "document" => Adapter {            create: Err("A document arrives as its file — from Files, a scan or Photos — never as a record written here"),            update: Some(document_update),            // Into the bin, its file with it; its Undo takes it back out.            delete: Ok(document_delete),            restore: Ok(Restore::Engine(document_untrash)),            reorder: None,            derived: &[],            final_update: None,        },        "project" => Adapter {            create: Err("A project is made with its name and its slug by create_project"),            update: Some(project_update),            delete: Err("Projects are archived, not deleted; set status to \"archived\" with update_record instead"),            restore: Err("Projects are archived, not deleted"),            reorder: None,            derived: &["slug"],            final_update: None,        },        "photo" | "video" | "media" => Adapter {            create: Err("A picture enters as its bytes — the app's picker, the share sheet or a chat — never as a record written here"),            update: Some(if id == "media" {                media_tables::library_update            } else {                media_tables::picture_update            }),            // Into the bin, photo or video by its id; its Undo takes it back out.            delete: Ok(media_tables::picture_remove),            restore: Ok(Restore::Engine(media_tables::picture_untrash)),            reorder: None,            derived: if id == "media" { &[] } else { &["review_by", "review_at"] },            final_update: None,        },        "album" => Adapter {            create: Err("An album is made from its pictures: create_album with them, or keep one Cotton suggests"),            update: Some(media_tables::album_update),            delete: Err("Albums are never deleted; set state to \"dismissed\" with update_record instead"),            restore: Err("Albums are never deleted"),            reorder: None,            // `title_by` is a column of the one definition now; who named an album            // still goes back only beside its name (`media_tables::TITLE_BY`).            derived: &["kind", "starts_at", "ends_at", "home_label", "decided_at", "title_by"],            final_update: None,        },        "album_item" => Adapter {            create: Ok(media_tables::album_item_create),            update: Some(media_tables::album_item_update),            delete: Ok(media_tables::album_item_remove),            restore: Err("A picture taken out of an album goes back in with create_record — its album_id and record_id — not by undo"),            reorder: None,            derived: &[],            final_update: None,        },        "toolkit" => Adapter {            create: Ok(toolkit_create),            update: Some(toolkit_update),            delete: Ok(toolkit_delete),            restore: Err("A deleted toolkit stays deleted; make it again with create_record"),            reorder: None,            derived: &["shipped", "position"],            final_update: None,        },        "story" => Adapter {            create: Err("Stories arrive from the apps people post them in; nothing writes one here"),            update: Some(story_update),            delete: Err("A story stays for ever; only its picture is let go, unless it is kept"),            restore: Err("A story is never deleted"),            reorder: None,            derived: &[],            final_update: None,        },        "duplicate" => Adapter {            create: Err("The Mac proposes the pairs that look like copies; nothing writes one here"),            update: Some(media_tables::duplicate_update),            delete: Err("A pair is answered, never deleted; set state to \"confirmed\" or \"dismissed\" with update_record instead"),            restore: Err("A pair is never deleted"),            reorder: None,            derived: &[],            final_update: None,        },        "face" => Adapter {            create: Err("The Mac finds the faces it asks about; nothing writes one here"),            update: Some(engine_views::face_update),            delete: Err("A face is answered, never deleted; set decision to \"yes\" or \"no\" with update_record instead"),            restore: Err("A face is never deleted"),            reorder: None,            derived: &["question", "crop", "likelihood", "photo_id", "suggested_person_id"],            final_update: Some("An answered face is not asked again: a yes names the person in it and a no stops the question, and neither has a way back here"),        },        "person_handle" => Adapter {            create: Ok(super::person_handles::create),            update: Some(super::person_handles::update),            delete: Ok(super::person_handles::remove),            restore: Ok(Restore::Recreate),            reorder: None,            derived: &["normalised", "source", "verified_at", "position"],            final_update: None,        },        "email" => Adapter {            create: Err("An email arrives from its mailbox, never as a record written here"),            update: Some(mail_chat_writes::email_update),            delete: Err("An email goes to the bin from its mailbox, never deleted here"),            restore: Err("An email is never deleted here"),            reorder: None,            derived: &["thread_id", "subject", "from_name", "from_email", "sent_at", "body", "trashed_at"],            final_update: None,        },        "email_thread" => Adapter {            create: Err("A conversation is made by the emails that arrive in it, never written here"),            update: Some(mail_chat_writes::email_thread_update),            delete: Ok(mail_chat_writes::email_thread_trash),            restore: Ok(Restore::Engine(mail_chat_writes::email_thread_untrash)),            reorder: None,            derived: &["subject", "first_at", "last_at", "email_count", "summary_by", "trashed_at"],            final_update: None,        },        "message" => Adapter {            // A text to WhatsApp goes out only from Comms, by the owner's own tap, through the outbox the Mac            // drains (22 Nov 2026): a message row is never written to send one.            create: Err("A message arrives with an import; a text to WhatsApp is sent from Comms, never written here"),            update: None,            delete: Ok(mail_chat_writes::message_bin),            restore: Ok(Restore::Engine(mail_chat_writes::message_unbin)),            reorder: None,            derived: &[],            final_update: None,        },        "thread" => Adapter {            create: Err("A chat begins with its first message, never as a record written here"),            update: Some(mail_chat_writes::thread_update),            delete: Ok(mail_chat_writes::thread_archive),            restore: Ok(Restore::Engine(mail_chat_writes::thread_unarchive)),            reorder: None,            derived: &["title", "photo_key", "kind", "description", "last_message_at", "last_message_preview", "summary_by"],            final_update: None,        },        "todo_recurrence" => Adapter {            create: Err("A repeating todo is made from a todo: open the todo and say how it repeats"),            update: Some(recurrence_update),            delete: Err("A repeating todo is stopped from its todo, never deleted here"),            restore: Err("A repeating todo is never deleted here"),            reorder: None,            derived: &[],            final_update: None,        },        "session" => Adapter {            create: Err("A session is logged by the assistant that runs it, never written here"),            update: Some(shop_writes::session_update),            delete: Err("Sessions are never deleted"),            restore: Err("Sessions are never deleted"),            reorder: None,            derived: &[],            final_update: None,        },        "secret" => Adapter {            create: Err("A password is saved with its value on the Passwords screen, never written here"),            update: Some(shop_writes::secret_update),            delete: Ok(shop_writes::secret_trash),            restore: Ok(Restore::Engine(shop_writes::secret_untrash)),            reorder: None,            derived: &["kind", "last_used_at"],            final_update: None,        },        // A screen's board, written whole and held to what this build draws        // (`presentation::save_board`). Its undo writes the board it replaced        // back the same way.        "board" => Adapter {            create: Err("No board is created: each screen that draws one (home, tools, database) already has its record; change it with update_record"),            update: Some(engine_views::board_update),            // A delete PUTS THE SHIPPED BOARD BACK; the board it replaced is            // in the change's before, written back with update_record.            delete: Ok(engine_views::board_reset),            restore: Err("A board put back to the one this build ships is changed again with update_record; the change's before holds the board it replaced"),            reorder: None,            derived: &["name", "drawn"],            final_update: None,        },        // The database's themes, shaped as `board`: written whole and held to        // what this build draws (`presentation::save_theme`); a delete puts        // the default back.        "theme" => Adapter {            create: Err("No theme is created: the themes are paper, plain and database (this database's own); change one with update_record"),            update: Some(engine_views::theme_update),            delete: Ok(engine_views::theme_reset),            restore: Err("A theme put back to its default is changed again with update_record; the change's before holds the theme it replaced"),            reorder: None,            derived: &["name", "drawn", "worn"],            final_update: None,        },        "storage" => Adapter {            create: Err("Storage rows come from each device's reading; change a row's keep rule with update_record"),            update: Some(engine_views::storage_update),            delete: Err("Storage rows are the device's reading and are never deleted"),            restore: Err("Storage rows are never deleted"),            reorder: None,            derived: &[],            final_update: None,        },        _ => return None,    })}/// One write a built-in's adapter can be asked for — what [`plan`] reads.#[derive(Debug, Clone, Copy)]pub(super) enum Op<'a> {    Create(&'a Data),    Update(&'a Data),    Delete,    Restore,    Reorder,}/// Every existing tool a write will call for `op`, in order — read BEFORE/// the first write so a plan that would stop halfway never starts: the/// engine's own ([`engine_plan`]), and the two that file a record under a/// project where its project is a link ([`PROJECT_LINKS`]). Empty values ask/// for everything the verb could reach.fn plan(id: &str, op: Op<'_>) -> Vec<&'static str> {    let column = PROJECT_LINKS        .iter()        .find(|(table, _)| *table == id)        .map(|(_, column)| *column);    let (Some(column), Op::Create(values) | Op::Update(values)) = (column, op) else {        return engine_plan(id, op);    };    if !values.is_empty() && !values.contains_key(column) {        return engine_plan(id, op);    }    let mut rest = values.clone();    rest.remove(column);    let mut tools = match op {        Op::Update(_) if rest.is_empty() && !values.is_empty() => Vec::new(),        Op::Update(_) => engine_plan(id, Op::Update(&rest)),        _ => engine_plan(id, Op::Create(&rest)),    };    tools.extend(["link_to_project", "unlink_from_project"]);    tools}fn engine_plan(id: &str, op: Op<'_>) -> Vec<&'static str> {    if matches!(op, Op::Restore) && cotton_core::constants::BinKind::parse(id).is_some() {        return vec!["restore_from_bin"];    }    match (id, op) {        ("transaction", Op::Create(values)) => {            let mut tools = vec!["record_transaction"];            if values                .keys()                .any(|k| matches!(k.as_str(), "notes" | "period_start" | "period_end"))            {                tools.push("update_transaction");            }            tools        }        ("transaction", Op::Update(_)) => vec!["update_transaction"],        ("money_account", Op::Update(_)) => vec!["update_money_account"],        ("transaction", _) => vec!["delete_transaction"],        ("evidence", _) => vec!["remove_evidence"],        ("todo", Op::Create(values)) => {            let mut tools = vec!["create_todo"];            if values                .keys()                .any(|key| !matches!(key.as_str(), "title" | "notes" | "label" | "due_at"))            {                tools.push("update_todo");            }            tools        }        // A bin move is the generic verb's own, as a note's is.        ("todo", Op::Delete) => Vec::new(),        ("todo", Op::Restore) => vec!["restore_from_bin"],        ("todo", _) => vec!["update_todo"],        ("note", Op::Create(_)) => vec!["create_note"],        // The page's Archive is a write of `archived_at` ([`archive_verbs`]).        ("note", Op::Update(values)) => {            let mut tools = vec!["update_note"];            if values.is_empty() || values.contains_key("archived_at") {                tools.extend(["archive_note", "unarchive_note"]);            }            tools        }        // A bin move is the generic verb's own: no tool of the notes engine        // stands behind it.        ("note", Op::Delete) => Vec::new(),        ("note", _) => vec!["restore_from_bin"],        ("journal", Op::Update(_)) => vec!["update_note"],        ("journal", _) => vec!["append_journal"],        ("event", Op::Create(_)) => vec!["create_event"],        ("event", Op::Update(values)) => {            let mut tools = Vec::new();            if values.is_empty() || values.keys().any(|key| key != "my_response") {                tools.push("update_event");            }            if values.is_empty() || values.contains_key("my_response") {                tools.push("respond_to_invite");            }            tools        }        ("event", Op::Delete) => vec!["delete_event"],        ("person", Op::Create(_)) => vec!["create_person"],        ("person", Op::Update(values)) => {            let mut tools = Vec::new();            if values.is_empty() || values.keys().any(|key| key != "summary") {                tools.push("update_person");            }            if values.is_empty() || values.contains_key("summary") {                tools.push("update_summary");            }            tools        }        ("person", Op::Delete) => vec!["archive_person"],        ("person", Op::Restore) => vec!["unarchive_person"],        ("document", Op::Update(_)) => vec!["update_document"],        ("document", Op::Delete) => vec!["delete_document"],        ("project", Op::Update(_)) => vec!["update_project"],        ("photo", Op::Update(_)) => vec!["update_photo"],        ("photo", Op::Delete) => vec!["remove_photo"],        ("video", Op::Update(_)) => vec!["update_video"],        ("video", Op::Delete) => vec!["remove_video"],        ("media", Op::Delete) => vec!["remove_photo", "remove_video"],        // A name or a cover through `update_album`, a state through        // `decide_album` — and an undo may need both, so both are asked for.        ("album", Op::Update(_)) => vec!["update_album", "decide_album"],        // The undo of a put-in that kept a suggestion also re-opens it: that        // undo asks for `decide_album` itself ([`permit_tool`]), so a plain        // take-out never needs it.        ("album_item", Op::Create(_) | Op::Delete) => vec!["update_album"],        ("duplicate", Op::Update(_)) => vec!["decide_duplicate"],        // Keep is a direct write of `kept` ([`story_update`]): no tool stands behind it.        ("story", _) => Vec::new(),        ("toolkit", Op::Create(_)) => Vec::new(),        ("toolkit", Op::Update(_)) => vec!["update_toolkit"],        ("toolkit", _) => vec!["delete_toolkit"],        ("face", Op::Update(_)) => vec!["update_face"],        ("person_handle", _) => vec!["update_person"],        ("session", Op::Update(values)) => {            let mut tools = Vec::new();            if values.is_empty() || values.contains_key("project_id") {                tools.push("move_session");            }            if values.is_empty() || values.contains_key("title") {                tools.push("rename_session");            }            tools        }        ("secret", Op::Update(_)) => vec!["update_secret"],        ("secret", Op::Delete) => vec!["delete_secret"],        ("secret", Op::Restore) => vec!["restore_from_bin"],        ("email", Op::Update(_)) => vec!["update_email"],        ("email_thread", Op::Update(_)) => vec!["update_summary"],        ("thread", Op::Update(values)) => {            let mut tools = Vec::new();            if values.is_empty() || values.contains_key("pinned_at") {                tools.push("set_thread_pinned");            }            if values.is_empty() || values.contains_key("muted_until") {                tools.push("set_thread_muted");            }            if values.is_empty() || values.contains_key("summary") {                tools.push("update_summary");            }            tools        }        ("thread", Op::Delete | Op::Restore) => vec!["set_thread_archived"],        ("todo_recurrence", Op::Update(_)) => vec!["update_todo_recurrence"],        _ => Vec::new(),    }}/// [`plan`] for a table id — what `tables::tools_reached` reads.pub(super) fn plan_for(id: &str, op: Op<'_>) -> Vec<&'static str> {    if id == super::bin_table::TABLE {        return super::bin_table::plan(op);    }    if [super::activity_tables::ACTIVITY, super::activity_tables::CALLS].contains(&id) {        return super::activity_tables::plan(id, op);    }    plan(id, op)}/// Every tool `op` will call is one this caller may call — asked before the/// first write, so an owner-only step late in a plan refuses the whole write/// rather than leaving its first half behind.pub(super) fn permit(ctx: &Ctx<'_>, definition: &TableDefinition, op: Op<'_>) -> Valid<()> {    adapter_for(definition)?;    for name in plan(definition.rows_table(), op) {        let owner_only = tool_by_name(name).is_some_and(|tool| tool.scope == McpScope::Owner);        if owner_only && !ctx.is_owner_app() {            return Err(ToolFailure::new(format!(                "only the owner's own app can do this to {}",                definition.plural.to_lowercase()            )));        }    }    Ok(())}/// One more tool a write reaches beyond its [`plan`] — asked for at the step/// that needs it, before that step writes: the undo of a put-in that re-opens/// the suggestion it kept.pub(super) fn permit_tool(ctx: &Ctx<'_>, definition: &TableDefinition, name: &str) -> Valid<()> {    let owner_only = tool_by_name(name).is_some_and(|tool| tool.scope == McpScope::Owner);    if owner_only && !ctx.is_owner_app() {        return Err(ToolFailure::new(format!(            "only the owner's own app can do this to {}",            definition.plural.to_lowercase()        )));    }    Ok(())}/// Why a change of `verb` to this built-in cannot be undone, or `None` when it/// can: the engine has no way to write its inverse.pub(super) fn undo_refusal(definition: &TableDefinition, verb: Verb) -> Option<String> {    if super::bin_table::is_bin(definition) {        return super::bin_table::undo_refusal(verb);    }    if super::activity_tables::is_activity(definition) {        return Some(super::activity_tables::undo_refusal(definition, verb));    }    let Some(adapter) = adapter(definition.rows_table()) else {        return Some(read_only(definition).message().to_string());    };    match verb {        Verb::Create if put_away(definition.rows_table()).is_some() => None,        Verb::Create | Verb::Restore => adapter.delete.err().map(str::to_string),        Verb::Delete => adapter.restore.err().map(str::to_string),        Verb::Update | Verb::Link => match adapter.update {            None => Some(format!("{} are added to, never edited", definition.plural)),            Some(_) => adapter.final_update.map(str::to_string),        },        Verb::Reorder => adapter            .reorder            .is_none()            .then(|| format!("{} cannot be reordered yet", definition.plural)),        Verb::Move | Verb::MoveIn => {            Some("undoing a move needs the cross-database coordinator".to_string())        }    }}/// Whether Undo of this built-in's delete creates the record again/// ([`recreate`]) — and so must be handed the day it was first made.pub(super) fn recreated_by_undo(definition: &TableDefinition) -> bool {    adapter(definition.rows_table()).is_some_and(|adapter| matches!(adapter.restore, Ok(Restore::Recreate)))}fn adapter_for(definition: &TableDefinition) -> Valid<Adapter> {    adapter(definition.rows_table()).ok_or_else(|| read_only(definition))}/// A write to this built-in is possible at all.pub(super) fn writable(definition: &TableDefinition) -> Valid<()> {    if super::activity_tables::is_activity(definition) {        return super::activity_tables::writable(definition);    }    if super::bin_table::is_bin(definition) {        return Ok(());    }    adapter_for(definition).map(|_| ())}fn refuse_derived(adapter: &Adapter, definition: &TableDefinition, values: &Data) -> Valid<()> {    match values        .keys()        .find(|key| adapter.derived.contains(&key.as_str()) || computed_key(definition, key))    {        Some(key) => Err(set_by_cotton(definition, key)),        None => Ok(()),    }}/// `create_record` on a built-in: its own tool writes it, and the change is/// read around the write./// These existing text fields retain their engine's edit side effects when/// their definition changes to a place pick. New place fields use the core writer.pub(super) fn native_place_columns(definition: &TableDefinition) -> &'static [&'static str] {    match definition.engine.as_deref() {        Some("people") => &["city"],        Some("calendar") => &["location"],        _ => &[],    }}/// Why no record of this built-in is created through the generic verbs, or/// `Ok` when its own tool makes one. Asked before a create's values are/// checked, so a table that takes no create says where it is made instead of/// naming a column it would have needed.pub(super) fn creatable(definition: &TableDefinition) -> Valid<Create> {    if super::bin_table::is_bin(definition) {        return Err(super::bin_table::create(definition));    }    if super::activity_tables::is_activity(definition) {        return Err(super::activity_tables::refused(definition));    }    adapter_for(definition)?.create.map_err(ToolFailure::new)}pub(super) fn create(ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data) -> ToolResult {    // Existing text columns still run their engine (calendar sync, contact    // semantics); only the new dataset companion facts use the row writer.    let (plain, place) = super::place_values::split(definition, values, native_place_columns(definition));    let values = &plain;    let make = creatable(definition)?;    let adapter = adapter_for(definition)?;    refuse_derived(&adapter, definition, values)?;    permit(ctx, definition, Op::Create(values))?;    // A project that is a link is filed once the record stands.    let mut born = values.clone();    let filed = project_link_column(definition)        .and_then(|column| born.remove(column))        .filter(|project| !project.is_null());    // A journal "create" appends to the day's page when there is one: the    // change then records what the append changed, not a birth.    let existing = if definition.rows_table() == "journal" {        journal_page_for(ctx, values)?    } else {        None    };    let beside_was = beside(ctx, definition, "", values)?;    let id = make(ctx, definition, &born)?;    super::place_values::write(ctx, definition, &id, &place)?;    if let Some(project) = &filed {        file_under(ctx, definition, &id, project)?;    }    let after = read_one(ctx, definition, &id)?        .ok_or_else(|| ToolFailure::new("the record was written but cannot be read back"))?;    let moved = records::beside_moved(&beside_was, &beside(ctx, definition, &id, &after.data)?);    let change = match existing.filter(|before| before.id == id) {        Some(before) => {            let (was, mut now) = records::diff(&before.data, &after.data);            now.extend(moved);            record_change(                ctx,                definition.rows_table(),                Some(id.as_str()),                Verb::Update,                Value::Object(was),                Value::Object(now),            )?        }        None => {            let mut recorded = after.data.clone();            recorded.extend(moved);            record_change(                ctx,                definition.rows_table(),                Some(id.as_str()),                Verb::Create,                Value::Null,                Value::Object(recorded),            )?        }    };    ctx.commit()?;    Ok(answer(ctx, definition, &change, Some(&after)))}/// How a built-in whose Archive is not its Delete puts a record away and/// brings it back, and the tools that stand behind each.struct ArchiveVerbs {    put_away: Remove,    bring_back: Remove,    tools: [&'static str; 2],}/// A note's Delete moves it to the bin and its Archive puts it away where the/// owner still reads it: two acts, so the Archive has verbs of its own. Every/// other built-in archives by its delete and restore.fn archive_verbs(table: &str) -> Option<ArchiveVerbs> {    match table {        "note" => Some(ArchiveVerbs {            put_away: note_archive,            bring_back: note_unarchive,            tools: ["archive_note", "unarchive_note"],        }),        _ => None,    }}/// Does `patch` name the column this built-in's records are archived (or/// binned) by? The page's "Archive this …" is a write of that column — a day/// puts the record away, null brings it back — and the engine's own verb for/// each is its adapter's delete and restore.pub(super) fn names_gone(definition: &TableDefinition, patch: &Data) -> bool {    definition        .archived        .as_ref()        .is_some_and(|column| patch.contains_key(column))}pub(super) fn update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let (mut plain, place) = super::place_values::split(definition, patch, native_place_columns(definition));    // A column the object's definition adds and leaves the person (an    // event's kind) is no column of the engine's: it is written beside it.    let served = super::served_values::split(ctx, definition, &mut plain)?;    if !served.is_empty() {        permit(ctx, definition, Op::Update(&served))?;    }    let patch = &plain;    if super::bin_table::is_bin(definition) {        return super::bin_table::update(ctx, definition, id, patch);    }    if super::activity_tables::is_activity(definition) {        return super::activity_tables::update(ctx, definition, id, patch);    }    let adapter = adapter_for(definition)?;    refuse_derived(&adapter, definition, patch)?;    let mut rest = patch.clone();    let gone = definition        .archived        .as_ref()        .and_then(|column| rest.remove(column));    // Every refusal before the first write: a patch that archives AND edits    // must not leave its first half behind.    let put_away = match (&gone, archive_verbs(definition.rows_table())) {        (None, _) => None,        // An Archive that is not the table's Delete has verbs of its own.        (Some(Value::Null | Value::Bool(false)), Some(verbs)) => {            permit_tool(ctx, definition, verbs.tools[1])?;            Some((verbs.bring_back, false))        }        (Some(_), Some(verbs)) => {            permit_tool(ctx, definition, verbs.tools[0])?;            Some((verbs.put_away, true))        }        // A chat's archive is a switch, not a day: off brings it back.        (Some(Value::Null | Value::Bool(false)), None) => {            let restore = match adapter.restore.map_err(ToolFailure::new)? {                Restore::Engine(restore) => restore,                Restore::Recreate => {                    return Err(ToolFailure::new(format!(                        "{} are deleted, not archived; undo brings a deleted one back",                        definition.plural                    )))                }            };            permit(ctx, definition, Op::Restore)?;            Some((restore, false))        }        // An event has no Archive (architect 1650): its archive column is the        // bin's, and a write of it reached the whole series from a later        // day's long press. Delete asks how far it reaches; this does not.        (Some(_), None) if definition.rows_table() == "event" => {            return Err(ToolFailure::new(                "An event has no Archive — Delete it, and it waits in the bin",            ))        }        (Some(_), None) => {            let delete = adapter.delete.map_err(ToolFailure::new)?;            permit(ctx, definition, Op::Delete)?;            Some((delete, true))        }    };    let filed = project_link_column(definition).and_then(|column| rest.remove(column));    if filed.is_some() {        permit(ctx, definition, Op::Update(patch))?;    }    let update = if rest.is_empty() {        None    } else {        permit(ctx, definition, Op::Update(&rest))?;        Some(adapter.update.ok_or_else(|| {            ToolFailure::new(format!(                "{} are added to, never edited; create a record instead",                definition.plural            ))        })?)    };    // An archived record takes no edit: it comes back first, and is put away last.    if let Some((bring_back, false)) = put_away {        bring_back(ctx, definition, id)?;    }    if let Some(update) = update {        update(ctx, definition, id, &rest)?;    }    if let Some(project) = &filed {        file_under(ctx, definition, id, project)?;    }    if let Some((put_away, true)) = put_away {        put_away(ctx, definition, id)?;    }    super::place_values::write(ctx, definition, id, &place)?;    super::served_values::write(ctx, definition, id, served)?;    Ok(())}/// What this built-in's engine can move BESIDE the record a write names/// (`records::BESIDE`), read before and after the write so the change says/// what moved: who named an album, the album a picture goes into or comes/// out of, and the missed run a repeating todo's tick clears. Every other/// built-in moves nothing beside its record.pub(super) fn beside(    ctx: &Ctx<'_>,    definition: &TableDefinition,    id: &str,    record: &Data,) -> Valid<Data> {    match definition.rows_table() {        "theme" => super::definition_writes::theme_beside(ctx, id),        "board" => super::definition_writes::board_beside(ctx, id),        "album" => media_tables::album_beside(ctx, id),        "album_item" => media_tables::album_item_beside(ctx, record),        "money_account" => usual_beside(ctx),        "todo" => todos::missed_beside(ctx, id),        _ => Ok(Data::new()),    }}/// Which account is the usual one, beside whichever account a write names:/// making one usual takes the mark off another, and its Undo gives it back.pub(super) const USUAL_ACCOUNT: &str = "@usual_account";fn usual_beside(ctx: &Ctx<'_>) -> Valid<Data> {    let usual = maybe_row(        ctx,        &Query::on("cotton_money_accounts")            .columns(&["id"])            .eq("is_default", 1_i64)            .filter(Filter::IsNull("archived_at".into())),    )?;    let mut beside = Data::new();    beside.insert(        USUAL_ACCOUNT.into(),        usual.and_then(|row| text(&row, "id")).map_or(Value::Null, Value::from),    );    Ok(beside)}/// The one write the generic verbs take on an account: `is_default` true/// makes it the usual account and false turns it off, so none is usual and/// the bar asks (`update_money_account`'s `usual`); the Undo of either puts/// the mark back where it was (`@usual_account`).fn money_account_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    values: &Data,) -> Valid<()> {    if let Some(was) = values.get(USUAL_ACCOUNT) {        let accounts = crate::mcp::handlers::money::model::load_money_accounts(ctx)?;        match was.as_str() {            Some(usual) => crate::mcp::handlers::money::model::make_usual(ctx, &accounts, usual)?,            None => crate::mcp::handlers::money::model::clear_usual(ctx, &accounts)?,        }        ctx.commit()?;        return Ok(());    }    let mut args = Map::new();    args.insert("id".into(), Value::from(id));    for (key, value) in values {        let argument =            match key.as_str() {                "name" => "name",                "is_pooled" => "isPooled",                "is_default" => "usual",                _ => return Err(ToolFailure::new(                    "Only an account's name, pooled choice and usual choice can be changed here.",                )),            };        args.insert(argument.into(), value.clone());    }    call(        ctx,        definition,        "update_money_account",        crate::mcp::handlers::money::accounts::update_money_account,        Value::Object(args),    )?;    Ok(())}fn cannot_put_back(definition: &TableDefinition, beside: &Data) -> ToolFailure {    let keys: Vec<&str> = beside.keys().map(String::as_str).collect();    ToolFailure::new(format!(        "this change to {} also moved {} beside the record, which its undo cannot put back",        definition.plural.to_lowercase(),        keys.join(", ")    ))}/// The undo of a create: the record goes, and what the create moved beside it/// is put back — or the undo is refused, never reported as done with/// something left moved.////// On a built-in whose engine never deletes, the add is TAKEN BACK when the/// table takes adds back ([`takes_back`]) and the store's three conditions/// hold (`cotton_store::take_back`): the record is erased on every device as/// if it was never made. Otherwise it is put away in the table's own state./// `through` is the stamp of the last receipt of the add's own act (its/// change row), or `None` when the add had an effect outside its own rows.pub(super) fn uncreate(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    record: &Data,    beside: &Data,    through: Option<&str>,) -> Valid<Uncreated> {    if definition.rows_table() == "album_item" {        adapter_for(definition)?;        permit(ctx, definition, Op::Delete)?;        return media_tables::album_item_uncreate(ctx, definition, id, record, beside).map(|()| Uncreated::Gone);    }    if !beside.is_empty() {        return Err(cannot_put_back(definition, beside));    }    if let (Some((column, state)), true) = (put_away(definition.rows_table()), adapter_for(definition)?.delete.is_err()) {        let mut patch = Data::new();        patch.insert(column.to_string(), Value::from(state));        // Asked as the put-away it may become: one permission either way.        permit(ctx, definition, Op::Update(&patch))?;        if let (true, Some(through)) = (takes_back(definition.rows_table()), through) {            let table = source(definition)?.table;            let refused = match ctx.writer_actor() {                Some(asker) => cotton_store::take_back::refusal(ctx.read.driver(), asker, table, id, through)                    .map_err(sql_err)?,                None => Some(cotton_store::take_back::Refusal::NotAPerson),            };            if refused.is_none() {                // Nothing the record said outlives it in the change log.                super::forget_changes(ctx, id)?;                ctx.writer()?.take_back(table, id, through);                return Ok(Uncreated::TakenBack);            }        }        if record.get(column) != Some(&Value::from(state)) {            update(ctx, definition, id, &patch)?;        }        return Ok(Uncreated::PutAway);    }    // An add to a table whose Delete waits in the bin is taken back, never    // binned: an Undo of an add that left the record in the bin would leave    // it behind. One the store will not take back (changed since, made    // elsewhere) goes to the bin as a Delete would.    if let (true, Some(through)) = (cotton_core::records::receipt::lands_in_bin(definition), through) {        permit(ctx, definition, Op::Delete)?;        let table = source(definition)?.table;        let refused = match ctx.writer_actor() {            Some(asker) => cotton_store::take_back::refusal(ctx.read.driver(), asker, table, id, through)                .map_err(sql_err)?,            None => Some(cotton_store::take_back::Refusal::NotAPerson),        };        if refused.is_none() {            super::forget_changes(ctx, id)?;            ctx.writer()?.take_back(table, id, through);            return Ok(Uncreated::TakenBack);        }    }    delete(ctx, definition, id)?;    Ok(Uncreated::Gone)}/// How an add was taken back.pub(super) enum Uncreated {    /// The record is gone, by the table's own delete.    Gone,    /// The add was taken back: the record is erased on every device, and its    /// change rows with it.    TakenBack,    /// The engine never deletes this table's records: the record stays, in    /// the table's own put-away state.    PutAway,}/// The state that takes an add back on a built-in whose engine never/// deletes, when the add is not the person's own fresh one to take back:/// every add carries Undo, and for these the undo puts the record away as/// the person would by hand (a thought is dismissed, a project archived). A/// journal day has no such state: its words are emptied, and an empty day is/// not listed.pub(super) fn put_away(table: &str) -> Option<(&'static str, &'static str)> {    match table {        "album" => Some(("state", "dismissed")),        "project" => Some(("status", "archived")),        "journal" => Some(("body", "")),        _ => None,    }}/// The built-ins whose add is taken back by the store's take-back. An order/// is not: recording one moves stock, an effect outside its own rows, so its/// Undo cancels it. A project and a store are archived.fn takes_back(table: &str) -> bool {    matches!(table, "thought" | "album" | "journal")}/// Whether Undo of an add still puts the record away once the record has/// changed since: true where the put-away state keeps what changed. A/// journal day's put-away empties its words, so a day written to since is/// left alone.pub(super) fn puts_away_once_changed(definition: &TableDefinition) -> bool {    definition.rows_table() != "journal"        && put_away(definition.rows_table()).is_some()        && adapter(definition.rows_table()).is_some_and(|adapter| adapter.delete.is_err())}/// An undo's patch: the columns Cotton derives are left out (the engine sets/// them again from what is put back), what moved beside the record goes back/// with it where the built-in can put it back, and a patch with nothing else/// is refused.pub(super) fn update_for_undo(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,    beside: &Data,) -> Valid<()> {    if definition.rows_table() == "board" {        if let Some(moved) = beside.get("@board_row") {            if let Some(row) = moved.get("was").and_then(Value::as_object) {                update_row(ctx, crate::presentation::BOARD_DEFINITIONS, id, row.clone())?;            } else {                ctx.writer()?.retract(crate::presentation::BOARD_DEFINITIONS, id, crate::mcp::writer::Retract::Machine("board_undo"));            }            ctx.commit()?;            return Ok(());        }    }    if definition.rows_table() == "theme" {        if let Some(moved) = beside.get("@theme_row") {            if let Some(row) = moved.get("was").and_then(Value::as_object) {                update_row(ctx, crate::presentation::THEME_DEFINITIONS, id, row.clone())?;            } else {                ctx.writer()?.retract(crate::presentation::THEME_DEFINITIONS, id, crate::mcp::writer::Retract::Machine("theme_undo"));            }            ctx.commit()?;            return Ok(());        }        let text = patch.get("definition").and_then(Value::as_str).ok_or_else(|| ToolFailure::new("The theme change has no previous definition"))?;        let previous: Value = serde_json::from_str(text).map_err(|why| ToolFailure::new(why.to_string()))?;        // History is a before-image, not a newly authored theme. Applying        // today's validation here would strand edits from an older build.        update_row(ctx, crate::presentation::THEME_DEFINITIONS, id, serde_json::json!({"definition":previous,"updated_at":now_iso(ctx)}).as_object().unwrap().clone())?;        ctx.commit()?;        return Ok(());    }    if super::bin_table::is_bin(definition) {        return super::bin_table::undo_restore(ctx, definition, id, patch);    }    if super::activity_tables::is_activity(definition) {        return Err(ToolFailure::new(super::activity_tables::undo_refusal(definition, Verb::Update)));    }    let adapter = adapter_for(definition)?;    let mut writable: Data = patch        .iter()        .filter(|(key, _)| {            !adapter.derived.contains(&key.as_str()) && !computed_key(definition, key)        })        .map(|(key, value)| (key.clone(), value.clone()))        .collect();    for (key, moved) in beside {        match (definition.rows_table(), key.as_str()) {            ("album", media_tables::TITLE_BY) | ("money_account", USUAL_ACCOUNT) => {                writable.insert(key.clone(), moved.get("was").cloned().unwrap_or(Value::Null));            }            // One Undo of a tick opens the whole run it cleared again.            ("todo", cotton_core::records::MISSED) => todos::reopen_the_missed_run(ctx, moved)?,            _ => return Err(cannot_put_back(definition, beside)),        }    }    if writable.is_empty() {        return Err(ToolFailure::new(format!(            "this change to {} touched only what Cotton sets itself, so there is nothing to undo",            definition.plural.to_lowercase()        )));    }    update(ctx, definition, id, &writable)}/// Who wrote a record, where its table says: an Undo writes through the/// engine's own verbs, which sign the row as the assistant, and must not.const AUTHOR_COLUMNS: [&str; 2] = ["author_kind", "author_label"];/// [`figure_total`] over the evaluator's rows (`derivation_rows`, with the/// money projection and computed values): the sum of `added` over the rows/// `clauses` keep whose date falls in `span` — or its lowest or highest, with/// the date of the row that holds it (the earliest, on a tie) — in the one/// currency its rows are in (`mixed` across two)./// Cached numeric columns already hold their typed values. Narrow the source/// first and join by record id, rather than decoding its whole history to/// build an IN list. Other engine-resolved columns still use their resolver.fn computed_extreme(    read: &ReadDb<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    span: Option<(&str, &str)>,    op: cotton_core::definitions::SummaryOp,    added: &str,) -> Valid<Option<super::FigureTotal>> {    let zone = crate::mcp::handlers::common::read_where_zone(read)?;    use cotton_core::definitions::SummaryOp;    let Some(column) = definition.column(added).filter(|column| column.computed.is_some()        && matches!(column.column_type, ColumnType::Number | ColumnType::Bytes | ColumnType::Amount)) else {        return Ok(None);    };    let source = source(definition)?;    if source.columns.contains(&added) {        return Ok(None);    }    let physical = |name: &str| source.columns.contains(&name)        && !is_computed_column(definition.rows_table(), name)        && !RESOLVED_COLUMNS.contains(&(definition.rows_table(), name))        && definition.column(name).is_some_and(|column| column.computed.is_none()            && column.multiple != Some(true) && column.column_type != ColumnType::AccountNumber);    let quote = |name: &str| format!("\"{}\"", name.replace('"', "\"\""));    let mut query = base_query(&source);    for column in &source.gone {        query = query.filter(Filter::IsNull((*column).into()));    }    if definition.rows_table() == "journal" {        query = query.filter(Filter::Static(JOURNAL_DAY_HAS_WORDS));    }    for clause in clauses {        if !physical(&clause.column) || narrowing(definition.rows_table(), &clause.column).is_some() {            return Ok(None);        }        for filter in stored_narrowing(definition, &source, clause, &zone)? {            query = query.filter(filter);        }    }    let day = match definition.date.as_deref() {        Some(day) if physical(day) => {            if let Some((from, until)) = span {                query = query.filter(Filter::Gte(day.into(), SqlValue::Text(from.into())))                    .filter(Filter::Lt(day.into(), SqlValue::Text(until.into())));            }            let day = quote(day);            format!("CASE WHEN typeof({day})='text' THEN {day} ELSE '' END")        }        Some(_) => return Ok(None),        None if span.is_some() => return Ok(None),        None => "''".into(),    };    let currency = column.currency.as_deref();    let currency_column = currency.filter(|name| definition.column(name).is_some());    let currency_sql = match currency_column {        Some(name) if physical(name) => {            let name = quote(name);            format!("CASE WHEN typeof({name})='text' THEN {name} END")        }        Some(_) => return Ok(None),        None => "NULL".into(),    };    let id = if definition.rows_table() == "device" { "device_id" } else { "id" };    let (sql, mut params) = read.sub_select(&query,        &format!("{id} AS figure_id, {day} AS figure_day, {currency_sql} AS figure_currency")).map_err(sql_err)?;    params.extend([SqlValue::Text(definition.id.clone()), SqlValue::Text(added.into())]);    let order = match op { SummaryOp::Min => "ASC", SummaryOp::Max => "DESC", _ => return Ok(None) };    let sql = format!("WITH candidates AS MATERIALIZED (        SELECT c.value AS figure_value, f.figure_day, f.figure_currency        FROM ({sql}) f CROSS JOIN _computed c        WHERE c.table_id=? AND c.record_id=f.figure_id AND c.key=? AND typeof(c.value)='integer')        SELECT figure_value AS total, figure_day AS at,            (SELECT json_group_array(DISTINCT figure_currency) FROM candidates) AS currencies        FROM candidates ORDER BY figure_value {order}, figure_day ASC LIMIT 1");    let Some(row) = read.driver().get(&sql, &params).map_err(sql_err)? else {        return Ok(Some(super::FigureTotal::default()));    };    let values: Vec<Value> = serde_json::from_str(row.text("currencies").unwrap_or("[]"))        .map_err(|error| ToolFailure::new(error.to_string()))?;    let mut codes = std::collections::BTreeSet::new();    if currency_column.is_some() {        codes.extend(values.iter().filter_map(Value::as_str).filter(|code| !code.trim().is_empty()).map(str::to_string));    } else {        codes.extend(currency.filter(|code| !code.trim().is_empty()).map(str::to_string));    }    let mixed = codes.len() > 1;    Ok(Some(super::FigureTotal {        total: row.int("total").unwrap_or(0),        currency: codes.into_iter().next().filter(|_| !mixed),        mixed,        on: row.text("at").filter(|day| !day.is_empty()).map(str::to_string),    }))}pub(super) fn rows_total(    read: &ReadDb<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    span: Option<(&str, &str)>,    op: cotton_core::definitions::SummaryOp,    added: &str,    resolved: &mut super::FigureRows,) -> Valid<super::FigureTotal> {    let zone = crate::mcp::handlers::common::read_where_zone(read)?;    use cotton_core::definitions::SummaryOp;    if !resolved.contains_key(&definition.id) {        let mut rows: Vec<super::Stored> = derivation_rows(read.driver(), read.workspace_id(), definition)?            .into_iter()            .map(|(id, data)| super::Stored { id, data, created_at: None, updated_at: None, deleted_at: None, byline: None })            .collect();        super::with_computed_read(read, definition, &mut rows)?;        resolved.insert(definition.id.clone(), rows);    }    let rows = resolved.get(&definition.id).expect("the projection was resolved in this pass");    let date = definition.date.as_deref();    let currency = definition.column(added).and_then(|column| column.currency.clone());    let mut total = 0_i64;    let mut held: Option<(i64, String)> = None;    let mut currencies = std::collections::BTreeSet::new();    for row in rows.iter().map(|row| &row.data) {        if !clauses.iter().all(|clause| records::holds(row, clause, &zone)) {            continue;        }        if let Some((from, until)) = span {            let day = date.and_then(|date| row.get(date)).and_then(Value::as_str).unwrap_or_default();            if day < from || day >= until {                continue;            }        }        let Some(value) = row.get(added).and_then(Value::as_i64) else { continue };        let day = date.and_then(|date| row.get(date)).and_then(Value::as_str).unwrap_or_default().to_string();        let beats = |(best, on): &(i64, String)| match op {            SummaryOp::Min => value < *best || (value == *best && day < *on),            SummaryOp::Max => value > *best || (value == *best && day < *on),            SummaryOp::Count | SummaryOp::Sum => false,        };        match op {            SummaryOp::Min | SummaryOp::Max if held.as_ref().is_none_or(beats) => held = Some((value, day)),            SummaryOp::Min | SummaryOp::Max => {}            SummaryOp::Count | SummaryOp::Sum => total = total.saturating_add(value),        }        let code = match currency.as_deref() {            Some(named) if definition.column(named).is_some() => row.get(named).and_then(Value::as_str).map(str::to_string),            other => other.map(str::to_string),        };        currencies.extend(code.filter(|code| !code.trim().is_empty()));    }    let mixed = currencies.len() > 1;    let (total, on) = match held {        Some((value, day)) => (value, Some(day).filter(|day| !day.is_empty())),        None => (total, None),    };    Ok(super::FigureTotal { total, currency: currencies.into_iter().next().filter(|_| !mixed), mixed, on })}/// The stamps an Undo puts back on a built-in's row: when it was edited (where/// the definition shows that column) and who wrote it, as the row holds them now.pub(super) fn stamps(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<Data> {    // A table the engine answers as a view has no row of its own to stamp.    let Some(table) = builtin_store_table(definition.rows_table()) else {        return Ok(Data::new());    };    let held = |column: &str| cotton_store::schema::specs::codec_of(table, column).is_some();    let columns: Vec<&str> = AUTHOR_COLUMNS        .into_iter()        .chain(definition.column(records::EDITED_AT).map(|_| records::EDITED_AT))        .filter(|column| held(column))        .collect();    if columns.is_empty() {        return Ok(Data::new());    }    let row = maybe_row(ctx, &Query::on(table).columns(&columns).eq("id", id.to_string()))?;    Ok(columns        .iter()        .map(|column| {            let value = row.as_ref().and_then(|row| row.get(*column)).cloned().unwrap_or(Value::Null);            (column.to_string(), value)        })        .collect())}/// Write `wanted` stamps back onto a built-in's row — only those the Undo's/// own write moved. `updated_at` named in the write keeps it from moving now.pub(super) fn restamp(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, wanted: &Data) -> Valid<()> {    let now = stamps(ctx, definition, id)?;    let mut patch: Map<String, Value> = wanted        .iter()        .filter(|(column, value)| now.get(*column) != Some(*value))        .map(|(column, value)| (column.clone(), value.clone()))        .collect();    if patch.is_empty() {        return Ok(());    }    if !patch.contains_key(records::EDITED_AT) {        if let Some(at) = now.get(records::EDITED_AT) {            patch.insert(records::EDITED_AT.into(), at.clone());        }    }    update_row(ctx, source(definition)?.table, id, patch)?;    ctx.commit()}fn bin_put_away(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    let kind = cotton_core::constants::BinKind::parse(definition.rows_table())        .ok_or_else(|| ToolFailure::new(format!("{} has no Bin source", definition.plural)))?;    crate::mcp::handlers::bin::put_away(ctx, kind, id)}fn bin_bring_back(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(ctx, definition, "restore_from_bin", crate::mcp::handlers::bin::restore_from_bin,        json!({"kind": definition.rows_table(), "id": id})).map(|_| ())}pub(super) fn delete(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    if super::bin_table::is_bin(definition) {        return super::bin_table::delete(ctx, definition, id);    }    if super::activity_tables::is_activity(definition) {        return Err(super::activity_tables::refused(definition));    }    let adapter = adapter_for(definition)?;    let delete = adapter.delete.map_err(ToolFailure::new)?;    permit(ctx, definition, Op::Delete)?;    delete(ctx, definition, id)}pub(super) fn restore(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    before: &Data,) -> Valid<()> {    if super::bin_table::is_bin(definition) {        return Err(super::bin_table::restore());    }    if super::activity_tables::is_activity(definition) {        return Err(super::activity_tables::refused(definition));    }    let adapter = adapter_for(definition)?;    let restore = adapter.restore.map_err(ToolFailure::new)?;    permit(ctx, definition, Op::Restore)?;    match restore {        Restore::Engine(restore) => restore(ctx, definition, id),        Restore::Recreate => recreate(ctx, definition, id, before),    }}/// The undo of a retract (design 3.5): a CREATE of the same row id, minted/// now, so it is stamped above the retract and the row is live again. Each/// field takes what this device's receipts above the retract say — a change/// that arrived for the row while it was gone, dormant until now — and only/// where there is none, what history's `before` held: a plain create from/// `before` would overwrite that later change. It names no child; the fold/// brings back the owning children that are live by their own receipts.fn recreate(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    before: &Data,) -> Valid<()> {    let source = source(definition)?;    let table = source.table;    if cotton_store::receipts::retract_stamp(ctx.db(), table, id)        .map_err(|error| ToolFailure::new(error.to_string()))?        .is_none()    {        return Err(ToolFailure::new(format!(            "That {} was not deleted here, so there is nothing to bring back",            definition.name.to_lowercase()        )));    }    let mut patch: Map<String, Value> = before        .iter()        .filter(|(key, _)| {            cotton_store::schema::specs::codec_of(table, key).is_some()                && !RESOLVED_COLUMNS.contains(&(definition.rows_table(), key.as_str()))        })        .map(|(key, value)| {            let stored = if TEXT_LISTS.contains(&(definition.rows_table(), key.as_str())) {                Value::from(value.to_string())            } else {                value.clone()            };            (key.clone(), stored)        })        .collect();    let dormant = cotton_store::receipts::dormant_fields(ctx.db(), table, id)        .map_err(|error| ToolFailure::new(error.to_string()))?;    for (field, value) in dormant {        if cotton_store::schema::specs::codec_of(table, &field).is_some() {            patch.insert(field, value);        }    }    insert_row(ctx, table, id, patch)?;    ctx.commit()}pub(super) fn reorder(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    position: f64,) -> Valid<()> {    if super::activity_tables::is_activity(definition) {        return Err(super::activity_tables::refused(definition));    }    let adapter = adapter_for(definition)?;    let place = adapter.reorder.ok_or_else(|| {        ToolFailure::new(format!("{} cannot be reordered yet", definition.plural))    })?;    permit(ctx, definition, Op::Reorder)?;    place(ctx, definition, id, position)}// ── argument mapping helpers ────────────────────────────────────────────────fn put(args: &mut Map<String, Value>, key: &str, value: &Value) {    args.insert(key.to_string(), value.clone());}/// A due value: a day goes as `dueDate`, an instant as `dueAt`, null clears.fn put_due(args: &mut Map<String, Value>, value: &Value) {    match value.as_str() {        Some(day) if records::is_date(day) => put(args, "dueDate", value),        _ => put(args, "dueAt", value),    }}fn project_slug(ctx: &Ctx<'_>, value: &Value) -> Valid<Option<String>> {    let Some(id) = value.as_str() else {        return Ok(None);    };    let slug = project_slug_of(&projects(ctx)?, id)        .ok_or_else(|| ToolFailure::new("That project is no longer here"))?;    Ok(Some(slug))}// ── todo ────────────────────────────────────────────────────────────────────fn todo_priority(definition: &TableDefinition, value: &Value) -> Valid<Value> {    match value.as_i64() {        _ if value.is_null() => Ok(json!("none")),        Some(0) => Ok(json!("none")),        Some(1) => Ok(json!("high")),        _ => Err(ToolFailure::new(format!(            "{} take priority 1 (high) or 0 (none)",            definition.plural        ))),    }}fn todo_args(    definition: &TableDefinition,    values: &Data,    args: &mut Map<String, Value>,) -> Valid<()> {    for (key, value) in values {        match key.as_str() {            "title" | "notes" | "label" => put(args, key, value),            "due_at" => put_due(args, value),            "snoozed_until" => put(args, "snoozedUntil", value),            "priority" => {                let priority = todo_priority(definition, value)?;                put(args, "priority", &priority);            }            "status" if value.is_null() => return Err(cannot_clear(definition, key)),            "status" => put(args, "status", value),            other => return Err(set_by_cotton(definition, other)),        }    }    Ok(())}fn todo_create(ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data) -> Valid<String> {    let (born, later): (Data, Data) = values        .iter()        .map(|(k, v)| (k.clone(), v.clone()))        .partition(|(key, _)| matches!(key.as_str(), "title" | "notes" | "label" | "due_at"));    let mut args = Map::new();    todo_args(definition, &born, &mut args)?;    let id = created_id(&call(        ctx,        definition,        "create_todo",        todos::create_todo,        Value::Object(args),    )?)?;    // The definition's defaults (status open, priority 0) ride in every    // create's values, and create_todo already made the todo so: only what    // differs from the row it wrote is a second write, so a plain create is    // one write (and a record made only-you stays one act with its mark).    let made = read_one(ctx, definition, &id)?.map(|stored| stored.data).unwrap_or_default();    let later: Data = later.into_iter().filter(|(key, value)| made.get(key) != Some(value)).collect();    if !later.is_empty() {        todo_update(ctx, definition, &id, &later)?;    }    Ok(id)}fn todo_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let mut args = Map::new();    args.insert("id".into(), Value::from(id));    todo_args(definition, patch, &mut args)?;    call(        ctx,        definition,        "update_todo",        todos::update_todo,        Value::Object(args),    )    .map(|_| ())}// ── note and journal ────────────────────────────────────────────────────────fn note_args(    definition: &TableDefinition,    values: &Data,    args: &mut Map<String, Value>,) -> Valid<()> {    for (key, value) in values {        match key.as_str() {            "title" | "body" if value.is_null() => return Err(cannot_clear(definition, key)),            "title" | "body" => put(args, key, value),            ATTACHMENTS_KEY => put_attachments(args, value),            // The one definition the object serves gives a note's columns            // their defaults (its kind `note`, its author the person, not            // pinned), which a create fills in: what this engine makes.            other if definition.column(other).and_then(|column| column.default.as_ref()) == Some(value) => {}            other => return Err(set_by_cotton(definition, other)),        }    }    Ok(())}/// A record's whole picture list for its engine's own write: null takes/// every picture off, which the engine spells `[]`.fn put_attachments(args: &mut Map<String, Value>, value: &Value) {    let list = if value.is_null() {        Value::Array(Vec::new())    } else {        value.clone()    };    args.insert(ATTACHMENTS_KEY.into(), list);}fn note_create(ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data) -> Valid<String> {    let mut args = Map::new();    note_args(definition, values, &mut args)?;    created_id(&call(        ctx,        definition,        "create_note",        notes::create_table_note,        Value::Object(args),    )?)}fn note_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let mut args = Map::new();    args.insert("id".into(), Value::from(id));    note_args(definition, patch, &mut args)?;    call(        ctx,        definition,        "update_note",        notes::update_note,        Value::Object(args),    )    .map(|_| ())}fn note_archive(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(        ctx,        definition,        "archive_note",        notes::archive_note,        json!({ "id": id }),    )    .map(|_| ())}/// A note's Delete: into the bin, where it waits until the bin is emptied.fn note_trash(ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str) -> Valid<()> {    notes::set_trashed(ctx, id, true)}/// The Undo of [`note_trash`]: out of the bin through the same write.fn note_untrash(ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str) -> Valid<()> {    notes::set_trashed(ctx, id, false)}fn note_unarchive(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(        ctx,        definition,        "unarchive_note",        notes::unarchive_note,        json!({ "id": id }),    )    .map(|_| ())}/// The journal page already standing for the day a create names — today's,/// in the owner's zone, when it names none.fn journal_page_for(ctx: &Ctx<'_>, values: &Data) -> Valid<Option<Stored>> {    let day = match values.get("journal_date").and_then(Value::as_str) {        Some(day) => day.to_string(),        None => today_in(&workspace_timezone(ctx)?, ctx.now.timestamp_millis())?,    };    let query = Query::on("cotton_notes")        .columns(&["id"])        .eq("kind", "journal".to_string())        .eq("journal_date", day);    let Some(row) = maybe_row(ctx, &query)? else {        return Ok(None);    };    let definition = super::definition(ctx, "journal")?;    read_one(ctx, &definition, &text(&row, "id").unwrap_or_default())}/// `create_record` on the journal adds to a day's page. The list's bar files/// what was typed under the table's title column, and a day's page has no/// title of its own to type: words that arrive as `title` with no `body` ARE/// the entry.fn journal_create(ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data) -> Valid<String> {    let mut args = Map::new();    let mut said = None;    for (key, value) in values {        match key.as_str() {            "body" => put(&mut args, "text", value),            "title" => said = Some(value),            "journal_date" => put(&mut args, "date", value),            "project_id" => {                if let Some(slug) = project_slug(ctx, value)? {                    args.insert("project".into(), Value::from(slug));                }            }            other => return Err(set_by_cotton(definition, other)),        }    }    if !args.contains_key("text") {        match said {            Some(words) => put(&mut args, "text", words),            None => {                return Err(ToolFailure::new(format!(                    "A journal page needs its {}: the words to add to the day",                    label_in_sentence(definition, "body")                )))            }        }    }    created_id(&call(        ctx,        definition,        "append_journal",        notes::append_journal,        Value::Object(args),    )?)}/// `update_record` on a journal page: the day's words are a sheet the owner/// keeps writing on, so `body` (and `title`) are rewritten whole by the notes/// engine's own `update_note`. The day itself never moves.// ── story ───────────────────────────────────────────────────────────────────/// A story is answered by Keep alone: `kept` true holds its picture past the/// day the app keeps it, false lets the sweep drop it. Everything else is the/// app's to say.fn story_update(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, patch: &Data) -> Valid<()> {    let mut kept = None;    for (key, value) in patch {        match (key.as_str(), value) {            ("kept", Value::Bool(wanted)) => kept = Some(*wanted),            ("kept", _) => return Err(ToolFailure::new("kept is true or false")),            (other, _) => return Err(set_by_cotton(definition, other)),        }    }    let Some(kept) = kept else {        return Err(ToolFailure::new("Keep is the one thing a story is answered by"));    };    let present = ctx        .db()        .get("SELECT id FROM cotton_stories WHERE id = ?", &[SqlValue::Text(id.to_string())])        .map_err(|error| ToolFailure::new(error.to_string()))?;    if present.is_none() {        return Err(ToolFailure::new("That story is not here"));    }    let mut row = Map::new();    row.insert("kept".into(), Value::Bool(kept));    ctx.writer()?.upsert("cotton_stories", id, row);    ctx.commit()}fn journal_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let mut args = Map::new();    args.insert("id".into(), Value::from(id));    for (key, value) in patch {        match key.as_str() {            "body" if value.is_null() => return Err(cannot_clear(definition, key)),            "title" | "body" => put(&mut args, key, value),            other => return Err(set_by_cotton(definition, other)),        }    }    call(        ctx,        definition,        "update_note",        notes::update_note,        Value::Object(args),    )    .map(|_| ())}// ── event ───────────────────────────────────────────────────────────────────/// An event's columns as the calendar tools name them. Null clears what the/// tools let be cleared; a title and a start are never cleared.fn event_args(    definition: &TableDefinition,    values: &Data,    args: &mut Map<String, Value>,) -> Valid<()> {    for (key, value) in values {        match key.as_str() {            "title" | "starts_at" if value.is_null() => {                return Err(cannot_clear(definition, key))            }            "title" | "location" | "notes" | "rrule" => put(args, key, value),            "starts_at" => put(args, "startsAt", value),            "ends_at" => put(args, "endsAt", value),            "all_day" => {                args.insert("allDay".into(), Value::Bool(value.as_bool() == Some(true)));            }            // The owner's switch that puts a Cotton event on Google.            "on_google" => {                args.insert("onGoogle".into(), Value::Bool(value.as_bool() == Some(true)));            }            "my_response" => {}            other => return Err(set_by_cotton(definition, other)),        }    }    Ok(())}/// The owner's reply to an invitation — `respond_to_invite`, the owner's own/// app's alone ([`call`] keeps it so).fn event_respond(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    values: &Data,) -> Valid<()> {    let Some(response) = values.get("my_response") else {        return Ok(());    };    if response.is_null() {        return Err(cannot_clear(definition, "my_response"));    }    call(        ctx,        definition,        "respond_to_invite",        events::respond_to_invite,        json!({ "id": id, "response": response }),    )    .map(|_| ())}fn event_create(ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data) -> Valid<String> {    let mut args = Map::new();    event_args(definition, values, &mut args)?;    // Null is "none" on a create, and the tool reads an absent key as none.    args.retain(|_, value| !value.is_null());    let id = created_id(&call(        ctx,        definition,        "create_event",        events::create_event,        Value::Object(args),    )?)?;    event_respond(ctx, definition, &id, values)?;    Ok(id)}fn event_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let mut args = Map::new();    event_args(definition, patch, &mut args)?;    // A start moved on its own takes the end with it: the event keeps its    // length, as it does when dragged on a calendar — and a start moved past    // the old end is never refused for an end nobody touched.    // A whole day given a time of day becomes timed and keeps no end of its    // day (`events::names_a_time_of_day`): its length is a day's, not an hour's.    if let (Some(start), false) = (args.get("startsAt").and_then(Value::as_str), args.contains_key("endsAt")) {        let was = read_one(ctx, definition, id)?.map(|stored| stored.data).unwrap_or_default();        let ms = |value: Option<&Value>| value.and_then(Value::as_str).and_then(parse_ms);        let timed_now = was.get("all_day") == Some(&Value::Bool(true))            && !args.contains_key("allDay")            && events::names_a_time_of_day(ctx, start, None)?;        if let (Some(new_start), Some(old_start), Some(old_end), false) =            (parse_ms(start), ms(was.get("starts_at")), ms(was.get("ends_at")), timed_now)        {            args.insert("endsAt".into(), Value::from(iso_of_ms(new_start + (old_end - old_start))));        }    }    if !args.is_empty() {        args.insert("id".into(), Value::from(id));        call(            ctx,            definition,            "update_event",            events::update_event,            Value::Object(args),        )?;    }    event_respond(ctx, definition, id, patch)}/// One day of a repeating event edited on its own (`scope: "this"`): that/// day becomes its own row and the series stays as it was. Answers the day's/// row id.pub(super) fn event_occurrence_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    series: &str,    occurrence_at: &str,    patch: &Data,) -> Valid<String> {    let mut args = Map::new();    event_args(definition, patch, &mut args)?;    args.insert("id".into(), Value::from(series));    args.insert("occurrenceAt".into(), Value::from(occurrence_at));    args.insert("scope".into(), Value::from("this"));    let out = call(ctx, definition, "update_event", events::update_event, Value::Object(args))?;    out.get("id")        .and_then(Value::as_str)        .map(str::to_string)        .ok_or_else(|| ToolFailure::new("update_event answered no id for the day it made its own"))}fn event_delete(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(        ctx,        definition,        "delete_event",        events::delete_event,        json!({ "id": id }),    )    .map(|_| ())}fn event_untrash(ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str) -> Valid<()> {    events::untrash_event(ctx, id)}// ── person ──────────────────────────────────────────────────────────────────/// A person's columns as the people tools name them. The owner's own app/// names two people alike when the owner says so, so a write from it carries/// `allowDuplicateName`; an assistant's is still asked.fn person_args(    ctx: &Ctx<'_>,    definition: &TableDefinition,    values: &Data,    args: &mut Map<String, Value>,) -> Valid<()> {    for (key, value) in values {        match key.as_str() {            "full_name" if value.is_null() => return Err(cannot_clear(definition, key)),            "full_name" => put(args, "fullName", value),            "role_title" => put(args, "roleTitle", value),            "org" | "city" | "timezone" | "language" => put(args, key, value),            "birthday" => put(args, key, &person_birthday(definition, value)?),            "avatar_key" if value.is_null() => put(args, "avatarKey", value),            "avatar_key" => {                return Err(ToolFailure::new(format!(                    "A photograph is added from the app's picker; {} here can only be taken off",                    label_in_sentence(definition, key)                )))            }            "summary" => {}            other => return Err(set_by_cotton(definition, other)),        }    }    if ctx.is_owner_app() && args.contains_key("fullName") {        args.insert("allowDuplicateName".into(), Value::Bool(true));    }    Ok(())}/// A birthday as the page writes it — "1992-08-17", or "--08-17" when the/// year is not known — as the people tool takes it: `{month, day, year}`,/// null clearing it. The contacts import never overwrites it: a value set/// here differs from the import's snapshot, and Cotton then wins/// (`cotton_core::rules::contact_sync`).fn person_birthday(definition: &TableDefinition, value: &Value) -> Valid<Value> {    if value.is_null() {        return Ok(Value::Null);    }    let text = value.as_str().unwrap_or_default();    let number = |part: &str, digits: usize| {        (part.len() == digits && part.bytes().all(|byte| byte.is_ascii_digit())).then(|| part.parse::<i64>().ok()).flatten()    };    let parts: Vec<&str> = text.strip_prefix("--").unwrap_or(text).split('-').collect();    let (year, month, day) = match (text.starts_with("--"), parts.as_slice()) {        (true, [month, day]) => (Some(None), number(month, 2), number(day, 2)),        (false, [year, month, day]) => (number(year, 4).map(Some), number(month, 2), number(day, 2)),        _ => (None, None, None),    };    match (year, month, day) {        (Some(year), Some(month @ 1..=12), Some(day @ 1..=31)) => {            Ok(json!({ "month": month, "day": day, "year": year }))        }        _ => Err(ToolFailure::new(format!(            "{} is a day, like 1992-08-17, or --08-17 without the year",            label_in_sentence(definition, "birthday")        ))),    }}/// A person's summary is the summaries engine's to write (`update_summary`):/// it stamps who wrote it and when.fn person_summary(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    values: &Data,) -> Valid<()> {    let Some(summary) = values.get("summary") else {        return Ok(());    };    call(        ctx,        definition,        "update_summary",        summaries::update_summary,        json!({ "kind": "person", "id": id, "summary": summary }),    )    .map(|_| ())}fn person_create(ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data) -> Valid<String> {    let mut args = Map::new();    person_args(ctx, definition, values, &mut args)?;    args.retain(|_, value| !value.is_null());    let id = created_id(&call(        ctx,        definition,        "create_person",        people::create_person,        Value::Object(args),    )?)?;    if values.get("summary").is_some_and(|summary| !summary.is_null()) {        person_summary(ctx, definition, &id, values)?;    }    Ok(id)}fn person_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let mut args = Map::new();    person_args(ctx, definition, patch, &mut args)?;    if !args.is_empty() {        args.insert("id".into(), Value::from(id));        call(            ctx,            definition,            "update_person",            people::update_person,            Value::Object(args),        )?;    }    person_summary(ctx, definition, id, patch)}fn person_archive(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(        ctx,        definition,        "archive_person",        people::archive_person,        json!({ "id": id }),    )    .map(|_| ())}fn person_unarchive(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(        ctx,        definition,        "unarchive_person",        people::unarchive_person,        json!({ "id": id }),    )    .map(|_| ())}// ── repeating todo ──────────────────────────────────────────────────────────/// `update_record` on a repeating todo: `update_todo_recurrence` replaces the/// whole template, so the columns the patch leaves alone are the stored/// row's own — and so is the state before the edit the tool asks for.fn recurrence_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    const COLUMNS: [&str; 7] =        ["title", "notes", "priority", "rrule", "dtstart", "paused", "materialized_until"];    let row = maybe_row(        ctx,        &Query::on("cotton_todo_recurrences").columns(&COLUMNS).eq("id", id.to_string()),    )?    .ok_or_else(|| super::not_found(definition, id))?;    let stored = |key: &str| row.get(key).cloned().unwrap_or(Value::Null);    let mut args = Map::new();    args.insert("recurrenceId".into(), Value::from(id));    for key in ["title", "notes", "priority", "rrule", "dtstart"] {        args.insert(key.into(), stored(key));    }    args.insert("paused".into(), Value::Bool(flag(&row, "paused")));    args.insert(        "previous".into(),        json!({            "rrule": stored("rrule"),            "dtstart": stored("dtstart"),            "materializedUntil": stored("materialized_until"),        }),    );    for (key, value) in patch {        match key.as_str() {            "title" | "rrule" | "dtstart" | "paused" if value.is_null() => {                return Err(cannot_clear(definition, key))            }            "priority" if value.is_null() => {                args.insert(key.clone(), Value::from(0));            }            "title" | "notes" | "priority" | "rrule" | "dtstart" | "paused" => put(&mut args, key, value),            other => return Err(set_by_cotton(definition, other)),        }    }    call(        ctx,        definition,        "update_todo_recurrence",        crate::mcp::handlers::recurrence::update_todo_recurrence,        Value::Object(args),    )    .map(|_| ())}// ── project ─────────────────────────────────────────────────────────────────/// `update_record` on a project: its name, description and status, through/// `update_project`, which finds it by the slug it never changes.fn project_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let slug = read_one(ctx, definition, id)?        .and_then(|stored| stored.data.get("slug").and_then(Value::as_str).map(str::to_string))        .ok_or_else(|| super::not_found(definition, id))?;    let mut args = Map::new();    args.insert("slug".into(), Value::from(slug));    for (key, value) in patch {        match key.as_str() {            "name" | "status" if value.is_null() => return Err(cannot_clear(definition, key)),            "name" | "status" => put(&mut args, key, value),            // The tool clears a description with the empty string.            "description" if value.is_null() => {                args.insert(key.clone(), Value::from(""));            }            "description" => put(&mut args, key, value),            other => return Err(set_by_cotton(definition, other)),        }    }    call(        ctx,        definition,        "update_project",        projects::write::update_project,        Value::Object(args),    )    .map(|_| ())}// ── document ────────────────────────────────────────────────────────────────/// The column a locked document's page takes its file's password in. The/// definition declares it write-only (`cotton_core::definitions::WRITE_ONLY_COLUMNS`):/// a password is never a column a read answers — no store table holds it, so/// [`source`] never selects it — and a write hands it to the documents engine,/// which tries it and keeps it nowhere.pub const UNLOCK_PASSWORD: &str = "unlock_password";/// The password an `update_record` on a document asks to try, read BEFORE the/// file is taken — as `documents::tools::password_attempt` reads/// `update_document`'s — so the dispatcher runs the try with nothing held.pub fn password_attempt(args: &Map<String, Value>) -> Option<(String, Vec<String>)> {    if args.get("table").and_then(Value::as_str) != Some("document") {        return None;    }    let id = args.get("id").and_then(Value::as_str)?;    let password = args        .get("patch")        .and_then(|patch| patch.get(UNLOCK_PASSWORD))        .and_then(Value::as_str)        .map(str::trim)        .filter(|password| !password.is_empty())?;    Some((id.to_string(), vec![password.to_string()]))}/// A document goes to the bin with its file, through the documents engine's/// own verb; only the bin's erase removes it for good, and a read statement's/// paper is refused the bin as it is refused the erase.fn document_delete(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(        ctx,        definition,        "delete_document",        documents::tools::delete_document,        json!({ "documentId": id, "confirm": true }),    )    .map(|_| ())}/// The Undo of [`document_delete`]: out of the bin through the same write.fn document_untrash(ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str) -> Valid<()> {    documents::tools::set_document_trashed(ctx, id, false)}/// `update_record` on a document: its title, through `update_document`. What/// the reading found (kind, issuer, dates) is the reading's to say.fn document_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,) -> Valid<()> {    let mut args = Map::new();    args.insert("documentId".into(), Value::from(id));    for (key, value) in patch {        match key.as_str() {            "title" if value.is_null() => return Err(cannot_clear(definition, key)),            "title" => put(&mut args, key, value),            // The file's password is tried, never kept on the record: a            // right one opens the document and its reading starts again.            UNLOCK_PASSWORD => {                let Some(password) = value.as_str().filter(|password| !password.trim().is_empty())                else {                    return Err(ToolFailure::new("Type the file's password to open it"));                };                args.insert("passwordCandidates".into(), json!([password]));            }            other => return Err(set_by_cotton(definition, other)),        }    }    let out = call(        ctx,        definition,        "update_document",        documents::tools::update_document,        Value::Object(args),    )?;    if out.get("unlocked") == Some(&Value::Bool(false)) {        return Err(ToolFailure::new("That password did not open this document"));    }    Ok(())}/// The built-in ids the generic verbs WRITE through an adapter — every other/// built-in is read only here.pub const WRITABLE_BUILTINS: &[&str] = &[    "ai_budget",    "toolkit",    "money_account",    "storage",    "evidence",    "email",    "email_thread",    "message",    "thread",    "todo_recurrence",    "session",    "secret",    "project",    "todo",    "note",    "journal",    "event",    "person",    "document",    "transaction",    "photo",    "video",    "media",    "album",    "album_item",    "story",    "duplicate",    "face",    "person_handle",    "board",    "theme",    "voice_word",];fn transaction_args(values: &Data) -> Map<String, Value> {    values        .iter()        .map(|(key, value)| {            let mapped = match key.as_str() {                "amount_minor" => "amountMinor",                "amount_known" => "amountKnown",                "occurred_on" => "occurredOn",                "account_id" => "accountId",                "counterparty_person_id" => "personId",                "due_date" => "dueDate",                "for_period" => "forPeriod",                "between_us" => "betweenUs",                "moves_money" => "movesMoney",                "repeat_day" => "repeatDay",                "settles_transaction_id" => "settlesTransactionId",                "transfer_of" => "transferOf",                other => other,            };            (mapped.to_string(), value.clone())        })        .collect()}fn transaction_create(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    values: &Data,) -> Valid<String> {    let out = call(        ctx,        definition,        "record_transaction",        crate::mcp::handlers::records_2::money::record_transaction,        Value::Object(transaction_args(values)),    )?;    created_id(&out)}fn transaction_update(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    values: &Data,) -> Valid<()> {    let mut args = transaction_args(values);    args.insert("id".into(), json!(id));    call(        ctx,        definition,        "update_transaction",        crate::mcp::handlers::records_2::money::update_transaction,        Value::Object(args),    )?;    Ok(())}/// A person takes off a movement only the evidence they attached; a/// statement line's stays (`money::evidence::a_person_may_remove`).fn evidence_remove(ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str) -> Valid<()> {    use crate::mcp::handlers::money::evidence::{a_person_may_remove, retract_evidence, STAYS_WITH_THE_MOVEMENT};    let row = maybe_row(        ctx,        &Query::on("cotton_money_evidence").columns(&["kind", "attached_by"]).eq("id", id.to_string()),    )?    .ok_or_else(|| ToolFailure::new("That evidence is no longer here"))?;    let word = |key: &str| row.get(key).and_then(Value::as_str).unwrap_or_default().to_string();    if !a_person_may_remove(&word("kind"), &word("attached_by")) {        return Err(ToolFailure::new(STAYS_WITH_THE_MOVEMENT));    }    retract_evidence(ctx, id).map(|_| ())}/// A kit made by the ordinary create, at an id of its own ([`make_toolkit`]).////// [`make_toolkit`]: crate::mcp::handlers::tool_packages::make_toolkitfn toolkit_create(ctx: &mut Ctx<'_>, _definition: &TableDefinition, values: &Data) -> Valid<String> {    let out = crate::mcp::handlers::tool_packages::make_toolkit(ctx, values)?;    created_id(&out)}/// A kit of the person's changed; a shipped kit is refused here — the/// generic update keeps a record's id, and a shipped kit changes only as a/// copy (update_toolkit answers it).fn toolkit_update(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, values: &Data) -> Valid<()> {    if crate::toolkits::is_shipped_id(id) {        return Err(ToolFailure::new(            "a kit Cotton ships is never changed in place; update_toolkit saves your changed copy",        ));    }    let mut args = values.clone();    args.insert("id".into(), json!(id));    call(ctx, definition, "update_toolkit", crate::mcp::handlers::tool_packages::update_toolkit, Value::Object(args))?;    Ok(())}fn toolkit_delete(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(ctx, definition, "delete_toolkit", crate::mcp::handlers::tool_packages::delete_toolkit, json!({"id": id}))?;    Ok(())}fn transaction_delete(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    call(        ctx,        definition,        "delete_transaction",        crate::mcp::handlers::records_2::money::delete_transaction,        json!({"id":id}),    )?;    Ok(())}#[cfg(test)]mod tests {    use super::*;    use cotton_core::definitions::builtin_table_definition;    /// RULE: The generic verbs write exactly the listed built-ins through their own tools, and every other built-in is read only.    #[test]    fn the_writable_builtins_are_exactly_the_adapted_ones() {        for definition in cotton_core::definitions::builtin_table_definitions() {            assert_eq!(                adapter(&definition.id).is_some(),                WRITABLE_BUILTINS.contains(&definition.id.as_str()),                "{}",                definition.id            );        }    }    /// RULE: Generic list input requires a writable create; a declared create flow or capture owns its own submission, so it must not be mistaken for a generic record write.    #[test]    fn a_list_takes_the_bar_only_where_its_create_is_taken() {        for definition in cotton_core::definitions::builtin_table_definitions() {            // A view's create is its source's (`through_view`).            let taken = adapter(definition.rows_table()).is_some_and(|adapter| adapter.create.is_ok());            let typed = definition.engine.as_deref() != Some("vault")                && definition.columns.iter().any(|column| column.readonly != Some(true));            let create_flow = definition.create.as_ref().is_some_and(|create| create.path.is_some())                || definition.commands.as_ref().is_some_and(|commands| commands.iter()                    .any(|command| command.kind == cotton_core::definitions::CommandKind::Create));            if taken {                assert_ne!(definition.add, Some(false), "{} takes a create", definition.id);            } else if typed && definition.capture.is_none() && !create_flow {                assert_eq!(definition.add, Some(false), "{} offers a bar its create refuses", definition.id);            }        }    }    /// The built-ins the app's Settings screens delete through their own store (`SettingsRecords.sources` in CottonUI), never the generic verb; they are not held to `delete: false`.    const SETTINGS_TABLES: [&str; 11] = [        "account", "agent_login", "assistant", "code_default", "connection", "device", "import", "session", "storage", "tool_order",        // A kit deleted is gone for good (delete_toolkit's retract): the seed never writes it again.        "toolkit",    ];    /// RULE: A built-in whose generic delete refuses every record says delete false, and one whose delete takes some records says delete_when on a read-only column its engine answers, so a page offers Delete exactly where it is taken.    ///    /// A journal day is added to, a project is archived; a    /// movement read from a statement is refused and one recorded by hand    /// taken. The Settings tables and the vault delete through their own    /// stores and are not held to it.    #[test]    fn a_page_offers_delete_only_where_the_delete_is_taken() {        for definition in cotton_core::definitions::builtin_table_definitions() {            if SETTINGS_TABLES.contains(&definition.id.as_str()) || definition.engine.as_deref() == Some("vault") {                continue;            }            let taken = super::super::bin_table::is_bin(&definition)                || adapter(&definition.id).is_some_and(|adapter| adapter.delete.is_ok());            if !taken {                assert_eq!(definition.delete, Some(false), "{} offers a Delete its engine refuses", definition.id);            }            if let Some(when) = &definition.delete_when {                assert!(taken, "{} offers Delete on some records, but its engine takes none", definition.id);                let column = definition.column(&when.column).expect("a validated when");                assert_eq!(column.readonly, Some(true), "{}: what the engine answers, never what a page writes", definition.id);            }        }    }    /// RULE: Every Delete a built-in page offers waits in the bin, asked first with where it waits (deletion.bin), undone by taking it back out; a table whose delete cannot reach the bin says delete false.    ///    /// The architect's one rule (5 Oct 2026). A removal the definition names    /// otherwise ("Remove from album") is not a Delete. The Settings tables    /// delete through their own stores and are not held to it.    #[test]    fn every_delete_a_page_offers_waits_in_the_bin() {        use cotton_core::records::receipt::lands_in_bin;        for definition in cotton_core::definitions::builtin_table_definitions() {            let id = definition.id.as_str();            let named_otherwise = definition                .deletion                .as_ref()                .and_then(|words| words.label.as_deref())                .is_some_and(|label| label != "Delete");            if SETTINGS_TABLES.contains(&id) || definition.delete == Some(false) || named_otherwise {                continue;            }            assert!(lands_in_bin(&definition), "{id} offers a Delete that does not wait in the bin; bring it to the bin or say delete false");            let adapter = adapter(id).unwrap_or_else(|| panic!("{id} has no adapter"));            assert!(adapter.delete.is_ok(), "{id}");            assert!(matches!(adapter.restore, Ok(Restore::Engine(_))), "{id}: a bin move is undone by taking it back out, never by a recreate");            // The vault asks in its own words (`PasswordsRecords`). Every other            // question says where the record waits, worded by the Bin's place on            // Home (`deletion.bin`, the app's `BinShelf`).            if definition.engine.as_deref() != Some("vault") {                let bin = definition.deletion.as_ref().and_then(|words| words.bin);                assert_eq!(bin, Some(true), "{id}: its question does not say the record waits in the bin");            }        }    }    /// RULE: Columns the engine computes or stamps are readonly in the shipped definition, because a card must never offer an editor for measured facts or audit provenance.    #[test]    fn every_derived_column_is_a_column_of_its_table() {        for definition in cotton_core::definitions::builtin_table_definitions() {            for key in crate::mcp::handlers::common::WRITE_STAMP_COLUMNS.iter().chain(crate::mcp::handlers::common::AUTHOR_STAMP_COLUMNS) {                if let Some(column) = definition.column(key) {                    assert_eq!(column.readonly, Some(true), "{}.{key} is recorded by the writer", definition.id);                }            }            if super::super::activity_tables::is_activity(&definition) {                for column in &definition.columns {                    assert_eq!(column.readonly, Some(true), "{}.{} is an activity engine fact", definition.id, column.key);                }            }            let derived = adapter(&definition.id).map_or(&[][..], |adapter| adapter.derived);            for key in derived {                let column = definition.column(key).unwrap_or_else(|| panic!("{}.{key}", definition.id));                assert_eq!(column.readonly, Some(true), "{}.{key} is filled by the engine", definition.id);            }        }    }    /// RULE: An album's states sort open, kept, dismissed when read descending, so `LISTED_FIRST_BY` puts a suggestion waiting for its answer at the head of the list.    #[test]    fn an_albums_states_sort_open_first() {        let album = builtin_table_definition("album").expect("album is shipped");        let mut states = album            .column("state")            .and_then(|column| column.choices.clone())            .expect("an album's state is a choice");        states.sort();        states.reverse();        assert_eq!(states, ["open", "kept", "dismissed"]);        assert!(LISTED_FIRST_BY.contains(&("album", "state", Order::Desc)));    }}#[cfg(test)]mod figure_column_tests {    use super::*;    /// RULE: A grouped list's computed figure reads `_computed` by its own columns (Owed's    /// running "balance_after"), and a signed formula over a stored amount flipped by a stored    /// word is SQL over the row itself (By person's "between you" sums owed_signed so, 170de0385);    /// a word that is no `_computed` column fails the whole list (a rename once wrote    /// `column_name = ...` and Cotton Money opened on a blank fan).    #[test]    fn a_computed_figure_reads_the_kept_value() {        let definition: TableDefinition = serde_json::from_str(include_str!("../../../../../cotton-core/kits/personal/tables/money_owed.json")).unwrap();        let source = source(&definition).unwrap();        let signed = figure_column(&definition, &source, "owed_signed").unwrap();        let kept = figure_column(&definition, &source, "balance_after").unwrap();        assert!(!signed.contains("_computed"), "owed_signed is summed over the row: {signed}");        let db = cotton_store::Driver::open_in_memory().unwrap();        db.run(cotton_store::schema::ddl::COMPUTED_TABLE, &[]).unwrap();        db.run(&format!("CREATE TABLE {} (id TEXT PRIMARY KEY, amount_minor INTEGER, direction TEXT)", source.table), &[]).unwrap();        db.run(&format!("INSERT INTO {} (id, amount_minor, direction) VALUES ('tx-1', 4100, 'in'), ('tx-2', 900, 'out')", source.table), &[]).unwrap();        db.run("INSERT INTO _computed (table_id, record_id, key, value) VALUES ('money_owed', 'tx-1', 'balance_after', -4100)", &[]).unwrap();        let rows = db.all(&format!("SELECT {signed} AS signed, {kept} AS kept FROM {} ORDER BY id", source.table), &[]).unwrap();        assert_eq!(rows[0].get("signed"), Some(&rusqlite::types::Value::Integer(-4100)));        assert_eq!(rows[1].get("signed"), Some(&rusqlite::types::Value::Integer(900)));        assert_eq!(rows[0].get("kept"), Some(&rusqlite::types::Value::Integer(-4100)));        assert!(figure_column(&definition, &source, "no_such_figure").is_err());    }}#[cfg(test)]mod money_narrowing_guards {    // RULE: A statement link is narrowed by workspace-scoped evidence in SQL before pagination because materializing every line id makes unbooked pages exceed SQLite's bind limit.    #[test]    fn statement_links_do_not_materialize_workspace_line_ids() {        let source = include_str!("builtin.rs");        let function = source.split_once("fn statement_line_transaction(").unwrap().1;        let body = function.split_once("\nfn narrowing(").unwrap().0;        assert!(!body.contains("let lines = rows("));        assert!(!body.contains("booked_line_ids"));        assert!(body.contains("cotton_money_evidence"));    }}/// Whether `definition`'s list is read narrowed to ids (`among`): the/// store's own list is; a list another engine reads (Email's, the bin,/// media views, settings, activity, calls) refuses it rather than answer/// every row, so a kept order (`cotton_ffi::methods::shell_order`) never/// pages such a table off `among`.pub fn reads_among(definition: &TableDefinition) -> bool {    !(media_tables::is_view(definition) || super::bin_table::is_bin(definition)        || super::email_views::handles(definition.rows_table()) || super::engine_views::handles(definition)        || super::settings_tables::handles(definition) || super::activity_tables::is_activity(definition)        || definition.rows_table() == "call")}