Cotton code
4506 lines · 199.6 KB · RustRaw
//! The GENERIC VERBS — one set of tools over every table, addressed by the//! table definition's id: `list_records`, `get_record_by_table`,//! `create_record`, `update_record`, `delete_record`, `reorder_records`,//! `link_records` and `undo`.//!//! A table a person defined (a definition with no engine) lives in//! `cotton_records`, one row per record with its values as one JSON object//! (store v47). A built-in table keeps its own storage: the verbs READ it//! through its definition's columns, and WRITE it only by calling the tool//! that already writes it ([`builtin`]) — never a second writer. A built-in no//! adapter covers is read only here, and says so.//!//! Every write leaves a CHANGE in `cotton_changes` — its byline, the values//! before and after — and answers it, so the app can show who changed what and//! offer the undo. The before and after are READ from the database around the//! write, never computed from the request, so what a change says is what the//! file held, whatever the writer normalised. What a built-in's engine moved//! BESIDE the record (an open album a picture put in kept, who named a renamed//! album) rides on the change as `@` keys holding `{was, now}`//! (`records::BESIDE`), read the same way, and its undo puts each back or is//! refused. The pure half — the value encoding, patches, diffs and the undo//! rules — is `cotton_core::records`.//!//! # Paging//!//! `list_records` pages by OFFSET: `page` is how many records to skip (0 when//! absent), `limit` how many to answer (50, at most [`MAX_PAGE_SIZE`]), and the answer's//! `next_page` is the `page` to ask for next, or null at the end. An offset is//! a plain number the phone can hold without decoding a cursor, and a person's//! own tables are small enough that a row inserted mid-scroll costs one//! repeated slip, not a correctness problem.//!//! # Bylines//!//! A write from the owner's own app is `"user"`; an assistant's is the name its//! connection was given (`Ctx::agent`, the token's name — the MCP transport//! does not pass a client name of its own), or `"assistant"` where that is//! empty.use cotton_core::definitions::{builtin_table_definitions, TableDefinition};use cotton_core::records::{    self, Change, Condition, Current, Data, Inverse, RecordError, Verb, WhereClause,    DEFAULT_ASSISTANT_BYLINE, USER_BYLINE,};use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::common::{    bounded_limit, insert_row, now_iso, optional_string, projects, resolve_project, update_row,    Valid,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::ReadDb;pub mod activity_tables;mod album_groups;mod ai_usage;pub mod arrangement_writes;pub mod assistant_words;mod automations;pub mod bin_table;pub mod hidden;pub mod builtin;mod call_tables;pub(crate) mod chat_views;mod connection_words;pub mod day_plan;mod yearly_dates;mod money_runway;pub mod definition_writes;mod device_words;pub mod device_writes;mod email_views;mod engine_views;mod everything;pub mod groups;mod mail_chat_writes;pub mod media_tables;pub mod own_values;pub mod served_values;mod person_handles;mod person_words;pub mod record_counts;pub mod record_page_read;mod session_table;mod settings_tables;mod shop_writes;pub mod reservations;mod acts;pub mod samples;/// Every EXISTING tool a generic verb over `table` stands in for — the kind's/// own verbs from the compiled grid (`surface::TOOL_SURFACE`), and for a write/// the tools its adapter will call. A caller that refuses tools by name (an/// assistant run's deny list) asks this, so a generic verb is never a way/// round a refusal: `list_records { table: "secret" }` reaches `list_secrets`.pub fn tools_reached(tool: &str, table: &str) -> Vec<&'static str> {    use crate::mcp::surface::TOOL_SURFACE;    let table = table.trim();    let mut out: Vec<&'static str> = Vec::new();    if let Some((_, cells)) = TOOL_SURFACE.iter().find(|(kind, _)| *kind == table) {        let wanted = match tool {            "list_records" | "get_record_by_table" => vec![&cells.list, &cells.get],            "create_record" => vec![&cells.create],            "update_record" | "link_records" | "reorder_records" => vec![&cells.update],            "delete_record" => vec![&cells.remove],            _ => Vec::new(),        };        out.extend(wanted.into_iter().filter_map(|cell| cell.tool()));    }    for name in media_tables::tools_read(tool, table) {        if !out.contains(&name) {            out.push(name);        }    }    if table == bin_table::TABLE {        out.extend(bin_table::tools(tool));    }    let empty = Data::new();    let ops: Vec<builtin::Op<'_>> = match tool {        "create_record" => vec![builtin::Op::Create(&empty)],        // A built-in's archive column is written by its delete and restore tools.        "update_record" if cotton_core::definitions::builtin_table_definition(table).is_some_and(|d| d.archived.is_some()) => {            vec![builtin::Op::Update(&empty), builtin::Op::Delete, builtin::Op::Restore,            ]        }        "update_record" | "link_records" => vec![builtin::Op::Update(&empty)],        "reorder_records" => vec![builtin::Op::Reorder],        "delete_record" => vec![builtin::Op::Delete],        _ => Vec::new(),    };    for op in ops {        for name in builtin::plan_for(table, op) {            if !out.contains(&name) {                out.push(name);            }        }    }    out}pub fn handlers() -> HandlerGroup {    &[        ("list_records", list_records),        ("summarize_records", summarize_records),        ("get_record_by_table", get_record_by_table),        ("create_record", create_record),        ("reserve_record", reservations::reserve_record),        ("run_record_act", acts::run_record_act),        ("cancel_reservation", reservations::cancel_reservation),        ("update_record", update_record),        ("save_theme", crate::presentation::save_theme_tool),        ("get_board", crate::presentation::get_board_tool),        ("update_board", crate::presentation::update_board_tool),        ("delete_record", delete_record),        ("reorder_records", reorder_records),        ("link_records", link_records),        ("undo", undo),        ("list_groups", groups::list_groups),        ("create_group", groups::create_group),        ("update_group", groups::update_group),        ("delete_group", groups::delete_group),        ("update_definition", definition_writes::update_definition),        ("arrange_tools", arrangement_writes::arrange_tools),    ]}/// Where a made table's records live: the real table its package declares,/// one column per column key (tools as packages,/// `cotton_store::schema::package_shape`).pub fn made_table(table_id: &str) -> String {    format!("cotton_{table_id}")}/// Does this file hold the made table yet? A definition steps the file when/// it arrives (`package_shape::after_definitions`), so a table missing is one/// whose definition this file has not folded: it holds no records.pub fn made_held(ctx: &Ctx<'_>, table_id: &str) -> Valid<bool> {    Ok(ctx        .read        .driver()        .get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(made_table(table_id))],        )        .map_err(sql_err)?        .is_some())}/// Before a write: the file steps to the shape its definitions declare, so a/// made table a code path writes (the notification table) is there.fn made_ready(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid<()> {    if made_held(ctx, definition.rows_table())? {        return Ok(());    }    let (_, refused) = cotton_store::schema::package_shape::step_file(ctx.read.driver()).map_err(sql_err)?;    if let Some((_, why)) = refused.iter().find(|(id, _)| *id == definition.id) {        return Err(ToolFailure::new(format!("{} cannot take its own table: {why}", definition.plural)));    }    if !made_held(ctx, definition.rows_table())? {        return Err(ToolFailure::new(format!("{} has no table on this file", definition.plural)));    }    Ok(())}/// Who last wrote a made table's record (`byline` is a name a tool's own/// column may use).pub const MADE_BYLINE: &str = "record_byline";/// A made table's column, quoted for SQL. Every key reaching here was/// validated as a definition id (`[a-z][a-z0-9_]*`).fn col(key: &str) -> String {    format!("\"{key}\"")}/// Every made table this database holds: the tables a person defined or/// brought, and the ones Cotton's own code makes.pub fn made_definitions(ctx: &Ctx<'_>) -> Valid<Vec<TableDefinition>> {    let mut made: Vec<TableDefinition> = crate::definitions::definition_rows(ctx, None)?        .iter()        .filter_map(|row| TableDefinition::from_json(&row.definition).ok())        .filter(is_user_table)        .collect();    made.push(automations::notification_definition());    Ok(made)}/// The value a made table's column holds, as the record's JSON: a bool is/// `true`/`false`, a whole number an integer, NULL no value at all.pub fn made_value(column: &cotton_core::definitions::Column, value: Option<&SqlValue>,) -> Option<Value> {    match value? {        SqlValue::Null | SqlValue::Blob(_) => None,        SqlValue::Integer(n) if column.column_type == cotton_core::definitions::ColumnType::Bool =>        {            Some(Value::Bool(*n != 0))        }        SqlValue::Integer(n) => Some(Value::from(*n)),        SqlValue::Real(f) => serde_json::Number::from_f64(*f).map(Value::Number),        SqlValue::Text(text) => Some(Value::from(text.clone())),    }}/// The change log every generic write appends to (store v47).pub const CHANGES: &str = "cotton_changes";/// `list_records`' page when the caller names none, and its ceiling.pub const DEFAULT_PAGE_SIZE: i64 = 50;pub const MAX_PAGE_SIZE: i64 = crate::mcp::handlers::common::MAX_LIST;/// The most rows a light read (`columns`) answers in one page.pub const MAX_LIGHT_PAGE: i64 = 2_000_000;/// How many ids one `IN (…)` names: well under SQLite's variable limit.pub(crate) const IN_CHUNK: usize = 400;fn refuse(error: RecordError) -> ToolFailure {    ToolFailure::new(error.to_string())}fn sql_err(error: impl std::fmt::Display) -> ToolFailure {    ToolFailure::new(error.to_string())}/// Who this call's writes are by — see the module header.pub fn byline(ctx: &Ctx<'_>) -> String {    if let Some(label) = automations::byline_as() {        label    } else if ctx.is_owner_app() {        USER_BYLINE.to_string()    } else if ctx.agent.trim().is_empty() {        DEFAULT_ASSISTANT_BYLINE.to_string()    } else {        ctx.agent.to_string()    }}// ── definitions ─────────────────────────────────────────────────────────────/// The definition of `table` — `crate::definitions::resolve_table_on_file`'s answer,/// the same one the app's own list (`definitions.tables`) draws from.////// A table a person defined is its synced row, VALIDATED — a row that does not/// parse or does not validate is refused, never read around, so no column key/// that `validate` would refuse ever reaches a query.////// A BUILT-IN is always the definition the app SHIPS, whatever its synced row/// says: the row carries a person's own instructions, and nothing a device/// wrote into it can widen what a read selects or what a write reaches. Before/// the server's seed has synced, there is no row and the shipped file is the/// definition anyway (the app draws from the same file).pub fn definition(ctx: &Ctx<'_>, table: &str) -> Valid<TableDefinition> {    let table = table.trim();    crate::home_arrangement::require_table(ctx.read.driver(), ctx.workspace_id, table).map_err(ToolFailure::new)?;    if table == cotton_core::definitions::automations::NOTIFICATIONS {        return Ok(automations::notification_definition());    }    let shipped = builtin_table_definitions().iter().find(|definition| definition.id == table);    let row = crate::definitions::definition_rows(ctx, Some(table))?        .into_iter()        .next();    if row.as_ref().is_none_or(|row| crate::definitions::retired_builtin(row, shipped)) {        return Err(crate::definitions::no_tool_draws(ctx.read.driver(), ctx.workspace_id));    }    crate::definitions::resolve_table_on_file(ctx.read.driver(), table, shipped, row.as_ref(),    )}fn is_user_table(definition: &TableDefinition) -> bool {    // A view names no engine; it reads as its source does — a built-in's    // store, or a made table's (ruling 10:52 IST 17 Oct 2026).    definition.engine.is_none() && definition.store_table().is_none()}/// How a table's records are put away into its archive — what/// `list_records { archived: true }` lists and the Archived link counts.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Archive<'a> {    /// The date or bool column the definition names `archived`.    Column(&'a str),    /// A built-in whose `status` has an `archived` choice (projects, stores).    Status,}/// The table's archive, or `None` when its records are never archived. An/// event's `archived` column is its bin: a binned record is deleted, waiting,/// never archived.pub fn archive_of(definition: &TableDefinition) -> Option<Archive<'_>> {    match definition.archived.as_deref() {        Some("trashed_at") => None,        Some(column) => Some(Archive::Column(column)),        None => definition            .column("status")            .and_then(|column| column.choices.as_ref())            .filter(|choices| choices.iter().any(|choice| choice == "archived"))            .map(|_| Archive::Status),    }}// ── one stored record ───────────────────────────────────────────────────────/// One record as the verbs answer it.#[derive(Debug, Clone, PartialEq)]pub struct Stored {    pub id: String,    /// Every value, keyed by column key; an absent key is null.    pub data: Data,    pub created_at: Option<String>,    pub updated_at: Option<String>,    /// When it was deleted (a built-in: archived); `None` while it is live.    pub deleted_at: Option<String>,    pub byline: Option<String>,}impl Stored {    fn to_json(&self, definition: &TableDefinition) -> Value {        // A record a view shows is its source's record, and opens as one.        let table = definition.rows_table();        let mut record = json!({            "table": table,            "id": self.id,            "data": self.data,            "created_at": self.created_at,            "updated_at": self.updated_at,            "deleted_at": self.deleted_at,            "byline": self.byline,        });        if let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) {            records::project_read_data(definition, data);        }        // An edit or a delete of a repeating event must say how far it reaches        // (`scope`), so its record names the columns that ask: the app asks        // "Only this one" or "Every one" before it writes, never guessing        // from the table. A day already made its own row holds no repeat and        // names none.        let repeats = self.data.get("rrule").and_then(Value::as_str).is_some_and(|rule| !rule.trim().is_empty());        if table == "event" && repeats {            record["scope_columns"] = json!(OCCURRENCE_COLUMNS.iter().copied().chain(["rrule"]).collect::<Vec<_>>());        }        record    }    fn live(&self) -> Option<&Data> {        self.deleted_at.is_none().then_some(&self.data)    }}/// The values a reader may receive. Keep the stored record whole until this/// boundary: writes, undo and account matching need the original value, while/// a typed account number is never allowed to leave a read as anything but its/// ending.fn read_json(definition: &TableDefinition, stored: &Stored) -> Value {    stored.to_json(definition)}/// Storage's stored typed facts, without measuring a file or its catalogue.pub fn stored_storage_facts(ctx: &Ctx<'_>) -> ToolResult {    let definition = definition(ctx, "storage")?;    let stored = engine_views::storage_facts(ctx)?;    Ok(read_json(&definition, &stored))}/// A change is also a read. Its before and after maps must carry the same/// projection as a record page, otherwise a generic write would expose the/// full account number through its receipt.fn read_change(definition: &TableDefinition, change: &Change) -> Change {    let mut shown = change.clone();    for data in [&mut shown.before, &mut shown.after] {        if let Value::Object(data) = data {            records::project_read_data(definition, data);        }    }    shown}/// A made table's row read with `SELECT r.*`, as the record the verbs answer:/// every stored column the definition draws, keyed by column key.pub fn stored_from_row(definition: &TableDefinition, row: &cotton_store::Row) -> Stored {    let data: Data = definition        .columns        .iter()        .filter(|column| column.computed.is_none())        .filter_map(|column| {            Some((column.key.clone(), made_value(column, row.get(&column.key))?,            ))        })        .collect();    Stored {        id: row.text("id").unwrap_or_default().to_string(),        data,        created_at: row.text("created_at").map(str::to_string),        updated_at: row.text("updated_at").map(str::to_string),        deleted_at: row.text("deleted_at").map(str::to_string),        byline: row.text(MADE_BYLINE).map(str::to_string),    }}fn load_user(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<Option<Stored>> {    if !made_held(ctx, definition.rows_table())? {        return Ok(None);    }    let row = ctx        .read        .driver()        .get(            &format!("SELECT * FROM {} WHERE workspace_id = ? AND id = ?", made_table(definition.rows_table())),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(id.to_string()),            ],        )        .map_err(sql_err)?;    Ok(row.map(|row| stored_from_row(definition, &row)))}/// One record of any table, deleted or not.fn load(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<Option<Stored>> {    if is_user_table(definition) {        load_user(ctx, definition, id)    } else {        // A shipped table's record with the values of the columns its owner        // added (`own_values`) and those the copy keeps for the object's        // definition (`served_values`), so a patch and its Undo diff them too.        let mut stored = builtin::read_one(ctx, definition, id)?;        if let Some(stored) = stored.as_mut() {            own_values::merge(ctx, definition, std::slice::from_mut(stored))?;            served_values::merge(ctx, definition, std::slice::from_mut(stored))?;        }        Ok(stored)    }}/// The refusal for a record that is not there. It says what the record was/// and never prints `id`, which is nothing a person can read.fn not_found(definition: &TableDefinition, _id: &str) -> ToolFailure {    ToolFailure::new(cotton_core::records::receipt::no_longer_here(definition))}/// A live record, or the refusal.fn load_live(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<Stored> {    match load(ctx, definition, id)? {        Some(stored) if stored.deleted_at.is_none() => Ok(stored),        Some(_) => Err(not_found(definition, id)),        None => Err(not_found(definition, id)),    }}// ── links ───────────────────────────────────────────────────────────────────/// Does `target` name a live record of table `link_to`?fn link_target_exists(ctx: &Ctx<'_>, link_to: &str, target: &str) -> Valid<bool> {    let definition = definition(ctx, link_to)?;    Ok(match load(ctx, &definition, target)? {        Some(stored) => stored.deleted_at.is_none(),        None => false,    })}/// Every link value in `values` names a live record of its column's target.fn check_links(ctx: &Ctx<'_>, definition: &TableDefinition, values: &Data) -> Valid<()> {    for (key, value) in values {        let (Some(column), Some(target)) = (definition.column(key), value.as_str()) else {            continue;        };        let Some(link_to) = column.link_to.as_deref() else {            continue;        };        if !link_target_exists(ctx, link_to, target)? {            return Err(ToolFailure::new(format!(                "{key:?} links to {link_to}, and there is no {link_to} {target:?}"            )));        }    }    Ok(())}// ── the change log ──────────────────────────────────────────────────────────/// Why a change of `verb` to this table cannot be undone, or `None`: a table a/// person defined can undo every verb; a built-in only what its engine can/// write the inverse of.fn undo_refusal(definition: &TableDefinition, verb: Verb) -> Option<String> {    if is_user_table(definition) {        None    } else {        builtin::undo_refusal(definition, verb)    }}/// A first machine-wide choice replaces legacy per-tool rules; the nullable/// intent alone cannot reconstruct them after the Mac has applied it.fn change_undo_refusal(definition: &TableDefinition, change: &Change) -> Option<String> {    // A delete and its put back write the bin's mark alone (`delete_now`,    // `restore_now`): undoing one forges no fact, whatever the record holds    // (Books 1.0.0 (3) and (4) walks, 7 Nov 2026: a found or imported book's    // Remove refused its Undo over `source`).    let marks_the_bin = matches!(change.verb, Verb::Delete | Verb::Restore);    if is_user_table(definition) && !marks_the_bin {        if let Some(column) = definition.columns.iter().find(|column| {            column.readonly == Some(true) && column.computed.is_none()                // Place companions belong to the same reversible pick/raw edit.                // An independent producer fact remains non-undoable here.                && !definition.columns.iter().any(|owner| {                    owner.column_type == cotton_core::definitions::ColumnType::Place                        && owner.place.as_ref().is_some_and(|place|                            place.id == column.key || place.country == column.key || place.zone == column.key)                        && (change.before.get(&owner.key).is_some() || change.after.get(&owner.key).is_some())                })                && (change.before.get(&column.key).is_some() || change.after.get(&column.key).is_some())        }) {            return Some(RecordError::Readonly { column: column.key.clone() }.to_string());        }    }    if definition.has_engine() && matches!(definition.id.as_str(), "device" | "storage")        && change.after.get("keep_bytes").is_some()        && change.before.get("keep_bytes").is_none_or(Value::is_null) {        return Some("The previous Files rules were set tool by tool; change Files or Storage to choose them again.".into());    }    undo_refusal(definition, change.verb)}/// A change as every verb answers it. `undoable` and `reason` are said on/// every change, so the app offers Undo only where it will work and can say/// why not where it will not. `receipt` is what the change says to the/// person — a verb and the record's name — worded here and nowhere else.fn change_json(ctx: &Ctx<'_>, definition: &TableDefinition, change: &Change, record: Option<&Stored>) -> Value {    let change = read_change(definition, change);    let now = record.map(|stored| {        let mut data = stored.data.clone();        records::project_read_data(definition, &mut data);        Value::Object(data)    });    let rows = crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id);    let dates = cotton_core::records::page::DateWords::of_rows(&rows);    let words = cotton_core::records::receipt::ReceiptWords::of_rows(&rows);    let mut receipt = cotton_core::records::receipt::receipt(definition, change.verb, &change.before, &change.after, now.as_ref(), &dates, &words);    if let Some(said) = bin_table::restored_said(ctx, definition, change.verb, &change.before, now.as_ref()) {        receipt.said = said;    }    if receipt.kind == cotton_core::records::receipt::ReceiptKind::Changed {        let zone = crate::mcp::handlers::common::workspace_timezone_or_null(ctx).ok().flatten();        let at = chrono::DateTime::from_timestamp_millis(crate::mcp::handlers::common::now_ms(ctx));        let page_words = cotton_core::records::page::Words::of_rows(&rows);        receipt.values = cotton_core::records::receipt::value_changes(definition, &change.before, &change.after, zone.as_deref(), at, &page_words);    }    let refusal = if change.undone_by.is_some() {        Some(RecordError::AlreadyUndone.to_string())    } else {        change_undo_refusal(definition, &change)    };    json!({        "id": change.id,        "table": change.table_id,        "record_id": change.record_id,        "verb": change.verb.as_str(),        "byline": change.byline,        "before": change.before,        "after": change.after,        "created_at": change.created_at,        "undone_by": change.undone_by,        "undoable": refusal.is_none(),        "reason": refusal,        "receipt": receipt,    })}/// The answer of an add taken back: "Removed <name>", with no Undo — the/// record is gone on every device as if it was never made, and no change row/// stands for it./// The database's date words (its `dates` lines over the kit's), which a/// receipt names a record by when a clock time names it.pub(crate) fn date_words(ctx: &Ctx<'_>) -> cotton_core::records::page::DateWords {    cotton_core::records::page::DateWords::of_rows(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id))}fn taken_back_json(ctx: &Ctx<'_>, definition: &TableDefinition, change: &Change) -> Value {    let change = read_change(definition, change);    json!({        "id": change.id,        "table": change.table_id,        "record_id": change.record_id,        "verb": change.verb.as_str(),        "byline": change.byline,        "before": change.before,        "after": change.after,        "created_at": change.created_at,        "undone_by": Value::Null,        "undoable": false,        "reason": Value::Null,        "receipt": cotton_core::records::receipt::removed(definition, &change.before, &date_words(ctx), &cotton_core::records::receipt::ReceiptWords::of_rows(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id))),    })}/// Verify the actual shared setting cells, before a machine-wide write can/// report success. A table projection can resolve a different approval's value.pub fn verify_device_settings(db: &cotton_store::Driver, device: &str, patch: &Data) -> Valid<()> {    let rows = db.all("SELECT id,workspace_id FROM cotton_devices WHERE device_id = ? AND revoked_at IS NULL", &[SqlValue::Text(device.to_string())]).map_err(sql_err)?;    for row in rows {        let database = row.text("workspace_id").unwrap_or_default();        let found = crate::mcp::read_db::ReadDb::new(db, database).by_id("cotton_devices", row.text("id").unwrap_or_default()).map_err(sql_err)?;        let same = |a: &Value, b: &Value| a == b || ((a.is_f64() || b.is_f64())            && a.as_f64().zip(b.as_f64()).is_some_and(|(a,b)| a == b));        if found.as_ref().is_none_or(|found| patch.iter().any(|(key, value)| found.get(key).is_none_or(|saved| !same(saved, value)))) {            return Err(ToolFailure::new(format!("Device setting could not be written in database {database}")));        }    }    Ok(())}/// Run one write verb as ONE transaction: the record's own write, the change/// row, and an undo's `undone_by` commit together or not at all. The writes/// inside commit as they go (a built-in's own tool reads what an earlier step/// wrote); the transaction around them is what makes the whole indivisible.pub fn atomically<T>(ctx: &mut Ctx<'_>, write: impl FnOnce(&mut Ctx<'_>) -> Valid<T>) -> Valid<T> {    let db = ctx.read.driver();    let mut failure: Option<ToolFailure> = None;    let outcome = db.transaction(|_| match write(&mut *ctx) {        Ok(value) => Ok(value),        Err(error) => {            failure = Some(error);            Err(cotton_store::StoreError::refused("the write was refused"))        }    });    match outcome {        Ok(value) => Ok(value),        Err(error) => {            ctx.discard_queued();            Err(failure.unwrap_or_else(|| sql_err(error)))        }    }}/// [`atomically`], for a generic verb whose own change row is the action's/// history: the engine's acts inside keep none of their own (slice 6b-2).pub fn atomically_noted<T>(ctx: &mut Ctx<'_>, write: impl FnOnce(&mut Ctx<'_>) -> Valid<T>,) -> Valid<T> {    ctx.noting_history(|ctx| atomically(ctx, write))}/// Record a write an engine has already made as the generic records verbs do.////// An engine calls this inside [`atomically_noted`], after its own writer has/// queued the mutation and before that transaction commits.  The change and/// engine row therefore arrive together, and callers never manufacture a/// receipt or a change-shaped JSON answer of their own.  `undoable` and/// `undo_reason` are explicit because an engine command may have no inverse/// even where a stored-table adapter normally would.pub fn record_engine_change(    ctx: &mut Ctx<'_>,    table: &str,    record_id: Option<&str>,    verb: Verb,    before: Value,    after: Value,    record: Option<&Stored>,    undoable: bool,    undo_reason: Option<String>,) -> ToolResult {    let definition = definition(ctx, table)?;    let change = record_change(ctx, &definition.id, record_id, verb, before, after)?;    ctx.commit()?;    let mut written = answer(ctx, &definition, &change, record);    written["change"]["undoable"] = Value::Bool(undoable);    written["change"]["reason"] = if undoable {        Value::Null    } else {        undo_reason.map_or_else(            || Value::from("This engine action cannot be undone."),            Value::from,        )    };    Ok(written)}/// Queue one change row; the caller commits it with the write it records.fn record_change(    ctx: &mut Ctx<'_>,    table: &str,    record_id: Option<&str>,    verb: Verb,    before: Value,    after: Value,) -> Valid<Change> {    let id = ctx.new_uuid();    record_change_as(ctx, id, table, record_id, verb, before, after)}/// [`record_change`] under an id the caller minted first — an undo names its/// change row in its fact before the row is written.fn record_change_as(    ctx: &mut Ctx<'_>,    id: String,    table: &str,    record_id: Option<&str>,    verb: Verb,    before: Value,    after: Value,) -> Valid<Change> {    let change = Change {        id,        table_id: table.to_string(),        record_id: record_id.map(str::to_string),        verb,        byline: byline(ctx),        before,        after,        created_at: now_iso(ctx),        undone_by: None,    };    let mut patch = Map::new();    patch.insert("id".into(), Value::from(change.id.clone()));    patch.insert("table_id".into(), Value::from(change.table_id.clone()));    patch.insert(        "record_id".into(),        change.record_id.clone().map_or(Value::Null, Value::from),    );    patch.insert("verb".into(), Value::from(verb.as_str()));    patch.insert("byline".into(), Value::from(change.byline.clone()));    patch.insert("before".into(), change.before.clone());    patch.insert("after".into(), change.after.clone());    patch.insert("created_at".into(), Value::from(change.created_at.clone()));    insert_row(ctx, CHANGES, &change.id, patch)?;    Ok(change)}/// What a built-in's engine can move beside the record (`records::BESIDE`),/// read now; a table a person defined moves nothing beside its records.fn beside_now(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str, record: &Data) -> Valid<Data> {    if is_user_table(definition) {        Ok(Data::new())    } else {        builtin::beside(ctx, definition, id, record)    }}/// `undone_by` is read from the change's undo fact (slice 6: a history row is/// a fact, so nothing ever writes it back into the row).const CHANGE_COLUMNS: &str =    "id, table_id, record_id, verb, byline, before, after, created_at, \     (SELECT u.undo_change_id FROM cotton_undos u WHERE u.id = 'undo:' || cotton_changes.id) AS undone_by, \     COALESCE(NULLIF(_born, ''), _hlc) AS born";fn change_from_row(row: &cotton_store::Row) -> Valid<(Change, String)> {    let json_of = |column: &str| {        row.text(column)            .and_then(|text| serde_json::from_str::<Value>(text).ok())            .unwrap_or(Value::Null)    };    let verb_text = row.text("verb").unwrap_or_default();    let verb = Verb::parse(verb_text).ok_or_else(|| {        ToolFailure::new(format!(            "this change was written by a newer build (verb {verb_text:?}) and cannot be undone here"        ))    })?;    Ok((        Change {            id: row.text("id").unwrap_or_default().to_string(),            table_id: row.text("table_id").unwrap_or_default().to_string(),            record_id: row.text("record_id").map(str::to_string),            verb,            byline: row.text("byline").unwrap_or_default().to_string(),            before: json_of("before"),            after: json_of("after"),            created_at: row.text("created_at").unwrap_or_default().to_string(),            undone_by: row.text("undone_by").map(str::to_string),        },        row.text("born").unwrap_or_default().to_string(),    ))}fn load_change(ctx: &Ctx<'_>, id: &str) -> Valid<(Change, String)> {    find_change(ctx, id)?.ok_or_else(|| ToolFailure::new(format!("there is no change {id:?}")))}fn find_change(ctx: &Ctx<'_>, id: &str) -> Valid<Option<(Change, String)>> {    ctx.read        .driver()        .get(            &format!("SELECT {CHANGE_COLUMNS} FROM {CHANGES} WHERE workspace_id = ? AND id = ?"),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(id.to_string()),            ],        )        .map_err(sql_err)?        .map(|row| change_from_row(&row))        .transpose()}/// Every change on `table` written after the one born at `born`, in the order/// written. "After" is by the change's own birth stamp (the hybrid clock every/// write carries), which orders two writes in the same millisecond and two/// devices' writes alike — a wall-clock `created_at` does neither.fn later_changes(ctx: &Ctx<'_>, table: &str, born: &str) -> Valid<Vec<Change>> {    let rows = ctx        .read        .driver()        .all(            &format!(                "SELECT {CHANGE_COLUMNS} FROM {CHANGES} \                 WHERE workspace_id = ? AND table_id = ? AND COALESCE(NULLIF(_born, ''), _hlc) > ? \                 ORDER BY born"            ),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(table.to_string()),                SqlValue::Text(born.to_string()),            ],        )        .map_err(sql_err)?;    rows.iter()        .filter_map(|row| change_from_row(row).ok())        .map(|(change, _)| Ok(change))        .collect()}/// A write's answer: the change it recorded and the record as it now stands.fn answer(ctx: &Ctx<'_>, definition: &TableDefinition, change: &Change, record: Option<&Stored>) -> Value {    json!({        "change": change_json(ctx, definition, change, record),        "record": record.map(|stored| read_json(definition, stored)),    })}// ── arguments ───────────────────────────────────────────────────────────────fn table_arg(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Valid<TableDefinition> {    let table = optional_string(args, "table")        .ok_or_else(|| ToolFailure::new("table is required: the table's id, e.g. \"todo\""))?;    definition(ctx, &table)}/// A write to a view is a write to its source: the record a view shows is the/// source's record (`TableDefinition::source`). A record made from a view/// starts with the value each of the view's single-value conditions keeps —/// added from Ahead, a row is expected — and each default the view's own/// columns name (Ahead's certainty), unless the ask names its own: the same/// start the app's "+" on the view shows.fn through_view<'a>(ctx: &Ctx<'_>, args: &'a Map<String, Value>, create: bool,) -> Valid<std::borrow::Cow<'a, Map<String, Value>>> {    let Some(table) = optional_string(args, "table") else { return Ok(std::borrow::Cow::Borrowed(args)) };    let definition = definition(ctx, &table)?;    let Some(source) = &definition.source else { return Ok(std::borrow::Cow::Borrowed(args)) };    let mut args = args.clone();    args.insert("table".into(), Value::from(source.table.clone()));    if create {        if let Some(Value::Object(data)) = args.get_mut("data") {            for (column, kept) in source.where_.iter().flat_map(|where_| where_.iter()) {                if !kept.is_object() && !kept.is_array() && !kept.is_null() {                    data.entry(column.clone()).or_insert_with(|| kept.clone());                }            }            for column in definition.columns.iter().filter(|column| column.computed.is_none()) {                if let Some(start) = &column.default {                    data.entry(column.key.clone()).or_insert_with(|| start.clone());                }            }        }    }    Ok(std::borrow::Cow::Owned(args))}fn id_arg(args: &Map<String, Value>, key: &str) -> Valid<String> {    let id = optional_string(args, key).ok_or_else(|| ToolFailure::new(format!("{key} is required")))?;    Ok(occurrence_of(&id).map_or(id.clone(), |(series, _)| series.to_string()))}fn record_id_arg(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Valid<String> {    let id = id_arg(args, "id")?;    if crate::mcp::handlers::money::occurrences::identity(&id).is_some() {        if table_arg(ctx,args)?.rows_table() != "transaction" { return Err(ToolFailure::new("This occurrence identity belongs to Money.")); }        if let Some((stored,_)) = crate::mcp::handlers::money::occurrences::resolve(&ctx.read,&id)? { return Ok(stored); }    }    Ok(id)}/// A later occurrence of a repeating event as the Calendar lists it,/// `<id>@<starts_at>` (`day_plan`): the series' id and that start. Opened,/// it is the series at that time; written to, it is the series.fn occurrence_of(id: &str) -> Option<(&str, &str)> {    let (series, starts) = id.split_once('@')?;    (crate::mcp::handlers::common::is_uuid(series) && crate::mcp::handlers::common::parse_ms(starts).is_some())        .then_some((series, starts))}/// A project by id or by slug.fn project_arg(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Valid<Option<String>> {    let Some(project) = optional_string(args, "project") else {        return Ok(None);    };    let all = projects(ctx)?;    if all.iter().any(|known| known.id == project) {        return Ok(Some(project));    }    resolve_project(&all, Some(&project))}fn read_only(definition: &TableDefinition) -> ToolFailure {    ToolFailure::new(format!(        "{} are read only through the generic verbs for now.",        definition.plural    ))}// ── reads ───────────────────────────────────────────────────────────────────/// A `where` value as SQLite holds it: JSON's `true` is `1` once/// `json_extract` reads it, and a whole number stays an integer so `1` and/// `1.0` compare equal either way.pub(crate) fn sql_value(value: &Value) -> SqlValue {    match value {        Value::Bool(flag) => SqlValue::Integer(i64::from(*flag)),        Value::Number(number) => match number.as_i64() {            Some(whole) => SqlValue::Integer(whole),            None => SqlValue::Real(number.as_f64().unwrap_or_default()),        },        Value::String(text) => SqlValue::Text(text.clone()),        Value::Null | Value::Array(_) | Value::Object(_) => SqlValue::Null,    }}/// The SQL a list of a table a person defined reads its columns through:/// each column is its own column of the made table, named only once the/// definition has validated its key; a computed column lives in the/// device-local `_computed`, joined once per column the list names (`c_<n>`,/// its table and key BOUND in the join).struct UserColumns<'a> {    definition: &'a TableDefinition,    /// The computed keys joined, in the order their joins are written.    joined: Vec<String>,}impl<'a> UserColumns<'a> {    fn new(definition: &'a TableDefinition) -> Self {        UserColumns { definition, joined: Vec::new(),        }    }    /// The expression one column reads as, its bound parameter (if any)    /// pushed onto `params` where the expression stands.    fn expr(&mut self, key: &str, _params: &mut Vec<SqlValue>) -> String {        let definition = self.definition;        if definition.column(key).is_some_and(|column| column.computed.is_some()) {            let n = match self.joined.iter().position(|joined| joined == key) {                Some(n) => n,                None => {                    self.joined.push(key.to_string());                    self.joined.len() - 1                }            };            return format!("c_{n}.value");        }        match definition.column(key) {            Some(column) => format!("r.{}", col(&column.key)),            // A key the definition does not name holds nothing.            None => "NULL".into(),        }    }    /// The FROM clause — the records and one join per computed column named —    /// with the joins' bound keys, which come before every other parameter.    fn from(&self) -> (String, Vec<SqlValue>) {        let mut sql = format!(" FROM {} r", made_table(&self.definition.id));        for n in 0..self.joined.len() {            sql.push_str(&format!(                " LEFT JOIN _computed c_{n} ON c_{n}.table_id = ? AND c_{n}.record_id = r.id AND c_{n}.key = ?"            ));        }        let params = self            .joined            .iter()            .flat_map(|key| {                [SqlValue::Text(self.definition.id.clone()), SqlValue::Text(key.clone()),                ]            })            .collect();        (sql, params)    }}/// One `where` entry over a table a person defined, appended to `sql`.fn user_where(    columns: &mut UserColumns<'_>,    clause: &WhereClause,    sql: &mut String,    params: &mut Vec<SqlValue>,    zone: &cotton_core::records::Zone,) {    let mut target = columns.expr(&clause.column, params);    // A range's last day, holding nothing, reads as its first    // (`WhereClause::first_day`).    if let Some(first) = &clause.first_day {        target = format!("COALESCE(NULLIF({target}, ''), {})", columns.expr(first, params));    }    sql.push_str(" AND ");    sql.push_str(&condition_sql(&target, &clause.condition, params, zone));}/// One scalar condition, shared by stored and cached definition columns.fn condition_sql(target: &str, condition: &Condition, params: &mut Vec<SqlValue>, zone: &cotton_core::records::Zone) -> String {    match condition {        Condition::Is(value) => {            params.push(sql_value(value));            format!("{target} = ?")        }        Condition::OneOf(values) => {            params.extend(values.iter().map(sql_value));            format!("{target} IN ({})", vec!["?"; values.len()].join(", "))        }        Condition::Present(present) => {            let test = if *present { "<>" } else { "=" };            format!("COALESCE({target}, '') {test} ''")        }        Condition::NoneOf(values) => {            params.extend(values.iter().map(sql_value));            format!("NULLIF({target}, '') NOT IN ({})", vec!["?"; values.len()].join(", "))        }        Condition::Month(month) => yearly_dates::in_month(target, *month),        Condition::WithinDays(days) => within_days(target, *days),        Condition::On(day) => on_day(target, *day, zone),        Condition::Bound(bound) => {            let (compare, number) = bound.sql();            params.push(SqlValue::Real(number));            // A blank or a text is no number, so it is in no bound.            format!("(typeof({target}) IN ('integer', 'real') AND {target} {compare} ?)")        }    }}/// A date value — a day or an instant — in a window of days about now/// (`cotton_core::records::within_days`). The days are a parsed whole/// number, so they are written in place.pub(super) fn within_days(value: &str, window: cotton_core::records::DayWindow) -> String {    use cotton_core::records::DayWindow;    match window {        DayWindow::Within(days) => format!("julianday({value}) >= julianday('now', '-{days} days')"),        DayWindow::Before(days) => format!("julianday({value}) < julianday('now', '-{days} days')"),        DayWindow::Ahead(days) => format!(            "julianday({value}) >= julianday('now', '-1 days') AND julianday({value}) <= julianday('now', '+{days} days')"        ),    }}/// A date value on a day named against today (`cotton_core::records::on_day`)/// where the reader stands (`zone`: today there, and the zone a moment is read/// as its day in): a bare day is that day, a moment is read at the zone's/// offset on that day. Today and the offset are this build's own figures, a/// formatted date and a whole number, so they are written in place.pub(super) fn on_day(value: &str, day: cotton_core::records::DayOn, zone: &cotton_core::records::Zone) -> String {    use chrono::{Datelike, Offset, TimeZone};    use cotton_core::records::DayOn;    let noon = zone.today.and_hms_opt(12, 0, 0).expect("noon is a time");    let offset = zone.tz.offset_from_utc_datetime(&noon).fix().local_minus_utc() / 60;    let held = format!("(CASE WHEN length(trim({value})) = 10 THEN trim({value}) ELSE date({value}, '{offset:+} minutes') END)");    let today = zone.today.format("%Y-%m-%d");    match day {        DayOn::Today => format!("{held} = '{today}'"),        DayOn::ThisDay => format!(            "strftime('%m-%d', {held}) = '{:02}-{:02}' AND {held} < '{:04}-01-01'",            zone.today.month(),            zone.today.day(),            zone.today.year()        ),        DayOn::FromToday => format!("{held} >= '{today}'"),        DayOn::BeforeToday => format!("{held} < '{today}'"),    }}/// One ORDER BY term of a made table's list: the rows that hold nothing —/// NULL or an empty text — last whichever way it runs, text compared/// whatever its capitals, numbers as numbers.fn user_order_term(columns: &mut UserColumns<'_>, key: &str, descending: bool, params: &mut Vec<SqlValue>,) -> String {    // NULLIF: an empty text is no value, so the blanks tie among themselves    // and fall to the tie, as two NULLs do.    let blank = columns.expr(key, params);    let value = columns.expr(key, params);    let direction = if descending { "DESC" } else { "ASC" };    format!("NULLIF({blank}, '') IS NULL, NULLIF({value}, '') COLLATE NOCASE {direction}")}/// What a list asks of a stale computed index: it cannot order, filter or/// search on a computed column until the index is rebuilt — at the next fold/// or file open — and a read may not rebuild it. An assistant reads it as line/// `tables.being_worked_out` of set `refusal`, the database's row first; the/// app's boundary answers it typed, `could_not_read` with `why: moving`/// ([`take_being_worked_out`]), and the database definition says it.pub const BEING_WORKED_OUT: &str = "tables.being_worked_out";/// [`BEING_WORKED_OUT`] in these line rows' words — the kit's for none.pub fn being_worked_out_words(lines: &[cotton_core::rules::shell_lines::LineRow]) -> String {    cotton_core::rules::shell_lines::resolve("refusal", BEING_WORKED_OUT, lines, &[])        .expect("the refusal line set ships tables.being_worked_out")}/// The refusal of a list whose computed index is being worked out, in this/// database's words.pub(crate) fn being_worked_out(db: &cotton_store::Driver, workspace_id: &str) -> ToolFailure {    note_being_worked_out();    ToolFailure::new(being_worked_out_words(&crate::presentation::line_rows(db, workspace_id)))}/// What a write that reads a computed column asks of the index. On a handle/// that rebuilds beside its folds — the server, a device — a stale index/// refuses: the background pass is working it out, and a call never waits/// on it (Mac 165, 21 Oct 2026). Elsewhere it is rebuilt here.pub(crate) fn computed_in_step(ctx: &Ctx<'_>) -> Valid<()> {    if !ctx.db().indexes_beside() {        return crate::derive::ensure_current(ctx.db()).map_err(sql_err);    }    if crate::derive::is_current(ctx.db()).map_err(sql_err)? {        Ok(())    } else {        Err(being_worked_out(ctx.db(), ctx.workspace_id))    }}thread_local! {    /// Whether a read on THIS thread was refused because the computed index    /// was being worked out — set where the refusal is made (a read is    /// answered on the thread that asked it), taken once by the method that    /// answers the app, which says so in its own typed code. The refusal's    /// words are a line a database may reword, so they never decide it.    static BEING_WORKED_OUT_HERE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}/// Note that a read on this thread met the computed index before its/// background rebuild was done (passivemove rule 3).pub(crate) fn note_being_worked_out() {    BEING_WORKED_OUT_HERE.with(|here| here.set(true));}/// Whether a read on this thread was refused as a table mid-move since the/// last time this was asked — and forget it.pub fn take_being_worked_out() -> bool {    BEING_WORKED_OUT_HERE.with(std::cell::Cell::take)}/// Facts beside a list, all computed over its complete filtered scope.#[derive(Default)]pub(super) struct ListExtras {    pub sections: Option<Vec<Value>>,    pub summaries: Option<Vec<ListSummary>>,    /// A narrow cut read by position (`builtin::list`): each row    /// `[id, …columns]` as the answer says it, the page's records left empty.    pub cut_rows: Option<Vec<Value>>,    /// A plan read `sectioned` (`day_plan::Plan::sectioned`): its keys and    /// each row's `[id, key]`, answered instead of a page.    pub sectioned: Option<Value>,}/// One named grouping's figures, using the same format as tile summaries.#[derive(serde::Serialize)]pub(super) struct ListSummary {    pub by: String,    pub key: String,    pub label: String,    pub figures: Vec<cotton_core::records::SummaryValue>,}/// One page of a table's live records.pub struct Page {    pub records: Vec<Stored>,    pub more: bool,    /// How many live records the whole list holds — every page's filters, no    /// page's bounds — so a face can say "12 / 340" or "40 photos".    pub total: i64,}/// HIDE FROM SCREEN (CORE 4, add 2): a list of his films' tables reads no hidden title, no row naming one by a link and/// no play of one: left out in the WHERE the list reads by, so its `total`, its pages and its `more` are made without/// them (a page of `records: []` beside `total: 5` was the answer when they were dropped afterwards). One JSON/// parameter per test, however many are hidden./// Home's figures over his films' tables read through it too (CORE 5, L3: `made_figure_total`, `first_day`), so no/// figure, today's or a future one, counts a hidden title.fn leave_out_hidden(db: &cotton_store::Driver, workspace_id: &str, definition: &TableDefinition, columns: &mut UserColumns<'_>, sql: &mut String, params: &mut Vec<SqlValue>) -> Valid<()> {    if !hidden::FAMILY.contains(&definition.id.as_str()) {        return Ok(());    }    let shut = hidden::hiding_in(db, workspace_id).map_err(sql_err)?.all();    if shut.is_empty() {        return Ok(());    }    let listed = Value::from(shut.into_iter().collect::<Vec<_>>()).to_string();    sql.push_str(" AND r.id NOT IN (SELECT value FROM json_each(?))");    params.push(SqlValue::Text(listed.clone()));    for link in hidden::LINKS.iter().filter(|link| definition.column(link).is_some()) {        let held = columns.expr(link, params);        sql.push_str(&format!(" AND COALESCE({held}, '') NOT IN (SELECT value FROM json_each(?))"));        params.push(SqlValue::Text(listed.clone()));    }    Ok(())}#[allow(clippy::too_many_arguments)]fn list_user(    ctx: &Ctx<'_>,    definition: &TableDefinition,    project: Option<&str>,    query: Option<&str>,    clauses: &[WhereClause],    offset: i64,    limit: i64,    archived: bool,    span: Option<(&str, &str)>,    view: &day_plan::View,) -> Valid<Page> {    let zone = crate::mcp::handlers::common::reading_zone(ctx, view.timezone.as_deref(), view.today.as_deref())?;    let mut columns = UserColumns::new(definition);    let mut sql = String::from(" WHERE r.workspace_id = ? AND r.deleted_at IS NULL");    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    if let Some(among) = &view.among {        let marks = vec!["?"; among.len()].join(", ");        sql.push_str(&format!(" AND r.id IN ({marks})"));        params.extend(among.iter().cloned().map(SqlValue::Text));    }    leave_out_hidden(ctx.db(), ctx.workspace_id, definition, &mut columns, &mut sql, &mut params)?;    keep_span(definition, &mut columns, span, &mut sql, &mut params)?;    // A record whose archive column holds a day or true is put away: out of    // the list, and the whole of the Archived list.    if let Some(column) = &definition.archived {        let held = columns.expr(column, &mut params);        let test = if archived { "NOT IN" } else { "IN" };        sql.push_str(&format!(" AND COALESCE({held}, '') {test} ('', 0)"));    }    if let Some(project) = project {        if definition.project.is_none() {            return Err(ToolFailure::new(format!(                "{} do not belong to projects",                definition.plural            )));        }        let held = columns.expr(definition.project.as_deref().unwrap_or_default(), &mut params,        );        sql.push_str(&format!(" AND {held} = ?"));        params.push(SqlValue::Text(project.to_string()));    }    if let Some(query) = query {        // Every word somewhere in the title or a text column — the same rule        // as `records::matches_query` — a computed one read from `_computed`.        let searched: Vec<&str> = records::searchable_columns(definition)            .into_iter()            .filter(|key| Some(*key) != definition.project.as_deref())            // A whole account number remains in the file for statement            // matching. It is not a search term: SQL must never see its            // middle digits, whose projection is core-owned.            .filter(|key| definition.column(key).is_none_or(|column| {                column.column_type != cotton_core::definitions::ColumnType::AccountNumber            }))            .collect();        if searched.is_empty() {            sql.push_str(" AND 0");        } else {            for word in query.split_whitespace() {                let mut any = Vec::with_capacity(searched.len());                for key in &searched {                    let target = columns.expr(key, &mut params);                    any.push(format!("instr(lower({target}), lower(?)) > 0"));                    params.push(SqlValue::Text(word.to_string()));                }                sql.push_str(&format!(" AND ({})", any.join(" OR ")));            }        }    }    for clause in clauses {        user_where(&mut columns, clause, &mut sql, &mut params, &zone);    }    // Precedence, as a built-in's (`builtin::list`): a hand-made order; else    // the definition's `sort` (unless it orders only inside the days of a    // list split by day); else its date, newest first; else the latest    // written.    let mut order_params = Vec::new();    let sort = definition.sort.as_ref().filter(|_| !builtin::sorts_within_days(definition));    let order = if let Some(order) = &definition.order {        let order = col(order);        format!("r.{order} IS NULL, r.{order}, r.created_at, r.id")    } else if let Some(sort) = sort.filter(|sort| sort.next == Some(true)) {        // The next time each row's yearly day comes round from the reader's        // day (`yearly_dates`), the undated last; ties by the sort's tie,        // else by the date itself.        let today = yearly_dates::reader_day(ctx, view)?;        let direction = if sort.descending == Some(true) { "DESC" } else { "ASC" };        let [undated, past, day] = yearly_dates::next_terms(|| columns.expr(&sort.column, &mut order_params), &today);        let tie = user_order_term(&mut columns, sort.tie.as_deref().unwrap_or(&sort.column), sort.tie_descends(), &mut order_params);        format!("{undated}, {past} {direction}, {day} {direction}, {tie}, r.updated_at DESC, r.id")    } else if let Some(sort) = sort {        let descending = sort.descending == Some(true);        let mut terms = vec![user_order_term(&mut columns, &sort.column, descending, &mut order_params,        )];        if let Some(tie) = &sort.tie {            terms.push(user_order_term(&mut columns, tie, sort.tie_descends(), &mut order_params,            ));        }        terms.push("r.updated_at DESC, r.id".into());        terms.join(", ")    } else if let Some(date) = &definition.date {        let missing = columns.expr(date, &mut order_params);        let value = columns.expr(date, &mut order_params);        format!("{missing} IS NULL, {value} DESC, r.updated_at DESC, r.id")    } else {        "r.updated_at DESC, r.id".to_string()    };    // A list that reads a computed column before its page is cut reads the    // index, so the index must be this build's and in step.    if !columns.joined.is_empty() && !crate::derive::is_current(ctx.read.driver()).map_err(sql_err)? {        return Err(being_worked_out(ctx.db(), ctx.workspace_id));    }    if !made_held(ctx, definition.rows_table())? {        return Ok(Page { records: Vec::new(), more: false, total: 0,        });    }    let (from, mut bound) = columns.from();    bound.extend(params);    let total = ctx        .read        .driver()        .get(&format!("SELECT COUNT(*) AS n{from}{sql}"), &bound)        .map_err(sql_err)?        .and_then(|row| row.int("n"))        .unwrap_or(0);    if limit == 0 {        return Ok(Page { records: Vec::new(), more: false, total,        });    }    let sql = format!("SELECT r.*{from}{sql} ORDER BY {order} LIMIT ? OFFSET ?");    bound.extend(order_params);    bound.push(SqlValue::Integer(limit + 1));    bound.push(SqlValue::Integer(offset));    let rows = ctx.read.driver().all(&sql, &bound).map_err(sql_err)?;    let mut records: Vec<Stored> = rows        .iter()        .map(|row| stored_from_row(definition, row))        .collect();    let more = records.len() as i64 > limit;    records.truncate(limit as usize);    Ok(Page {        records,        more,        total,    })}/// Every live record of a made table, its values only.fn live_made(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid<Vec<Data>> {    if !made_held(ctx, definition.rows_table())? {        return Ok(Vec::new());    }    let sql = format!("SELECT * FROM {} WHERE workspace_id = ? AND deleted_at IS NULL", made_table(definition.rows_table()));    let rows = ctx.read.driver().all(&sql, &[SqlValue::Text(ctx.workspace_id.to_string())]).map_err(sql_err)?;    let data = rows.iter().map(|row| stored_from_row(definition, row).data);    // HIDE FROM SCREEN: a summary, a chart or a sparkline over his films' tables, drawn on his screen, counts no hidden    // title (a chart's top rows and its labels would name it).    if !hidden::FAMILY.contains(&definition.id.as_str()) {        return Ok(data.collect());    }    let hiding = hidden::hiding(ctx).map_err(sql_err)?;    let ids: Vec<Option<String>> = rows.iter().map(|row| row.text("id").map(str::to_string)).collect();    Ok(data.zip(ids).filter(|(row, id)| !hiding.hides(id.as_deref(), row)).map(|(row, _)| row).collect())}/// A tool figure's total (`tool.figures[].summary`): how many rows, or the/// sum, lowest or highest of one column, and — for an amount — the one/// currency its rows are in (`mixed` when they are in more than one, so no/// total is said across them). A lowest or highest carries `on`, the date/// (the table's `date`) of the row that holds it.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct FigureTotal {    pub total: i64,    pub currency: Option<String>,    pub mixed: bool,    pub on: Option<String>,}/// One summary figure of a tool, over `definition`'s live rows on `today`/// (the person's own day, for `period`) — ONE indexed read on a made table/// or a built-in's store, the read Home asks for each figure of its tools./// A `where` here is a list's, over stored columns; one the table does not/// take is refused, never ignored.pub fn figure_total(    read: &ReadDb<'_>,    definition: &TableDefinition,    summary: &cotton_core::definitions::FigureSummary,    today: chrono::NaiveDate,) -> Valid<FigureTotal> {    figure_total_in_snapshot(read, definition, summary, today, &mut FigureRows::new())}// Resolved rows belong only to this figure pass and its caller's snapshot.// Never retain a balance or a record payload across read invocations.pub(crate) type FigureRows = std::collections::BTreeMap<String, Vec<Stored>>;pub(crate) fn figure_total_in_snapshot(    read: &ReadDb<'_>,    definition: &TableDefinition,    summary: &cotton_core::definitions::FigureSummary,    today: chrono::NaiveDate,    resolved: &mut FigureRows,) -> Valid<FigureTotal> {    let filter = summary.where_.as_ref().map(|filter| serde_json::to_value(filter).expect("an ordered map is JSON"));    let mut clauses = records::parse_where(definition, filter.as_ref()).map_err(refuse)?;    // A figure over a view counts the view's rows (`viewed`).    clauses.extend(viewed(definition)?);    let span = match summary.period {        Some(period) => Some(kept_span(read, definition, &clauses, period, today)?),        None => None,    };    let span = span.as_ref().map(|(from, until)| (from.as_str(), until.as_str()));    let column = summary.column.as_deref();    if money_runway::handles(definition) { return money_runway::figure(read,definition,&clauses,span,summary.op,column,today,resolved); }    if is_user_table(definition) {        made_figure_total(read, definition, &clauses, span, summary.op, column)    } else {        builtin::figure_total(read, definition, &clauses, span, summary.op, column, resolved)    }}/// The half-open span of days `period` keeps over `definition`'s rows that/// `clauses` keep, from the person's own `today`: a fixed stretch, or the/// first day after today the rows hold (`next_day`; none held, an empty span).fn kept_span(    read: &ReadDb<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    period: cotton_core::definitions::FigurePeriod,    today: chrono::NaiveDate,) -> Valid<(String, String)> {    if let Some(span) = period_span(period, today) {        return Ok(span);    }    let tomorrow = today.checked_add_days(chrono::Days::new(1)).expect("a day follows");    let first = if is_user_table(definition) { first_day(read, definition, clauses, tomorrow)? } else { None };    let first = first.and_then(|day| chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").ok());    Ok(match first {        Some(day) => days_from(day, 1),        None => days_from(tomorrow, 0),    })}/// The first day on or after `from` that a made table's live rows kept by/// `clauses` fall on, by the table's own date.fn first_day(read: &ReadDb<'_>, definition: &TableDefinition, clauses: &[WhereClause], from: chrono::NaiveDate) -> Valid<Option<String>> {    let zone = crate::mcp::handlers::common::read_where_zone(read)?;    let date = definition.date.as_deref().ok_or_else(|| {        ToolFailure::new(format!("{} have no date a period can keep", definition.plural))    })?;    let held = read        .driver()        .get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(made_table(definition.rows_table()))])        .map_err(sql_err)?        .is_some();    if !held {        return Ok(None);    }    let mut columns = UserColumns::new(definition);    let mut predicate = String::from(" WHERE r.workspace_id = ? AND r.deleted_at IS NULL");    let mut params = vec![SqlValue::Text(read.workspace_id().to_string())];    if let Some(archived) = &definition.archived {        let held = columns.expr(archived, &mut params);        predicate.push_str(&format!(" AND COALESCE({held}, '') IN ('', 0)"));    }    for clause in clauses {        user_where(&mut columns, clause, &mut predicate, &mut params, &zone);    }    leave_out_hidden(read.driver(), read.workspace_id(), definition, &mut columns, &mut predicate, &mut params)?;    let on = columns.expr(date, &mut params);    predicate.push_str(&format!(" AND {on} >= ?"));    params.push(SqlValue::Text(from.format("%Y-%m-%d").to_string()));    if !columns.joined.is_empty() && !crate::derive::is_current(read.driver()).map_err(sql_err)? {        return Err(being_worked_out(read.driver(), read.workspace_id()));    }    let (rows, mut bound) = columns.from();    bound.extend(params);    let row = read.driver().get(&format!("SELECT MIN(substr({on}, 1, 10)) AS day{rows}{predicate}"), &bound).map_err(sql_err)?;    Ok(row.and_then(|row| row.text("day").map(str::to_string)))}/// The half-open span of days a fixed `period` keeps, from the person's own/// `today`; `None` for `next_day`, whose day the rows say ([`kept_span`]).pub(crate) fn period_span(period: cotton_core::definitions::FigurePeriod, today: chrono::NaiveDate) -> Option<(String, String)> {    use chrono::Datelike;    Some(match period {        cotton_core::definitions::FigurePeriod::ThisMonth => {            let first = today.with_day(1).expect("every month has a first day");            let next = first.checked_add_months(chrono::Months::new(1)).expect("a month follows");            (first.format("%Y-%m-%d").to_string(), next.format("%Y-%m-%d").to_string())        }        cotton_core::definitions::FigurePeriod::Today => days_from(today, 1),        cotton_core::definitions::FigurePeriod::Tomorrow => {            let tomorrow = today.checked_add_days(chrono::Days::new(1)).expect("a day follows");            days_from(tomorrow, 1)        }        cotton_core::definitions::FigurePeriod::Next7Days => days_from(today, 7),        cotton_core::definitions::FigurePeriod::ThisYear => {            let first = chrono::NaiveDate::from_ymd_opt(today.year(), 1, 1).expect("every year has a first day");            let next = chrono::NaiveDate::from_ymd_opt(today.year() + 1, 1, 1).expect("a year follows");            (first.format("%Y-%m-%d").to_string(), next.format("%Y-%m-%d").to_string())        }        cotton_core::definitions::FigurePeriod::NextDay => return None,    })}/// A made table's rows kept to `span` by the table's own date — a figure's/// period and a list's alike; a table with no date keeps no period.fn keep_span(    definition: &TableDefinition,    columns: &mut UserColumns<'_>,    span: Option<(&str, &str)>,    predicate: &mut String,    params: &mut Vec<SqlValue>,) -> Valid<()> {    let Some((from, until)) = span else { return Ok(()) };    let date = definition.date.as_deref().ok_or_else(|| {        ToolFailure::new(format!("{} have no date a period can keep", definition.plural))    })?;    let date = columns.expr(date, params);    predicate.push_str(&format!(" AND {date} >= ? AND {date} < ?"));    params.push(SqlValue::Text(from.to_string()));    params.push(SqlValue::Text(until.to_string()));    Ok(())}/// `days` whole days from `today`, as the half-open span a period keeps.fn days_from(today: chrono::NaiveDate, days: u64) -> (String, String) {    let until = today.checked_add_days(chrono::Days::new(days)).expect("a day follows");    (today.format("%Y-%m-%d").to_string(), until.format("%Y-%m-%d").to_string())}/// [`figure_total`] over a made table: its live, unarchived rows.fn made_figure_total(    read: &ReadDb<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    span: Option<(&str, &str)>,    op: cotton_core::definitions::SummaryOp,    column: Option<&str>,) -> Valid<FigureTotal> {    let zone = crate::mcp::handlers::common::read_where_zone(read)?;    use cotton_core::definitions::SummaryOp;    let none = FigureTotal::default();    let held = read        .driver()        .get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(made_table(definition.rows_table()))])        .map_err(sql_err)?        .is_some();    if !held {        return Ok(none);    }    let mut columns = UserColumns::new(definition);    let mut predicate = String::from(" WHERE r.workspace_id = ? AND r.deleted_at IS NULL");    let mut params = vec![SqlValue::Text(read.workspace_id().to_string())];    if let Some(archived) = &definition.archived {        let held = columns.expr(archived, &mut params);        predicate.push_str(&format!(" AND COALESCE({held}, '') IN ('', 0)"));    }    for clause in clauses {        user_where(&mut columns, clause, &mut predicate, &mut params, &zone);    }    leave_out_hidden(read.driver(), read.workspace_id(), definition, &mut columns, &mut predicate, &mut params)?;    keep_span(definition, &mut columns, span, &mut predicate, &mut params)?;    // A lowest or highest is one row's value, read with its row's date; how    // many currencies the kept rows are in is a read of its own (`counted`).    let extreme = match op {        SummaryOp::Min => Some("ASC"),        SummaryOp::Max => Some("DESC"),        SummaryOp::Count | SummaryOp::Sum => None,    };    let mut counted = None;    let (select, currency) = match column {        None => ("COUNT(*) AS total, NULL AS currency, 0 AS currencies, NULL AS at".to_string(), None),        Some(added) => {            if definition.column(added).is_none() {                return Err(refuse(RecordError::UnknownColumn { plural: definition.plural.clone(), column: added.to_string() }));            }            let summed = columns.expr(added, &mut params);            let named = definition.column(added).and_then(|column| column.currency.clone());            let held = named.as_deref().filter(|named| definition.column(named).is_some()).map(|named| columns.expr(named, &mut params));            match (extreme, held) {                (Some(_), held) => {                    let at = match definition.date.as_deref() {                        Some(date) => columns.expr(date, &mut params),                        None => "NULL".to_string(),                    };                    predicate.push_str(&format!(" AND {summed} IS NOT NULL"));                    counted = held.as_ref().map(|held| format!("COUNT(DISTINCT {held}) AS currencies"));                    let currency = held.clone().unwrap_or_else(|| "NULL".to_string());                    // A computed value rests as text: ranked as a number, never as words.                    (format!("CAST({summed} AS INTEGER) AS total, CAST({summed} AS REAL) AS ranked, {currency} AS currency, 0 AS currencies, {at} AS at"), named.filter(|_| held.is_none()))                }                (None, Some(held)) => (format!("COALESCE(SUM({summed}), 0) AS total, MIN({held}) AS currency, COUNT(DISTINCT {held}) AS currencies, NULL AS at"), None),                (None, None) => (format!("COALESCE(SUM({summed}), 0) AS total, NULL AS currency, 0 AS currencies, NULL AS at"), named),            }        }    };    let order = match (extreme, column) {        (Some(direction), Some(_)) => format!(" ORDER BY ranked {direction}, at ASC LIMIT 1"),        _ => String::new(),    };    if !columns.joined.is_empty() && !crate::derive::is_current(read.driver()).map_err(sql_err)? {        return Err(being_worked_out(read.driver(), read.workspace_id()));    }    let (from, mut bound) = columns.from();    bound.extend(params);    let row = read.driver().get(&format!("SELECT {select}{from}{predicate}{order}"), &bound).map_err(sql_err)?;    let total = row.as_ref().and_then(|row| row.int("total")).unwrap_or(0);    let currencies = match &counted {        Some(counted) => read.driver().get(&format!("SELECT {counted}{from}{predicate}"), &bound).map_err(sql_err)?,        None => row.clone(),    };    let currencies = currencies.as_ref().and_then(|row| row.int("currencies")).unwrap_or(0);    let currency = row        .as_ref()        .and_then(|row| row.text("currency").map(str::to_string))        .or(currency.filter(|code| !code.trim().is_empty()));    let on = row.as_ref().and_then(|row| row.text("at").map(str::to_string));    Ok(FigureTotal { total, currency, mixed: currencies > 1, on })}/// `summarize_records { table }` → `{ table, summary: [figure] }` — every/// figure the table's `tile.summary` asks for, computed by/// `records::summarize` over all of the table's live records (a table a/// person defined; a built-in has no tile summary and answers an empty list)./// Each figure is `{ op, column?, label?, value, currency? }`. A sparkline/// face's tile adds `sparkline: { table, value, at, days, points: [{at, value,/// t}], low?, high?, last? }` (`records::sparkline`); asked with a `record`,/// the answer adds `sparklines`, one per page section that draws a line, over/// that record's linked rows. A chart face's tile adds `chart: { kind, by, x,/// y, currency?, buckets: [{start, value}], total, left_out? }`/// (`records::chart`), its window ending with the period of `today` when/// given; a chart reads a built-in's records too. A table that ships a chart/// view adds `view_chart`, that view's series, the same shape.pub fn summarize_records(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let definition = table_arg(ctx, args)?;    let figures = if definition.tile.summary.is_empty() || !is_user_table(&definition) {        Vec::new()    } else {        let data = live_made(ctx, &definition)?;        records::summarize(&definition, &data, &cotton_core::records::page::Words::of_rows(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id)), &records::where_zone(Some(&crate::mcp::handlers::common::workspace_timezone(ctx)?))).map_err(refuse)?    };    let mut answer = json!({ "table": definition.id, "summary": figures });    let json = |points| serde_json::to_value(points).map_err(|error| ToolFailure::new(error.to_string()));    if let Some(line) = &definition.tile.sparkline {        answer["sparkline"] = json(sparkline_points(ctx, line, None)?)?;    }    if let Some(face) = &definition.tile.chart {        let series = chart_series(ctx, &definition, face, args)?;        answer["chart"] = serde_json::to_value(series).map_err(|error| ToolFailure::new(error.to_string()))?;    }    // The table's chart view over the same records.    if let Some(face) = view_chart(&definition) {        let series = chart_series(ctx, &definition, face, args)?;        answer["view_chart"] = serde_json::to_value(series).map_err(|error| ToolFailure::new(error.to_string()))?;    }    // A record's page: each section's line over that record's linked rows.    if let Some(record) = args.get("record").and_then(Value::as_str) {        let mut lines = Vec::new();        for line in definition.page.iter().filter_map(|section| section.sparkline.as_ref()) {            lines.push(json(sparkline_points(ctx, line, Some(record))?)?);        }        answer["record"] = Value::from(record);        answer["sparklines"] = Value::Array(lines);    }    Ok(answer)}/// The chart a table's chart view draws, when it ships one.pub fn view_chart(definition: &TableDefinition) -> Option<&cotton_core::definitions::ChartFace> {    definition.views.iter().flatten().find_map(|view| view.chart.as_ref())}/// The chart face's series over the table's live records — a table a person/// defined read from its rows, a built-in through its engine's own list, so a/// kit's table and Money draw by the same `records::chart`. The window ends/// with the period of `today` (the reader's YYYY-MM-DD), or of now's UTC day.fn chart_series(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    face: &cotton_core::definitions::ChartFace,    args: &Map<String, Value>,) -> Result<records::ChartSeries, ToolFailure> {    let today = match args.get("today").and_then(Value::as_str) {        Some(day) => chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d")            .map_err(|_| ToolFailure::new(format!("today is a day, YYYY-MM-DD, not {day:?}")))?,        None => ctx.now.date_naive(),    };    let data: Vec<Data> = if is_user_table(definition) {        live_made(ctx, definition)?    } else {        // Every live record, a page at a time; the chart's `where` is the        // core's to apply, so an engine's narrowing never decides a total.        const PAGE: i64 = 500;        let view = day_plan::View::default();        let mut data = Vec::new();        let mut offset = 0;        loop {            let (mut page, _) = builtin::list(ctx, definition, None, None, &[], offset, PAGE, &view, None, None, Total::Skipped,            )?;            // The columns an engine works out (a movement's amount) are            // filled the way list_records fills them.            derive_records(ctx, definition, &mut page.records, args, false)?;            let read = page.records.len() as i64;            data.extend(page.records.into_iter().map(|stored| stored.data));            if !page.more || read == 0 {                break data;            }            offset += read;        }    };    let at = match args.get("at").and_then(Value::as_str) {        Some(at) if face.by == cotton_core::definitions::ChartPeriod::Hour => chrono::DateTime::parse_from_rfc3339(at)            .map_err(|_| ToolFailure::new("at is an instant with an offset, RFC3339"))?,        None if face.by == cotton_core::definitions::ChartPeriod::Hour => ctx.now.fixed_offset(),        _ => today.and_hms_opt(0, 0, 0).unwrap().and_utc().fixed_offset(),    };    records::chart_at(face, definition, &data, at, &cotton_core::records::page::Words::of_rows(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id))).map_err(refuse)}/// The sparkline face's points: the live records of the table the line/// names, through `records::sparkline` over the window ending now.fn sparkline_points(    ctx: &Ctx<'_>,    line: &cotton_core::definitions::Sparkline,    record: Option<&str>,) -> Result<records::SparklinePoints, ToolFailure> {    let of = definition(ctx, &line.table)?;    if !is_user_table(&of) {        return Err(ToolFailure::new(format!(            "tile.sparkline reads {:?}, which is not a table a person defined",            of.id        )));    }    let data = live_made(ctx, &of)?;    records::sparkline(line, &of, &data, record, ctx.now).map_err(refuse)}/// `list_records { table, project?, query?, where?, page?, limit? }` →/// `{ table, records: [record], next_page, total }` — `total` how many live/// records every page of this list holds together.////// `where` narrows by column (`records::parse_where` reads it): a table a/// person defined filters any declared column in SQL; a built-in filters its/// stored columns the same way and every other column only through its/// engine's own narrowing (`builtin::NARROWINGS`) — one it cannot narrow by is/// refused, never ignored.pub fn list_records(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    list_answer(ctx, args, Total::Counted)}/// Whether a list's answer carries `total`, the whole list's count. A count/// is a question about every row the filter matches — for the mail list,/// every thread of the mailbox — so a reader that keeps only the page's ids/// (a filter's check) never asks it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Total {    Counted,    Skipped,}/// [`list_records`], with or without its `total` ([`Total`]).pub fn list_answer(ctx: &mut Ctx<'_>, args: &Map<String, Value>, total: Total) -> ToolResult {    list_answer_resolved(ctx, args, total).map(|(_, answer)| answer)}/// Keep the definition that produced the rows with their internal answer, so/// the app can resolve their slips from the same read without parsing it again.pub fn list_answer_resolved(ctx: &mut Ctx<'_>, args: &Map<String, Value>, total: Total) -> Valid<(TableDefinition, Value)> {    // `total: false`: a reader that knows the count (a kept cut filling a    // page) never asks the whole list's again.    let total = if args.get("total") == Some(&Value::Bool(false)) { Total::Skipped } else { total };    let definition = table_arg(ctx, args)?;    // A named view reads the table as the view does — its order, slip and    // tile — and narrows the read by its `where`, as the phone's read does.    let (definition, args) = match optional_string(args, "view") {        Some(view) => {            let (definition, view) = as_view_reads(ctx, &definition, &view)?;            let mut narrowed = view.narrow(args);            narrow_to_current(ctx, &definition, &view, &mut narrowed)?;            (definition, std::borrow::Cow::Owned(narrowed))        }        None => (definition, std::borrow::Cow::Borrowed(args)),    };    let answer = list_answer_on(ctx, &definition, &args, total)?;    Ok((definition, answer))}/// RULE (Cotton Story contract, 17 Nov 2026): a view of the current record/// (`ToolView::current`) reads only the rows that link the linked table's/// row most lately chosen (the greatest `by`; while none holds one, the/// newest row): Story's Scenes, Characters, Places, Notes and Script show/// the current story's rows alone. With no linked row at all the view/// reads nothing. Any other view is left as it is.pub fn narrow_to_current(ctx: &mut Ctx<'_>, definition: &TableDefinition, view: &cotton_core::definitions::tool_views::ToolView, args: &mut Map<String, Value>) -> Valid<()> {    let Some(current) = view.current.as_ref() else { return Ok(()) };    let Some(linked) = definition.column(&current.column).and_then(|column| column.link_to.clone()) else { return Ok(()) };    let target = self::definition(ctx, &linked)?;    let mut ask = Map::new();    ask.insert("table".into(), Value::from(linked.clone()));    ask.insert("limit".into(), Value::from(1000));    let listed = list_answer_on(ctx, &target, &ask, Total::Skipped)?;    let records = listed["records"].as_array().cloned().unwrap_or_default();    let said = |record: &Value, key: &str| record["data"][key].as_str().or_else(|| record[key].as_str()).unwrap_or_default().to_string();    let chosen = records.iter().filter(|record| !said(record, &current.by).is_empty()).max_by_key(|record| (said(record, &current.by), said(record, "created_at")));    let newest = || records.iter().max_by_key(|record| said(record, "created_at"));    let id = chosen.or_else(newest).and_then(|record| record["id"].as_str()).map(str::to_string);    let mut filter = args.get("where").and_then(Value::as_object).cloned().unwrap_or_default();    filter.insert(current.column.clone(), match id {        Some(id) => Value::from(id),        None => serde_json::json!({ "present": false }),    });    args.insert("where".into(), Value::Object(filter));    Ok(())}/// The table as a tool view reads it (`view`: the view's id, or/// `<tool>/<view>`): the view's own order, slip and tile in place of the/// table's (`ToolView::over`). A view that declares none reads the table as/// it is; a view this table has none of is refused, never ignored.fn as_view_reads(ctx: &Ctx<'_>, definition: &TableDefinition, named: &str) -> Valid<(TableDefinition, cotton_core::definitions::tool_views::ToolView)> {    let (tool, id) = match named.split_once('/') {        Some((tool, id)) => (Some(tool), id),        None => (None, named),    };    let reads = |view: &&cotton_core::definitions::tool_views::ToolView| {        view.id == id && view.read.get("table").and_then(Value::as_str) == Some(definition.id.as_str())    };    let tables = crate::definitions::table_definitions(ctx)?;    if let Some(view) = tables        .definitions        .iter()        .filter_map(|home| home.tool.as_ref().map(|found| (home, found)))        .filter(|(home, found)| tool.is_none_or(|tool| found.key.as_deref().unwrap_or(&home.id) == tool))        .flat_map(|(_, found)| found.views.iter())        .find(reads)    {        return Ok((view.over(definition), view.clone()));    }    // A tool's own views (an imported Birthdays over People's person table,    // or a kit tool whose views its manifest carries), as `shell.fan` reads them.    let tools = crate::definitions::tool_definitions(ctx)?;    let (found, view) = tools        .definitions        .iter()        .filter(|found| tool.is_none_or(|tool| found.id == tool))        .flat_map(|found| found.views.iter().map(move |view| (found, view)))        .find(|(_, view)| reads(view))        .ok_or_else(|| ToolFailure::new(format!("{} have no view {named:?}", definition.plural)))?;    // The columns the tool added to this table are hidden in its own look    // and drawn in the tool's views.    let mut read = view.over(definition);    for contribution in found.contributes.iter().filter(|contribution| contribution.table == definition.id) {        let key = cotton_core::definitions::owner::contributed_key(&found.id, &contribution.column.key);        if let Some(column) = read.columns.iter_mut().find(|column| column.key == key) {            column.hidden = None;        }    }    Ok((read, view.clone()))}/// The same list over a definition already resolved in this read transaction./// Composed readers can resolve the catalogue once without decoding the same/// row for every count and stamp. No filter or engine rule is bypassed.pub fn list_answer_on(ctx: &mut Ctx<'_>, definition: &TableDefinition, args: &Map<String, Value>, total: Total) -> ToolResult {    if definition.engine.as_deref() == Some("everything") {        archived_arg(definition, args)?;        return everything::list(ctx, &Value::Object(args.clone()));    }    if args.get("last_changed") == Some(&Value::Bool(true)) {        if args.keys().any(|key| {            !matches!(key.as_str(), "table" | "last_changed" | "timezone" | "today")        }) {            return Err(ToolFailure::new("last_changed reads the whole table; ask without filters or paging",            ));        }        let changed = if is_user_table(&definition) {            let mut columns = UserColumns::new(&definition);            let mut predicate = String::from(" WHERE r.workspace_id = ? AND r.deleted_at IS NULL");            let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];            if let Some(column) = &definition.archived {                let held = columns.expr(column, &mut params);                predicate.push_str(&format!(" AND COALESCE({held}, '') IN ('', 0)"));            }            for clause in shown(&definition, &[])? {                user_where(&mut columns, &clause, &mut predicate, &mut params, &crate::mcp::handlers::common::reading_zone(ctx, args.get("timezone").and_then(Value::as_str), args.get("today").and_then(Value::as_str))?);            }            if !columns.joined.is_empty() && !crate::derive::is_current(ctx.read.driver()).map_err(sql_err)? {                return Err(being_worked_out(ctx.db(), ctx.workspace_id));            }            let (from, mut bound) = columns.from();            bound.extend(params);            let row = if made_held(ctx, definition.rows_table())? {                ctx.read.driver().get(                    &format!("SELECT MAX(r.updated_at) AS changed{from}{predicate}"), &bound,                ).map_err(sql_err)?            } else {                None            };            row.and_then(|row| row.text("changed").map(str::to_string))        } else {            builtin::last_changed(ctx, &definition)?        };        return Ok(json!({"table":definition.id, "last_changed":changed}));    }    if (args.contains_key("from") || args.contains_key("to")) && !money_runway::handles(definition) {        return Err(ToolFailure::new("A date window applies to a monthly Money runway view."));    }    let count_only = match args.get("count_only") {        None | Some(Value::Bool(false)) => false,        Some(Value::Bool(true)) => true,        Some(_) => return Err(ToolFailure::new("count_only is true or false")),    };    if count_only && args.keys().any(|key| !matches!(key.as_str(), "table" | "count_only" | "today" | "timezone" | "from" | "to")) {        return Err(ToolFailure::new("count_only reads the whole table; ask without filters or paging",        ));    }    let archived = archived_arg(&definition, args)?;    // `among` narrows the list's own read, never a read that names its rows    // itself (ids, a group) or the archive.    if let Some(among) = args.get("among").filter(|among| !among.is_null()) {        if !among.as_array().is_some_and(|ids| ids.iter().all(Value::is_string)) {            return Err(ToolFailure::new("among is a list of record ids"));        }        if args.get("ids").is_some_and(|ids| !ids.is_null()) || archived.is_some() || groups::named_in_where(&definition, args).is_some() {            return Err(ToolFailure::new("among narrows a list's own read; ask without ids, a group or archived"));        }    }    // A group of a list read as a day plan is that list narrowed to its    // members (`groups::planned`); any other is read in the group's order.    let mut members = None;    if let Some(group) = groups::named_in_where(&definition, args) {        // A filter group is the table's list narrowed by its filter.        if let Some(asked) = groups::filtered(ctx, &definition, &group, args)? {            return list_answer(ctx, &asked, total);        }        if is_user_table(&definition) || !groups::planned(&definition) {            return groups::list_in_group(ctx, &definition, &group, args);        }        members = Some(groups::planned_members(ctx, &definition, &group, args)?);    }    if let Some(ids) = args.get("ids") {        return list_by_ids(ctx, &definition, ids, args);    }    let project = project_arg(ctx, args)?;    let query = optional_string(args, "query");    // The group's `where` names its members alone (`groups::checked`).    let mut clauses = match members {        Some(_) => Vec::new(),        None => records::parse_where(&definition, args.get("where")).map_err(refuse)?,    };    clauses.extend(shown(&definition, &clauses)?);    let offset = match args.get("page") {        None | Some(Value::Null) => 0,        Some(value) => value            .as_i64()            .filter(|page| *page >= 0)            .ok_or_else(|| ToolFailure::new("page is the number of records to skip, 0 or more"))?,    };    // The Archived link's count alone: `limit: 0` beside `archived: true`.    let limit = match args.get("limit").and_then(Value::as_i64) {        _ if count_only => 0,        Some(0) if archived.is_some() => 0,        // A light read's rows are its few columns: a whole list's cut reads        // them in one page.        _ if args.get("columns").is_some_and(Value::is_array) => bounded_limit(args, DEFAULT_PAGE_SIZE, MAX_LIGHT_PAGE).max(1),        _ => bounded_limit(args, DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE).max(1),    };    if definition.derived == Some(true) {        crate::mcp::handlers::money_views::validate_view_day(ctx, &definition.id, args)            .map_err(ToolFailure::new)?;    }    let view = day_plan::View::of(args);    if view.cut && view.columns.is_none() {        return Err(ToolFailure::new("a cut names its columns"));    }    // A list kept to a stretch of days by the table's own date — a business    // Home's section (`period`, the words a figure keeps its rows by), from    // the person's own `today`. Only a made table keeps one.    let span = match args.get("period").filter(|period| !period.is_null()) {        None => None,        Some(period) => {            let period: cotton_core::definitions::FigurePeriod = serde_json::from_value(period.clone())                .map_err(|_| ToolFailure::new("period is this_month, today, tomorrow, next_7_days, next_day or this_year"))?;            if !is_user_table(&definition) {                return Err(ToolFailure::new(format!("{} are not read by period", definition.plural)));            }            let today = view.today.clone().ok_or_else(|| ToolFailure::new("a period is read from today: say today"))?;            let today = chrono::NaiveDate::parse_from_str(&today, "%Y-%m-%d").map_err(|_| ToolFailure::new("today is a day, YYYY-MM-DD"))?;            Some(kept_span(&ctx.read, &definition, &clauses, period, today)?)        }    };    if archived.is_some() && view.section.is_some() {        return Err(ToolFailure::new(format!(            "The archived {} are not read in sections; ask without section",            definition.plural.to_lowercase()        )));    }    let (mut page, mut extras) = if is_user_table(&definition) {        if view.section.is_some() {            return Err(ToolFailure::new(format!(                "{} is not read in sections; ask without section",                definition.plural            )));        }        let page = list_user(            ctx,            &definition,            project.as_deref(),            query.as_deref(),            &clauses,            offset,            limit,            archived.is_some(),            span.as_ref().map(|(from, until)| (from.as_str(), until.as_str())),            &view,        )?;        (page, ListExtras::default())    } else {        builtin::list(            ctx,            &definition,            project.as_deref(),            query.as_deref(),            &clauses,            offset,            limit,            &view,            archived,            members.as_deref(),            total,        )?    };    if count_only {        return Ok(json!({"table": definition.id, "total": page.total}));    }    if view.columns.is_some() {        // A light read derives only the values its columns may be: a kept        // computed value only where one of them is computed.        if view.columns.iter().flatten().any(|key| definition.column(key).is_some_and(|column| column.computed.is_some())) {            with_computed(ctx, &definition, &mut page.records)?;        }        own_values::merge(ctx, &definition, &mut page.records)?;    } else {        derive_records(ctx, &definition, &mut page.records, args, false)?;    }    let next = (page.more && limit > 0).then_some(offset + page.records.len() as i64);    let mut answer = if view.cut {        // A narrow cut: each row `[id, …columns]`, its values as a record        // reads them, and no count (the cutter counts what it cut).        let asked = view.columns.as_deref().unwrap_or_default();        let rows: Vec<Value> = extras.cut_rows.take().unwrap_or_else(|| page.records.iter().map(|stored| {            let data = records::public_read_data(&definition, &stored.data);            Value::Array(std::iter::once(Value::from(stored.id.as_str()))                .chain(asked.iter().map(|key| data.get(key).cloned().unwrap_or(Value::Null))).collect())        }).collect());        // The rows moved in, never through `json!` (which would copy them).        let mut answer = json!({"table": definition.id, "columns": std::iter::once("id").chain(asked.iter().map(String::as_str)).collect::<Vec<_>>(), "next_page": next});        answer["rows"] = Value::Array(rows);        answer    } else {        json!({            "table": definition.id,            "records": page.records.iter().map(|stored| read_json(&definition, stored)).collect::<Vec<_>>(),            "next_page": next,        })    };    if total == Total::Counted && !view.cut {        answer["total"] = Value::from(page.total);    }    // A list read as a day plan says how many each section holds over the    // WHOLE list (`day_plan`), so a heading never counts only the rows read.    if let Some(sections) = extras.sections {        answer["sections"] = Value::from(sections);    }    if let Some(sectioned) = extras.sectioned.take() {        answer["sectioned"] = sectioned;    }    if let Some(summaries) = extras.summaries {        answer["summaries"] = json!(summaries);    }    // `heads: false` — a reader that keeps the heads its first read said (a    // whole list's cut) reads a page without reading every row again.    if args.get("heads") == Some(&Value::Bool(false)) {        return Ok(answer);    }    // A grouped list whose group says figures (`ListGrouping::summary`):    // each group's head lines, over ALL of that group's rows the list keeps,    // never only the page read.    if definition.group.as_ref().is_some_and(|group| !group.summary.is_empty()) {        answer["group_heads"] = json!(group_heads(ctx, &definition, &clauses)?);    } else if records::opening_column(&definition).is_some() {        let mut head = opening_head(ctx, &definition)?.unwrap_or(records::GroupHead { value: Value::Null, lines: Vec::new() });        let mut resolved = FigureRows::new();        // A runway's extrema read the SAME complete date window as its        // balances, never just the visible page, nor Home's default window.        let today = if money_runway::handles(&definition) {            let window = money_runway::window_for_list(ctx, &definition, &view)?;            resolved.insert(definition.id.clone(), money_runway::rows(&ctx.read, &definition, &window)?);            let zone = view.timezone.clone().unwrap_or(crate::mcp::handlers::common::workspace_timezone(ctx)?);            let day = view.today.clone().unwrap_or(crate::mcp::handlers::common::today_in(&zone, ctx.now.timestamp_millis())?);            chrono::NaiveDate::parse_from_str(&day, "%Y-%m-%d").map_err(|error| ToolFailure::new(error.to_string()))?        } else {            ctx.now.date_naive()        };        head.lines.extend(crate::tool_figures::running_head_lines(&ctx.read, &definition, today, &mut resolved));        if !head.lines.is_empty() {            answer["group_heads"] = json!([head]);        }    }    Ok(answer)}/// The line an ungrouped list says above its first row/// (`records::opening_head`): the opening the evaluator kept for its running.fn opening_head(ctx: &Ctx<'_>, definition: &TableDefinition) -> Valid<Option<records::GroupHead>> {    let Some((key, _)) = records::opening_column(definition) else { return Ok(None) };    let kept = |key: &str| -> Valid<Option<cotton_store::driver::Row>> {        ctx.read            .driver()            .get(                "SELECT value FROM _computed WHERE table_id = ? AND record_id = ? AND key = ?",                &[SqlValue::Text(definition.id.clone()), SqlValue::Text(crate::derive::OPENING_ROW.into()), SqlValue::Text(key.into())],            )            .map_err(sql_err)    };    let Some(opening) = kept(key)?.and_then(|row| row.int("value")) else { return Ok(None) };    let currency = kept(&crate::derive::opening_currency_key(key))?.and_then(|row| row.text("value").map(str::to_string));    Ok(records::opening_head(definition, &Value::from(opening), currency.as_deref(), &cotton_core::records::page::Words::of_rows(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id))))}/// The heads of a grouped list (`records::group_heads`) over every live row/// `clauses` keep, worked out by the file in one statement grouped by the/// group's column (`builtin::grouped`, or a made table's own): never a walk/// of the rows. A figure with its own `where` is one more statement over/// its rows; a group it keeps none of says that figure over nothing.fn group_heads(ctx: &Ctx<'_>, definition: &TableDefinition, clauses: &[records::WhereClause]) -> Valid<Vec<records::GroupHead>> {    let Some(group) = definition.group.as_ref().filter(|group| !group.summary.is_empty()) else {        return Ok(Vec::new());    };    let summaries = &group.summary;    let plain: Vec<&cotton_core::definitions::TileSummary> = summaries.iter().filter(|summary| summary.where_.is_none()).collect();    let mut heads: Vec<(Value, Vec<Option<records::SummaryValue>>)> = group_figures(ctx, definition, clauses, &group.column, &plain)?        .into_iter()        .map(|(value, said)| {            let mut said = said.into_iter();            let held = summaries.iter().map(|summary| if summary.where_.is_none() { said.next() } else { None }).collect();            (value, held)        })        .collect();    for (at, summary) in summaries.iter().enumerate().filter(|(_, summary)| summary.where_.is_some()) {        let filter = serde_json::to_value(summary.where_.as_ref()).map_err(sql_err)?;        let mut asked = clauses.to_vec();        asked.extend(records::parse_where(definition, Some(&filter)).map_err(refuse)?);        let found: std::collections::HashMap<String, records::SummaryValue> = group_figures(ctx, definition, &asked, &group.column, &[summary])?            .into_iter()            .filter_map(|(value, mut said)| Some((value.to_string(), said.pop()?)))            .collect();        for (value, held) in &mut heads {            held[at] = Some(found.get(&value.to_string()).cloned().unwrap_or_else(|| over_nothing(definition, summary)));        }    }    let words = cotton_core::records::page::Words::of_rows(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id));    Ok(heads        .into_iter()        .map(|(value, held)| records::group_head(definition, value, &held.into_iter().flatten().collect::<Vec<_>>(), &words))        .collect())}/// One figure over no rows: none counted, nothing summed, no least.fn over_nothing(definition: &TableDefinition, summary: &cotton_core::definitions::TileSummary) -> records::SummaryValue {    let value = if summary.op == cotton_core::definitions::SummaryOp::Count { Value::from(0) } else { Value::Null };    let (_, currency) = records::figure_columns(definition, summary);    records::figure_from_store(definition, summary, value, currency.map(|_| (0, None)))}/// Each group's value and `summaries`' figures over its rows, in one/// statement grouped by `column`: a built-in's through its source's SQL/// (`builtin::grouped`), a made table's over its own rows.fn group_figures(    ctx: &Ctx<'_>,    definition: &TableDefinition,    clauses: &[records::WhereClause],    column: &str,    summaries: &[&cotton_core::definitions::TileSummary],) -> Valid<Vec<(Value, Vec<records::SummaryValue>)>> {    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    let aggregates = |expr: &mut dyn FnMut(&str) -> Valid<String>| -> Valid<String> {        let mut out = vec!["COUNT(*) AS \"@rows\"".to_string()];        for (n, summary) in summaries.iter().enumerate() {            let (value, currency) = records::figure_columns(definition, summary);            out.push(match value {                None => format!("COUNT(*) AS f{n}"),                Some(value) => {                    let value = expr(&value.key)?;                    match summary.op {                        cotton_core::definitions::SummaryOp::Min => format!("MIN({value}) AS f{n}"),                        cotton_core::definitions::SummaryOp::Max => format!("MAX({value}) AS f{n}"),                        _ => format!("SUM(CASE WHEN typeof({value}) IN ('integer', 'real') THEN {value} END) AS f{n}"),                    }                }            });            if let Some(currency) = currency {                let currency = expr(currency)?;                let text = format!("CASE WHEN typeof({currency}) = 'text' THEN {currency} END");                out.push(format!("COUNT(DISTINCT {text}) AS f{n}_currencies, MIN({text}) AS f{n}_currency"));            }        }        Ok(out.join(", "))    };    let groups = if is_user_table(definition) {        if !made_held(ctx, definition.rows_table())? {            return Ok(Vec::new());        }        let mut columns = UserColumns::new(definition);        let mut sql = String::from(" WHERE r.workspace_id = ? AND r.deleted_at IS NULL");        let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];        for clause in clauses {            user_where(&mut columns, clause, &mut sql, &mut params, &zone);        }        let group_expr = columns.expr(column, &mut params);        let selected = aggregates(&mut |column_name: &str| Ok(columns.expr(column_name, &mut Vec::new())))?;        let (from, mut bound) = columns.from();        bound.extend(params);        let grouped = definition.column(column);        ctx.read            .driver()            .all(&format!("SELECT {group_expr} AS \"@group\", {selected}{from}{sql} GROUP BY 1 ORDER BY 1"), &bound)            .map_err(sql_err)?            .into_iter()            .map(|row| (grouped.and_then(|grouped| made_value(grouped, row.get("@group"))).unwrap_or(Value::Null), row))            .collect()    } else {        builtin::grouped(ctx, definition, clauses, column, aggregates)?    };    Ok(groups        .into_iter()        .map(|(value, row)| {            let said = summaries                .iter()                .enumerate()                .map(|(n, summary)| {                    let (column, currency) = records::figure_columns(definition, summary);                    let figure = row.get(&format!("f{n}"));                    let figure = match column {                        Some(column) => crate::derive::stored_value(figure, column.column_type),                        None => crate::derive::stored_value(figure, cotton_core::definitions::ColumnType::Number),                    };                    let currencies = currency.map(|_| {                        (row.int(&format!("f{n}_currencies")).unwrap_or(0), row.text(&format!("f{n}_currency")).map(str::to_string))                    });                    records::figure_from_store(definition, summary, figure, currencies)                })                .collect();            (value, said)        })        .collect())}/// `archived: true` — the table's archive instead of its list — refused on a/// table whose records are never archived, and beside `ids` or a group,/// which name their records themselves.fn archived_arg<'a>(    definition: &'a TableDefinition,    args: &Map<String, Value>,) -> Valid<Option<Archive<'a>>> {    match args.get("archived") {        None | Some(Value::Null | Value::Bool(false)) => Ok(None),        Some(Value::Bool(true)) => {            let archive = archive_of(definition).ok_or_else(|| {                ToolFailure::new(format!("{} are never archived", definition.plural))            })?;            if args.get("ids").is_some_and(|ids| !ids.is_null()) {                return Err(ToolFailure::new("ids names the records itself; ask without archived",                ));            }            if groups::named_in_where(definition, args).is_some() {                return Err(ToolFailure::new("A group lists its live records; ask without archived",                ));            }            Ok(Some(archive))        }        Some(_) => Err(ToolFailure::new("archived is true or false")),    }}/// The list's own records (`shows`), as clauses on every column of it the/// read's `where` does not name itself: the Money list is the places money/// sits, and a read of the settled ledgers names `section` and gets them.fn shown(definition: &TableDefinition, asked: &[records::WhereClause],) -> Valid<Vec<records::WhereClause>> {    let mut clauses = viewed(definition)?;    let Some(shows) = &definition.shows else {        return Ok(clauses);    };    let shows = serde_json::to_value(shows).map_err(sql_err)?;    clauses.extend(records::parse_where(definition, Some(&shows))        .map_err(refuse)?        .into_iter()        .filter(|clause| !asked.iter().any(|asked| asked.column == clause.column)));    Ok(clauses)}/// A view's own rows among its source's (`TableDefinition::source`): its/// where holds on every read of it, and no ask widens it — unlike `shows`,/// a default an ask on the same column replaces.pub(crate) fn viewed(definition: &TableDefinition) -> Valid<Vec<records::WhereClause>> {    let Some(where_) = definition.source.as_ref().and_then(|source| source.where_.as_ref()) else {        return Ok(Vec::new());    };    let where_ = serde_json::to_value(where_).map_err(sql_err)?;    records::parse_where(definition, Some(&where_)).map_err(refuse)}/// `list_records { table, ids }`: the live records among `ids`, in the order/// asked — one read of each by its id, so a caller that holds a page's links/// (the app's link titles) never pages the whole linked table to find them./// An id with no live record is left out, as a deleted record is from any/// list. `ids` narrows alone: with `project`, `query`, `where`, `page` or/// `limit` beside it the ask is refused, never half-honoured.fn list_by_ids(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    ids: &Value,    args: &Map<String, Value>,) -> ToolResult {    if let Some(other) = ["project", "query", "where", "page", "limit", "section", "day",    ]        .into_iter()        .find(|key| args.get(*key).is_some_and(|value| !value.is_null()))    {        return Err(ToolFailure::new(format!(            "ids names the records itself; ask without {other}"        )));    }    let ids: Vec<&str> = match ids.as_array() {        Some(ids) if !ids.is_empty() && ids.len() as i64 <= MAX_PAGE_SIZE => ids            .iter()            .map(|id| id.as_str().map(str::trim).filter(|id| !id.is_empty()))            .collect::<Option<_>>()            .ok_or_else(|| ToolFailure::new("each of ids is one record id"))?,        _ => {            return Err(ToolFailure::new(format!(                "ids is a list of 1 to {MAX_PAGE_SIZE} record ids"            )))        }    };    if definition.derived == Some(true) {        crate::mcp::handlers::money_views::validate_view_day(ctx, &definition.id, args)            .map_err(ToolFailure::new)?;    }    let runway = if money_runway::handles(definition) {        let window = money_runway::window_for_list(ctx, definition, &day_plan::View::of(args))?;        Some(money_runway::rows(&ctx.read, definition, &window)?)    } else { None };    let mut seen = std::collections::HashSet::new();    let mut records = Vec::new();    // A page's ids of a built-in read together, never one read each: in the    // order asked, each once, a record no longer live left out.    let occurrences = definition.rows_table() == "transaction"        && ids.iter().any(|id| crate::mcp::handlers::money::occurrences::identity(id).is_some());    if runway.is_none() && !occurrences && !is_user_table(definition) {        let asked: Vec<&str> = ids.iter().copied().filter(|id| seen.insert(*id)).collect();        if let Some(mut read) = builtin::read_many(ctx, definition, &asked)? {            own_values::merge(ctx, definition, &mut read)?;            served_values::merge(ctx, definition, &mut read)?;            let mut by_id: std::collections::HashMap<String, Stored> = read.into_iter().map(|stored| (stored.id.clone(), stored)).collect();            records.extend(asked.iter().filter_map(|id| by_id.remove(*id)).filter(|stored| stored.deleted_at.is_none()));            return ids_answer(ctx, definition, records, args);        }        seen.clear();    }    for id in ids {        if !seen.insert(id) {            continue;        }        let stored = if let Some(runway) = &runway {            runway.iter().find(|stored| stored.id == id).cloned()        } else if definition.rows_table() == "transaction" {            if let Some((source, _)) = crate::mcp::handlers::money::occurrences::identity(id) {                let mut stored = load(ctx, definition, source)?.filter(|stored| stored.deleted_at.is_none());                if let Some(stored) = &mut stored {                    if let Some((_, occurrence)) = crate::mcp::handlers::money::occurrences::resolve(&ctx.read, id)? {                        at_money_occurrence(stored, id, &occurrence);                    }                }                stored            } else { load(ctx, definition, id)? }        } else { load(ctx, definition, id)? };        if let Some(stored) = stored.filter(|stored| stored.deleted_at.is_none()) {            records.push(stored);        }    }    ids_answer(ctx, definition, records, args)}/// `list_by_ids`' answer over the records it read, derived as a list's.fn ids_answer(ctx: &mut Ctx<'_>, definition: &TableDefinition, mut records: Vec<Stored>, args: &Map<String, Value>) -> ToolResult {    derive_records(ctx, definition, &mut records, args, false)?;    Ok(json!({        "table": definition.id,        "records": records.iter().map(|stored| read_json(definition, stored)).collect::<Vec<_>>(),        "next_page": Value::Null,        "total": records.len(),    }))}/// `get_record_by_table { table, id }` → the record, deleted or not.pub fn get_record_by_table(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let definition = table_arg(ctx, args)?;    let id = record_id_arg(ctx, args)?;    if definition.engine.as_deref() == Some("everything") {        return everything::get(ctx, &id);    }    if definition.derived == Some(true) {        crate::mcp::handlers::money_views::validate_view_day(ctx, &definition.id, args)            .map_err(ToolFailure::new)?;    }    // A move retracts the source rows, so its tombstone is asked for only    // when the table no longer holds the id: the history is unindexed by    // record, and reading it before every get cost a phone's page its first    // draw (threadload, 16 Oct 2026).    let Some(mut stored) = load(ctx, &definition, &id)? else {        if let Some(moved) = crate::mcp::record_moves::lookup_moved(ctx.db(), &id)            .map_err(|error| ToolFailure::new(error.to_string()))?        {            return Ok(moved);        }        return Err(not_found(&definition, &id).into());    };    if let Some((_, starts)) = optional_string(args, "id").as_deref().and_then(occurrence_of) {        at_occurrence(&mut stored, starts);    }    if let Some(asked) = optional_string(args,"id") {        if let Some((_,occurrence)) = crate::mcp::handlers::money::occurrences::resolve(&ctx.read,&asked)? {            at_money_occurrence(&mut stored, &asked, &occurrence);            if money_runway::handles(&definition) {                let view=day_plan::View::of(args);                let window=money_runway::window_for_list(ctx,&definition,&view)?;                if let Some(found)=money_runway::rows(&ctx.read,&definition,&window)?.into_iter().find(|row|row.id==asked) {stored=found;}            }        }    }    derive_records(ctx, &definition, std::slice::from_mut(&mut stored), args, true,    )?;    let mut page = read_json(&definition, &stored);    let unavailable = super::tool_packages::computed_unavailable(ctx.db(), ctx.workspace_id, &definition)?;    if !unavailable.is_empty() {        page["computed_unavailable"] = serde_json::to_value(unavailable).map_err(sql_err)?;    }    if let Some(name) = edited_by(ctx, &definition, &id) {        page["edited_by"] = Value::from(name);    }    let person = edited_by_person(ctx, &definition, &id);    page["edited_by_person_id"] = person        .as_ref()        .map(|p| Value::from(p.person_id.clone()))        .unwrap_or(Value::Null);    page["edited_by_photo_key"] = person        .and_then(|p| p.photo_key)        .map(Value::from)        .unwrap_or(Value::Null);    Ok(page)}/// A repeating event read at one later occurrence: its id that occurrence's,/// its start that time and its end as long after as the series' is.fn at_money_occurrence(stored: &mut Stored, asked: &str, occurrence: &Data) {    stored.id = asked.into();    for key in ["occurred_on", "due_date", "for_period", "stored_id", "occurrence_index"] {        if let Some(value) = occurrence.get(key) { stored.data.insert(key.into(), value.clone()); }    }}fn at_occurrence(stored: &mut Stored, starts: &str) {    use crate::mcp::handlers::common::{parse_ms, text};    let length = match (text(&stored.data, "starts_at"), text(&stored.data, "ends_at"),    ) {        (Some(from), Some(to)) => parse_ms(&to).zip(parse_ms(&from)).map(|(to, from)| to - from),        _ => None,    };    let ends = match (length, parse_ms(starts)) {        (Some(length), Some(at)) => chrono::DateTime::from_timestamp_millis(at + length)            .map(|end| Value::from(end.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string())),        _ => None,    };    stored.id = format!("{}@{starts}", stored.id);    stored.data.insert("starts_at".into(), Value::from(starts));    if let Some(ends) = ends {        stored.data.insert("ends_at".into(), ends);    }}/// The BYLINE of a record in a SHARED database: the name of the person whose/// device last wrote its row ([`cotton_store::membership::author_name`]), for/// the page's Edited line to read "by Ben". The personal database has one/// writer and names nobody; a row whose author cannot be named has none.fn edited_by(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Option<String> {    let db = ctx.read.driver();    let shared = db        .get(            "SELECT kind FROM cotton_workspaces WHERE id = ?",            &[SqlValue::Text(ctx.workspace_id.to_string())],        )        .ok()        .flatten()        .is_some_and(|row| row.text("kind") == Some("shared"));    if !shared {        return None;    }    let table = if is_user_table(definition) {        made_table(definition.rows_table())    } else {        cotton_core::definitions::builtin_store_table(&definition.id)?.to_string()    };    let storage_id = if definition.has_engine() && definition.id == "device" {        device_words::approval_for(ctx, id).ok().flatten()?    } else {        id.to_string()    };    let hlc = db        .get(            &format!("SELECT _hlc FROM {table} WHERE workspace_id = ? AND id = ?"),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(storage_id),            ],        )        .ok()        .flatten()        .and_then(|row| row.text("_hlc").map(str::to_string))?;    cotton_store::membership::author_name(db, &hlc).ok().flatten()}// ── writes ──────────────────────────────────────────────────────────────────fn edited_by_person(    ctx: &Ctx<'_>,    definition: &TableDefinition,    id: &str,) -> Option<cotton_store::member_person::BoundPerson> {    let db = ctx.read.driver();    if !db        .get(            "SELECT kind FROM cotton_workspaces WHERE id=?",            &[SqlValue::Text(ctx.workspace_id.to_string())],        )        .ok()        .flatten()        .is_some_and(|r| r.text("kind") == Some("shared"))    {        return None;    }    let table = if is_user_table(definition) {        made_table(definition.rows_table())    } else {        cotton_core::definitions::builtin_store_table(&definition.id)?.to_string()    };    let storage_id = if definition.has_engine() && definition.id == "device" {        device_words::approval_for(ctx, id).ok().flatten()?    } else {        id.to_string()    };    let hlc = db        .get(            &format!("SELECT _hlc FROM {table} WHERE workspace_id=? AND id=?"),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(storage_id),            ],        )        .ok()        .flatten()?        .text("_hlc")?        .to_owned();    cotton_core::keys::member_actions::author_person(db, ctx.workspace_id, &hlc)        .ok()        .flatten()}fn data_arg<'a>(args: &'a Map<String, Value>, key: &str) -> Valid<&'a Value> {    args.get(key).ok_or_else(|| {        ToolFailure::new(format!(            "{key} is required: an object of column keys and values"        ))    })}/// `create_record { table, data }` → `{ change, record }` — or, where the/// write cannot be made until the person picks one value, `{ ask }`/// ([`cotton_core::records::receipt::Ask`]) and nothing is written: the/// caller sends the same create again with the ask's column set.pub fn create_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let written = create_record_now(ctx, args)?;        if written.get("ask").is_some() {            return Ok(written);        }        automations::run(ctx, written)    })}/// A trusted Rust producer fills a definition-owned table's facts. This is/// deliberately absent from MCP dispatch: authored writes still honor readonly./// Type checks, links, receipts, transactions and automations are shared.pub fn create_produced_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let signed = byline(ctx);        let written = create_record_as(ctx, args, &signed, true)?;        automations::run(ctx, written)    })}/// A trusted import keeps the source namespace and id on the row. Repeated/// arrivals return that row unchanged, even when source fields have changed./// This is shared by every importer and is absent from public tool dispatch.pub fn create_imported_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let written = create_imported_record_now(ctx, args)?;        if written["change"].is_null() { return Ok(written); }        automations::run(ctx, written)    })}// Shared by ordinary imports and capacity-checked imports. A reservation runs// its automations after closing Writing, so a rule cannot bypass capacity.fn create_imported_record_now(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let definition=table_arg(ctx,args)?;    if !is_user_table(&definition) || !definition.column("import_id").is_some_and(|c|c.column_type==cotton_core::definitions::ColumnType::Text) {        return Err(ToolFailure::new("This table needs an import id text column"));    }    let data=data_arg(args,"data")?;    let source=data.get("import_id").and_then(Value::as_str).filter(|s|s.split_once(':').is_some_and(|(source,id)|!source.trim().is_empty()&&!id.trim().is_empty()))        .ok_or_else(||ToolFailure::new("Import id needs a source and its id, like parse:abc123"))?;    let found=ctx.db().all(&format!("SELECT * FROM {} WHERE workspace_id=? AND import_id=?",made_table(definition.rows_table())),        &[ctx.workspace_id.to_owned().into(),source.to_owned().into()]).map_err(sql_err)?;    if found.len()>1 {return Err(ToolFailure::new("More than one row has this import id"));}    if let Some(row)=found.first() {return Ok(json!({"change":null,"record":read_json(&definition,&stored_from_row(&definition,row))}));}    let signed=byline(ctx);    create_record_as(ctx,args,&signed,true)}/// The update half of the trusted producer path; never a public tool verb.pub fn update_produced_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let written = update_record_now_as(ctx, args, true)?;        automations::run(ctx, written)    })}/// Who authors this write, for the readonly rule: the typed actor comes from/// authentication, never tool arguments or bylines. The owner or a member at/// a device's screen is the app.fn author<'a>(ctx: &'a Ctx<'_>) -> records::Author<'a> {    use cotton_store::actor::Actor;    match ctx.writer_actor() {        Some(Actor::Token(id)) => records::Author::Token(id.as_str()),        Some(Actor::Owner(_) | Actor::Member(_)) => records::Author::App,        _ => records::Author::Other,    }}fn validation_definition(definition: &TableDefinition, producer: bool) -> TableDefinition {    let mut checked = definition.clone();    // Native tables still run their own engine's write policy below.    if producer && !definition.has_engine() {        for column in &mut checked.columns {            column.readonly = Some(false);        }    }    checked}/// A record made in `table` from `data` inside a caller's own transaction —/// `create_record` without its `atomically`, automations included — so a/// thought filed into any table is made the way every record is.pub fn create_record_within(ctx: &mut Ctx<'_>, table: &str, data: Value) -> ToolResult {    let args = json!({ "table": table, "data": data });    let args = args.as_object().expect("an object");    let written = create_record_now(ctx, args)?;    if written.get("ask").is_some() {        return Ok(written);    }    automations::run(ctx, written)}/// The add that made `record_id` in `table`, taken back by that add's own/// Undo — refused, as every Undo is, when the record changed since.pub fn take_back_add(ctx: &mut Ctx<'_>, table: &str, record_id: &str) -> ToolResult {    let made = add_of(ctx, table, record_id)?.ok_or_else(|| {        ToolFailure::new("the add that made it is not recorded here, so it stays")    })?;    let args = json!({ "change_id": made });    automations::undo_group(ctx, args.as_object().expect("an object"))}/// The change id of the latest add that made `record_id` in `table`.fn add_of(ctx: &Ctx<'_>, table: &str, record_id: &str) -> Valid<Option<String>> {    Ok(ctx        .read        .driver()        .get(            &format!(                "SELECT id FROM {CHANGES} WHERE workspace_id = ? AND table_id = ? AND record_id = ? \                 AND verb = ? ORDER BY COALESCE(NULLIF(_born, ''), _hlc) DESC LIMIT 1"            ),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(table.to_string()),                SqlValue::Text(record_id.to_string()),                SqlValue::Text(Verb::Create.as_str().to_string()),            ],        )        .map_err(sql_err)?        .and_then(|row| row.text("id").map(str::to_string)))}fn create_record_now(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = &*through_view(ctx, args, true)?;    let signed = byline(ctx);    let definition = table_arg(ctx, args)?;    let held = held_from_birth(ctx, &definition, args)?;    if let Some(table) = &held {        ctx.writer()?.holding_next_create(table);    }    let written = create_record_as(ctx, args, &signed, false).map_err(|refusal| said_to(ctx, &definition, refusal))?;    if held.is_some() {        let writer = ctx.writer()?;        if written.get("ask").is_some() {            writer.drop_hold();        } else if writer.hold_waiting() {            writer.drop_hold();            return Err(ToolFailure::new(ONE_WRITE_REFUSAL));        }    }    Ok(written)}/// What a create asked to be only-you is refused with when its record was/// not minted in the same act as its mark.pub const ONE_WRITE_REFUSAL: &str =    "a record made only-you is written with its mark in one write, and this one was not: nothing was kept";/// The physical table a create's `audience: "only_you"` holds its record in/// — the new-record form's Only you, the owner's own choice at their app/// (`cotton_store::audience`). `None` for no audience, or `everyone`, which/// every record already is. An assistant never chooses it: `set_audience` is/// the owner's act, and so is its form twin.fn held_from_birth(ctx: &Ctx<'_>, definition: &TableDefinition, args: &Map<String, Value>) -> Valid<Option<String>> {    let Some(audience) = args.get("audience").filter(|value| !value.is_null()) else {        return Ok(None);    };    let audience = audience.as_str().unwrap_or_default();    if !cotton_store::audience::AUDIENCES.contains(&audience) {        return Err(ToolFailure::new(format!("audience is one of {}", cotton_store::audience::AUDIENCES.join(", "))));    }    if audience != cotton_store::audience::ONLY_YOU {        return Ok(None);    }    if !ctx.is_owner_app() {        return Err(ToolFailure::new("only the owner's own app makes a record only-you"));    }    let target = crate::mcp::handlers::keep_rules::record_target(&cotton_store::keep::record_target_of(&definition.id, "_"));    Ok(cotton_store::keep::record_target(&target).map(|(table, _)| table.to_string()))}/// A refusal as its reader needs it. An assistant is told the column's KEY —/// the word it writes next. The owner's own app shows the sentence to a/// person, who has only ever seen the column's name on the page: every key of/// the table the sentence quotes becomes that name, and the verbs' own/// plumbing is not mentioned.fn said_to(ctx: &Ctx<'_>, definition: &TableDefinition, refusal: ToolFailure) -> ToolFailure {    if !ctx.is_owner_app() {        return refusal;    }    let mut sentence = refusal.message().replace(" through the generic verbs", "");    for column in &definition.columns {        sentence = sentence.replace(&format!("{:?}", column.key), &column.label());    }    ToolFailure::new(sentence)}/// A package's sample row, created the way any record is — defaults filled,/// every value checked, automations run — under the byline "sample", so the/// rows a tool came with are told apart from the owner's own. A shipped/// table's record carries it on its create change (`cotton_changes.byline`),/// which later edits never rewrite: that row is what `samples` finds again.pub const SAMPLE_BYLINE: &str = "sample";pub fn create_sample_record(ctx: &mut Ctx<'_>, table: &str, data: &Value) -> ToolResult {    let args = json!({ "table": table, "data": data });    let args = args.as_object().expect("an object");    atomically_noted(ctx, |ctx| {        let written = {            let _sample = automations::Bylined::as_label(SAMPLE_BYLINE);            create_record_as(ctx, args, SAMPLE_BYLINE, false)?        };        automations::run(ctx, written)    })}/// A saved page whose address was typed where its title goes. The app's one/// input writes what was typed into a table's title column, and on Reader/// what is typed is the address: read as a title it left the required Link/// empty and the save was refused for a missing link the person had just/// given. `None` when the data names its own `url`, or the title is words.fn typed_address(data: &Map<String, Value>) -> Option<Map<String, Value>> {    if data.get("url").is_some_and(|url| !url.is_null()) {        return None;    }    let typed = data.get("title")?.as_str()?.trim();    let address = as_address(typed)?;    let mut out = data.clone();    out.remove("title");    out.insert("url".into(), Value::from(address));    Some(out)}/// `typed` as a web address — as it stands with its scheme, or with `https://`/// put before a bare host ("example.com/a") — or `None` for anything else.fn as_address(typed: &str) -> Option<String> {    if typed.is_empty() || typed.chars().any(char::is_whitespace) {        return None;    }    let lower = typed.to_ascii_lowercase();    if lower.starts_with("http://") || lower.starts_with("https://") {        return Some(typed.to_string());    }    if typed.contains("://") {        return None;    }    let host = typed.split(['/', '?', '#']).next().unwrap_or_default();    let mut labels = host.split('.');    let well_formed = host.contains('.')        && labels.all(|label| {            !label.is_empty() && label.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')        })        && host            .rsplit('.')            .next()            .is_some_and(|tld| tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()));    well_formed.then(|| format!("https://{typed}"))}fn create_record_as(ctx: &mut Ctx<'_>, args: &Map<String, Value>, byline: &str, producer: bool) -> ToolResult {    let definition = table_arg(ctx, args)?;    reservations::require_action(ctx, &definition.id)?;    // A built-in that takes no create says where it is made before any value    // is checked: a missing required column is not the reason.    if !is_user_table(&definition) {        builtin::creatable(&definition)?;    }    // Capture inputs build immutable lines once. They remain read-only on    // existing pages; this create-only validation exception does not permit patches.    let mut create_definition = validation_definition(&definition, producer);    // This page field is an engine input even though its rows draw it as an    // immutable fact. The dictation adapter is the only writer.    if definition.id == "voice_word" {        if let Some(column) = create_definition.columns.iter_mut().find(|column| column.key == "term") {            column.readonly = Some(false);        }    }    let worded = match data_arg(args, "data")? {        Value::Object(data) if definition.id == "page" => typed_address(data).map(Value::Object),        _ => None,    };    let data = match &worded {        Some(data) => data,        None => data_arg(args, "data")?,    };    let values = records::validate_create_as(&create_definition, data, author(ctx)).map_err(refuse)?;    let values = place_values::resolve(ctx, &definition, &values, None)?;    check_links(ctx, &definition, &values)?;    if !is_user_table(&definition) {        let (values, own) = own_values::split(&definition, &values);        let mut written = builtin::create(ctx, &definition, &values)?;        if let Some(id) = written["record"]["id"].as_str().map(str::to_string).filter(|_| !own.is_empty()) {            own_values::write(ctx, &definition, &id, &own)?;            ctx.commit()?;            if let Some(data) = written["record"]["data"].as_object_mut() {                data.extend(own.into_iter().filter(|(_, value)| !value.is_null()));                records::project_read_data(&definition, data);            }        }        return Ok(written);    }    let id = if let Some(key) = &definition.row_key {        let id = values.get(key).and_then(Value::as_str).filter(|value| !value.trim().is_empty())            .ok_or_else(|| refuse(RecordError::Required { column: key.clone() }))?.to_string();        if load(ctx, &definition, &id)?.is_some() {            return patch_record(ctx, &definition, &id, &values, Verb::Update);        }        id    } else { ctx.new_uuid() };    let mut patch = values.clone();    patch.retain(|_, value| !value.is_null());    let now = now_iso(ctx);    patch.insert("id".into(), Value::from(id.clone()));    patch.insert("created_at".into(), Value::from(now.clone()));    patch.insert("updated_at".into(), Value::from(now));    patch.insert(MADE_BYLINE.into(), Value::from(byline));    made_ready(ctx, &definition)?;    insert_row(ctx, &made_table(definition.rows_table()), &id, patch)?;    ctx.commit()?;    let stored = load_live(ctx, &definition, &id)?;    let change = record_change(        ctx,        &definition.id,        Some(id.as_str()),        Verb::Create,        Value::Null,        Value::Object(stored.data.clone()),    )?;    ctx.commit()?;    Ok(answer(ctx, &definition, &change, Some(&stored)))}/// Write `values` over a user-table record — only the columns that moved.fn write_user(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    before: &Stored,    values: &Data,) -> Valid<()> {    // Each column is its own: the write names every key that moved, and a    // key that went away is named with null.    let mut patch = Map::new();    for (key, value) in values {        if before.data.get(key) != Some(value) {            patch.insert(key.clone(), value.clone());        }    }    for key in before.data.keys() {        if !values.contains_key(key) {            patch.insert(key.clone(), Value::Null);        }    }    patch.insert(MADE_BYLINE.into(), Value::from(byline(ctx)));    patch.insert("updated_at".into(), Value::from(now_iso(ctx)));    update_row(ctx, &made_table(definition.rows_table()), &before.id, patch)?;    ctx.commit()}/// Patch one record and record the change as `verb` (update or link).fn patch_record(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    patch: &Data,    verb: Verb,) -> ToolResult {    // A write of a built-in's archive column is the one edit an archived    // record takes (it comes back) and the one that leaves it archived.    let gone = !is_user_table(definition) && builtin::names_gone(definition, patch);    let before = if gone {        load(ctx, definition, id)?.ok_or_else(|| not_found(definition, id))?    } else {        load_live(ctx, definition, id)?    };    records::validate_reveal_patch(definition, &before.data, patch).map_err(refuse)?;    let wanted = records::apply_patch(&before.data, patch);    if let Some(key) = &definition.row_key {        if wanted.get(key) != before.data.get(key) {            return Err(refuse(RecordError::Readonly { column: key.clone() }));        }    }    if records::same_record(&wanted, &before.data) {        return Err(refuse(RecordError::NothingToChange));    }    let beside_was = beside_now(ctx, definition, id, &before.data)?;    if is_user_table(definition) {        write_user(ctx, definition, &before, &wanted)?;    } else {        // The engine takes its own columns; an added column's value is kept        // beside it (`own_values`).        let (engine, own) = own_values::split(definition, patch);        if !engine.is_empty() || own.is_empty() {            builtin::update(ctx, definition, id, &engine)?;        }        if !own.is_empty() {            own_values::write(ctx, definition, id, &own)?;            ctx.commit()?;        }    }    // A write whose own tool takes the record away (a run's Cancel deletes    // its queue row) leaves no record to read back: its change says what was    // written, and the answer's record is null.    let after = if activity_tables::update_takes_it_away(definition) {        load(ctx, definition, id)?.filter(|after| after.deleted_at.is_none())    } else if gone {        load(ctx, definition, id)?    } else {        Some(load_live(ctx, definition, id)?)    };    let after_data = after.as_ref().map_or(&wanted, |after| &after.data);    let (mut was, mut now) = records::diff(&before.data, after_data);    if now.is_empty() {        // The record's own tool took the write and kept nothing different —        // there is no change to record, and saying one happened would be false.        return Err(refuse(RecordError::NothingToChange));    }    carry_edited(definition, &before, &mut was);    definition_writes::carry_theme_override(&beside_was, &mut was);    now.extend(records::beside_moved(        &beside_was,        &beside_now(ctx, definition, id, after_data)?,    ));    let change = record_change(        ctx,        &definition.id,        Some(id),        verb,        Value::Object(was),        Value::Object(now),    )?;    ctx.commit()?;    // Mutation history keeps stored choices (including NULL defaults); the    // returned device row wears the same effective readings as a fresh get.    let mut shown = after.clone();    if let Some(record) = shown.as_mut() {        device_words::device_words(ctx, definition, std::slice::from_mut(record), None)?;    }    Ok(answer(ctx, definition, &change, shown.as_ref()))}/// `update_record { table, id, patch }` → `{ change, record }`.pub fn update_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let written = update_record_now(ctx, args)?;        automations::run(ctx, written)    })}fn update_record_now(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    update_record_now_as(ctx, args, false)}fn update_record_now_as(ctx: &mut Ctx<'_>, args: &Map<String, Value>, producer: bool) -> ToolResult {    let args = &*through_view(ctx, args, false)?;    let definition = table_arg(ctx, args)?;    reservations::require_action(ctx, &definition.id)?;    let id = record_id_arg(ctx, args)?;    let checked = validation_definition(&definition, producer);    // A readonly column sent back with the value the row holds is not a write to it.    // Read in any state: whether an archived or missing record takes the    // patch is `patch_record`'s to say (bringing one back is the one edit    // an archived built-in takes).    let patch = data_arg(args, "patch")?;    let asked = match load(ctx, &definition, &id)? {        Some(stored) => records::without_unchanged_readonly(&checked, patch, &stored.data),        None => patch.clone(),    };    let patch = records::validate_patch_as(&checked, &asked, author(ctx))        .map_err(|error| said_to(ctx, &definition, refuse(error)))?;    let patch = place_values::resolve(ctx, &definition, &patch, Some(&id))?;    check_links(ctx, &definition, &patch)?;    if !is_user_table(&definition) {        builtin::writable(&definition).map_err(|refusal| said_to(ctx, &definition, refusal))?;    }    let patch = if definition.id == "event" && !is_user_table(&definition) {        let asked = optional_string(args, "id").unwrap_or_else(|| id.clone());        match repeating_event_edit(ctx, &definition, &asked, &id, patch, optional_string(args, "scope").as_deref(),        )            .map_err(|refusal| said_to(ctx, &definition, refusal))?        {            SeriesEdit::Series(patch) => patch,            SeriesEdit::Answered(answer) => return Ok(answer),        }    } else {        patch    };    patch_record(ctx, &definition, &id, &patch, Verb::Update)        .map_err(|refusal| said_to(ctx, &definition, refusal))}/// Which row a delete of a repeating event removes — never silent about its/// reach (architect, 5 Oct): without `scope` it is refused with the question;/// `"all"` is the series; `"this"` makes the day the id names its own row/// first, so that day alone goes to the bin as "<title> on <day>" and comes/// back from there or by Undo, the rest of the series untouched.fn repeating_event_delete(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    asked: &str,    series: &str,    scope: Option<&str>,) -> Valid<String> {    use crate::mcp::handlers::common::text;    let stored = load_live(ctx, definition, series)?;    if !text(&stored.data, "rrule").is_some_and(|rule| !rule.trim().is_empty()) {        return Ok(series.to_string());    }    let title = text(&stored.data, "title").unwrap_or_else(|| "This event".into());    match scope {        Some("all") => Ok(series.to_string()),        Some("this") => {            let occurrence_at = match occurrence_of(asked) {                Some((_, starts)) => starts.to_string(),                None => {                    text(&stored.data, "starts_at").ok_or_else(|| not_found(definition, series))?                }            };            let mut same = Data::new();            same.insert("title".into(), Value::from(title));            builtin::event_occurrence_update(ctx, definition, series, &occurrence_at, &same)        }        Some(other) => Err(ToolFailure::new(format!(            "scope is \"this\" (Only this one) or \"all\" (Every one), not {other:?}"        ))),        None => Err(ToolFailure::new(format!(            "{title} repeats — delete only this one, or every one? Send scope \"this\" or \"all\"."        ))),    }}/// What an edit of a repeating event comes to.enum SeriesEdit {    /// Every one: this patch, written to the series.    Series(Data),    /// Only this one: done, and this is the answer.    Answered(Value),}/// The columns an edit of one day of a repeating event can change — what/// that day's own row holds apart from the series.const OCCURRENCE_COLUMNS: [&str; 6] = ["title", "starts_at", "ends_at", "all_day", "location", "notes",];/// An edit of a repeating event is never silent about its reach (architect,/// 5 Oct): without `scope` it is refused with the question; `"this"` makes/// the day it names (`<series>@<start>`, or the series' own first day) its own/// row and leaves the series as it was; `"all"` changes the series — a time/// moved on a later day moves every day by the same amount. A one-off event,/// and one day already its own row, are edited as they are.fn repeating_event_edit(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    asked: &str,    series: &str,    mut patch: Data,    scope: Option<&str>,) -> Valid<SeriesEdit> {    use crate::mcp::handlers::common::{iso_of_ms, parse_ms, text};    let stored = load_live(ctx, definition, series)?;    let repeats = text(&stored.data, "rrule").is_some_and(|rule| !rule.trim().is_empty());    let reaches_a_day = patch.keys().any(|key| OCCURRENCE_COLUMNS.contains(&key.as_str()) || key == "rrule");    if !repeats || !reaches_a_day {        return Ok(SeriesEdit::Series(patch));    }    let day = occurrence_of(asked).map(|(_, starts)| starts.to_string());    match scope {        Some("all") => {            // A time given for a later day is that day's: the series moves by            // the same amount, from its own first day.            if let Some(day) = day.as_deref().and_then(parse_ms) {                let first = text(&stored.data, "starts_at").as_deref().and_then(parse_ms);                if let Some(first) = first {                    for key in ["starts_at", "ends_at"] {                        if let Some(at) = patch.get(key).and_then(Value::as_str).and_then(parse_ms) {                            patch.insert(key.into(), Value::from(iso_of_ms(at - day + first)));                        }                    }                }            }            Ok(SeriesEdit::Series(patch))        }        Some("this") => {            if patch.contains_key("rrule") {                return Err(ToolFailure::new(                    "How an event repeats belongs to every day of it — change it with scope \"all\" (Every one)",                ));            }            let occurrence_at = match day {                Some(day) => day,                None => {                    text(&stored.data, "starts_at").ok_or_else(|| not_found(definition, series))?                }            };            let mut before = stored.clone();            if occurrence_of(asked).is_some() {                at_occurrence(&mut before, &occurrence_at);            }            let own = builtin::event_occurrence_update(ctx, definition, series, &occurrence_at, &patch)?;            let after = load_live(ctx, definition, &own)?;            let (mut was, mut now) = records::diff(&before.data, &after.data);            // Only the day's own columns: Undo writes `was` back to the day's            // row, which must never be given the series' repeat.            was.retain(|key, _| OCCURRENCE_COLUMNS.contains(&key.as_str()));            now.retain(|key, _| OCCURRENCE_COLUMNS.contains(&key.as_str()));            if now.is_empty() {                return Err(refuse(RecordError::NothingToChange));            }            let change = record_change(ctx, &definition.id, Some(&own), Verb::Update, Value::Object(was), Value::Object(now),            )?;            ctx.commit()?;            Ok(SeriesEdit::Answered(answer(ctx, definition, &change, Some(&after),            )))        }        Some(other) => Err(ToolFailure::new(format!(            "scope is \"this\" (Only this one) or \"all\" (Every one), not {other:?}"        ))),        None => Err(ToolFailure::new(format!(            "{} repeats — change only this one, or every one? Send scope \"this\" or \"all\".",            text(&stored.data, "title").unwrap_or_else(|| "This event".into())        ))),    }}/// `link_records { table, id, column, target_id }` → `{ change, record }`./// A null `target_id` clears the link.pub fn link_records(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| link_records_now(ctx, args))}fn link_records_now(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let definition = table_arg(ctx, args)?;    let id = record_id_arg(ctx, args)?;    let column = id_arg(args, "column")?;    let edges = definition.columns.iter().any(|c| c.key == column && c.edges == Some(true));    if edges && !is_user_table(&definition) {        return link_person_edge(ctx, &definition, &id, &column, args);    }    records::link_column(&definition, &column).map_err(refuse)?;    let target = match args.get("target_id") {        None => {            return Err(ToolFailure::new(                "target_id is required: the id to link to, or null to clear the link",            ))        }        Some(Value::Null) => Value::Null,        Some(Value::String(target)) if !target.trim().is_empty() => Value::from(target.trim()),        Some(_) => {            return Err(ToolFailure::new(                "target_id is the id of the record to link to, or null",            ))        }    };    let mut patch = Data::new();    patch.insert(column, target);    let patch = records::validate_patch(&definition, &Value::Object(patch)).map_err(refuse)?;    check_links(ctx, &definition, &patch)?;    if !is_user_table(&definition) {        builtin::writable(&definition)?;    }    patch_record(ctx, &definition, &id, &patch, Verb::Link)}/// `link_records` on a person-edge column: naming a person who is not on the/// record adds them, naming one who is takes them off — so a pick sheet of/// people writes one edge per tap. The change says the people before and/// after.fn link_person_edge(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    column: &str,    args: &Map<String, Value>,) -> ToolResult {    let Some(Value::String(person)) = args.get("target_id") else {        return Err(ToolFailure::new("target_id is the person to add, or to take off when they are on it already",        ));    };    let person = person.trim().to_string();    let before = load_live(ctx, definition, id)?;    let is_person = !ctx        .read        .driver()        .all(            "SELECT id FROM cotton_people WHERE workspace_id = ? AND id = ?",            &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(person.clone()),            ],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .is_empty();    if !is_person {        return Err(ToolFailure::new(format!("no person has the id {person}")));    }    let edge = cotton_store::protocol::derived_id::link_id_for(        &cotton_store::protocol::derived_id::LinkRow {            from_kind: &definition.id,            from_id: id,            to_kind: "person",            to_id: &person,            to_database: None,        },        ctx.file.id(),    );    let held = !ctx        .read        .driver()        .all("SELECT id FROM cotton_links WHERE id = ?", &[SqlValue::Text(edge.clone())],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .is_empty();    if held {        ctx.writer()?.retract("cotton_links", &edge, crate::mcp::writer::Retract::Relation);    } else {        let mut row = Map::new();        row.insert("id".into(), Value::from(edge.clone()));        row.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()),        );        row.insert("from_kind".into(), Value::from(definition.id.clone()));        row.insert("from_id".into(), Value::from(id.to_string()));        row.insert("to_kind".into(), Value::from("person"));        row.insert("to_id".into(), Value::from(person.clone()));        row.insert("created_at".into(), Value::from(now_iso(ctx)));        ctx.writer()?.upsert("cotton_links", &edge, row);    }    ctx.commit()?;    let after = load_live(ctx, definition, id)?;    let was = before.data.get(column).cloned().unwrap_or(Value::Null);    let now = after.data.get(column).cloned().unwrap_or(Value::Null);    let change = record_change(        ctx,        &definition.id,        Some(id),        Verb::Link,        json!({ column: was }),        json!({ column: now }),    )?;    ctx.commit()?;    Ok(answer(ctx, definition, &change, Some(&after)))}/// `delete_record { table, id }` → `{ change, record }`. A user-table record/// is soft-deleted (`deleted_at`), so `undo` brings it back at its own id; a/// built-in is removed the way its own tool removes one.pub fn delete_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let mut answered = atomically_noted(ctx, |ctx| delete_record_now(ctx, args))?;    // A Bin put away is not a thing on this phone: the receipt says what the    // person sees (`receipt::binned_said`).    let put_away = answered["change"]["receipt"]["said"]        .as_str()        .and_then(cotton_core::records::receipt::binned_said_put_away);    if let Some(said) = put_away {        if !crate::mcp::handlers::bin::bin_shown(ctx)? {            answered["change"]["receipt"]["said"] = Value::from(said);        }    }    Ok(answered)}fn delete_record_now(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = &*through_view(ctx, args, false)?;    let definition = table_arg(ctx, args)?;    reservations::require_action(ctx, &definition.id)?;    let mut id = record_id_arg(ctx, args)?;    if definition.id == "event" && !is_user_table(&definition) {        let asked = optional_string(args, "id").unwrap_or_else(|| id.clone());        id = repeating_event_delete(ctx, &definition, &asked, &id, optional_string(args, "scope").as_deref(),        )?;        // One day of a series goes to the bin by its day, as the bin names it:        // "Moved Swimming on Thu 8 Oct to the bin" (architect 2005).        let day = crate::mcp::handlers::common::maybe_row(            ctx,            &crate::mcp::read_db::Query::on("cotton_events").columns(&["series_id", "starts_at", "title"]).eq("id", id.clone()),        )?        .unwrap_or_default();        let on = crate::mcp::handlers::common::text(&day, "series_id")            .and(crate::mcp::handlers::common::text(&day, "starts_at"))            .map(|at| -> Valid<Option<String>> {                let zone = crate::mcp::handlers::common::workspace_timezone_or_null(ctx)?.unwrap_or_else(|| "UTC".to_string());                let dates = cotton_core::records::page::DateWords::of_rows(&crate::presentation::line_rows(ctx.db(), ctx.workspace_id));                Ok(cotton_core::records::page::weekday_date_of(&at, &zone, &dates))            })            .transpose()?            .flatten();        let mut answered = delete_and_record(ctx, &definition, &id, |ctx| {            delete_now(ctx, &definition, &id)        })?;        if let (Some(on), Some(title)) = (on, crate::mcp::handlers::common::text(&day, "title")) {            answered["change"]["receipt"]["said"] = Value::from(cotton_core::records::receipt::binned_said(&format!("{title} on {on}"), true),            );        }        return Ok(answered);    }    delete_and_record(ctx, &definition, &id, |ctx| {        delete_now(ctx, &definition, &id)    })}/// `remove_evidence`: any piece of evidence off its movement — a statement/// line's too, which the generic delete keeps — recorded as the generic/// delete records one, so Undo puts it back. Answers the change with the/// tool's own `removed`, `id` and `transactionId`.pub fn remove_evidence_recorded(ctx: &mut Ctx<'_>, id: &str) -> ToolResult {    atomically_noted(ctx, |ctx| {        let definition = definition(ctx, "evidence")?;        let mut on = String::new();        let mut answered = delete_and_record(ctx, &definition, id, |ctx| {            on = crate::mcp::handlers::money::evidence::retract_evidence(ctx, id)?;            Ok(())        })?;        answered["removed"] = Value::Bool(true);        answered["id"] = Value::from(id);        answered["transactionId"] = Value::from(on);        Ok(answered)    })}/// Delete one live record by `remove`, and record the change: what it held/// (and what moved beside it) kept as `before`, so Undo can bring it back.fn delete_and_record(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    remove: impl FnOnce(&mut Ctx<'_>) -> Valid<()>,) -> ToolResult {    let definition = definition.clone();    let id = id.to_string();    let before = load_live(ctx, &definition, &id)?;    let beside_was = beside_now(ctx, &definition, &id, &before.data)?;    let gone: Option<String> = None;    remove(ctx)?;    let after = load(ctx, &definition, &id)?;    // A shipped record its engine deleted outright (a retract, not the bin    // or its archive) takes its added columns' values with it — cleared, not    // erased, since an erase at its id would refuse its Undo; `was` keeps    // them, so Undo writes them back with the record (`restore_now`).    if after.is_none() && !is_user_table(&definition) && own_values::has_own(&definition) {        own_values::clear(ctx, &definition, &id)?;    }    // An erase out of the bin keeps nothing of what the row said.    let mut was = if bin_table::is_bin(&definition) {        bin_table::erased_values(&before.data)    } else {        before.data.clone()    };    was.extend(records::beside_moved(        &beside_was,        &beside_now(ctx, &definition, &id, &before.data)?,    ));    carry_edited(&definition, &before, &mut was);    // Undo makes such a record again: it keeps the day it was first made,    // never the day it came back.    if !is_user_table(&definition) && builtin::recreated_by_undo(&definition) {        if let Some(made) = &before.created_at {            was.entry("created_at".to_string()).or_insert_with(|| Value::from(made.clone()));        }    }    let change = record_change(        ctx,        &definition.id,        Some(id.as_str()),        Verb::Delete,        Value::Object(was),        Value::Null,    )?;    ctx.commit()?;    let mut answered = answer(ctx, &definition, &change, after.as_ref());    if let Some(said) = gone {        answered["change"]["receipt"]["said"] = Value::from(said);    }    Ok(answered)}fn delete_now(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<()> {    if !is_user_table(definition) {        return builtin::delete(ctx, definition, id);    }    let now = now_iso(ctx);    let mut patch = Map::new();    patch.insert("deleted_at".into(), Value::from(now.clone()));    patch.insert("updated_at".into(), Value::from(now));    patch.insert(MADE_BYLINE.into(), Value::from(byline(ctx)));    update_row(ctx, &made_table(definition.rows_table()), id, patch)?;    ctx.commit()}/// A made table's record keeps when it was edited beside its data, so the/// change's `before` carries it there: an Undo puts it back ([`restamp`]). A/// built-in that has the column already carries it in its diff.fn carry_edited(definition: &TableDefinition, stored: &Stored, side: &mut Data) {    if is_user_table(definition) {        side.insert(            records::EDITED_AT.into(),            stored.updated_at.clone().map_or(Value::Null, Value::from),        );    }}/// What an Undo keeps of a record while it writes the record back: when it/// was edited and who wrote it, read before the inverse write.fn kept_stamps(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<Data> {    if !is_user_table(definition) {        return builtin::stamps(ctx, definition, id);    }    let mut kept = Data::new();    if let Some(stored) = load(ctx, definition, id)? {        kept.insert(            records::EDITED_AT.into(),            stored.updated_at.map_or(Value::Null, Value::from),        );    }    Ok(kept)}/// An Undo leaves no trace: after its inverse write the record is edited when/// it was before the undone change (`was`), or — where a later change still/// stands on it — when that change left it (`kept`), and a note keeps its/// author. Without this an archive and its Undo lift the note to the top of/// Home.fn restamp(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    was: Option<&Value>,    kept: &Data,) -> Valid<()> {    let mut wanted = kept.clone();    match was {        Some(at) if wanted.contains_key(records::EDITED_AT) => {            wanted.insert(records::EDITED_AT.into(), at.clone());        }        _ => {}    }    if !is_user_table(definition) {        return builtin::restamp(ctx, definition, id, &wanted);    }    let Some(Value::String(at)) = wanted.remove(records::EDITED_AT) else {        return Ok(());    };    let mut patch = Map::new();    patch.insert(records::EDITED_AT.into(), Value::from(at));    update_row(ctx, &made_table(definition.rows_table()), id, patch)?;    ctx.commit()}/// `before` is what the record held when it was deleted — what a built-in/// whose delete was a retract is created again from.fn restore_now(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    id: &str,    before: &Data,) -> Valid<()> {    reservations::require_action(ctx, &definition.id)?;    if !is_user_table(definition) {        builtin::restore(ctx, definition, id, before)?;        // Its added columns' values come back with it (a retract erased them).        let (_, own) = own_values::split(definition, before);        own_values::write(ctx, definition, id, &own)?;        return ctx.commit();    }    // The record comes back holding what it held, never only out of the bin:    // a table the object keeps no bin for took the object's delete, and its    // tombstone, folded here, erased the row, so clearing `deleted_at` alone    // made it again with every column empty (whole walk, Cotton Cinemas Dev,    // 8 Nov 2026: an undone film was no longer a film).    let mut patch: Map<String, Value> = definition        .columns        .iter()        .filter(|column| column.computed.is_none())        .filter_map(|column| before.get(&column.key).map(|value| (column.key.clone(), value.clone())))        .collect();    let now = now_iso(ctx);    if load(ctx, definition, id)?.is_none() {        patch.insert("created_at".into(), Value::from(now.clone()));    }    patch.insert("deleted_at".into(), Value::Null);    patch.insert("updated_at".into(), Value::from(now));    patch.insert(MADE_BYLINE.into(), Value::from(byline(ctx)));    update_row(ctx, &made_table(definition.rows_table()), id, patch)?;    ctx.commit()}/// Each listed record's position now (null: none, or no such live record).fn positions(ctx: &Ctx<'_>, definition: &TableDefinition, ids: &[String]) -> Valid<Data> {    let key = records::order_column(definition).map_err(refuse)?;    let mut out = Data::new();    for id in ids {        let value = load(ctx, definition, id)?            .filter(|stored| stored.deleted_at.is_none())            .and_then(|stored| stored.data.get(key).cloned())            .unwrap_or(Value::Null);        out.insert(id.clone(), value);    }    Ok(out)}/// Put each record at its position (null: none).fn place(ctx: &mut Ctx<'_>, definition: &TableDefinition, wanted: &Data) -> Valid<()> {    if !is_user_table(definition) {        builtin::permit(ctx, definition, builtin::Op::Reorder)?;    }    for (id, position) in wanted {        if is_user_table(definition) {            let key = records::order_column(definition).map_err(refuse)?;            let mut patch = Map::new();            patch.insert(key.to_string(), position.clone());            patch.insert("updated_at".into(), Value::from(now_iso(ctx)));            patch.insert(MADE_BYLINE.into(), Value::from(byline(ctx)));            update_row(ctx, &made_table(definition.rows_table()), id, patch)?;        } else {            let position = position.as_f64().ok_or_else(|| {                ToolFailure::new(format!(                    "{} cannot take a record out of the order",                    definition.plural                ))            })?;            builtin::reorder(ctx, definition, id, position)?;        }    }    ctx.commit()}/// `reorder_records { table, ids }` → `{ change, record: null }`. The listed/// records take positions 1, 2, 3 … in the order given; the rest keep theirs.pub fn reorder_records(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| reorder_records_now(ctx, args))}fn reorder_records_now(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let definition = table_arg(ctx, args)?;    records::order_column(&definition).map_err(refuse)?;    if !is_user_table(&definition) {        builtin::writable(&definition)?;    }    let ids: Vec<String> = match args.get("ids") {        Some(Value::Array(items)) => items            .iter()            .map(|item| {                item.as_str()                    .map(str::to_string)                    .ok_or_else(|| ToolFailure::new("ids is a list of record ids"))            })            .collect::<Valid<_>>()?,        _ => {            return Err(ToolFailure::new(                "ids is required: the record ids in their new order",            ))        }    };    let plan = records::plan_reorder(&ids).map_err(refuse)?;    for id in &ids {        load_live(ctx, &definition, id)?;    }    let before = positions(ctx, &definition, &ids)?;    let wanted: Data = plan        .into_iter()        .map(|(id, position)| (id, Value::from(position)))        .collect();    place(ctx, &definition, &wanted)?;    let after = positions(ctx, &definition, &ids)?;    let (was, now) = records::diff(&before, &after);    if now.is_empty() {        return Err(refuse(RecordError::NothingToChange));    }    let change = record_change(        ctx,        &definition.id,        None,        Verb::Reorder,        Value::Object(was),        Value::Object(now),    )?;    ctx.commit()?;    Ok(answer(ctx, &definition, &change, None))}/// The change of an add made by a built-in's OWN verb (a captured thought, an/// album, an order, a project) rather than `create_record`: written as the/// same create change, so the add's receipt is the one every add shows and/// its Undo is asked the one way. Commits what the verb has queued, so the/// record reads back, then the change row; answers the change as every write/// does.pub fn record_added(ctx: &mut Ctx<'_>, table: &str, id: &str) -> ToolResult {    ctx.noting_history(Ctx::commit)?;    let definition = definition(ctx, table)?;    let stored = load_live(ctx, &definition, id)?;    let change = record_change(        ctx,        &definition.id,        Some(id),        Verb::Create,        Value::Null,        Value::Object(stored.data.clone()),    )?;    ctx.commit()?;    Ok(change_json(ctx, &definition, &change, Some(&stored)))}/// `undo { change_id }` → `{ change, undone, record }`: the change the undo/// wrote, the change it reversed (now carrying `undone_by`), and the record as/// it now stands (null for a reorder).pub fn undo(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| automations::undo_group(ctx, args))}/// Whether `change` is the update that archived its record: it set the/// table's `archived` column.fn archived_by(definition: &TableDefinition, change: &Change) -> bool {    matches!(change.verb, Verb::Update | Verb::Link)        && definition            .archived            .as_ref()            .and_then(|column| change.after.get(column))            .is_some_and(|set| !set.is_null() && *set != Value::Bool(false))}/// Whether this file holds the undo fact `fact` — the change is undone,/// here or by a twin undo on another device.fn undo_fact_held(ctx: &Ctx<'_>, fact: &str) -> Valid<bool> {    Ok(ctx        .db()        .get(            "SELECT 1 AS held FROM cotton_undos WHERE id = ?",            &[SqlValue::Text(fact.to_string())],        )        .map_err(sql_err)?        .is_some())}/// Write the undo fact of `change_id`, whose undo is the change `undo_change_id`,/// and make the act it opens an undo ([`crate::mcp::writer::Writer::undoing`]).fn write_undo_fact(ctx: &mut Ctx<'_>, fact: &str, change_id: &str, undo_change_id: &str,) -> Valid<()> {    let at = now_iso(ctx);    let actor = byline(ctx);    let mut row = Map::new();    row.insert("id".into(), Value::from(fact));    row.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()),    );    row.insert("change_id".into(), Value::from(change_id));    row.insert("undo_change_id".into(), Value::from(undo_change_id));    row.insert("at".into(), Value::from(at));    row.insert("actor".into(), Value::from(actor));    let writer = ctx.writer()?;    writer.upsert(cotton_store::fact_hooks::UNDOS_TABLE, fact, row);    writer.undoing(fact);    Ok(())}/// The undo fact alone, for an inverse that is not a patch (a delete, a/// restore, a reorder): it marks the change undone, which is all `undone_by`/// was. The act's other writes do not name it — only a patch's do (slice 3b).fn write_undo_mark(ctx: &mut Ctx<'_>, change_id: &str, undo_change_id: &str) -> Valid<()> {    let fact = cotton_store::fact_hooks::undo_fact_id(change_id);    let mut row = Map::new();    row.insert("id".into(), Value::from(fact.clone()));    row.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()),    );    row.insert("change_id".into(), Value::from(change_id));    row.insert("undo_change_id".into(), Value::from(undo_change_id));    row.insert("at".into(), Value::from(now_iso(ctx)));    row.insert("actor".into(), Value::from(byline(ctx)));    ctx.writer()?.upsert(cotton_store::fact_hooks::UNDOS_TABLE, &fact, row);    Ok(())}fn undo_now(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let change_id = id_arg(args, "change_id")?;    let (original, born) = load_change(ctx, &change_id)?;    if groups::is_group_change(&original.table_id) {        return groups::undo(ctx, original, &born);    }    let definition = definition(ctx, &original.table_id)?;    reservations::require_action(ctx, &definition.id)?;    let fact = cotton_store::fact_hooks::undo_fact_id(&original.id);    if original.undone_by.is_some() || undo_fact_held(ctx, &fact)? {        return Err(refuse(RecordError::AlreadyUndone));    }    if let Some(reason) = change_undo_refusal(&definition, &original) {        return Err(ToolFailure::new(format!(            "this change cannot be undone: {reason}"        )));    }    let later = later_changes(ctx, &original.table_id, &born)?;    let current = match (&original.verb, &original.record_id) {        (Verb::Reorder, _) => {            let ids: Vec<String> = original                .after                .as_object()                .map(|object| object.keys().cloned().collect())                .unwrap_or_default();            Current::Positions(positions(ctx, &definition, &ids)?)        }        // A record its own change archived is put away, not gone: the undo        // reads it as it stands, or an archive could never be undone.        (_, Some(id)) if archived_by(&definition, &original) => {            Current::Record(load(ctx, &definition, id)?.map(|stored| stored.data))        }        (_, Some(id)) => {            Current::Record(load(ctx, &definition, id)?.and_then(|stored| stored.live().cloned()))        }        (_, None) => Current::Record(None),    };    let inverse = match records::plan_undo(&original, &later, &current, definition.order.as_deref()) {        // An add whose record has changed since is not taken back; where the        // table has a put-away state, its Undo puts the record away as it is.        Err(RecordError::ChangedSince { .. })            if original.verb == Verb::Create                && !is_user_table(&definition)                && builtin::puts_away_once_changed(&definition)                && matches!(current, Current::Record(Some(_))) =>        {            Inverse::Delete {                record_id: original.record_id.clone().unwrap_or_default(),            }        }        // A refusal names the record by its name, never by its id.        Err(RecordError::ChangedSince { .. }) if original.record_id.is_some() => {            let named = match &current {                Current::Record(Some(now)) => Value::Object(now.clone()),                _ if original.after.is_object() => original.after.clone(),                _ => original.before.clone(),            };            return Err(ToolFailure::new(format!(                "{} has changed since this change was made; undoing it now would overwrite the later edit",                cotton_core::records::receipt::record_name_in(&definition, &named, &date_words(ctx))            )));        }        planned => planned.map_err(refuse)?,    };    // What the change moved beside its record: put back with it, or the undo    // is refused — never "undone" with something left where the change put it.    let beside = records::beside_of(&original);    // The edited time the record goes back to: the one before the undone    // change, unless a later change still stands on the record.    let cancelled: Vec<&str> = later        .iter()        .filter_map(|other| other.undone_by.as_deref().map(|by| [other.id.as_str(), by]))        .flatten()        .collect();    let edited_since = later.iter().any(|other| {        other.id != original.id            && other.record_id == original.record_id            && !cancelled.contains(&other.id.as_str())    });    let edited_was = original        .before        .get(records::EDITED_AT)        .filter(|_| !edited_since)        .cloned();    let undo_change_id = ctx.new_uuid();    let mut verb = inverse.verb();    // The keys a later write has taken since: left as they are, and named.    let taken = match &inverse {        Inverse::Patch { taken, .. } => taken.clone(),        _ => Vec::new(),    };    let (record_id, before, after) = 'inverse: {        match &inverse {        Inverse::Delete { record_id } => {            let before = load_live(ctx, &definition, record_id)?;            let beside_was = beside_now(ctx, &definition, record_id, &before.data)?;            if is_user_table(&definition) {                delete_now(ctx, &definition, record_id)?;            } else {                // The add's own act ends at its change row — unless it set an                // automation off, an effect outside its own rows.                let through = (original.verb == Verb::Create && !automations::ran_for(ctx, &original.id)?)                    .then_some(born.as_str());                match builtin::uncreate(ctx, &definition, record_id, &before.data, &beside, through,                    )? {                    builtin::Uncreated::Gone => {}                    builtin::Uncreated::PutAway => {                        // The record stays, put away: the undo's own change is that update.                        let after = load_live(ctx, &definition, record_id)?;                        let (was, now) = records::diff(&before.data, &after.data);                        verb = Verb::Update;                        break 'inverse (Some(record_id.clone()), Value::Object(was), Value::Object(now),                            );                    }                    builtin::Uncreated::TakenBack => {                        // The signed erase is the whole trace: no change row is                        // written, and the add's own went with the record.                        ctx.commit()?;                        let change = Change {                            id: ctx.new_uuid(),                            table_id: definition.id.clone(),                            record_id: Some(record_id.clone()),                            verb: Verb::Delete,                            byline: byline(ctx),                            before: Value::Object(before.data.clone()),                            after: Value::Null,                            created_at: now_iso(ctx),                            undone_by: None,                        };                        let undone = Change {                            undone_by: Some(change.id.clone()),                            ..original                        };                        return Ok(json!({                            "change": taken_back_json(ctx, &definition, &change),                            "undone": change_json(ctx, &definition, &undone, None),                            "record": Value::Null,                        }));                    }                }            }            let mut recorded = before.data.clone();            recorded.extend(records::beside_moved(                &beside_was,                &beside_now(ctx, &definition, record_id, &before.data)?,            ));            carry_edited(&definition, &before, &mut recorded);            (                Some(record_id.clone()),                Value::Object(recorded),                Value::Null,            )        }        Inverse::Restore { record_id, data } => {            if !beside.is_empty() {                return Err(ToolFailure::new(format!(                    "this change cannot be undone: it also moved {} beside the record",                    beside.keys().cloned().collect::<Vec<_>>().join(", ")                )));            }            let kept = kept_stamps(ctx, &definition, record_id)?;            restore_now(ctx, &definition, record_id, data)?;            restamp(ctx, &definition, record_id, edited_was.as_ref(), &kept)?;            let after = load_live(ctx, &definition, record_id)?;            (                Some(record_id.clone()),                Value::Null,                Value::Object(after.data),            )        }        Inverse::Patch { record_id, patch, .. } => {            // THE UNDO IS A FACT (slice 3b): written first in the act, and            // every write of the act names it, so of two devices undoing this            // change one act stands everywhere and the other parks whole.            write_undo_fact(ctx, &fact, &original.id, &undo_change_id)?;            let before = match archived_by(&definition, &original) {                true => load(ctx, &definition, record_id)?.ok_or_else(|| not_found(&definition, record_id))?,                false => load_live(ctx, &definition, record_id)?,            };            // A made table's edited time rides beside its data, never in it.            let mut patch = patch.clone();            if definition.column(records::EDITED_AT).is_none() {                patch.remove(records::EDITED_AT);            }            records::validate_reveal_patch(&definition, &before.data, &patch).map_err(refuse)?;            let beside_was = beside_now(ctx, &definition, record_id, &before.data)?;            let kept = kept_stamps(ctx, &definition, record_id)?;            if is_user_table(&definition) {                let wanted = records::apply_patch(&before.data, &patch);                write_user(ctx, &definition, &before, &wanted)?;            } else {                let (engine, own) = own_values::split(&definition, &patch);                if !engine.is_empty() || own.is_empty() {                    builtin::update_for_undo(ctx, &definition, record_id, &engine, &beside)?;                }                if !own.is_empty() {                    own_values::write(ctx, &definition, record_id, &own)?;                    ctx.commit()?;                }            }            restamp(ctx, &definition, record_id, edited_was.as_ref(), &kept)?;            let after = load_live(ctx, &definition, record_id)?;            let (mut was, mut now) = records::diff(&before.data, &after.data);            carry_edited(&definition, &before, &mut was);            definition_writes::carry_theme_override(&beside_was, &mut was);            now.extend(records::beside_moved(                &beside_was,                &beside_now(ctx, &definition, record_id, &after.data)?,            ));            (                Some(record_id.clone()),                Value::Object(was),                Value::Object(now),            )        }        Inverse::Reorder { positions: wanted } => {            let ids: Vec<String> = wanted.keys().cloned().collect();            let before = positions(ctx, &definition, &ids)?;            place(ctx, &definition, wanted)?;            let after = positions(ctx, &definition, &ids)?;            let (was, now) = records::diff(&before, &after);            (None, Value::Object(was), Value::Object(now))        }        }    };    if !matches!(inverse, Inverse::Patch { .. }) {        write_undo_mark(ctx, &original.id, &undo_change_id)?;    }    let change = record_change_as(        ctx,        undo_change_id,        &definition.id,        record_id.as_deref(),        verb,        before,        after,    )?;    ctx.commit()?;    let undone = Change {        undone_by: Some(change.id.clone()),        ..original    };    let record = match &record_id {        Some(id) => load(ctx, &definition, id)?,        None => None,    };    let mut answered = change_json(ctx, &definition, &change, record.as_ref());    // The Undo of a tick that cleared a missed run says only "Undone": it    // took back the whole run, which no one record's verb can say (R9).    if records::beside_of(&undone).contains_key(records::MISSED) {        if let Some(said) = answered.pointer_mut("/receipt/said") {            *said = Value::from("Undone");        }    }    Ok(json!({        "change": answered,        "undone": change_json(ctx, &definition, &undone, None),        "record": record.as_ref().map(|stored| read_json(&definition, stored)),        "taken": taken,    }))}// ── the bin ─────────────────────────────────────────────────────────────────//// A deleted record of a table a person defined is SOFT-deleted, so it waits in// the one kind-generic bin beside a binned email or password: `list_bin` shows// it as kind `record` (with its table), `restore_from_bin` brings it back —// recording a `restore` change, as any generic write does — and `empty_bin`// alone erases it, with the change rows whose before and after still hold its// values./// The bin entry kind a user-table record answers as.pub const BIN_KIND: &str = "record";/// One soft-deleted record waiting in the bin.pub struct Binned {    pub id: String,    pub table: String,    pub title: String,    pub deleted_at: String,    /// The table's own name, for a record of a table a person made: what    /// kind of record it was (292, walker291: a Records card read only    /// '2026-12-14').    pub table_name: Option<String>,    /// The record's title, when its table titles it by a date: typed, so the    /// Bin says the day in words, never the stored ISO text.    pub title_at: Option<String>,}/// Where a record of the bin lives: a group (`cotton_groups`) or a made table.enum Located {    Group,    Made(TableDefinition),}/// The groups' rows of the bin, or one of them.fn group_rows(ctx: &Ctx<'_>, id: Option<&str>, binned_only: bool) -> Valid<Vec<cotton_store::Row>> {    let mut sql = format!("SELECT id, name, deleted_at FROM {} WHERE workspace_id = ?", groups::GROUPS);    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    if let Some(id) = id {        sql.push_str(" AND id = ?");        params.push(SqlValue::Text(id.to_string()));    }    if binned_only {        sql.push_str(" AND deleted_at IS NOT NULL");    }    ctx.read.driver().all(&sql, &params).map_err(sql_err)}/// A made table's rows of the bin, or one of them.fn made_rows(ctx: &Ctx<'_>, definition: &TableDefinition, id: Option<&str>, binned_only: bool,) -> Valid<Vec<cotton_store::Row>> {    if !made_held(ctx, definition.rows_table())? {        return Ok(Vec::new());    }    let mut sql = format!("SELECT * FROM {} WHERE workspace_id = ?", made_table(definition.rows_table()));    let mut params = vec![SqlValue::Text(ctx.workspace_id.to_string())];    if let Some(id) = id {        sql.push_str(" AND id = ?");        params.push(SqlValue::Text(id.to_string()));    }    if binned_only {        sql.push_str(" AND deleted_at IS NOT NULL");    }    ctx.read.driver().all(&sql, &params).map_err(sql_err)}/// Whether the Bin asked now shows one binned row (`hidden::bin_shows`, THE Bin's gate): read the hidden set once/// per call and ask this of every row.fn shown_in_bin(hiding: &hidden::Hiding, located: &Located, row: &cotton_store::Row) -> bool {    let data = match located {        Located::Made(definition) if !hiding.groups.is_empty() => stored_from_row(definition, row).data,        _ => Data::new(),    };    hidden::bin_shows(hiding, row.text("id"), &data)}/// Which table of the Bin asked now holds `id` (`hidden::bin_shows`): one the other Bin holds is not here, as one/// that is nowhere. Every erase, restore and read of one binned record by its id finds it through this.fn locate_binned(ctx: &Ctx<'_>, id: &str) -> Valid<Option<Located>> {    let Some(located) = locate(ctx, id)? else { return Ok(None) };    let rows = match &located {        Located::Group => group_rows(ctx, Some(id), false)?,        Located::Made(definition) => made_rows(ctx, definition, Some(id), false)?,    };    let hiding = hidden::hiding(ctx).map_err(sql_err)?;    Ok(rows.first().filter(|row| shown_in_bin(&hiding, &located, row)).map(|_| located))}/// Which table of the bin holds `id`, if any.fn locate(ctx: &Ctx<'_>, id: &str) -> Valid<Option<Located>> {    if !group_rows(ctx, Some(id), false)?.is_empty() {        return Ok(Some(Located::Group));    }    for definition in made_definitions(ctx)? {        if !made_rows(ctx, &definition, Some(id), false)?.is_empty() {            return Ok(Some(Located::Made(definition)));        }    }    Ok(None)}/// One row of the bin as it names itself.fn binned_of(table: &str, title: Option<String>, row: &cotton_store::Row) -> Binned {    Binned {        id: row.text("id").unwrap_or_default().to_string(),        table: table.to_string(),        title: title            .map(|title| title.trim().to_string())            .filter(|title| !title.is_empty())            .unwrap_or_else(|| "(untitled)".to_string()),        deleted_at: row.text("deleted_at").unwrap_or_default().to_string(),        table_name: None,        title_at: None,    }}fn group_binned(row: &cotton_store::Row) -> Binned {    // A deleted group waits here under its own name, like any record.    binned_of(groups::TABLE, row.text("name").map(str::to_string), row)}fn made_binned(definition: &TableDefinition, row: &cotton_store::Row) -> Binned {    let title = row.text(&definition.title).map(str::to_string);    let dated = definition        .column(&definition.title)        .is_some_and(|column| matches!(column.column_type, cotton_core::definitions::ColumnType::Date));    let mut binned = binned_of(&definition.id, if dated { None } else { title.clone() }, row);    binned.table_name = Some(definition.name.clone());    if dated {        binned.title = String::new();        binned.title_at = title;    }    binned}/// Every soft-deleted record of the Bin asked now (`hidden::bin_shows`): groups and every made table's. Left out as/// they are read, so every list, count and erase made of these is made without the other Bin's.fn every_binned(ctx: &Ctx<'_>) -> Valid<Vec<(Binned, Located)>> {    let hiding = hidden::hiding(ctx).map_err(sql_err)?;    let mut all: Vec<(Binned, Located)> = group_rows(ctx, None, true)?        .iter()        .filter(|row| shown_in_bin(&hiding, &Located::Group, row))        .map(|row| (group_binned(row), Located::Group))        .collect();    for definition in made_definitions(ctx)? {        let located = Located::Made(definition.clone());        for row in made_rows(ctx, &definition, None, true)? {            if shown_in_bin(&hiding, &located, &row) {                all.push((made_binned(&definition, &row), Located::Made(definition.clone())));            }        }    }    all.sort_by(|(a, _), (b, _)| {        b.deleted_at.cmp(&a.deleted_at).then_with(|| a.id.cmp(&b.id))    });    Ok(all)}/// The newest `limit` soft-deleted records, newest first.pub fn binned(ctx: &Ctx<'_>, limit: i64) -> Valid<Vec<Binned>> {    Ok(every_binned(ctx)?.into_iter().take(limit.max(0) as usize).map(|(binned, _)| binned).collect())}/// One record as the bin names it, in the bin or out of it — `deleted_at` is/// empty for one that is out. `None` when this workspace has no such record.pub fn bin_record(ctx: &Ctx<'_>, id: &str) -> Valid<Option<Binned>> {    Ok(match locate_binned(ctx, id)? {        None => None,        Some(Located::Group) => group_rows(ctx, Some(id), false)?.first().map(group_binned),        Some(Located::Made(definition)) => made_rows(ctx, &definition, Some(id), false)?.first().map(|row| made_binned(&definition, row)),    })}/// The table a record of the bin is erased from.fn storage_of(located: &Located) -> String {    match located {        Located::Group => groups::GROUPS.to_string(),        Located::Made(definition) => made_table(definition.rows_table()),    }}/// ERASE record `id` for good, with every change that names it, inside the caller's write: a verb that destroys a/// record's bytes by its own rule (`reason`), not the bin's (Comms: a WhatsApp outbox row about a message deleted for/// everyone, chat CONTRACT.md "Editing and deleting his own message"). A record not here is nothing to erase.pub fn erase_record(ctx: &mut Ctx<'_>, id: &str, reason: &str) -> Valid<()> {    let Some(located) = locate(ctx, id)? else { return Ok(()) };    forget_changes(ctx, id)?;    ctx.writer()?.erase(&storage_of(&located), id, reason);    Ok(())}/// Erase one soft-deleted record for good, with every change that names it —/// what `erase_binned` does to each, for the bin table's `delete_record`.pub fn erase_one_binned(ctx: &mut Ctx<'_>, id: &str) -> Valid<()> {    let Some(located) = locate_binned(ctx, id)? else {        return Err(ToolFailure::new("no such record in this workspace"));    };    atomically_noted(ctx, |ctx| {        forget_changes(ctx, id)?;        ctx.writer()?.erase(&storage_of(&located), id, "bin");        ctx.commit()    })}/// Bring one soft-deleted record back out of the bin: `None` when there is no/// such record, `Some(false)` when it was not in the bin, `Some(true)` once it/// is back — with its `restore` change, in one transaction.pub fn restore_binned(ctx: &mut Ctx<'_>, id: &str) -> Valid<Option<bool>> {    atomically_noted(ctx, |ctx| {        let definition = match locate_binned(ctx, id)? {            None => return Ok(None),            Some(Located::Group) => return groups::restore_binned(ctx, id).map(Some),            Some(Located::Made(definition)) => definition,        };        match load_user(ctx, &definition, id)? {            Some(stored) if stored.deleted_at.is_some() => {}            _ => return Ok(Some(false)),        }        restore_now(ctx, &definition, id, &Data::new())?;        let after = load_live(ctx, &definition, id)?;        record_change(            ctx,            &definition.id,            Some(id),            Verb::Restore,            Value::Null,            Value::Object(after.data),        )?;        ctx.commit()?;        Ok(Some(true))    })}/// Put a restored record back in the bin — the Undo of a restore through the/// bin table ([`restore_binned`]'s inverse) — recording the `delete` any/// delete of that record does.pub(super) fn bin_again(ctx: &mut Ctx<'_>, id: &str) -> Valid<()> {    let definition = match locate_binned(ctx, id)? {        None => return Err(ToolFailure::new("no such record in this workspace")),        Some(Located::Group) => return groups::bin_again(ctx, id),        Some(Located::Made(definition)) => definition,    };    let before = load_live(ctx, &definition, id)?;    delete_now(ctx, &definition, id)?;    record_change(        ctx,        &definition.id,        Some(id),        Verb::Delete,        Value::Object(before.data),        Value::Null,    )?;    ctx.commit()}/// Erase every soft-deleted record (deleted before `before`, when given) and/// the change rows that still hold its values. One delete per row, so every/// other device folds a tombstone. Answers how many records were erased.pub fn erase_binned(ctx: &mut Ctx<'_>, before: Option<&str>) -> Valid<i64> {    let doomed: Vec<(String, String)> = every_binned(ctx)?        .into_iter()        .filter(|(binned, _)| before.is_none_or(|before| binned.deleted_at.as_str() < before))        .map(|(binned, located)| (binned.id, storage_of(&located)))        .collect();    atomically_noted(ctx, |ctx| {        for (id, table) in &doomed {            forget_changes(ctx, id)?;            ctx.writer()?.erase(table, id, "bin");        }        ctx.commit()?;        Ok(doomed.len() as i64)    })}pub(crate) fn derivation_rows(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition) -> Valid<Vec<(String, Data)>> {    builtin::derivation_rows(db, workspace, definition)}pub(crate) fn derivation_rows_linked(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition, link: &str, target: &str) -> Valid<Vec<(String, Data)>> {    builtin::derivation_rows_linked(db, workspace, definition, link, target)}pub(crate) fn derivation_is_row_local(definition: &TableDefinition) -> Valid<bool> {    builtin::derivation_is_row_local(definition)}pub(crate) fn derivation_rows_for_ids(db: &cotton_store::Driver, workspace: &str, definition: &TableDefinition, ids: &[String]) -> Valid<Vec<(String, Data)>> {    builtin::derivation_rows_for_ids(db, workspace, definition, ids)}/// Add what the derive pass worked out for a made table's computed columns/// (`crate::derive`, the device-local `_computed`) to the records read.fn with_computed(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> {    with_computed_read(&ctx.read, definition, records)}/// [`with_computed`] over a read alone (a tool figure's).fn with_computed_read(read: &ReadDb<'_>, definition: &TableDefinition, records: &mut [Stored]) -> Valid<()> {    if money_runway::handles(definition) && records.iter().all(|record|record.data.contains_key("occurrence_index")) { return Ok(()); }    if !definition.has_computed() || records.is_empty() {        return Ok(());    }    // A whole table's read names more records than SQLite takes variables:    // asked in chunks, each found by id in its own chunk.    for chunk in records.chunks_mut(IN_CHUNK) {        let mut params = vec![SqlValue::Text(definition.id.clone())];        params.extend(chunk.iter().map(|record| SqlValue::Text(record.id.clone())));        let sql = format!(            "SELECT record_id, key, value FROM _computed WHERE table_id = ? AND record_id IN ({})",            vec!["?"; chunk.len()].join(", ")        );        let at: std::collections::HashMap<String, usize> = chunk.iter().enumerate().map(|(at, record)| (record.id.clone(), at)).collect();        for row in read.driver().all(&sql, &params).map_err(sql_err)? {            let (Some(id), Some(key)) = (row.text("record_id"), row.text("key")) else { continue;            };            let Some(column) = definition.column(key).filter(|column| column.computed.is_some()) else { continue;            };            if let Some(&at) = at.get(id) {                let value = crate::derive::stored_value(row.get("value"), column.column_type);                if !value.is_null() {                    chunk[at].data.insert(key.to_string(), value);                }            }        }    }    Ok(())}fn derive_records(    ctx: &mut Ctx<'_>,    definition: &TableDefinition,    records: &mut [Stored],    args: &Map<String, Value>,    whole: bool,) -> Valid<()> {    with_computed(ctx, definition, records)?;    own_values::merge(ctx, definition, records)?;    // What the object fills that this build keeps no column for: the copy    // keeps it (`served_values`), and every read answers it.    served_values::merge(ctx, definition, records)?;    place_values::merge(ctx, definition, records)?;    let reader_zone = crate::mcp::handlers::common::optional_zone(args)?;    // Where an owner's session message got to, as typed facts.    builtin::session_delivery(ctx, definition, records)?;    // A device's words are read against every device of the file.    device_words::device_words(ctx, definition, records, reader_zone.as_deref())?;    // A connection's kind and state in words, what it brought, and a code    // host's token line.    connection_words::connection_words(ctx, definition, records)?;    // A note's length in words and a repeating todo's done-before count.    record_counts::record_counts(ctx, definition, records)?;    // An assistant's key in words: what it may do, its expiry, its last    // use, and Disconnected or Expired once it is no longer live.    assistant_words::assistant_words(ctx, definition, records)?;    // A person's phones and emails, off their handles (v90).    person_words::person_handles(ctx, definition, records)?;    // What is owed between the owner and a person, on that person's page.    // A coding session's words count from now; a list is cut by the queue's    // window (a search's or one project's by none), and a page also reads its    // messages and its task list.    session_table::session_table_words(ctx, definition, records, args, whole)?;    if definition.id == "event" && definition.has_engine() {        // The day and the start time are the READER's, so they are answered        // here, where the read's own zone is known, never with the stored row.        let zone = crate::mcp::handlers::common::optional_zone(args)?;        for record in records.iter_mut() {            if let Some((day, time)) = builtin::event_day(ctx, &record.data, zone.as_deref())? {                record.data.insert("day".into(), Value::from(day));                if let Some(time) = time {                    record.data.insert("start_time".into(), Value::from(time));                }            }        }    }    if definition.derived != Some(true) {        return Ok(());    }    if definition.engine.as_deref() != Some("money") {        return Err(ToolFailure::new(            "This engine view is not available in this build.",        ));    }    let data = crate::mcp::handlers::money_views::engine_rows(        ctx,        &definition.id,        records            .iter()            .map(|r| (r.id.clone(), r.data.clone()))            .collect(),        args,    )    .map_err(ToolFailure::new)?;    for (record, data) in records.iter_mut().zip(data) {        record.data = data            .into_iter()            .filter(|(k, _)| definition.column(k).is_some())            .collect();    }    Ok(())}/// Delete every change row naming this record, whatever table it was written/// through — the step every erase takes before the row goes, because the/// change log syncs and nothing an erased record said may outlive it there —/// and the values of the columns its owner added (`own_values::erase`). One/// delete per row, so every other device folds a tombstone; the caller/// commits.pub fn forget_changes(ctx: &mut Ctx<'_>, id: &str) -> Valid<()> {    let changes: Vec<String> = ctx        .read        .driver()        .all(            &format!("SELECT id FROM {CHANGES} WHERE workspace_id = ? AND record_id = ?"),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(id.to_string()),            ],        )        .map_err(sql_err)?        .iter()        .filter_map(|row| row.text("id").map(str::to_string))        .collect();    for change in &changes {        ctx.writer()?.erase(CHANGES, change, "bin");    }    // After the history: an erase at the record's id takes the history it    // names with it, and a change erased twice is a write at an erased id.    own_values::erase(ctx, id)}#[cfg(test)]mod address_tests {    use super::*;    /// RULE: An address typed where a saved page's title goes is the page's link: Reader's one input saves it, with https put before a bare host, and words stay a title that still needs a link.    #[test]    fn an_address_typed_as_a_pages_title_is_its_link() {        let typed = |title: &str| {            let data = json!({ "title": title });            typed_address(data.as_object().unwrap()).map(|out| (out["url"].clone(), out.contains_key("title")))        };        assert_eq!(typed("https://example.com/a"), Some((json!("https://example.com/a"), false)));        assert_eq!(typed(" example.org/garden?x=1 "), Some((json!("https://example.org/garden?x=1"), false)));        assert_eq!(typed("a page about gardens"), None);        assert_eq!(typed("gardens"), None);        assert_eq!(typed("ftp://example.com/a"), None);        assert_eq!(typed("version 2.0"), None);        let named = json!({ "title": "example.com", "url": "https://example.net" });        assert_eq!(typed_address(named.as_object().unwrap()), None);    }}mod place_values;#[cfg(test)]mod account_number_read_tests {    use super::*;}/// Trusted imports reserve through the ordinary capacity judge, never generic claim writes.pub use reservations::{reserve_imported_record, cancel_reservation};pub use everything::{passwords_listed, table_facts as everything_facts};