//! The table definitions and the generic verbs, for the app — eleven methods //! inside `cotton_call`, answered on the phone's client build and on the Mac. //! //! ## One implementation //! //! Each `records.*` method IS an MCP tool, called through the same handler an //! assistant's connection reaches (`cotton_tools::mcp::handlers::tables`, with search in `records_2`): //! the request is the tool's arguments exactly, and the answer is the tool's //! answer exactly. Nothing here validates, delegates to an engine or undoes — //! a second copy of any of that would be a second opinion about who wins. //! //! | method | tool | request | answer | //! |-------------------|-----------------------|-------------------------------------------|-----------------------------------------| //! | `records.search` | `search_records` | `{query, kinds?, limit?, mode?}` | `{records: [{table,id,title,snippet}], totals}` | //! | `records.list` | `list_records` | `{table, project?, query?, where?, today?, page?, limit?, archived?}` or `{table, ids, today?}` | `{table, records: [Record], next_page, total}` | //! | `records.get` | `get_record_by_table` | `{table, id, today?}` | `Record` | //! | `records.page` | (the reads above) | `{table, id}` | `RecordPage` | //! | `records.head` | (`list_head`) | `{table}` | `{lines: [{reason, since, line}]}` | //! | `records.create` | `create_record` | `{table, data, audience?}` | `{change, record}` | //! | `records.update` | `update_record` | `{table, id, patch}` | `{change, record}` | //! | `records.delete` | `delete_record` | `{table, id, today?}` | `{change, record}` | //! | `records.link` | `link_records` | `{table, id, column, target_id \| null}` | `{change, record}` | //! | `records.reorder` | `reorder_records` | `{table, ids}` | `{change, record: null}` | //! | `records.undo` | `undo` | `{change_id}` | `{change, undone, record \| null}` | //! | `groups.list` | `list_groups` | `{table?, record?}` | `{table?, groups: [Group]}` | //! | `groups.create` | `create_group` | `{table, name, records? \| where?}` | `{change, group}` | //! | `groups.update` | `update_group` | `{id, name \| add \| remove \| order \| where}` | `{change, group}` | //! | `groups.delete` | `delete_group` | `{id}` | `{change, group: null}` | //! //! `records.list {table, archived: true}` answers only the table's archived //! records (never binned ones) in its usual order, `total` how many are //! archived — the list's last link, "Archived · n"; `limit: 0` beside it //! answers that count alone. A table whose records are never archived //! refuses it ("Todos are never archived"). Bring back is `records.update` //! clearing the archive column (`{archived_at: null}`, a chat's //! `{archived: false}`, a project's `{status: "active"}`). //! //! A `Group` is `{id, name, table, count, top: [Record]}` (and `holds` when //! `groups.list` was sent a `record`); `records.list {table, where: {group}}` answers //! a group's records, and `records.undo` takes a group's change like any other. //! //! A record's `links` (the engine's list of the records it is linked to, //! each `{table, id, title?, container?, when?, when_kind?}`) carry //! `kind_word` on every link naming its table: what that kind of record is //! called, `format` › `mark.` ("Money" for a transaction), else the //! table's key in words (`page::Words::kind_word`); and `@day_parts.when`, the //! link's day as the core says it. //! //! `records.page` `{table, id}` is the record page in words (Spec 11): its //! shape and colour, head, links, body, lists and acts, made by //! `cotton_core::records::page::record_page` from the definition's parts //! (`TableDefinition::resolved_parts`) — one function for every table, no //! kind of its own. It reads only through `records.get` and `records.list` //! here, so it answers exactly what those answer. An act's id is a command //! of the definition, run through `records.command`. A gone record is //! `record_not_found`, as `records.get`'s is. //! //! `records.command` `{table, id, command}` runs one command a BUILT-IN //! definition declares for its table (`commands`: Pin, Archive, Clear chat): //! the engine verb the definition names, with the arguments the definition //! binds — never a verb or an argument the caller chose. A command is one of //! four kinds (create, update, delete, open) and this is the one place that //! runs them; it answers a `CommandOutcome`: `{command, kind, receipt, undo, //! answer, open}` — `receipt` what happened in the person's words ("Pinned", //! else the label), `undo` the command that takes it back. //! //! The context is the owner's own app (`Ctx::phone`: this device, the `owner` //! scope), so every write's byline is `"user"`. A read runs through //! `ClientController::read_tool` (refused, and rolled back, if it wrote); a //! write through `ClientController::write` — the same outbox, the same `data` //! event with the tables it moved — and answers the tool's own answer, not the //! outbox envelope around it. //! //! ## The two definition lists //! //! `definitions.tables` answers `{definitions: [TableDefinition], refused: //! [{id, reason}]}` — `cotton_tools::definitions::table_definitions`, which //! resolves every id through the same function the verbs resolve a table by: //! the shipped built-ins (a synced built-in row adds only the instructions a //! person edited), then every table a person defined, validated. A row that //! does not validate is in `refused` with its reason, never silently dropped, //! and never in `definitions` — the list offers no table the verbs refuse. //! `definitions.tools` answers the same envelope over `cotton_tool_definitions` //! (empty until a tool is imported). Neither takes arguments. //! //! Both are reads with no tool of their own: an assistant is told a table's //! shape by the verbs' own refusals and the definitions' instructions, and the //! app needs the whole list at once to draw from. use std::collections::BTreeSet; use serde_json::{json, Value}; use cotton_core::definitions::{ CommandKind, CommandOutcome, CommandPick, PickKind, RecordCommand, TableDefinition, COMMAND_METHODS, }; use cotton_tools::mcp::protocol::{tool_by_name, McpScope}; use crate::handle::CottonHandle; use crate::methods::MethodError; use crate::shell::client::ClientController; /// Resolve a table as a reader may act on it. A reader's replica is useful /// for every read, but its store refuses every write; leaving write acts in a /// definition makes the app offer work it cannot do. pub(crate) fn resolve_reader_acts(mut definition: TableDefinition) -> TableDefinition { let allowed: BTreeSet = definition .commands .iter() .flatten() .filter(|command| matches!(command.kind, CommandKind::Open | CommandKind::Copy)) .map(|command| command.id.clone()) .collect(); if let Some(commands) = &mut definition.commands { commands.retain(|command| allowed.contains(&command.id)); } definition.acts = None; // Editors and archive toggles also derive from column authority, without // naming a command. Resolve those implicit write affordances here too. for column in &mut definition.columns { column.readonly = Some(true); column.editable_when = None; } definition.add = Some(false); definition.create = None; definition.capture = None; definition.paste = None; if let Some(chips) = &mut definition.chips { chips.sends = None; } if let Some(conversation) = &mut definition.conversation { conversation.sends = None; conversation.queue = None; conversation.can_send = Some(cotton_core::definitions::CanSend::Always(false)); } let resolve_sections = |sections: &mut Vec| { for section in sections { section.answers = None; section.actions = None; if let Some(commands) = &mut section.commands { commands.retain(|id| allowed.contains(id)); } if let Some(list) = &mut section.list { list.add = None; } } }; resolve_sections(&mut definition.page); if let Some(sections) = &mut definition.owner_sections { resolve_sections(sections); } if let Some(sections) = &mut definition.lists { resolve_sections(sections); } if let Some(parts) = &mut definition.parts { if parts .acts .main .as_ref() .is_some_and(|id| !allowed.contains(id)) { parts.acts.main = None; } parts.acts.more.retain(|id| allowed.contains(id)); if parts .acts .away .as_ref() .is_some_and(|id| !allowed.contains(id)) { parts.acts.away = None; } for card in parts .cards .iter_mut() .flatten() .chain(parts.strip.iter_mut().flatten()) { if card.act.as_ref().is_some_and(|id| !allowed.contains(id)) { card.act = None; } if let Some(acts) = &mut card.acts { acts.retain(|act| { matches!( act.as_str(), "copy" | "call" | "message" | "video_call" | "email" | "open" | "share" | "open_day" ) }); } card.switches = None; if card .clear_command .as_ref() .is_some_and(|id| !allowed.contains(id)) { card.clear_command = None; } if card .pick_command .as_ref() .is_some_and(|id| !allowed.contains(id)) { card.pick_command = None; } } } if let Some(slips) = &mut definition.slips { for (_, acts) in slips.acts.0.iter_mut() { acts.retain(|act| { matches!( act.as_str(), "copy" | "call" | "message" | "video_call" | "email" | "open" | "share" | "open_day" ) }); } } definition.on_open = definition.on_open.filter(|id| allowed.contains(id)); definition } #[cfg(test)] mod reader_acts_guard { use super::*; /// RULE: Role resolution leaves a reader only acts that cannot write its /// copy. This checks the resolved page parts, including field-card and /// slip acts, because filtering a command list alone still leaves a draw /// surface that can offer an edit or a delete. #[test] fn a_reader_resolves_only_read_or_navigation_acts() { let harmless_slip = |act: &str| { matches!( act, "copy" | "call" | "message" | "video_call" | "email" | "open" | "share" | "open_day" ) }; for shipped in cotton_core::definitions::builtin_table_definitions() { let definition = resolve_reader_acts(shipped.clone()); assert!( definition.commands.iter().flatten().all(|command| { matches!(command.kind, CommandKind::Open | CommandKind::Copy) }), "{}: {:?}", definition.id, definition.commands ); assert!( definition .columns .iter() .all(|column| column.readonly == Some(true) && column.editable_when.is_none()), "{} offered a field editor", definition.id ); let parts = definition.resolved_parts(); for id in parts .acts .main .iter() .chain(parts.acts.more.iter()) .chain(parts.acts.away.iter()) { assert!( definition.command(id).is_some_and(|command| matches!( command.kind, CommandKind::Open | CommandKind::Copy )), "{}: {id}", definition.id ); } for card in parts .cards .iter() .flatten() .chain(parts.strip.iter().flatten()) { assert!( card.act .as_ref() .is_none_or(|id| definition.command(id).is_some_and(|command| matches!( command.kind, CommandKind::Open | CommandKind::Copy ))), "{}: {:?}", definition.id, card.act ); assert!( card.acts.iter().flatten().all(|act| harmless_slip(act)), "{}: {:?}", definition.id, card.acts ); assert!( card.switches.is_none() && card.clear_command.is_none() && card.pick_command.is_none(), "{}: {card:?}", definition.id ); } assert!( definition .slips .as_ref() .into_iter() .flat_map(|slips| slips.acts.iter()) .flat_map(|(_, acts)| acts) .all(|act| harmless_slip(act)), "{}: {:?}", definition.id, definition.slips ); } } } #[path = "settings_tables.rs"] pub(crate) mod settings_tables; /// Every generic verb's method name and the MCP tool it calls. pub const VERBS: [(&str, &str); 14] = [ ("groups.create", "create_group"), ("groups.delete", "delete_group"), ("groups.list", "list_groups"), ("groups.update", "update_group"), ("records.create", "create_record"), ("records.delete", "delete_record"), ("records.get", "get_record_by_table"), ("records.link", "link_records"), ("records.list", "list_records"), ("records.reorder", "reorder_records"), ("records.search", "search_records"), ("records.summarize", "summarize_records"), ("records.undo", "undo"), ("records.update", "update_record"), ]; /// Every method this module answers, sorted. pub const METHODS: [&str; 31] = [ "definitions.board", "definitions.catalogue", "definitions.contributors", "definitions.passedOver", "definitions.resetBoard", "definitions.saveBoard", "definitions.saveTable", "definitions.saveTheme", "definitions.tables", "definitions.theme", "definitions.undoTheme", "definitions.tools", "groups.create", "groups.delete", "groups.list", "groups.update", "records.command", "records.create", "records.delete", "records.get", "records.head", "records.link", "records.list", "records.page", "records.reorder", "records.resolve", "records.search", "records.spoken", "records.summarize", "records.undo", "records.update", ]; /// The code a read's refusal carries. A `records.get` of a record the table /// no longer holds (deleted, binned, never there) is `record_not_found`, so /// a page that just deleted its record reads "gone" and not "could not be /// read"; every other refusal is `unreadable`. pub fn read_refusal_code(method: &str, reason: &str) -> &'static str { if matches!(method, "records.get" | "records.page") && cotton_core::records::receipt::says_no_longer_here(reason) { "record_not_found" } else { "unreadable" } } /// The MCP tool a `records.*` method calls. pub fn tool_for(method: &str) -> Option<&'static str> { VERBS .iter() .find(|(name, _)| *name == method) .map(|(_, tool)| *tool) } /// Answer one of [`METHODS`]. pub fn call( client: &ClientController, method: &str, request: &Value, ) -> Result { call_with_definition(client, method, request, None) } /// The links by which a row names a hidden title: a season's film, an episode's series or season, a play's film or /// episode, a downloaded file's film, episode or download, a list member's record or list. use cotton_tools::mcp::handlers::tables::hidden::LINKS as HIDDEN_LINKS; /// Whether a row (as records answer it: `{ id, data }`, or flat) is hidden, or names a hidden one. fn names_hidden(row: &Value, shut: &std::collections::BTreeSet) -> bool { let data = row.get("data").unwrap_or(row); row["id"].as_str().is_some_and(|id| shut.contains(id)) || HIDDEN_LINKS.iter().any(|key| data[*key].as_str().is_some_and(|id| shut.contains(id))) } pub(super) fn call_with_definition( client: &ClientController, method: &str, request: &Value, mut captured: Option<&mut Option>, ) -> Result { // HIDDEN (review of a8580dbc38, A6): a hidden category of his films is not deleted from under its titles (they // would come back on Home unasked); he stops hiding it first. And the shared list of lists never names one. let deletes_group = matches!(method, "records.delete" | "records.bin" | "records.erase") && request["table"] == "record_group"; if method == "groups.delete" || method == "groups.list" || deletes_group { let (mut shut, mut titles) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new()); let mut hidden_in: std::collections::BTreeMap = std::collections::BTreeMap::new(); client .read_rows("groups.hidden", &mut |ctx| { let hiding = super::cinemas_home::hiding(ctx)?; (shut, titles) = (hiding.groups, hiding.titles); if !titles.is_empty() { for (id, data) in cotton_tools::mcp::handlers::tables::groups::live_groups(ctx.read.driver(), Some(ctx.workspace_id))? { let n = cotton_tools::mcp::handlers::tables::groups::members_of(&data).iter().filter(|m| titles.contains(m.as_str())).count() as u64; hidden_in.insert(id, n); } } Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?; if (method == "groups.delete" || deletes_group) && request["id"].as_str().is_some_and(|id| shut.contains(id)) { let said = cotton_core::rules::shell_lines::LineSet::shipped("cinemas").and_then(|lines| lines.say("stream.hidden_delete_first", &[])).unwrap_or_default(); return Err(MethodError::new("hidden_category", said)); } if method == "groups.list" && !shut.is_empty() { let mut answer = call_with_definition(client, "groups.list.all", request, captured)?; if let Some(groups) = answer.get_mut("groups").and_then(Value::as_array_mut) { groups.retain(|group| !group["id"].as_str().is_some_and(|id| shut.contains(id))); // An open list's first titles and its count never name or count a hidden one. for group in groups.iter_mut() { if let Some(top) = group.get_mut("top").and_then(Value::as_array_mut) { top.retain(|item| !item["id"].as_str().is_some_and(|id| titles.contains(id))); } let gone = group["id"].as_str().and_then(|id| hidden_in.get(id)).copied().unwrap_or(0); if let (true, Some(count)) = (gone > 0, group["count"].as_u64()) { group["count"] = Value::from(count.saturating_sub(gone)); } } } return Ok(answer); } } // HIDDEN (re-review items 3 and 6): the shared reads of his films' tables never name a hidden title or category // (any app, the Data app's own included); a hidden one asked by its id is not found. use cotton_tools::mcp::handlers::tables::hidden::FAMILY; let family = request["table"].as_str().is_some_and(|table| FAMILY.contains(&table)); // Review 4, M3: a change to one by its id, outside Hidden, finds nothing (a hidden title is not there to change). let changes = matches!(method, "records.update" | "records.delete" | "records.link") && family; // Core 3: the shared Bin (`table: "bin"`) never erases or changes a hidden title, even while Hidden is open: he // cannot see it in that Bin; it is emptied from the Bin inside Hidden (`cinemas.erase { hidden: true }`). let bin_change = matches!(method, "records.update" | "records.delete" | "records.erase") && request["table"] == "bin"; if bin_change || (changes && super::cinemas_home::inside_hidden(client, false).is_err()) { let id = request["id"].as_str().unwrap_or_default().to_string(); let mut named = false; client .read_rows("records.hidden", &mut |ctx| { let hiding = super::cinemas_home::hiding(ctx)?; let mut shut = hiding.titles; shut.extend(hiding.groups); named = shut.contains(&id); if !named && !id.is_empty() { if let Some(table) = request["table"].as_str().filter(|table| *table != "bin") { let made = cotton_tools::mcp::handlers::tables::made_table(table); let rows = ctx.db().all(&format!("SELECT * FROM {made} WHERE workspace_id = ? AND id = ?"), &[rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(id.clone())]).map_err(|e| e.to_string())?; if let Some(row) = rows.iter().map(super::songs::json_row).next() { named = names_hidden(&json!(row), &shut); } } } Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?; if named { return Err(MethodError::new("not_found", "no such record")); } } // Lists, pages and searches of his films' tables, across tables and of the shared Bin leave hidden rows out where // they read them (`tables::leave_out_hidden`, `search_tables::append`, `hidden::bin_shows`: CORE 4 and 5), so // nothing is dropped from their answers here. One row asked by its id is judged here: a hidden one, or one that // names a hidden title (a season's series, a play's film), is not found (re-review 3, finding 2). if matches!(method, "records.get" | "records.head") && (family || request["table"] == "bin") { let mut shut = std::collections::BTreeSet::new(); client .read_rows("records.hidden", &mut |ctx| { shut = super::cinemas_home::hiding(ctx)?.all(); Ok(Value::Null) }) .map_err(|why| MethodError::new("unreadable", why))?; if !shut.is_empty() { if request["id"].as_str().is_some_and(|id| shut.contains(id)) { return Err(MethodError::new("not_found", "no such record")); } let answer = call_with_definition(client, &format!("{method}.unfiltered"), request, captured)?; let row = answer.get("record").or_else(|| answer.get("row")).unwrap_or(&answer); if names_hidden(row, &shut) { return Err(MethodError::new("not_found", "no such record")); } return Ok(answer); } } let method = method.strip_suffix(".unfiltered").unwrap_or(method); let method = if method == "groups.list.all" { "groups.list" } else { method }; if request["table"] == "bin" { if method == "records.get" { if let Some(row) = super::database_bin::records(client) .map_err(|error| MethodError::new("unreadable", error))? .into_iter() .find(|row| row["id"] == request["id"]) { return Ok(row); } } if method == "records.list" { // Read the ordinary Bin in pages before applying the same list // contract to the union. No per-kind or first-page truncation. let mut args = json!({"table":"bin","limit":200,"page":0}); if let Some(today) = request.get("today") { args["today"] = today.clone(); } // A table's "Deleted · n" (`{table: "todo"}`) reads that kind's // binned rows alone; `finish` narrows the union by it again. if let Some(Value::Object(filter)) = request.get("where") { if filter.len() == 1 && filter.get("table").is_some_and(Value::is_string) { args["where"] = Value::Object(filter.clone()); } } let mut rows = Vec::new(); loop { let answer = ordinary_call_with_definition(client, method, &args, captured.take())?; rows.extend(answer["records"].as_array().into_iter().flatten().cloned()); let Some(next) = answer["next_page"].as_u64() else { break; }; if next <= args["page"].as_u64().unwrap_or(0) { return Err(MethodError::new( "unreadable", "The Bin page did not advance", )); } args["page"] = json!(next); } rows.extend( super::database_bin::records(client) .map_err(|error| MethodError::new("unreadable", error))?, ); rows.sort_by(|a, b| { b["data"]["trashed_at"] .as_str() .cmp(&a["data"]["trashed_at"].as_str()) .then_with(|| a["id"].as_str().cmp(&b["id"].as_str())) }); return super::settings_list::finish(client, "bin", request, json!({"records":rows})); } } ordinary_call_with_definition(client, method, request, captured) } fn ordinary_call_with_definition( client: &ClientController, method: &str, request: &Value, captured: Option<&mut Option>, ) -> Result { if let Some(answer) = settings_tables::call(client, method, request) { return answer; } match method { "definitions.contributors" => { let table = request["table"] .as_str() .map(str::trim) .filter(|table| !table.is_empty()) .ok_or_else(|| { MethodError::new( "bad_request", "definitions.contributors takes the table whose record page is being drawn", ) })?; client .read_rows("definitions.contributors", &mut |ctx| { let found = cotton_tools::definitions::table_contributors(ctx, table) .map_err(|failure| failure.to_string())?; Ok(serde_json::json!({ "contributors": found })) }) .map_err(|reason| MethodError::new("unreadable", reason)) } // The board a screen draws and the theme the database wears (design // note 26203e21): `{definition, drawn: "row"|"default", passed_over?}` // — never nothing for a screen this build ships a default for. "definitions.board" => { let id = request["id"] .as_str() .map(str::trim) .filter(|id| !id.is_empty()) .ok_or_else(|| { MethodError::new( "bad_request", "definitions.board takes the board's id (home, tools, database)", ) })?; client .read_rows("definitions.board", &mut |ctx| { let drawn = cotton_tools::presentation::board(ctx.read.driver(), ctx.workspace_id, id)? .ok_or_else(|| format!("there is no board {id:?}"))?; serde_json::to_value(drawn).map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason)) } // A person's board for a screen, and putting the default back — each // with the receipt and the undo the shared rules give every write. "definitions.saveBoard" => { let definition = request .get("definition") .filter(|definition| definition.is_object()) .ok_or_else(|| { MethodError::new( "bad_request", "definitions.saveBoard takes the board as {definition}", ) })? .clone(); let id = definition["id"].as_str().unwrap_or_default().to_string(); let before = client .write_rows("definitions.saveBoard", &mut |ctx| { let before = cotton_tools::presentation::save_board(ctx, &definition) .map_err(|failure| failure.to_string())?; Ok(serde_json::json!({ "before": before })) }) .map_err(|reason| MethodError::new("board_refused", reason))?; Ok(board_receipt(&id, "Board saved", before["before"].clone())) } "definitions.resetBoard" => { let id = request["id"] .as_str() .map(str::trim) .filter(|id| !id.is_empty()) .ok_or_else(|| { MethodError::new("bad_request", "definitions.resetBoard takes the board's id") })? .to_string(); let before = client .write_rows("definitions.resetBoard", &mut |ctx| { let before = cotton_tools::presentation::reset_board(ctx, &id) .map_err(|failure| failure.to_string())?; Ok(serde_json::json!({ "before": before })) }) .map_err(|reason| MethodError::new("board_refused", reason))?; Ok(board_receipt( &id, "Board put back to the default", before["before"].clone(), )) } // Design note 26203e21 §9: a board part this build cannot draw is // skipped, and said ONCE — one Feedback row per database, board and // part, whatever device or launch meets it (a person method: the row // is the person's, in their own Feedback list). "definitions.passedOver" => { let word = |key: &str| { request[key] .as_str() .map(str::trim) .filter(|word| !word.is_empty()) }; let (Some(board), Some(part), Some(database_id)) = (word("board"), word("part"), word("databaseId")) else { return Err(MethodError::new( "bad_request", "definitions.passedOver takes the board, the part and the databaseId", )); }; let database = word("databaseName").unwrap_or(database_id); let note = format!( "The {board} board in {database} names a part this build cannot draw, \"{part}\", so it was skipped. A newer Cotton draws it; update this device." ); let context = serde_json::json!({ "surface": "board", "board": board, "part": part, "databaseId": database_id, "databaseName": database }); let key = format!("board-part:{database_id}:{board}:{part}"); let wrote = client .write_rows("definitions.passedOver", &mut |ctx| { let wrote = crate::phone::feedback_note::file_once( ctx, &key, ¬e, context.as_object().cloned().unwrap_or_default(), )?; Ok(serde_json::json!({ "filed": wrote })) }) .map_err(|reason| MethodError::new("write_refused", reason))?; Ok(wrote) } "definitions.saveTable" => save_table(client, request), // The database wears an authored theme — its own row (`theme_save`). "definitions.saveTheme" => crate::phone::theme_save::save(client, request), "definitions.undoTheme" => crate::phone::theme_save::undo(client, request), // What the database wears; a family this build does not ship is said // once in Feedback (`theme_save::read`). "definitions.theme" => crate::phone::theme_save::read(client), // Every definition the database draws, resolved and decoded by the // core: the app's one source of them (`phone::catalogue`). "definitions.catalogue" => crate::phone::catalogue::call(client, request), "definitions.tables" => { let reader = client .device_scope() .map_err(|reason| MethodError::new("unreadable", reason))? == cotton_core::device::scope::DeviceScope::Reader; client .read_rows("definitions.tables", &mut |ctx| { let mut listed = cotton_tools::definitions::table_definitions(ctx) .map_err(|failure| failure.to_string())?; if reader { listed.definitions = listed .definitions .into_iter() .map(resolve_reader_acts) .collect(); } serde_json::to_value(listed).map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason)) } "definitions.tools" => client .read_rows("definitions.tools", &mut |ctx| { let listed = cotton_tools::definitions::tool_definitions(ctx) .map_err(|failure| failure.to_string())?; serde_json::to_value(listed).map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason)), "records.command" => command(client, request, &NoMethods), "records.spoken" => spoken(client, request, &NoMethods), "records.page" => page(client, request), // A list's head: what the core says of its table above the slips // (`super::list_head`). "records.head" => super::list_head::read(client, request), // A record before it exists (a blank page, a form), said as a read // says one: the dispatch's resolve step attaches its column words // and date parts, so the face draws them and spells nothing. // A list's own picture from this phone (its Set picture act): the // file kept under a picture key and queued up, as a book's cover is, // and named on the list in the same write. "groups.update" if request.get("picturePath").is_some() => list_picture(client, request), "records.resolve" => match request.get("data") { Some(Value::Object(data)) => Ok(json!({ "id": "", "table": request["table"], "data": data })), _ => Err(MethodError::new("bad_request", "records.resolve takes the record's data")), }, _ => { let Some(tool) = tool_for(method) else { return Err(MethodError::new( "unknown_method", format!("this core answers no `{method}`"), )); }; let is_read = tool_by_name(tool).is_some_and(|entry| entry.scope == McpScope::Read); let mut args = if is_read && matches!(tool, "list_records" | "get_record_by_table") { read_args(client, request)? } else { crate::phone::tool_arguments(request)? }; // A book's `on_phone` is this device's answer, // never stored: a list read by it reads what this device keeps. if tool == "list_records" { super::books::narrow_where(client, &mut args)?; super::songs::narrow_where(client, &mut args)?; super::films::narrow_where(client, &mut args)?; super::pictures_here::narrow_where(client, &mut args)?; super::meetings_app::narrow_where(client, &mut args)?; } if is_read { let engine_snapshot = args .get("table") .and_then(Value::as_str) .is_some_and(|table| matches!(table, "device" | "storage")); let read = if tool == "list_records" && captured.is_some() { let mut definition = None; let mut body = |ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>| { let (resolved, answer) = cotton_tools::mcp::handlers::tables::list_answer_resolved( ctx, &args, cotton_tools::mcp::handlers::tables::Total::Counted, ) .map_err(|error| error.to_string())?; definition = Some(resolved); Ok(answer) }; let answer = if engine_snapshot { client.read_rows_snapshot(tool, &mut body) } else { client.read_tool_rows(tool, &mut body) }; *captured.expect("capture supplied") = definition; answer } else if engine_snapshot { client.read_tool_snapshot(tool, &args) } else { client.read_tool(tool, &args) }; // A record not found while the copy has not come whole is // `not_here_yet`, never "no longer here" (`copy_standing`). let mut answer = read.map_err(|reason| { let refused = MethodError::new(read_refusal_code(method, &reason), reason); if refused.code == "record_not_found" { super::copy_standing::not_here(super::copy_standing::of(client), refused) } else { refused } })?; if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some("meeting") { answer_device_facts(client, &mut answer) .map_err(|reason| MethodError::new("unreadable", reason))?; } if let Some(table) = args.get("table").and_then(Value::as_str).filter(|table| super::films::TABLES.contains(table)) { if matches!(tool, "list_records" | "get_record_by_table") { super::films::answer_on_phone(client, table, &mut answer)?; } } if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some(super::books::BOOK_TABLE) { super::books::answer_on_phone(client, &mut answer)?; } if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some(super::meetings_app::MEETING) { super::meetings_app::answer_on_phone(client, &mut answer)?; } if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some(super::pictures_here::MEDIA_TABLE) { super::pictures_here::answer_on_phone(client, &mut answer)?; } if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some(super::songs::SONG_TABLE) { super::songs::answer_on_phone(client, &mut answer)?; } if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some(super::songs::ALBUM_TABLE) { super::songs::answer_albums_on_phone(client, &mut answer)?; } if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some("vault_key") { answer_vault_fingerprints(&mut answer); } if matches!(tool, "list_records" | "get_record_by_table") && args.get("table").and_then(Value::as_str) == Some("device") { answer_device_removals(client, &mut answer)?; // A Mac's last-heard and free disk from the one row it // writes about itself (295 rule 8), before this device // marks its own row. super::presence::on_device_records(client, &mut answer); mark_this_device(client, &mut answer); answer_this_device_preferences(client, &mut answer)?; } if matches!(tool, "list_records" | "get_record_by_table") { if let Some(table @ ("device" | "storage")) = args.get("table").and_then(Value::as_str) { answer_sync_state(client, table, &mut answer)?; } } Ok(answer) } else { client .write(tool, &args) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason)) } } } } /// `groups.update {id, picturePath}`: the picture at `picturePath` (a JPEG, /// PNG, GIF or WebP the phone wrote) kept under a picture key, queued up to /// the object, and set as the list's own picture (`update_group {picture}`), /// in one write with the list's receipt and Undo. fn list_picture(client: &ClientController, request: &Value) -> Result { let bad = |why: &str| MethodError::new("bad_request", why.to_string()); let id = request["id"].as_str().map(str::trim).filter(|id| !id.is_empty()).ok_or_else(|| bad("groups.update takes the list's id"))?.to_string(); let path = request["picturePath"].as_str().filter(|path| !path.is_empty()).map(std::path::PathBuf::from).ok_or_else(|| bad("picturePath is the path of the picture the phone wrote"))?; let layout = client.layout().clone(); client .write_rows("groups.update", &mut |ctx| { let workspace_id = ctx.workspace_id.to_string(); let now = cotton_tools::mcp::handlers::common::now_iso(ctx); let key = super::media::keep_picture(ctx, &layout, &workspace_id, &path, &now, "a list's picture")?; let mut args = serde_json::Map::new(); args.insert("id".into(), Value::from(id.clone())); args.insert(cotton_tools::mcp::handlers::tables::groups::PICTURE.into(), Value::from(key)); cotton_tools::mcp::handlers::tables::groups::update_group(ctx, &args).map_err(|failure| failure.to_string()) }) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason)) } /// Fill what only THIS device can say about a meeting /// (`cotton_core::definitions::DEVICE_ANSWERED_COLUMNS`): `waiting_to_upload`, /// read off the device-local media ledger by the same function the meetings /// list reads it with (`reads_work::meeting_row_facts`). A meeting not waiting /// is left without the key, as every shared read leaves it. fn answer_device_facts(client: &ClientController, answer: &mut Value) -> Result<(), String> { let listed = answer.get("records").is_some_and(Value::is_array); if !listed && answer.get("data").is_none() { return Ok(()); } let mut records: Vec<&mut Value> = if listed { answer["records"] .as_array_mut() .into_iter() .flatten() .collect() } else { vec![answer] }; let ids: Vec = records .iter() .filter_map(|record| record["id"].as_str().map(str::to_string)) .collect(); if ids.is_empty() { return Ok(()); } let facts = client.with_file(|replica| crate::phone::reads_work::meeting_row_facts(replica, &ids))?; for record in records.iter_mut() { let waiting = record["id"] .as_str() .and_then(|id| facts.get(id)) .is_some_and(|found| found["waitingToUpload"] == Value::Bool(true)); if let (true, Some(data)) = ( waiting, record.get_mut("data").and_then(Value::as_object_mut), ) { data.insert("waiting_to_upload".to_string(), Value::Bool(true)); } } Ok(()) } /// Say each device key's fingerprint (`DEVICE_ANSWERED_COLUMNS` `fingerprint`), /// computed here from the row's public half as `vault.keys` computes it /// (`vault::wrap::fingerprint`), never read off a stored column: a stored one /// could be written by whoever published the key, and the fingerprint is /// what the owner checks against the asking device's own screen. fn answer_vault_fingerprints(answer: &mut Value) { let listed = answer.get("records").is_some_and(Value::is_array); let records: Vec<&mut Value> = if listed { answer["records"].as_array_mut().into_iter().flatten().collect() } else { vec![answer] }; for record in records { let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) else { continue }; data.remove("fingerprint"); let said = data.get("public_key").and_then(Value::as_str).and_then(cotton_core::vault::wrap::fingerprint); if let Some(said) = said { data.insert("fingerprint".to_string(), Value::String(said)); } } } /// The calendar belongs to the reader, including a composed read which calls /// several records handlers in one transaction. Explicit caller context wins. pub(crate) fn read_args( client: &ClientController, request: &Value, ) -> Result, MethodError> { let mut args = crate::phone::tool_arguments(request)?; if let Some(zone) = client.time_zone() { args.entry("timezone").or_insert_with(|| Value::from(zone)); } Ok(args) } /// Mark the reading device's own `device` row: its status is `this device` /// and its state the word it calls itself /// (`cotton_core::device::words::this_device`). Only the reader knows which /// row is its own; a device with no identity yet marks none. fn answer_device_removals( client: &ClientController, answer: &mut Value, ) -> Result<(), MethodError> { let Some(me) = client.self_device_id() else { return Ok(()); }; let database = client .with_file(|file| Ok(file.workspace_id.to_string())) .map_err(|error: String| MethodError::new("unreadable", error))?; let pending = cotton_client::transport::device_removals::pending_devices( &client.layout().device_removals_json(&me), &database, ) .map_err(|error| MethodError::new("removal_unreadable", error))?; let records: Vec<&mut Value> = match answer.get_mut("records").and_then(Value::as_array_mut) { Some(records) => records.iter_mut().collect(), None => vec![answer], }; for record in records { let waiting = record["id"].as_str().is_some_and(|id| pending.contains(id)); if let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) { if waiting && data.get("revoked_at").is_none_or(Value::is_null) { data.insert("removal_state".into(), Value::from("waiting")); } else { data.remove("removal_state"); } } } Ok(()) } fn mark_this_device(client: &ClientController, answer: &mut Value) { let Some(me) = client.self_device_id() else { return; }; // HostNoun.swift `lowerCase`: the Mac app's core is built for macOS. let reader = if cfg!(target_os = "macos") { "this Mac" } else { "this phone" }; let records: Vec<&mut Value> = match answer.get_mut("records").and_then(Value::as_array_mut) { Some(records) => records.iter_mut().collect(), None => vec![answer], }; // Signed in or not, said only where this app backs up to a personal // object — it syncs and its database is the person's own (Cotton; not a // business app): the column Sign in and Sign out are offered on // (`device.json`), read once per answer. An app that never syncs (Rigby) // says `local`, so Sync now is not offered where nothing ever syncs. Asked // of this client, never of a process-wide declaration. let session = if !client.syncs() { Some(LOCAL) } else { (client.genesis() == cotton_core::genesis::Genesis::Personal) .then(|| if client.signed_in() { SIGNED_IN } else { SIGNED_OUT }) }; // Add and Remove sample records stand on this device's row where the app // keeps no personal object to sign in to (Rigby, a business app) and on // every development build (`Flavor::Dev`: Cotton Dev, Books, Music and // Cinemas Dev), never on a live Cotton's: what `device.json`'s two acts // are offered on. let samples = !matches!(session, Some(SIGNED_IN | SIGNED_OUT)) || client.flavor() == Some(cotton_core::flavor::Flavor::Dev); for record in records { let own = record["id"].as_str() == Some(me.as_str()); if let (true, Some(data)) = (own, record.get_mut("data").and_then(Value::as_object_mut)) { cotton_core::device::words::this_device(data, reader); data.insert("devices_route".to_string(), Value::from("/devices")); if let Some(session) = session { data.insert(SESSION.to_string(), Value::from(session)); } if samples { data.insert(SAMPLES.to_string(), Value::from(SAMPLES_OFFERED)); } } } } /// This device's row's sign-in column and its two values (`device.json`). pub const SESSION: &str = "session"; pub const SIGNED_IN: &str = "signed_in"; pub const SIGNED_OUT: &str = "signed_out"; /// An app that never syncs (Rigby): nothing to sign in to, nothing to sync. pub const LOCAL: &str = "local"; /// This device's row's sample records column and its one value (`device.json`). pub const SAMPLES: &str = "samples"; pub const SAMPLES_OFFERED: &str = "offered"; /// Project the one copy reading onto this installation's Device and Storage /// rows. Read once per answer, after the engine snapshot releases its reader; /// remote devices and count-only answers never borrow this device's state. fn answer_sync_state( client: &ClientController, table: &str, answer: &mut Value, ) -> Result<(), MethodError> { let Some(own) = client.self_device_id() else { return Ok(()); }; let records: Vec<&mut Value> = match answer.get_mut("records").and_then(Value::as_array_mut) { Some(records) => records.iter_mut().collect(), None => vec![answer], }; let mut state = None; for record in records { let here = if table == "device" { record["id"] == own } else { record["data"]["device_id"] == own }; if !here { continue; } let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) else { continue; }; if state.is_none() { state = Some(super::sync_state::this_device_state(client)?); } data.extend(state.as_ref().expect("sync state was read").clone()); if table == "device" && !client.syncs() { super::device_here::without_sync(data); } } Ok(()) } /// Add the notification switches only to this installation's row. They live /// beside its client data, so a synced device row never claims another /// device's local preferences. fn answer_this_device_preferences( client: &ClientController, answer: &mut Value, ) -> Result<(), MethodError> { let Some(me) = client.self_device_id() else { return Ok(()); }; let preferences = crate::phone::device_preferences::facts(client)?; let Some(local) = preferences.get("data").and_then(Value::as_object) else { return Ok(()); }; let records: Vec<&mut Value> = match answer.get_mut("records").and_then(Value::as_array_mut) { Some(records) => records.iter_mut().collect(), None => vec![answer], }; for record in records { if record["id"].as_str() == Some(me.as_str()) { if let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) { data.extend(local.clone()); } } } Ok(()) } /// `records.page`: the record page in words, read through the generic verbs. fn page(client: &ClientController, request: &Value) -> Result { page_with(client, None, request) } /// The handle-aware page path: live engine rows (repository bytes and runner /// state) must be read through their signed host route even when a page asks /// for them again while assembling its cards. pub fn page_on(handle: &CottonHandle, request: &Value) -> Result { page_with(&handle.client(), Some(handle), request) } fn page_with( client: &ClientController, handle: Option<&CottonHandle>, request: &Value, ) -> Result { let named = |key: &str| { request .get(key) .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) }; let bad = |what: &str| MethodError::new("bad_request", format!("`records.page` needs {what}")); let table = named("table").ok_or_else(|| bad("a table"))?; let id = named("id").ok_or_else(|| bad("a record id"))?; let mut source = ClientPages { client, handle, made: None, refused: None, }; // One read answers the whole page: its opening, head, fact slips, the // lists that link to it with their counts and peeks, views and acts. let page = cotton_core::records::page::record_page_read(&mut source, table, id, named("view")) .map_err(|reason| page_refusal(reason, source.refused.take()))?; serde_json::to_value(page).map_err(|error| MethodError::new("unreadable", error.to_string())) } /// The refusal a page that could not be made answers. When the read that /// failed it was refused in TYPES — a transport's `server_refused` with its /// `details.status`, a cut read — the page answers that refusal itself, so /// `dispatch` says a Mac that never answered as the typed `mac_away` line and /// never as an `unreadable` carrying the transport's words (294 walk row G). /// Only a refusal the page itself made (a gone record, no such table) is /// coded here. fn page_refusal(reason: String, refused: Option) -> MethodError { match refused { Some(typed) if typed.message == reason => typed, _ => MethodError::new(read_refusal_code("records.page", &reason), reason), } } /// The handle's list boundary: native readers retain their own adapters; /// ordinary lists carry their already-resolved definition into slip rendering. pub(crate) fn list_on(handle: &CottonHandle, request: &Value) -> Result { let method = "records.list"; let client = handle.client(); // A view the app's kit folds into its one tool reads as its own tool's // (Cotton People's people/wishes is Birthdays' birthdays/wishes). let renamed; let request = match super::tool_acts::unfolded_view(&client, request)? { Some(asked) => { renamed = asked; &renamed } None => request, }; // A light read (`light: true`, a whole list's cut): the stored columns // alone, no slip, card or live columns said over them. let light = request.get("light") == Some(&Value::Bool(true)); let stripped; let request = if light { let mut asked = request.clone(); if let Some(asked) = asked.as_object_mut() { asked.remove("light"); } stripped = asked; &stripped } else { request }; let mut definition = None; let mut answer = if let Some(answer) = crate::phone::settings_message_imports::call(handle, method, request) { answer.and_then(|answer| { crate::phone::settings_list::finish(&client, "message_import", request, answer) })? } else if let Some(answer) = super::settings_devices::records_read_using(handle, method, request, Some(&mut definition)) { answer? } else if let Some(answer) = super::metering::records_read(handle, method, request) { answer? } else if let Some(answer) = settings_tables::call_on(handle, method, request) { answer? } else { call_with_definition(&client, method, request, Some(&mut definition))? }; // A narrow cut (`cut: true`, light too) is its rows' ids and columns alone. if light && request.get("cut") == Some(&Value::Bool(true)) { return Ok(answer); } if let Some(dealt) = group_deck(&client, Some(handle), request, &answer, definition.as_ref())? { return Ok(dealt); } if light { return Ok(answer); } outage_now_first(&client, request, &mut answer); resolve_slips_using(handle, method, request, &mut answer, definition, Live::Read)?; Ok(answer) } /// A group deck's read (`FaceId::GROUP`, Money's By person): the view's /// rows read whole, every page after the first, and answered as one card /// per record the card's people place names (`records::card::deal_groups`), /// each under its group's id with nothing more to page. Nil for any other /// read, and for a group view asked for its count, its ids or a section. pub(super) fn group_deck( client: &ClientController, handle: Option<&CottonHandle>, request: &Value, answer: &Value, definition: Option<&TableDefinition>, ) -> Result, MethodError> { use cotton_core::definitions::card::{CardSlot, FaceId}; use cotton_core::records::card::{deal_groups, CardPerson, CARD_KEY}; use cotton_core::records::page::PageSource; let Some((definition, card)) = definition.and_then(|definition| Some((definition, definition.card.as_ref()?))) else { return Ok(None); }; if card.face != FaceId::GROUP || ["ids", "count_only", "last_changed", "section"].iter().any(|key| request.get(*key).is_some_and(|v| !v.is_null())) { return Ok(None); } let Some((by, linked)) = card .fields .iter() .find(|field| field.slot == CardSlot::People) .and_then(|field| field.column.as_deref()) .and_then(|by| Some((by, definition.column(by)?.link_to.as_deref()?))) else { return Ok(None); }; let mut rows = rows_of(answer); let mut next = answer["next_page"].as_u64(); while let Some(page) = next { let mut args = request.clone(); args["page"] = json!(page); args["limit"] = json!(cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE); let more = call_with_definition(client, "records.list", &args, None)?; let read = rows_of(&more); next = more["next_page"].as_u64().filter(|after| *after > page && !read.is_empty()); rows.extend(read); } let mut source = ClientPages { client, handle, made: None, refused: None }; let lines = source.line_rows(); let words = cotton_core::records::page::Words::of_rows(&lines); let cards = cotton_core::records::card::card_words(&lines); let mut ids: Vec = Vec::new(); for (_, data) in &rows { for id in cotton_core::records::card::linked_ids(data.get(by)) { if !ids.contains(&id) { ids.push(id); } } } let mut people = std::collections::HashMap::new(); if let (false, Some(table)) = (ids.is_empty(), source.definition(linked)) { // A linked table no read answers today names nobody; the cards stand. for (id, data) in source.records(linked, &ids).unwrap_or_default() { people.insert(id, CardPerson::of(&table, &data, &words.dates)); } } let zone = source.time_zone().unwrap_or_else(|| "Etc/UTC".into()); let now = source.now().unwrap_or_else(chrono::Utc::now); let dealt = deal_groups(card, definition, &rows, &people, &zone, now, &words, &cards); let records: Vec = dealt .into_iter() .map(|group| { let id = if group.value.is_empty() { "none".to_string() } else { group.value.clone() }; json!({"table": definition.id, "id": id, "data": {(by): group.value, (CARD_KEY): group.card}}) }) .collect(); Ok(Some(json!({"table": definition.id, "total": records.len(), "next_page": null, "records": records}))) } /// Outages' first page leads with the one happening now, as this device /// sees it (`sync_state::outage_now`); a narrowed or counted read does not. fn outage_now_first(client: &ClientController, request: &Value, answer: &mut Value) { if request["table"] != "outage" || request["page"].as_u64().unwrap_or(0) != 0 || ["ids", "where", "query", "count_only", "last_changed"] .iter() .any(|key| request.get(*key).is_some_and(|v| !v.is_null())) { return; } let Some(now) = super::sync_state::outage_now(client) else { return; }; if let Some(records) = answer.get_mut("records").and_then(Value::as_array_mut) { records.insert(0, now); if let Some(total) = answer["total"].as_u64() { answer["total"] = Value::from(total + 1); } } } /// Attach resolved display words to record responses while the caller's /// database scope is held. A named subtitle opts into the core's renderer. pub(crate) fn resolve_slips_on( handle: &CottonHandle, method: &str, request: &Value, answer: &mut Value, ) -> Result<(), MethodError> { resolve_slips_using(handle, method, request, answer, None, Live::Read) } /// [`resolve_slips_on`] over a record that already carries its live read's /// columns: the live read itself (`device.facts`) dealing its card. pub(crate) fn resolve_live_slips_on( handle: &CottonHandle, method: &str, request: &Value, answer: &mut Value, ) -> Result<(), MethodError> { resolve_slips_using(handle, method, request, answer, None, Live::Carried) } /// Whether a record read still owes its table's live read /// (`records_live::overlay`) before its cards are dealt. #[derive(Clone, Copy, PartialEq, Eq)] enum Live { Read, Carried, } fn resolve_slips_using( handle: &CottonHandle, method: &str, request: &Value, answer: &mut Value, definition: Option, live: Live, ) -> Result<(), MethodError> { use cotton_core::records::page::PageSource; if !method.starts_with("records.") || !carries_records(answer) { return Ok(()); } let Some(table) = request["table"].as_str() else { return Ok(()); }; let client = handle.client(); let mut source = ClientPages { client: &client, handle: Some(handle), made: None, refused: None, }; let definition = match definition { Some(definition) => definition, None => match source.definition(table) { Some(definition) => definition, None => return Ok(()), }, }; if live == Live::Read && matches!(method, "records.get" | "records.list") { super::records_live::overlay(handle, &definition, answer); } if definition.slip.lines.is_some() { source .made .get_or_insert_with(Vec::new) .push(definition.clone()); attach_slip_rows(&mut source, &definition, answer); } // Asked whole (`said`), every record carries the one slip answer. let said = request["said"] == true; let (subtitle, caption) = resolved_slip_slots(&definition); if !said && !subtitle && !caption && definition.slip.figure.is_none() && definition.upcoming.is_none() && definition.card.is_none() && !cotton_core::records::page::reads_column_words(&definition) { return Ok(()); } let zone = source.time_zone(); let now = source.now(); let headed = day_headed(&definition, request); let rows = source.line_rows(); let words = cotton_core::records::page::Words::of_rows(&rows); if let (Some(card), Some(now)) = (&definition.card, now) { let cards = cotton_core::records::card::card_words(&rows); let groups = card_groups(&client, &definition, card, answer, &cards); let people = card_people(&mut source, &definition, card, answer, &words); let histories = card_histories(&mut source, &definition, card, answer, &words, &rows, zone.as_deref().unwrap_or("Etc/UTC"), now)?; // A table of several faces is dealt in the one the person chose. let chosen = if card.offers.len() > 1 { super::face_choice::of(&client, &definition.id, method)? } else { None }; attach_cards(&definition, card, zone.as_deref().unwrap_or("Etc/UTC"), now, answer, &words, &cards, &groups, &people, &histories, chosen.as_ref().map(|choices| &choices.chosen)); attach_statement_rows(&mut source, &definition, answer, &words, zone.as_deref().unwrap_or("Etc/UTC"), now)?; attach_health(&mut source, &definition, answer, &words, &cards, zone.as_deref().unwrap_or("Etc/UTC"), now); } attach_slip_lines(&definition, zone.as_deref(), now, headed, answer, &words); if said { attach_said(&definition, zone.as_deref().unwrap_or("Etc/UTC"), now, headed, answer, &words); } Ok(()) } /// Read the postings once with the account card, through the same visible /// list and calendar window as Money. A face never performs a second read. fn attach_statement_rows( source: &mut ClientPages, definition: &TableDefinition, answer: &mut Value, words: &cotton_core::records::page::Words, zone: &str, now: chrono::DateTime, ) -> Result<(), MethodError> { use cotton_core::records::page::Moment; use chrono::Datelike; if definition.id != "money_account" { return Ok(()); } let Some(today) = Moment::now(now, zone) else { return Ok(()); }; let (year, month, _) = cotton_core::transforms::zoned_clock::civil_from_days(today.day); let dates: Vec = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, 1) .expect("the local clock has a valid month").iter_days() .take_while(|date| date.month() == month as u32) .map(|date| date.format("%Y-%m-%d").to_string()).collect(); let records: Vec<&mut Value> = match answer { Value::Object(object) if object.contains_key("records") => object.get_mut("records").and_then(Value::as_array_mut).map(|rows| rows.iter_mut().collect()).unwrap_or_default(), one => vec![one], }; for record in records { let Some(id) = record["id"].as_str() else { continue; }; let postings = source.ask("records.list", serde_json::json!({ "table":"transaction", "where":{"account_id":id, "status":"actual", "moves_money":true, "occurred_on":{"values":dates}}, "limit":6 })).map_err(|error| MethodError::new("statement_read", error))?; let rows = cotton_core::records::card::statement_rows(&rows_of(&postings), zone, now, words); if let Some(fields) = record["data"]["@card"]["fields"].as_object_mut() { fields.insert("rows".into(), Value::Array(rows)); } } Ok(()) } /// A health record's card carries what its face draws (`health_card`): a /// day's measure its reading against the weeks before it, read once a day /// however many cards stand on it; a workout its stopwatch's words; a /// measurement its tag's. A day this copy cannot read is read as holding /// nothing: the card still says its own value. fn attach_health( source: &mut ClientPages, definition: &TableDefinition, answer: &mut Value, words: &cotton_core::records::page::Words, cards: &cotton_core::rules::shell_lines::LineSet, zone: &str, now: chrono::DateTime, ) { use super::health_card; if !health_card::carries(&definition.id) { return; } let records: Vec<&mut Value> = match answer { Value::Object(object) if object.contains_key("records") => object.get_mut("records").and_then(Value::as_array_mut).map(|rows| rows.iter_mut().collect()).unwrap_or_default(), one => vec![one], }; let mut days = health_card::DayRows::new(); for record in records { if !record["data"]["@card"]["fields"].is_object() { continue; } let Some(row) = record["data"].as_object().cloned() else { continue }; let (key, words) = match definition.id.as_str() { cotton_core::health::rows::DAY_TABLE => { let Some(day) = row.get("day").and_then(Value::as_str).map(str::to_string) else { continue }; let around = days.around(&day, |on| { source.ask("records.list", serde_json::json!({"table": cotton_core::health::rows::DAY_TABLE, "where": {"day": on}, "limit": 500})) .map(|listed| rows_of(&listed).into_iter().map(|(_, data)| data).collect()) .unwrap_or_default() }); ("reading", health_card::reading(definition, &row, &around, cards)) } cotton_core::health::rows::WORKOUT_TABLE => ("workout", health_card::workout(definition, &row, zone, now, words, cards)), _ => ("tag", health_card::tag(definition, &row, zone, now, words, cards)), }; if let Some(fields) = record["data"]["@card"]["fields"].as_object_mut() { fields.insert(key.into(), Value::Object(words)); } } } /// Thread faces draw the six visible messages carried by the core's card, /// never a second phone read after that card has appeared. #[allow(clippy::too_many_arguments)] fn card_histories( source: &mut ClientPages, definition: &TableDefinition, card: &cotton_core::definitions::card::CardFace, answer: &Value, words: &cotton_core::records::page::Words, rows: &[cotton_core::rules::shell_lines::LineRow], zone: &str, now: chrono::DateTime, ) -> Result, MethodError> { use cotton_core::records::page::PageSource; let mut histories = std::collections::HashMap::new(); let is_thread = |face: cotton_core::definitions::card::FaceId| matches!(face.as_str(), "thread" | "thread.slips"); if !is_thread(card.face) && !card.offers.iter().copied().any(is_thread) && !card.faces.iter().any(|choice| is_thread(choice.face)) { return Ok(histories); } let Some(layout) = definition.conversation.as_ref() else { return Ok(histories); }; let Some(link) = layout.links.first() else { return Ok(histories); }; let messages = source.definition(&layout.table).ok_or_else(|| MethodError::new("definition_missing", "the thread's message definition is missing"))?; let format = cotton_core::rules::shell_lines::LineSet::of_rows("format", rows) .ok_or_else(|| MethodError::new("lines_missing", "the thread's history has no format lines to say its times in"))?; let records: Vec<&Value> = match answer["records"].as_array() { Some(records) => records.iter().collect(), None => vec![answer], }; for record in records { if !answers_for(definition, record) { continue; } let Some(id) = record["id"].as_str() else { continue; }; let filter = serde_json::Map::from_iter([(link.clone(), Value::String(id.to_string()))]); let (total, recent) = source.list(&layout.table, &filter, 6).map_err(|error| MethodError::new("thread_history_read", error))?; // `page` is an offset, not a page number. Read precisely the oldest // visible row for the year, without filling fifty unrelated slips. let oldest = if total > 6 { rows_of( &source .ask("records.list", serde_json::json!({"table": layout.table, "where": filter, "page": total - 1, "limit": 1})) .map_err(|error| MethodError::new("thread_history_read", error))?, ) } else { recent.clone() }; let oldest_stamp = oldest.iter().filter_map(|(_, data)| data.get(&layout.at).and_then(Value::as_str)).min(); let history = cotton_core::records::card::thread_history( layout, &messages, record["data"]["kind"] == "group", &recent, total, oldest_stamp, zone, now, words, &format, ); histories.insert(id.to_string(), history); } Ok(histories) } /// The groups each record of this answer stands in, by record id, their /// names in the groups' own order joined by the cards set's `join` line — /// read only when the card has a group place. One query for the answer. fn card_groups( client: &ClientController, definition: &TableDefinition, card: &cotton_core::definitions::card::CardFace, answer: &Value, cards: &cotton_core::rules::shell_lines::LineSet, ) -> std::collections::HashMap { use cotton_core::definitions::card::CardSlot; let mut named = std::collections::HashMap::new(); if !card.fields.iter().any(|field| field.slot == CardSlot::Group) { return named; } let ids: Vec = match answer.get("records").and_then(Value::as_array) { Some(records) => records.iter().filter_map(|record| record["id"].as_str().map(str::to_string)).collect(), None => answer["id"].as_str().map(str::to_string).into_iter().collect(), }; if ids.is_empty() { return named; } let marks = vec!["?"; ids.len()].join(","); let sql = format!( "SELECT m.record_id AS record_id, g.name AS name FROM cotton_group_members m \ JOIN cotton_groups g ON g.id = m.group_id AND g.workspace_id = m.workspace_id \ WHERE m.workspace_id = ? AND g.table_id = ? AND g.deleted_at IS NULL AND m.record_id IN ({marks}) \ ORDER BY g.position, g.name" ); let rows = client .with_file(|file| { let text = |value: &str| rusqlite::types::Value::Text(value.to_string()); let mut params = vec![text(file.workspace_id), text(&definition.id)]; params.extend(ids.iter().map(|id| text(id))); file.driver.all(&sql, ¶ms).map_err(|error| error.to_string()) }) .unwrap_or_default(); let join = cards.say("join", &[]).unwrap_or_default(); let mut lists: std::collections::HashMap> = std::collections::HashMap::new(); for row in rows { if let (Some(id), Some(name)) = (row.text("record_id"), row.text("name")) { lists.entry(id.to_string()).or_default().push(name.to_string()); } } for (id, names) in lists { named.insert(id, names.join(&join)); } named } /// The records each card's people and account places name, by id: every /// record of this answer's link columns read in one batch per linked table, /// each said as its name and picture. A read carries no link expansion, so /// the card resolver reads them here, once for the answer. fn card_people( source: &mut ClientPages, definition: &TableDefinition, card: &cotton_core::definitions::card::CardFace, answer: &Value, words: &cotton_core::records::page::Words, ) -> std::collections::HashMap { use cotton_core::records::card::{linked_ids, linked_places, CardPerson}; use cotton_core::records::page::PageSource; let mut known = std::collections::HashMap::new(); for (_, key, table) in linked_places(card, definition) { let mut ids: Vec = Vec::new(); let mut note_people = |record: &Value| { if !answers_for(definition, record) { return; } for id in linked_ids(record["data"].get(key)) { if !ids.contains(&id) { ids.push(id); } } }; match answer.get("records").and_then(Value::as_array) { Some(records) => records.iter().for_each(&mut note_people), None => note_people(answer), } if ids.is_empty() { continue; } let Some(linked) = source.definition(table) else { continue; }; // A linked table no read answers today names nobody; the card stands. let Ok(found) = source.records(table, &ids) else { continue; }; for (id, data) in found { known.insert(id, CardPerson::of(&linked, &data, &words.dates)); } } known } /// Whether `record` is one of `definition`'s own rows, to be dealt its card, /// its people, its history and its slip lines: a record of the table, or — /// for a view — of the source table the view's rows are (`rows_table`). /// A view's read answers each row as its source's record, so it opens as /// one (`Stored::to_json`); matched against the view's id alone, every row /// of Owed was passed over and its deck drew the bare plain face instead of /// the view's receipt (6 Nov 2026). A record of any other table — one an /// answer carries beside its own — is still left alone. fn answers_for(definition: &TableDefinition, record: &Value) -> bool { record["table"].as_str().is_none_or(|table| table == definition.id || table == definition.rows_table()) } /// Each record's card, resolved against this read's now (`records::card`): /// the deck draws what lands under `@card` and composes no words. #[allow(clippy::too_many_arguments)] fn attach_cards( definition: &TableDefinition, card: &cotton_core::definitions::card::CardFace, zone: &str, now: chrono::DateTime, answer: &mut Value, words: &cotton_core::records::page::Words, cards: &cotton_core::rules::shell_lines::LineSet, groups: &std::collections::HashMap, people: &std::collections::HashMap, histories: &std::collections::HashMap, chosen: Option<&serde_json::Map>, ) { let resolve = |record: &mut Value| { if !answers_for(definition, record) { return; } let id = record["id"].as_str().unwrap_or_default().to_string(); let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) else { return }; let around = cotton_core::records::card::Around { group: groups.get(&id).map(String::as_str), people: Some(people), writable: true, thread: histories.get(&id) }; let resolved = cotton_core::records::card::resolve(card, definition, &id, data, zone, now, words, cards, around); if let Some(mut value) = resolved.and_then(|card| serde_json::to_value(card).ok()) { if let Some(drawn) = value["face"].as_str().filter(|_| chosen.is_some()).map(str::to_string) { value["face"] = json!(crate::methods::shell_deck::wear(definition, chosen, &drawn, data)); } data.insert(cotton_core::records::card::CARD_KEY.into(), value); } }; if let Some(records) = answer.get_mut("records").and_then(Value::as_array_mut) { records.iter_mut().for_each(resolve); } else if answer.get("data").is_some() { resolve(answer); } } /// Whether the list this read draws heads each day, so a slip's date under /// it says its clock time alone. A day-split table read whole, or one of the /// plan's own day sections (coming, earlier, one day, today), is drawn /// under day headings or a title naming the day; a tool view's other /// section (Calendar's "upcoming") is one flat list, and says the day. fn day_headed(definition: &TableDefinition, request: &Value) -> bool { (definition.day_grouping.is_some() || definition.by_day.is_some()) && matches!( request["section"].as_str(), None | Some("coming" | "earlier" | "today" | "day") ) } /// Count and stamp answers carry no records to draw. In particular Everything /// asks these for every table; none needs a definition or slip inputs. fn carries_records(answer: &Value) -> bool { let record = |value: &Value| value.get("data").is_some_and(Value::is_object); (answer.get("id").is_some() && record(answer)) || answer .get("records") .and_then(Value::as_array) .is_some_and(|rows| rows.iter().any(record)) || ["record", "before", "after"] .iter() .any(|key| answer.get(key).is_some_and(record)) } /// Every record of `definition`'s table the answer carries. fn answered_records<'a>(definition: &TableDefinition, answer: &'a mut Value) -> Vec<&'a mut Value> { let mut found = Vec::new(); if answer.get("id").is_some() && answer.get("data").is_some() { found.push(answer); } else { let Some(object) = answer.as_object_mut() else { return found; }; for (key, value) in object.iter_mut() { match key.as_str() { "records" => found.extend(value.as_array_mut().into_iter().flatten()), "record" | "before" | "after" => found.push(value), _ => {} } } } found.retain(|record| { record["table"] .as_str() .is_none_or(|table| table == definition.id) && record.get("data").is_some_and(Value::is_object) }); found } /// `slip.lines` on each record: the core's lines, which the app draws. fn attach_slip_rows( source: &mut ClientPages<'_>, definition: &TableDefinition, answer: &mut Value, ) { let records = answered_records(definition, answer); let ids: Vec = records .iter() .filter_map(|record| record["id"].as_str().map(str::to_string)) .collect(); let Ok(said) = cotton_core::records::page::resolve_slip_rows(source, definition, &ids) else { return; }; for record in records { let lines = record["id"] .as_str() .and_then(|id| said.get(id)) .cloned() .unwrap_or_default(); if let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) { data.insert( cotton_core::records::page::SLIP_LINES_KEY.into(), Value::from(lines), ); } } } fn resolved_slip_slots(definition: &TableDefinition) -> (bool, bool) { let named = definition.slip.with_names == Some(true); let formatted_caption = definition.slip.caption.as_ref().is_some_and(|caption| { caption .columns .iter() .flatten() .chain(caption.dates.iter().flatten()) .chain(caption.fields.iter().flatten()) .any(|key| { definition.column(key).is_some_and(|column| { column.format.is_some() || column.units.is_some() || matches!( column.column_type, cotton_core::definitions::ColumnType::Text | cotton_core::definitions::ColumnType::Longtext | cotton_core::definitions::ColumnType::Date ) }) }) }); ( named || cotton_core::records::page::subtitle_reads(definition), named || formatted_caption, ) } fn attach_slip_lines( definition: &TableDefinition, zone: Option<&str>, now: Option>, day_headed: bool, answer: &mut Value, said_in: &cotton_core::records::page::Words, ) { // A list split by day: each slip's foot is said by the core against this // read's now, with a series' missed count taken across the whole answer. let dated = now.filter(|_| definition.upcoming.is_some()); let missed = dated .map(|now| { let records = answer .get("records") .and_then(Value::as_array) .into_iter() .flatten() .chain(answer.get("data").is_some().then_some(&*answer)) .filter(|record| record["table"].as_str().is_none_or(|table| table == definition.id)) .filter_map(|record| record.get("data").and_then(Value::as_object)); cotton_core::records::page::missed_by_series( definition, records, zone.unwrap_or("Etc/UTC"), now, ) }) .unwrap_or_default(); let resolve = |record: &mut Value| { if !answers_for(definition, record) { return; } let Some(data) = record.get_mut("data").and_then(Value::as_object_mut) else { return; }; data.extend(cotton_core::records::page::computed_column_values( definition, data, now, )); // Each link says what kind of record it is (`format` › `mark.
`). for link in data.get_mut("links").and_then(Value::as_array_mut).into_iter().flatten() { if let Some(link) = link.as_object_mut() { if let Some(kind) = link.get("table").and_then(Value::as_str) { let word = said_in.kind_word(kind); link.insert("kind_word".into(), Value::String(word)); } } } if let Some(now) = now { let days = cotton_core::records::page::day_parts(definition, data, zone.unwrap_or("Etc/UTC"), now, &said_in.dates); if !days.is_empty() { data.insert(cotton_core::records::page::DAY_PARTS_KEY.into(), Value::Object(days)); } // A record's links (the engine's `links` list) carry each one's day too. for link in data.get_mut("links").and_then(Value::as_array_mut).into_iter().flatten() { if let Some(link) = link.as_object_mut() { cotton_core::records::page::attach_stamp_parts(link, &["when"], zone.unwrap_or("Etc/UTC"), now, &said_in.dates); } } } let numbers = cotton_core::records::page::number_parts(definition, data); if !numbers.is_empty() { data.insert(cotton_core::records::page::NUMBER_PARTS_KEY.into(), Value::Object(numbers)); } let words = cotton_core::records::page::column_words(definition, data, zone, now, said_in); if !words.is_empty() { data.insert( cotton_core::records::page::COLUMN_WORDS_KEY.into(), Value::Object(words), ); } if let Some(now) = dated { cotton_core::records::page::attach_dated_lines( definition, data, zone.unwrap_or("Etc/UTC"), now, &missed, &said_in.dates, ); } let lines = cotton_core::records::page::resolve_slip_lines(definition, data, zone, now, day_headed, said_in); let (subtitle, caption) = resolved_slip_slots(definition); if definition.slip.figure.is_some() { let figure = cotton_core::records::page::resolve_slip_figure(definition, data, zone, now, said_in); data.insert( cotton_core::records::page::SLIP_FIGURE_KEY.into(), figure.map(Value::String).unwrap_or(Value::Null), ); } if subtitle { data.insert( cotton_core::records::page::SLIP_SUBTITLE_KEY.into(), lines.subtitle.map(Value::String).unwrap_or(Value::Null), ); } if caption { data.insert( cotton_core::records::page::SLIP_CAPTION_LATE_KEY.into(), Value::Bool(lines.caption_late), ); data.insert( cotton_core::records::page::SLIP_CAPTION_KEY.into(), lines.caption.map(Value::String).unwrap_or(Value::Null), ); } }; if answer.get("id").is_some() && answer.get("data").is_some() { resolve(answer); } if let Some(records) = answer.get_mut("records").and_then(Value::as_array_mut) { for record in records { resolve(record); } } for key in ["record", "before", "after"] { if let Some(record) = answer.get_mut(key) { resolve(record); } } } /// A shell's own `records.*` ask: every record it is answered carries its /// slip (`attach_said`), whole on the first paint of whatever draws it. A /// narrow read (a count, a light or cut read) holds no record to say. pub(crate) fn asking_said(method: &str, mut request: Value) -> Value { let narrow = ["count_only", "light", "cut"].iter().any(|key| request[*key] == true) || request.get("columns").is_some(); if method.starts_with("records.") && !narrow { if let Some(asked) = request.as_object_mut() { asked.entry("said").or_insert(Value::Bool(true)); } } request } /// Every record of this answer carries its one slip answer /// (`methods::shell_slip`). fn attach_said( definition: &TableDefinition, zone: &str, now: Option>, day_headed: bool, answer: &mut Value, words: &cotton_core::records::page::Words, ) { use crate::methods::shell_slip::{said_of, Reading, SAID_KEY}; let reading = Reading::new(definition, zone, now, day_headed, words); let say = |record: &mut Value| { if !answers_for(definition, record) || !record.get("data").is_some_and(Value::is_object) { return; } let said = said_of(&reading, record); record["data"][SAID_KEY] = said; }; if answer.get("id").is_some() && answer.get("data").is_some() { say(answer); } for record in answer.get_mut("records").and_then(Value::as_array_mut).into_iter().flatten() { say(record); } for key in ["record", "before", "after"] { if let Some(record) = answer.get_mut(key) { say(record); } } } /// The page's reads: `records.get` and `records.list`, as the app makes /// them, and the definitions as `definitions.tables` answers them. struct ClientPages<'a> { client: &'a ClientController, handle: Option<&'a CottonHandle>, made: Option>, /// The last read this page asked that was refused, in its types (code and /// `details`): the core's page source carries a refusal as its message /// alone, and [`page_refusal`] answers this one when it is what failed /// the page. refused: Option, } impl ClientPages<'_> { fn ask(&mut self, method: &str, request: Value) -> Result { self.typed(method, request).map_err(|error| { let message = error.message.clone(); self.refused = Some(error); message }) } fn typed(&self, method: &str, request: Value) -> Result { if let Some(handle) = self.handle { if let Some(answer) = crate::phone::settings_message_imports::call(handle, method, &request) { return answer; } if let Some(answer) = super::settings_devices::records_read(handle, method, &request) { return answer; } if let Some(answer) = super::metering::records_read(handle, method, &request) { return answer; } if let Some(answer) = settings_tables::call_on(handle, method, &request) { return answer; } } call(self.client, method, &request) } } /// `{id, data}` of each record a list answers. fn rows_of(answer: &Value) -> Vec<(String, serde_json::Map)> { answer["records"] .as_array() .into_iter() .flatten() .filter_map(|record| { Some(( record["id"].as_str()?.to_string(), record["data"].as_object()?.clone(), )) }) .collect() } /// The database's shell lines, kept while its file has not moved on /// (`EventBus::moved`): every read that says words reads them, and a page of /// a list said them three times over. A write of a line is a data event. pub(crate) fn line_rows_kept(client: &ClientController) -> std::sync::Arc> { type Kept = (((u64, u64), Option), std::sync::Arc>); static KEPT: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); let key = (client.moved(), client.attached_database()); if let Some((_, rows)) = KEPT.lock().ok().and_then(|kept| kept.iter().find(|(at, _)| *at == key).cloned()) { return rows; } let mut rows = Vec::new(); let read = client.read_rows("records.page", &mut |ctx| { rows = cotton_tools::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); Ok(Value::Null) }); let rows = std::sync::Arc::new(rows); if read.is_ok() { if let Ok(mut kept) = KEPT.lock() { // One handle's lines per database, the newest count only. kept.retain(|((moved, database), _)| moved.0 != key.0 .0 || *database != key.1); if kept.len() >= 8 { kept.remove(0); } kept.push((key, std::sync::Arc::clone(&rows))); } } rows } impl cotton_core::records::page::PageSource for ClientPages<'_> { fn line_rows(&mut self) -> Vec { line_rows_kept(self.client).as_ref().clone() } fn handle_activity(&mut self, kind: &str, normalised: &str) -> Vec { let mut found = Vec::new(); let _ = self.client.read_rows("records.page", &mut |ctx| { found = cotton_tools::mcp::handlers::tables::record_page_read::handle_activity(ctx, kind, normalised); Ok(Value::Null) }); found } fn definitions(&mut self) -> Vec { let mut found = Vec::new(); let _ = self.client.read_rows("records.page", &mut |ctx| { found = cotton_tools::definitions::shared_table_definitions(ctx) .map_err(|failure| failure.to_string())? .definitions .clone(); Ok(Value::Null) }); found } fn time_zone(&mut self) -> Option { self.client.time_zone().map(str::to_string) } fn now(&mut self) -> Option> { Some(self.client.clock().now()) } fn definition(&mut self, table: &str) -> Option { if let Some(definition) = self .made .iter() .flatten() .find(|definition| definition.id == table) { return Some(definition.clone()); } // A page reads a handful of related tables. Resolve each named table // through the records reader, never the entire catalogue. This set // lives only for this page; the next call reads current definition rows. let mut found = None; self.client .read_rows("records.page", &mut |ctx| { found = Some( cotton_tools::mcp::handlers::tables::definition(ctx, table) .map_err(|failure| failure.to_string())?, ); Ok(Value::Null) }) .ok()?; let definition = found?; self.made .get_or_insert_with(Vec::new) .push(definition.clone()); Some(definition) } fn record(&mut self, table: &str, id: &str) -> Result, String> { let record = self.ask( "records.get", serde_json::json!({ "table": table, "id": id }), )?; // A read answers a deleted record too; its page is gone. if !record["deleted_at"].is_null() { let definition = self .definition(table) .ok_or_else(|| format!("there is no table {table:?}"))?; return Err(cotton_core::records::receipt::no_longer_here(&definition)); } let mut data = record["data"].as_object().cloned().unwrap_or_default(); // A table that declares a live read (the device page's `device.facts`) // has those columns resolved into its fact slips here, in the same // read: merged after the page was made, a group of live columns was // always empty and never drawn. A live read that fails leaves the // stored columns; the app's own live read says why. if let Some(handle) = self.handle.filter(|_| self.definition(table).is_some_and(|definition| definition.live_read.is_some())) { if let Ok(live) = super::records_live::call(handle, &serde_json::json!({ "table": table, "id": id })) { if let Some(fields) = live["data"].as_object() { data.extend(fields.clone()); } } } Ok(data) } fn records( &mut self, table: &str, ids: &[String], ) -> Result)>, String> { let mut found = Vec::new(); for some in ids.chunks(cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE as usize) { found.extend(rows_of(&self.ask( "records.list", serde_json::json!({ "table": table, "ids": some }), )?)); } Ok(found) } fn list( &mut self, table: &str, filter: &serde_json::Map, limit: usize, ) -> Result<(u64, Vec<(String, serde_json::Map)>), String> { let answer = self.ask( "records.list", serde_json::json!({ "table": table, "where": filter, "limit": limit.max(1) }), )?; let total = answer["total"].as_u64().unwrap_or_default(); let mut rows = rows_of(&answer); rows.truncate(limit); Ok((total, rows)) } fn read(&mut self, name: &str, args: &serde_json::Map) -> Result { // RULE: A record page's list calls only a read on PAGE_READS, by the same entry its own screen reads; a definition naming any other read draws nothing. if !cotton_core::definitions::PAGE_READS.contains(&name) { return Err(format!("a page reads no `read.{name}`")); } let entry = crate::phone::reads::read_for(&format!("read.{name}")) .ok_or_else(|| format!("this core answers no `read.{name}`"))?; crate::phone::answer_read(self.client, entry, args) } fn active_project_slugs(&mut self) -> Vec { let mut slugs = Vec::new(); let mut page = Some(0_u64); while let Some(at) = page { let asked = serde_json::json!({ "table": "project", "where": { "status": "active" }, "page": at, "limit": cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE, }); let Ok(answer) = self.ask("records.list", asked) else { break; }; slugs.extend( rows_of(&answer) .into_iter() .filter_map(|(_, data)| data.get("slug")?.as_str().map(str::to_string)), ); page = answer["next_page"].as_u64().filter(|next| *next > at); } slugs } } /// `records.command`: the ONE place a definition's command runs. The kind, /// the verb and the arguments are the definition's; the answer is a /// `CommandOutcome` — what happened in the definition's words, and the /// command that takes it back. pub(crate) fn command( client: &ClientController, request: &Value, methods: &dyn AppMethods, ) -> Result { let bad = |what: &str| MethodError::new("bad_request", format!("`records.command` needs {what}")); let named = |key: &str| { request .get(key) .and_then(Value::as_str) .filter(|value| !value.is_empty()) }; let table = named("table").ok_or_else(|| bad("a table"))?; let name = named("command").ok_or_else(|| bad("a command"))?; // The form's act runs before its record exists, on the form's values. if let Some(values) = request.get("values").filter(|values| !values.is_null()) { let definition = cotton_core::definitions::builtin_table_definition(table).ok_or_else(|| { refused(format!( "only a table Cotton ships has a form act, and {table} is not one" )) })?; let outcome = run_form_command(definition, name, values, methods)?; return serde_json::to_value(outcome) .map_err(|error| MethodError::new("unreadable", error.to_string())); } // A list's act runs on no record, told how many rows the person saw it for. if let Some(count) = request.get("count").filter(|count| !count.is_null()) { let definition = cotton_core::definitions::builtin_table_definition(table).ok_or_else(|| { refused(format!( "only a table Cotton ships has a list act, and {table} is not one" )) })?; // A count is a whole number of rows, however the caller's JSON spelled it (3 or 3.0). let whole = count.as_u64().or_else(|| { count .as_f64() .filter(|count| *count >= 0.0 && count.fract() == 0.0) .map(|count| count as u64) }); let count = whole .and_then(|count| u32::try_from(count).ok()) .ok_or_else(|| bad("a whole count of rows"))?; let outcome = run_list_command(definition, name, count, methods)?; return serde_json::to_value(outcome) .map_err(|error| MethodError::new("unreadable", error.to_string())); } let id = named("id").ok_or_else(|| bad("a record id"))?; // Package acts are re-read and validated by their writer; the replica supplies only the act id. let mut package = None; if cotton_core::definitions::builtin_table_definition(table).is_none() && carried_definition(table).is_none_or(|definition| definition.acts.iter().flatten().next().is_some()) { client .read_rows("records.command", &mut |ctx| { package = Some( cotton_tools::mcp::handlers::tables::definition(ctx, table) .map_err(|failure| failure.to_string())?, ); Ok(Value::Null) }) .map_err(refused)?; } if let Some(definition) = package .as_ref() .filter(|definition| definition.acts.iter().flatten().any(|act| act.id == name)) { let act = definition .acts .iter() .flatten() .find(|act| act.id == name) .unwrap(); let mut args = json!({"table":table,"id":id,"act":name}); if let Some(picks) = &act.picks { let values = request .get("picked") .and_then(Value::as_array) .filter(|values| values.len() == picks.len()) .ok_or_else(|| bad("one ordered answer per pick"))?; args["picked"] = Value::Array( picks .iter() .zip(values) .map(|(pick, value)| match (pick.kind, value) { (PickKind::Number, Value::String(text)) => picked_number(pick, text), (PickKind::Number, value) => { pick.number_value(Some(value)).map_err(refused) } (_, Value::String(_)) => Ok(value.clone()), _ => Err(bad("a string for this pick")), }) .collect::, _>>()?, ); } else if let Some(picked) = named("picked") { args["picked"] = match act.pick.as_ref() { Some(pick) if pick.kind == PickKind::Number => picked_number(pick, picked)?, _ => Value::String(picked.into()), }; } let answer = client .write("run_record_act", args.as_object().unwrap()) .map(crate::authoring::own_answer) .map_err(refused)?; let succeeded = answer.get("ok") != Some(&Value::Bool(false)); let outcome = CommandOutcome { command: act.id.clone(), kind: act.kind, receipt: succeeded.then(|| act.receipt.clone().unwrap_or_else(|| act.label.clone())), undo: succeeded.then(|| act.undo.clone()).flatten(), answer: Some(answer), open: None, undo_call: None, reveal: None, }; return serde_json::to_value(outcome) .map_err(|error| MethodError::new("unreadable", error.to_string())); } if package.is_some() && carried_definition(table).is_some_and(|definition| { !definition.commands.iter().flatten().any(|command| command.id == name) }) { return Err(refused("this package action is not offered".to_string())); } // The commands that run are THE BUILD'S: a built-in's own definition, or // the definition of a table Cotton itself carries (`carried_definition`) // — never the row a database stores, which anyone who can write a // definition could have changed. let carried; let definition = match cotton_core::definitions::builtin_table_definition(table) { Some(definition) => definition, None => { carried = carried_definition(table).ok_or_else(|| { refused(format!( "only a table Cotton ships has commands, and {table} is not one" )) })?; &carried } }; let outcome = if definition .commands .iter() .flatten() .any(|c| c.id == name && c.picks.is_some()) { run_ordered_method_command(client, definition, id, name, request.get("picked"), methods)? } else { run_command_with(client, definition, id, name, named("picked"), methods)? }; serde_json::to_value(outcome).map_err(|error| MethodError::new("unreadable", error.to_string())) } /// Ordered app-method picks use the same argument validation as single /// picks, then execute once. They never become a generic record patch. pub(crate) fn run_ordered_method_command( client: &ClientController, definition: &TableDefinition, id: &str, name: &str, picked: Option<&Value>, methods: &dyn AppMethods, ) -> Result { let command = definition .commands .iter() .flatten() .find(|c| c.id == name) .ok_or_else(|| refused("unknown command".into()))?; if command.method.is_none() { return Err(refused( "ordered command picks require an app method".into(), )); } let picks = command .picks .as_deref() .ok_or_else(|| refused("this command has no ordered picks".into()))?; let values = picked .and_then(Value::as_array) .filter(|v| v.len() == picks.len()) .ok_or_else(|| refused("answer every pick in order".into()))?; let mut normalized = command.clone(); normalized.pick = None; normalized.picks = None; let mut args = command_arguments(client, definition, id, &normalized, None, methods)?; for (pick, value) in picks.iter().zip(values) { let mut single = normalized.clone(); single.pick = Some(pick.clone()); let text = match value { Value::String(text) => Some(text.clone()), Value::Number(_) => Some(value.to_string()), Value::Null => None, _ => return Err(refused("this pick needs a value".into())), }; let answered = Value::Object(command_arguments( client, definition, id, &single, text.as_deref(), methods, )?); if let Some(value) = pick .argument .split('.') .try_fold(&answered, |value, key| value.get(key)) { put_at(&mut args, &pick.argument, value.clone()); } else if pick.optional != Some(true) { return Err(refused("this pick has no answer".into())); } } // These arguments have already passed the shipped bindings, current // authority condition, each pick's database, record and value checks. normalized.data = Some(cotton_core::definitions::OrderedMap( args.into_iter().collect(), )); normalized.bindings = None; normalized.when = None; let mut resolved = definition.clone(); *resolved .commands .as_mut() .unwrap() .iter_mut() .find(|c| c.id == name) .unwrap() = normalized; run_command_with(client, &resolved, id, name, None, methods) } /// `records.spoken`: a line said to Home, run as the shipped command whose /// spoken words it reads as whole (`CommandSpoken`) — its record and picked /// record found by name — or `null` when no command hears it, so the line /// stays a thought. A name two records share runs nothing. fn spoken( client: &ClientController, request: &Value, methods: &dyn AppMethods, ) -> Result { let words = request .get("words") .and_then(Value::as_str) .ok_or_else(|| MethodError::new("bad_request", "`records.spoken` needs words"))?; for definition in cotton_core::definitions::builtin_table_definitions() { for command in definition.commands.iter().flatten() { let Some(said) = &command.spoken else { continue; }; let Some(heard) = cotton_core::definitions::spoken::hear(said, words) else { continue; }; let Some(id) = named_record(client, definition, &heard.record)? else { continue; }; let pick_table = command.pick.as_ref().and_then(|pick| pick.table.as_deref()); let picked = match ( &heard.pick, pick_table.and_then(cotton_core::definitions::builtin_table_definition), ) { (Some(name), Some(table)) => match named_record(client, table, name)? { Some(picked) => Some(picked), None => continue, }, (Some(_), None) => continue, (None, _) => None, }; if command.pick.is_some() && picked.is_none() && said.pick_unsaid != Some(true) { continue; } let run = SpokenRun { counted: said .counted .as_ref() .zip(heard.counted) .map(|(counted, items)| (counted.argument.clone(), serde_json::json!(items))), unpicked: picked.is_none(), }; let outcome = run_command_heard( client, definition, &id, &command.id, picked.as_deref(), methods, Some(run), )?; return serde_json::to_value(outcome) .map_err(|error| MethodError::new("unreadable", error.to_string())); } } Ok(Value::Null) } /// What a spoken line adds to its command's run: its counted words as the /// argument the definition names, and whether it left the pick unsaid. pub(crate) struct SpokenRun { counted: Option<(String, Value)>, unpicked: bool, } /// The one record of `definition`'s table whose name is `name` (any case). /// This database's date words (its `dates` lines over the kit's): a record /// named by a clock time is called as this database says that time. fn client_date_words(client: &ClientController) -> cotton_core::records::page::DateWords { let mut rows = Vec::new(); let _ = client.read_rows("records.page", &mut |ctx| { rows = cotton_tools::presentation::line_rows(ctx.read.driver(), ctx.workspace_id); Ok(Value::Null) }); cotton_core::records::page::DateWords::of_rows(&rows) } fn named_record( client: &ClientController, definition: &TableDefinition, name: &str, ) -> Result, MethodError> { let answer = call( client, "records.list", &serde_json::json!({"table": definition.id, "limit": cotton_tools::mcp::handlers::tables::MAX_PAGE_SIZE}), )?; let dates = client_date_words(client); let named: Vec = rows_of(&answer) .into_iter() .filter(|(_, data)| { cotton_core::records::receipt::record_name_in(definition, &Value::Object(data.clone()), &dates) .trim() .to_lowercase() == name }) .map(|(id, _)| id) .collect(); Ok((named.len() == 1).then(|| named[0].clone())) } /// The build's own definition of a data table Cotton itself carries and /// lets declare commands (`CARRIED_COMMAND_TABLES`), including kit packages. pub(crate) fn carried_definition(table: &str) -> Option { cotton_tools::connections::domains::carried_table(table).or_else(|| { if !cotton_core::definitions::CARRIED_COMMAND_TABLES.contains(&table) { return None; } cotton_core::toolkits::shipped_kit_tools().into_iter() .flat_map(|package| package.tables).find(|definition| definition.id == table) // A kit's own table file (the personal kit's Films). .or_else(|| cotton_core::kit::table(table)) }) } /// `records.command` on a device: a command naming an app method runs it /// through this handle, by the same path its own screen calls. pub fn command_on(handle: &CottonHandle, request: &Value) -> Result { match request.get("privateKey").filter(|key| !key.is_null()) { Some(key) => command(&handle.client(), request, &KeyLent { methods: HandleMethods(handle), key }), None => command(&handle.client(), request, &HandleMethods(handle)), } } /// The app methods that open the vault for their one call with this /// device's own vault key, when the shell hands it (`privateKey`, read from /// the Keychain after the presence prompt): Keys › Devices' Approve, so the /// approval needs no five-minute unlock first. Any other method never sees /// the key. pub const KEY_LENT_METHODS: &[&str] = &["vault.approveDevice"]; /// A command run with this device's vault key lent to [`KEY_LENT_METHODS`] /// alone, for this one call; nothing keeps it. pub(crate) struct KeyLent<'a, M: AppMethods> { pub(crate) methods: M, pub(crate) key: &'a Value, } impl AppMethods for KeyLent<'_, M> { fn call(&self, method: &str, request: &Value) -> Result { if !KEY_LENT_METHODS.contains(&method) { return self.methods.call(method, request); } let mut lent = request.clone(); if let Some(args) = lent.as_object_mut() { args.insert("privateKey".to_string(), self.key.clone()); } self.methods.call(method, &lent) } fn answered_record(&self, table: &str, id: &str) -> Option { self.methods.answered_record(table, id) } } /// `records.spoken` on a device, as `records.command` runs there. pub fn spoken_on(handle: &CottonHandle, request: &Value) -> Result { spoken( &handle.client(), request, &HandleMethods(handle), ) } /// What runs a command's app method (`RecordCommand::method`). pub(crate) trait AppMethods { fn call(&self, method: &str, request: &Value) -> Result; /// A record the file does not hold but a method of this device answers /// (a device still asking to join is the serving Mac's pending entry, /// not a row): its data in the definition's keys, or `None`. fn answered_record(&self, _table: &str, _id: &str) -> Option { None } } /// No handle to run an app method on: a client alone runs only verbs. struct NoMethods; impl AppMethods for NoMethods { fn call(&self, method: &str, _request: &Value) -> Result { Err(refused(format!( "`{method}` runs only on this device's own handle" ))) } } /// A device's own methods, each the existing implementation its screen calls. struct HandleMethods<'a>(&'a CottonHandle); impl AppMethods for HandleMethods<'_> { fn call(&self, method: &str, request: &Value) -> Result { dispatch_method(self.0, method, request) } fn answered_record(&self, table: &str, id: &str) -> Option { if settings_tables::TABLES .iter() .any(|(known, _)| *known == table) { let request = json!({"table":table,"id":id}); let row = settings_tables::call_on(self.0, "records.get", &request) .or_else(|| settings_tables::call(&self.0.client(), "records.get", &request))? .ok()?; return row.get("data").cloned(); } match table { "bin" => call( &self.0.client(), "records.get", &json!({"table":table,"id":id}), ) .ok()? .get("data") .cloned(), "device" => { let pending = crate::methods::dispatch( self.0, "pairing.pending", &in_named_database(json!({})), ) .ok()?; waiting_device(&pending, id) } "member" => { let pending = crate::methods::dispatch( self.0, "devices.pending", &in_named_database(json!({})), ) .ok()?; asking_member(&pending, id) } "message_import" => crate::phone::settings_message_imports::call( self.0, "records.get", &in_named_database(json!({"table":table,"id":id})), )? .ok()? .get("data") .cloned(), _ => None, } } } /// A device asking to join, off `pairing.pending`'s answer, in the device /// definition's keys: what the page's Approve and Turn away are offered on /// and bound from (the digits it shows are echoed back by Approve). pub(crate) fn waiting_device(pending: &Value, pairing_id: &str) -> Option { let row = pending .get("pending")? .as_array()? .iter() .find(|row| row.get("pairingId").and_then(Value::as_str) == Some(pairing_id))?; Some(json!({ "name": row.get("name").cloned().unwrap_or(Value::Null), "status": "waiting", "digits": row.get("digits").cloned().unwrap_or(Value::Null), "asked_at": row.get("createdAt").cloned().unwrap_or(Value::Null), })) } /// A person asking to join with an invite, off the pending list (an entry /// carrying `inviteId`), in the member definition's keys. pub(crate) fn asking_member(pending: &Value, pairing_id: &str) -> Option { let row = pending.get("pending")?.as_array()?.iter().find(|row| { row.get("pairingId").and_then(Value::as_str) == Some(pairing_id) && row.get("inviteId").is_some_and(Value::is_string) })?; let said = |pointer: &str| row.pointer(pointer).cloned().unwrap_or(Value::Null); Some(json!({ "name": said("/person/name"), "fingerprint": said("/person/fingerprint"), "device_name": said("/name"), "device_fingerprint": said("/deviceFingerprint"), "digits": said("/digits"), "asked_at": said("/createdAt"), "status": "waiting", "state": "asking to join", "summary": "Asks to join with an invite", })) } /// `request` with the database this call is answered from, when one is /// named: an owner act (`devices.*`, `pairing.*`) keeps it to reach that /// database's serving Mac, and absent it is the household's own. pub(crate) fn in_named_database(mut request: Value) -> Value { if let (Some(database), Some(fields)) = ( crate::shell::client::named_database(), request.as_object_mut(), ) { fields.insert( crate::phone::databases::DATABASE.to_string(), Value::from(database), ); } request } /// Every [`COMMAND_METHODS`] entry to the module that answers it; anything /// else is refused before it is dispatched. fn dispatch_method( handle: &CottonHandle, method: &str, request: &Value, ) -> Result { match method_module(method) { // A signed call to the serving Mac, which holds the Cloudflare token and does the act, then one pull. Some(MethodModule::Domains) => crate::phone::domains::call(handle, method, request), // The page acts (`methods/page_acts.rs`): the method table itself, so // a served Mac runs its in-process engine and a phone its signed // call, and the act answers its receipt and Undo as its screen's did. Some(MethodModule::PageActs) => { crate::methods::dispatch(handle, method, &in_named_database(request.clone())) } // A Records thread's acts: the record and its link to the thread in one write. Some(MethodModule::Records) => crate::phone::record_acts::call(handle, method, request), Some(MethodModule::RecordMoves) => crate::phone::record_moves::call(handle, request), Some(MethodModule::Media) => crate::phone::media_describe::call(handle, method, request), // This Device's sample records: made and binned on this device's own write. Some(MethodModule::Samples) => crate::phone::samples::call(handle, method, request), None => Err(refused(format!( "`{method}` is not a method a command runs" ))), } } /// The module that answers a command's app method. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(crate) enum MethodModule { PageActs, Domains, Records, RecordMoves, Media, Samples, } /// Which module answers `method`: only a [`COMMAND_METHODS`] entry has one. pub(crate) fn method_module(method: &str) -> Option { if !COMMAND_METHODS.contains(&method) { return None; } match method { "domains.checkPrice" | "domains.register" | "domains.handOver" => { Some(MethodModule::Domains) } "records.recordAsTransaction" | "records.addToCalendar" => Some(MethodModule::Records), "records.move" => Some(MethodModule::RecordMoves), "samples.add" | "samples.remove" => Some(MethodModule::Samples), "media.describe" | "media.share" => Some(MethodModule::Media), // The method table itself, as for the page acts: on the serving Mac // the write and the re-plan behind it (`shell::front_door::set_reach`), // on a phone its own write, which the serving Mac follows. "workspace.setReach" | "device.serveFrom" | "device.becomeRunner" => { Some(MethodModule::PageActs) } "databases.remove" | "devices.revoke" | "pairing.approve" => Some(MethodModule::PageActs), // The command allowlist above is authority; new native engine commands // use the same dispatch as direct FFI calls, so no second list can drift. _ => Some(MethodModule::PageActs), } } fn refused(reason: String) -> MethodError { MethodError::new("write_refused", reason) } /// One command of `definition` on record `id`, by its kind, on a client alone. #[cfg(test)] pub(crate) fn run_command( client: &ClientController, definition: &TableDefinition, id: &str, name: &str, ) -> Result { run_command_with(client, definition, id, name, None, &NoMethods) } /// One command of `definition` on record `id`, by its kind, with the table /// the person picked for one that asks (`pick_table`) and what runs an app /// method. pub(crate) fn run_command_with( client: &ClientController, definition: &TableDefinition, id: &str, name: &str, picked: Option<&str>, methods: &dyn AppMethods, ) -> Result { run_command_heard(client, definition, id, name, picked, methods, None) } /// [`run_command_with`], and for a spoken command its counted words as the /// argument its definition names (`SpokenCounted`). fn run_command_heard( client: &ClientController, definition: &TableDefinition, id: &str, name: &str, picked: Option<&str>, methods: &dyn AppMethods, heard: Option, ) -> Result { let command = definition .command(name) .ok_or_else(|| refused(format!("{} has no command \"{name}\"", definition.plural)))?; // What happened is the definition's words, else the label; going // somewhere and the quiet stamp a page runs on opening say nothing. let quiet = command.kind == CommandKind::Open || definition.on_open.as_deref() == Some(name); let mut outcome = CommandOutcome { command: command.id.clone(), kind: command.kind, receipt: (!quiet).then(|| { command .receipt .clone() .unwrap_or_else(|| command.label.clone()) }), undo: command.undo.clone(), answer: None, open: None, undo_call: None, reveal: None, }; // A receipt of one word is a verb, and a verb names what it was done to // ("Pinned Example choir"); a sentence names it where it says `{name}` // ("Moved Dinner to the inbox"), else stands as the definition wrote it. // The name is read before the verb runs, since a delete leaves none. let named_at = |said: &str| said.contains(cotton_core::definitions::RECEIPT_NAME); let names_the_record = !quiet && matches!(command.kind, CommandKind::Update | CommandKind::Delete) && command .receipt .as_deref() .is_some_and(|said| !said.trim().contains(' ') || named_at(said)); if names_the_record { if let (Some(said), Ok(data)) = ( outcome.receipt.as_mut(), record_data(client, &definition.id, id), ) { if data.is_object() { let name = cotton_core::records::receipt::record_name_in(definition, &data, &client_date_words(client)); *said = if named_at(said) { said.replace(cotton_core::definitions::RECEIPT_NAME, &name) } else { format!("{said} {name}") }; } } } // What the person picked is said where the receipt says `{picked}`. if let (Some(said), Some(pick)) = (outcome.receipt.as_mut(), command.pick.as_ref()) { if said.contains(cotton_core::definitions::RECEIPT_PICKED) { let picked_said = picked .and_then(|picked| said_picked(client, pick, picked)) .unwrap_or_else(|| match pick.kind { PickKind::Number => "the number you entered".to_string(), PickKind::Text => "the words you entered".to_string(), PickKind::Datetime => "the time you picked".to_string(), PickKind::Record => "the one you picked".to_string(), PickKind::Database => "the database you picked".to_string(), PickKind::File => "the file you picked".to_string(), }); *said = said.replace(cotton_core::definitions::RECEIPT_PICKED, &picked_said); } } // A name that could not be read is never shown as its placeholder. if let Some(said) = outcome.receipt.as_mut().filter(|said| named_at(said)) { *said = said.replace( cotton_core::definitions::RECEIPT_NAME, &format!("this {}", definition.name.to_lowercase()), ); } match command.kind { CommandKind::Create | CommandKind::Update | CommandKind::Delete => { let answer = match command.method.as_deref() { // Preserve the method's answer. A command-only delete closes // its page by kind; only a real durable write may supply a // change envelope (including its id and undoable flag). Some(method) => { run_method(client, definition, id, command, method, picked, methods)? } None => run_verb(client, definition, id, command, picked, heard)?, }; // A verb that names what it made says it more exactly than the // definition can ("Made a todo: Fix the latch" over "Made a todo"). let said = answer .get("receipt") .and_then(Value::as_str) .or_else(|| { (command.kind == CommandKind::Create) .then(|| { answer .pointer("/change/receipt/said") .and_then(Value::as_str) }) .flatten() }) .filter(|said| !said.trim().is_empty()); if let (false, Some(said)) = (quiet, said) { outcome.receipt = Some(said.to_string()); } // THE METHOD'S OWN WAY BACK, when the definition names none: the // same method with what was there before (`workspace.setReach` // answers the household's reach as it was). Only the same method — // the way back from an allowlisted act is that act, never another. if outcome.undo.is_none() { outcome.undo_call = own_undo(command, &answer); } // A capture question is not a completed act: carry the question // to its caller without announcing a write that never happened. let pending = answer.get("pending") == Some(&Value::Bool(true)) || answer.get("ask").is_some_and(Value::is_object) || answer.get("platform_action").is_some_and(Value::is_string); if pending { outcome.receipt = None; outcome.undo = None; outcome.undo_call = None; } outcome.reveal = command.revealed(&answer); // The record the act made elsewhere, stood on once sync brings it // (an article's Fetch lands on its download). if !pending { outcome.open = command.landed(&answer); } outcome.answer = Some(answer); } // A copy is the device's own act: the value goes on its clipboard and // never through here. CommandKind::Copy => { return Err(refused(format!("{} copies on the device", command.label))) } // An ask is the device's own act too: it opens the conversation with // the business, where the customer's words go by the `message` verb. CommandKind::Ask => { return Err(refused(format!("{} opens the conversation on the device", command.label))) } CommandKind::Open if command.view.is_some() => { outcome.open = Some(serde_json::json!({ "url": view_route(client, definition, id, command)? })); } CommandKind::Open => { let column = command.opens.as_deref().unwrap_or_default(); let data = record_data(client, &definition.id, id)?; let held = data .get(column) .and_then(Value::as_str) .map(str::trim) .filter(|held| !held.is_empty()); let Some(held) = held else { return Err(not_offered(command)); }; let target = definition .column(column) .and_then(|column| column.link_to.as_deref()); outcome.open = Some(match target { Some(table) => serde_json::json!({ "table": table, "id": held }), None => serde_json::json!({ "url": held }), }); } } Ok(outcome) } /// The form's act (`RecordCommand::form`): its app method, with its `data` /// and its bindings read off the form's `values` — only columns the person /// can write, so a form never sends what the engine keeps — and what it /// reveals. Refused for any command that is not the form's act, and while a /// required column is empty. pub(crate) fn run_form_command( definition: &TableDefinition, name: &str, values: &Value, methods: &dyn AppMethods, ) -> Result { let command = definition .command(name) .filter(|command| command.is_form()) .ok_or_else(|| refused(format!("{} has no form act \"{name}\"", definition.plural)))?; let values = values .as_object() .ok_or_else(|| MethodError::new("bad_request", "a form's values are an object"))?; let written = |key: &str| { definition .column(key) .is_some_and(|column| column.readonly != Some(true)) }; let held = |key: &str| { let value = values .get(key) .filter(|_| written(key)) .cloned() .unwrap_or(Value::Null); match value { Value::Null => definition .column(key) .and_then(|column| column.default.clone()) .unwrap_or(Value::Null), Value::String(text) if text.trim().is_empty() => Value::Null, value => value, } }; if let Some(needed) = definition.columns.iter().find(|column| { column.required == Some(true) && column.readonly != Some(true) && held(&column.key).is_null() }) { return Err(MethodError::new( "bad_request", format!( "\"{}\" needs its {}", command.label, needed.name.as_deref().unwrap_or(&needed.key).to_lowercase() ), )); } let method = command .method .as_deref() .ok_or_else(|| refused(format!("\"{}\" names no app method", command.label)))?; if method_module(method).is_none() { return Err(refused(format!( "`{method}` is not a method a command runs" ))); } let mut args = serde_json::Map::new(); for (key, value) in command.data.iter().flat_map(|data| data.0.iter()) { args.insert(key.clone(), value.clone()); } for (argument, column) in command .bindings .iter() .flat_map(|bindings| bindings.0.iter()) { let value = held(column); if !value.is_null() { put_at(&mut args, argument, value); } } let answer = methods.call(method, &Value::Object(args))?; let said = answer .get("receipt") .and_then(Value::as_str) .filter(|said| !said.trim().is_empty()); let pending = answer.get("pending") == Some(&Value::Bool(true)) || answer.get("ask").is_some_and(Value::is_object) || answer.get("platform_action").is_some_and(Value::is_string); let reveal = command.revealed(&answer); if !pending && command.reveals.is_some() && reveal.is_none() { return Err(MethodError::new( "bad_answer", "The act ran but its one-time value did not come back; it cannot be shown again", )); } Ok(CommandOutcome { command: command.id.clone(), kind: command.kind, receipt: (!pending).then(|| { said.map(str::to_string) .or_else(|| command.receipt.clone()) .unwrap_or_else(|| command.label.clone()) }), undo: None, reveal, open: command.made(&definition.id, &answer), answer: Some(answer), undo_call: None, }) } /// A list's act (`RecordCommand::list`) for the `count` rows the person saw /// it offered over: its method is sent the count where it binds `$count` /// and decides, on its own fresh read, whether that is still so. pub(crate) fn run_list_command( definition: &TableDefinition, name: &str, count: u32, methods: &dyn AppMethods, ) -> Result { let command = definition .command(name) .ok_or_else(|| refused(format!("{} has no list act \"{name}\"", definition.plural)))?; let list = command .list .as_ref() .ok_or_else(|| refused(format!("\"{}\" is not a list's act", command.label)))?; if count < list.at_least { return Err(refused(format!( "\"{}\" is offered for at least {} rows", command.label, list.at_least ))); } let method = command .method .as_deref() .ok_or_else(|| refused(format!("\"{}\" names no app method", command.label)))?; if method_module(method).is_none() { return Err(refused(format!( "`{method}` is not a method a command runs" ))); } let mut args = serde_json::Map::new(); for (key, value) in command.data.iter().flat_map(|data| data.0.iter()) { args.insert(key.clone(), value.clone()); } for (argument, column) in command .bindings .iter() .flat_map(|bindings| bindings.0.iter()) { if column == cotton_core::definitions::COUNT_BINDING { put_at(&mut args, argument, Value::from(count)); } } let answer = methods.call(method, &Value::Object(args))?; let said = answer .get("receipt") .and_then(Value::as_str) .filter(|said| !said.trim().is_empty()) .map(str::to_string); // A flow the platform opens has changed nothing yet: it says nothing. let receipt = (answer.get("platform_action").is_none()).then(|| { said.unwrap_or_else(|| { RecordCommand::counted(command.receipt.as_deref().unwrap_or(&command.label), count) }) }); Ok(CommandOutcome { command: command.id.clone(), kind: command.kind, receipt, undo: None, reveal: None, open: None, answer: Some(answer), undo_call: None, }) } /// The way back an app method answered for itself — `{method, args}` naming /// the command's own method and an object of arguments — or `None`. fn own_undo(command: &RecordCommand, answer: &Value) -> Option { let method = command.method.as_deref()?; let undo = answer.get("undo")?; let args = undo.get("args").filter(|args| args.is_object())?; (undo.get("method").and_then(Value::as_str) == Some(method)) .then(|| serde_json::json!({ "method": method, "args": args })) } /// What the person picked, as a receipt says it: a moment in the device's /// own zone ("Thu 8 Oct, 9:00 am"; without one, in the zone it was sent in), /// a record by its name, or words as entered. `None` when it cannot be read. fn said_picked(client: &ClientController, pick: &CommandPick, picked: &str) -> Option { match pick.kind { PickKind::Number | PickKind::Text => Some(picked.trim().to_string()), PickKind::Datetime => { let at = chrono::DateTime::parse_from_rfc3339(picked.trim()).ok()?; const SPELT: &str = "%a %-d %b, %-I:%M %p"; Some( match client.time_zone() { Some(zone) => at .with_timezone(&cotton_core::device::words::Clock::in_zone(0, zone).zone) .format(SPELT) .to_string(), None => at.format(SPELT).to_string(), } .replace("AM", "am") .replace("PM", "pm"), ) } PickKind::Record => { let table = pick.table.as_deref()?; let definition = cotton_core::definitions::builtin_table_definition(table)?; let data = record_data(client, table, picked) .ok() .filter(Value::is_object)?; Some(cotton_core::records::receipt::record_name_in( definition, &data, &client_date_words(client), )) } PickKind::Database => crate::phone::databases::name_of(client, picked.trim()) .ok() .flatten(), // A file by its own name, never the path of the phone's copy. PickKind::File => picked.trim().rsplit('/').next().filter(|name| !name.is_empty()).map(str::to_string), } } /// Swift's command boundary carries text; the writer receives a JSON number. pub(super) fn picked_number(pick: &CommandPick, picked: &str) -> Result { let value = serde_json::from_str::(picked.trim()) .map_err(|_| MethodError::new("bad_request", "Enter a number"))?; pick.labelled_value(&value) .map_err(|why| MethodError::new("bad_request", why)) } /// The value a command's pick sends: a moment as the ISO 8601 timestamp it /// came as, words as trimmed text, a record as its id once it is found in /// the pick's table and still satisfies its filters. fn picked_value( client: &ClientController, command: &RecordCommand, pick: &CommandPick, picked: &str, ) -> Result { let picked = picked.trim(); match pick.kind { // A labelled number's Skip sends nothing. PickKind::Number if picked.is_empty() && pick.optional == Some(true) => Ok(Value::Null), PickKind::Number => picked_number(pick, picked), PickKind::Text if picked.is_empty() && pick.optional == Some(true) => Ok(Value::Null), PickKind::Text if picked.is_empty() => Err(MethodError::new( "bad_request", format!("\"{}\" needs the words you entered", command.label), )), PickKind::Text => Ok(Value::from(picked)), PickKind::File => pick .file_value(&Value::from(picked)) .map(Value::from) .map_err(|why| MethodError::new("bad_request", why)), PickKind::Datetime => chrono::DateTime::parse_from_rfc3339(picked) .map(|_| Value::from(picked)) .map_err(|_| { MethodError::new( "bad_request", format!( "\"{}\" needs a moment as an ISO 8601 timestamp, not \"{picked}\"", command.label ), ) }), PickKind::Record => { let table = pick.table.as_deref().unwrap_or_default(); let data = record_data(client, table, picked) .ok() .filter(Value::is_object); let Some(data) = data.filter(|_| !picked.is_empty()) else { let name = cotton_core::definitions::builtin_table_definition(table) .map_or(table.to_string(), |definition| { definition.name.to_lowercase() }); return Err(MethodError::new( "bad_request", format!("That {name} is no longer here"), )); }; if !pick.accepts(&data) { return Err(MethodError::new( "bad_request", format!("That record is not a choice for \"{}\"", command.label), )); } Ok(Value::from(picked)) } // One of the databases this device holds, and not the open one: an // act that reaches into a second database is never sent a made-up id. PickKind::Database => { let held = crate::phone::databases::name_of(client, picked) .ok() .flatten() .is_some(); let open = client .current_database() .ok() .is_some_and(|open| open == picked); if picked.is_empty() || !held { return Err(MethodError::new( "bad_request", "That database is not on this device".to_string(), )); } if open { return Err(MethodError::new( "bad_request", format!( "Pick another database for \"{}\": this is the open one", command.label ), )); } Ok(Value::from(picked)) } } } /// Put `value` at `argument`, a key or a dotted path of keys (`patch.project`). fn put_at(args: &mut serde_json::Map, argument: &str, value: Value) { let mut keys = argument.split('.').peekable(); let mut at = args; while let Some(key) = keys.next() { if keys.peek().is_none() { at.insert(key.to_string(), value); return; } let next = at .entry(key.to_string()) .or_insert_with(|| Value::Object(serde_json::Map::new())); if !next.is_object() { *next = Value::Object(serde_json::Map::new()); } at = next.as_object_mut().expect("an object just made"); } } fn not_offered(command: &RecordCommand) -> MethodError { MethodError::new( "not_offered", format!( "\"{}\" is not offered on this record as it stands now.", command.label ), ) } /// The record as it stands: the file's row, else what this device's /// methods answer for one the file does not hold (a device asking to join). fn record_of( client: &ClientController, table: &str, id: &str, methods: &dyn AppMethods, ) -> Result { match record_data(client, table, id) { Ok(data) if data.is_object() => Ok(data), held => methods.answered_record(table, id).map(Ok).unwrap_or(held), } } /// Where an act naming a tool view goes (`RecordCommand::view`): the view's /// own list narrowed to this record by its partition column, under the view's /// label with the record's title ("Between us with Ana") — the app's list /// route, so the rows opened from it push on the same stack. fn view_route( client: &ClientController, definition: &TableDefinition, id: &str, command: &RecordCommand, ) -> Result { let named = command.view.as_deref().unwrap_or_default(); let (tool, view) = named .split_once('/') .ok_or_else(|| refused(format!("{} names no tool view", command.label)))?; let view = client .read_rows("definitions.views", &mut |ctx| { let tables = cotton_tools::definitions::table_definitions(ctx).map_err(|e| e.to_string())?; let home = tables.definitions.iter().find(|table| { table.tool.as_ref().is_some_and(|home| home.key.as_deref().unwrap_or(&table.id) == tool) }); let found = home .and_then(|home| home.tool.as_ref()) .and_then(|home| home.views.iter().find(|candidate| candidate.id == view)); serde_json::to_value(found).map_err(|e| e.to_string()) }) .map_err(|reason| MethodError::new("unreadable", reason))?; let view: cotton_core::definitions::tool_views::ToolView = serde_json::from_value(view) .map_err(|_| refused(format!("{} names no view {named}", command.label)))?; let (Some(table), Some(partition)) = (view.read.get("table").and_then(Value::as_str), view.partition.as_deref()) else { return Err(refused(format!("the view {named} is drawn for no record"))); }; let mut narrowed = view.read.get("where").and_then(Value::as_object).cloned().unwrap_or_default(); narrowed.insert(partition.to_string(), Value::from(id)); let data = record_data(client, &definition.id, id)?; let name = data.get(definition.title.as_str()).and_then(Value::as_str).map(str::trim).unwrap_or_default(); let title = if name.is_empty() { view.label.clone() } else { format!("{} with {name}", view.label) }; let mut route = url::Url::parse("cotton:/").expect("a base"); route.set_path(&format!("/lists/{table}")); route.query_pairs_mut() .append_pair("where", &Value::Object(narrowed).to_string()) .append_pair("title", &title); Ok(format!("{}?{}", route.path(), route.query().unwrap_or_default())) } fn record_data(client: &ClientController, table: &str, id: &str) -> Result { let mut get = serde_json::Map::new(); get.insert("table".to_string(), Value::from(table)); get.insert("id".to_string(), Value::from(id)); if let Some(zone) = client.time_zone() { get.insert("timezone".into(), Value::from(zone)); } let mut record = client .read_tool("get_record_by_table", &get) .map_err(|reason| MethodError::new("unreadable", reason))?; // Device acts are offered against the reading device's projection, // including `status: this device`, just like records.get. Validate the // same row here: its persisted approval status cannot identify this phone. if table == "device" { mark_this_device(client, &mut record); } // A film's acts are offered by what this device keeps of it. if super::films::TABLES.contains(&table) { super::films::answer_on_phone(client, table, &mut record)?; } if table == super::books::BOOK_TABLE { super::books::answer_on_phone(client, &mut record)?; } if table == super::pictures_here::MEDIA_TABLE { super::pictures_here::answer_on_phone(client, &mut record)?; } if table == super::meetings_app::MEETING { super::meetings_app::answer_on_phone(client, &mut record)?; } if table == super::songs::SONG_TABLE { super::songs::answer_on_phone(client, &mut record)?; } if table == super::songs::ALBUM_TABLE { super::songs::answer_albums_on_phone(client, &mut record)?; } Ok(record.get("data").cloned().unwrap_or(Value::Null)) } /// A `create`, `update` or `delete` command's engine verb, with the arguments /// the definition binds; refused when its `when` does not hold on the record. fn run_verb( client: &ClientController, definition: &TableDefinition, id: &str, command: &RecordCommand, picked: Option<&str>, heard: Option, ) -> Result { let verb = command .verb .as_deref() .ok_or_else(|| refused(format!("\"{}\" names no engine verb", command.label)))?; // A pick a spoken line may leave unsaid is the verb's to answer. let unpicked; let asked = match &heard { Some(run) if run.unpicked && command.pick.is_some() => { unpicked = RecordCommand { pick: None, ..command.clone() }; &unpicked } _ => command, }; let mut args = command_arguments(client, definition, id, asked, picked, &NoMethods)?; if let Some((argument, value)) = heard.and_then(|run| run.counted) { args.insert(argument, value); } let Some(tool) = tool_by_name(verb) else { return Err(refused(format!("this build has no engine verb `{verb}`"))); }; if tool.scope == McpScope::Read { client .read_tool(verb, &args) .map_err(|reason| MethodError::new("unreadable", reason)) } else { let mut answer = client .write(verb, &args) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("write_refused", reason))?; // A create question carries the resolved input so the app can answer // through records.create without interpreting definition bindings. if command.kind == CommandKind::Create && verb == "create_record" { if let Some(ask) = answer.get_mut("ask").and_then(Value::as_object_mut) { ask.insert("table".into(), args["table"].clone()); ask.insert("data".into(), args["data"].clone()); } } Ok(answer) } } /// A command's app method, with the arguments the definition binds; refused /// unless it is on [`COMMAND_METHODS`], and when its `when` does not hold. fn run_method( client: &ClientController, definition: &TableDefinition, id: &str, command: &RecordCommand, method: &str, picked: Option<&str>, methods: &dyn AppMethods, ) -> Result { if method_module(method).is_none() { return Err(refused(format!( "`{method}` is not a method a command runs" ))); } let args = command_arguments(client, definition, id, command, picked, methods)?; // An act at the object on a phone not signed in says its own words. let answer = methods.call(method, &Value::Object(args)).map_err(|refusal| { match command.signed_out.as_ref().filter(|_| refusal.code == crate::phone::object_acts::SIGN_IN_FIRST) { Some(said) => MethodError { message: said.clone(), ..refusal }, None => refusal, } })?; // A dispatch the Mac's CI planned and refused is said as its refusal, never as the receipt. let refusal = answer .get("refused") .and_then(Value::as_array) .and_then(|said| said.first()) .and_then(Value::as_str); if let Some(said) = refusal { return Err(refused(said.to_string())); } Ok(answer) } /// The arguments a command sends: its `data`, then its bindings off the /// record; refused when its `when` does not hold on the record. fn command_arguments( client: &ClientController, definition: &TableDefinition, id: &str, command: &RecordCommand, picked: Option<&str>, methods: &dyn AppMethods, ) -> Result, MethodError> { let mut args = serde_json::Map::new(); for (key, value) in command.data.iter().flat_map(|data| data.0.iter()) { args.insert(key.clone(), value.clone()); } // The record is read only when a condition or a binding names one of its columns. let binds_a_column = command .bindings .iter() .flat_map(|bindings| bindings.0.iter()) .any(|(_, column)| !cotton_core::definitions::COMMAND_BINDINGS.contains(&column.as_str())); let record = if command.when.is_some() || binds_a_column || command.pick.as_ref().is_some_and(|pick| { pick.choices_from.is_some() || pick .database_by .as_deref() .is_some_and(|column| column != "$id") }) { Some(record_of(client, &definition.id, id, methods)?) } else { None }; if let Some(data) = &record { if !command.offered_on(data) { return Err(not_offered(command)); } } match (command.pick_table.as_deref(), command.pick.as_ref(), picked) { (Some(argument), _, Some(table)) => { args.insert(argument.to_string(), Value::from(table)); } (Some(_), _, None) => { return Err(MethodError::new( "bad_request", format!("\"{}\" needs the table the person picked", command.label), )) } (None, Some(pick), None) if !(matches!(pick.kind, PickKind::Text | PickKind::Number) && pick.optional == Some(true)) && !(pick.kind == PickKind::Number && pick.default.is_some()) => { let what = match pick.kind { PickKind::Number => "the number".to_string(), PickKind::Text => "the words".to_string(), PickKind::Datetime => "the moment".to_string(), PickKind::Record => format!( "the {}", pick.table.as_deref().unwrap_or("record").replace('_', " ") ), PickKind::Database => "the database".to_string(), PickKind::File => "the file".to_string(), }; return Err(MethodError::new( "bad_request", format!("\"{}\" needs {what} the person picked", command.label), )); } (None, None, Some(_)) => { return Err(MethodError::new( "bad_request", format!("\"{}\" does not ask for a pick", command.label), )) } (None, _, None) | (None, Some(_), Some(_)) => {} } for (argument, column) in command .bindings .iter() .flat_map(|bindings| bindings.0.iter()) { let value = match column.as_str() { "$id" => Value::from(id), "$id_list" => Value::from(vec![id]), column => record .as_ref() .and_then(|data| data.get(column)) .cloned() .unwrap_or(Value::Null), }; put_at(&mut args, argument, value); } // The pick goes in last, so no `data` or binding stands in for it. if let (None, Some(pick), Some(picked)) = (command.pick_table.as_deref(), command.pick.as_ref(), picked) { let value = if let Some(source) = &pick.choices_from { offered_choice(record.as_ref().and_then(Value::as_object), source, picked)? } else { let database = pick .database_by .as_deref() .map(|column| { if column == "$id" { Ok(id) } else { record .as_ref() .and_then(|data| data.get(column)) .and_then(Value::as_str) .filter(|value| !value.trim().is_empty()) .ok_or_else(|| { MethodError::new( "bad_request", "The record does not name the pick's database", ) }) } }) .transpose()?; let _scope = database .map(|database| client.name_database(Some(database))) .transpose() .map_err(|why| MethodError::new("database_not_held", why))?; picked_value(client, command, pick, picked)? }; put_at(&mut args, &pick.argument, value); } if let Some(pick) = command .pick .as_ref() .filter(|pick| pick.kind == PickKind::Number && pick.optional != Some(true) && picked.is_none()) { put_at( &mut args, &pick.argument, pick.number_value(None) .map_err(|why| MethodError::new("bad_request", why))?, ); } Ok(args) } /// Validate an engine-owned choice before any command method is called. pub(crate) fn offered_choice( record: Option<&serde_json::Map>, source: &str, picked: &str, ) -> Result { let choices = record .and_then(|record| record.get(source)) .and_then(Value::as_array) .filter(|choices| { !choices.is_empty() && choices .iter() .all(|choice| choice.as_str().is_some_and(|text| !text.trim().is_empty())) }) .ok_or_else(|| refused("The engine has not offered choices for this action".into()))?; if !choices.iter().any(|choice| choice.as_str() == Some(picked)) { return Err(refused("That choice is not offered for this record".into())); } Ok(Value::String(picked.into())) } /// A board write's answer: what happened in words, and the write that undoes /// it — the board it replaced saved again, or the default put back. /// `definitions.saveTable {table, : value, …}` — the owner's edit of one /// table from its tool's page: his own columns and the shipped ones he hides, /// how its records look, its list's acts and its stacks (`columns`, `slip`, /// `group`, `links`, `menu`, `groups`, …). It IS /// `update_definition`, the write an assistant makes, run as this device on /// the owner's own database: the same keys, the same refusals (columns, /// engines and commands are never accepted; an act the table does not offer /// is refused), the same row. Answers `{table, receipt, undo, definition}`, /// the undo being this method again with each changed key as it stood. fn save_table(client: &ClientController, request: &Value) -> Result { let args = crate::phone::tool_arguments(request)?; let table = args .get("table") .and_then(Value::as_str) .map(str::trim) .filter(|table| !table.is_empty()) .ok_or_else(|| { MethodError::new( "bad_request", "definitions.saveTable takes the table and the keys it changes", ) })? .to_string(); if args.len() < 2 { return Err(MethodError::new( "bad_request", "definitions.saveTable takes the table and the keys it changes", )); } let answer = client .write("update_definition", &args) .map(crate::authoring::own_answer) .map_err(|reason| MethodError::new("definition_refused", reason))?; let mut undo = answer["before"].as_object().cloned().unwrap_or_default(); undo.insert("table".into(), Value::from(table.clone())); Ok(json!({ "table": table, "receipt": "Saved", "undo": { "method": "definitions.saveTable", "args": undo }, "definition": answer["definition"], })) } fn board_receipt(id: &str, receipt: &str, before: Value) -> Value { let undo = if before.is_object() { serde_json::json!({ "method": "definitions.saveBoard", "args": { "definition": before } }) } else { serde_json::json!({ "method": "definitions.resetBoard", "args": { "id": id } }) }; serde_json::json!({ "id": id, "receipt": receipt, "undo": undo }) } #[cfg(test)] mod resolved_slip_tests { use super::*; /// RULE: A page resolves only the definitions it reads, so an unrelated broken definition cannot affect its slips or emit an unrelated refusal. #[test] fn a_page_resolves_only_its_named_definitions() { use crate::shell::client::phone_tests::attached_on_a_clock; use cotton_core::records::page::PageSource; let (_dir, client, _clock) = attached_on_a_clock(); client.with_writer(|file| { file.driver.run( "INSERT OR REPLACE INTO cotton_table_definitions (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) VALUES ('person', ?, '{', 1, 1, '2026-10-15', '2026-10-15')", &[rusqlite::types::Value::Text(file.workspace_id.to_string())], ).map_err(|error| error.to_string())?; crate::fixture::receipted(file.driver, "INSERT INTO cotton_table_definitions"); Ok(()) }).unwrap(); cotton_tools::definitions::take_definition_diagnostics(); let mut source = ClientPages { client: &client, handle: None, made: None, refused: None, }; assert_eq!(source.definition("todo").unwrap().id, "todo"); assert!(cotton_tools::definitions::take_definition_diagnostics().is_empty()); assert_eq!(source.definition("person").unwrap().id, "person"); assert!(cotton_tools::definitions::take_definition_diagnostics() .iter() .any(|problem| problem.id == "person")); } /// RULE: A caption over an ago column uses the same core formatter as a subtitle even without with_names, so day grouping or a clock rendering cannot replace its relative format on the wire. /// The ago column is set here rather than read from the shipped file: a shipped format is a look the owner may change. #[test] fn an_ago_caption_is_resolved_without_a_named_subtitle() { let mut definition = cotton_core::definitions::builtin_table_definitions() .iter().find(|&d| d.id == "sighting").cloned() .unwrap(); definition.slip.with_names = None; let seen_at = definition .columns .iter_mut() .find(|column| column.key == "seen_at") .unwrap(); seen_at.format = Some(cotton_core::definitions::ColumnFormat::Ago); seen_at.reading = Some("{datetime}".into()); let now = chrono::DateTime::parse_from_rfc3339("2026-10-14T00:03:00Z") .unwrap() .with_timezone(&chrono::Utc); definition.slip.caption = Some(cotton_core::definitions::SlipCaption { columns: Some(vec!["seen_at".into()]), status: None, dates: None, fields: None, near: None, date_form: None, form: None, }); let mut answer = serde_json::json!({"id":"invented-sighting","data":{"seen_at":"2026-10-14T00:00:00Z"}}); attach_slip_lines(&definition, Some("UTC"), Some(now), true, &mut answer, cotton_core::records::page::Words::shipped()); assert_eq!(answer["data"]["@slip_caption"], "3 min ago"); assert!(answer["data"].get("@slip_subtitle").is_none()); } /// RULE: Resolved slip metadata accompanies every returned record while typed data and null receipt sides stay intact; adding display words must never turn a missing before into a record or invent an absent records list. /// RULE: a read asked `said` carries the one slip answer on the record /// itself, so a surface holding the record draws it with no second ask. #[test] fn a_record_read_asked_said_carries_its_slip() { let definition = cotton_core::definitions::builtin_table_definition("todo") .unwrap() .clone(); let now = chrono::DateTime::parse_from_rfc3339("2026-10-01T10:00:00+05:30") .unwrap() .with_timezone(&chrono::Utc); let mut answer = serde_json::json!({"records": [{"id": "t1", "data": {"title": "Water the ferns"}}]}); attach_said(&definition, "UTC", Some(now), false, &mut answer, cotton_core::records::page::Words::shipped()); assert_eq!(answer["records"][0]["data"]["@said"]["slip"]["name"], "Water the ferns"); } /// RULE: a list split by day carries each slip's foot and strip as the /// core said them against this read's now, with a series' missed count /// taken across the whole answer: the face draws them, never a date. #[test] fn an_upcoming_answer_carries_the_cores_dated_lines() { let definition = cotton_core::definitions::builtin_table_definition("todo") .unwrap() .clone(); let now = chrono::DateTime::parse_from_rfc3339("2026-10-01T10:00:00+05:30") .unwrap() .with_timezone(&chrono::Utc); let bins = |id: &str, due: &str| { serde_json::json!({"id": id, "data": {"title": "Invented bins", "status": "open", "due_at": due, "recurrence_id": "series-bins"}}) }; let mut answer = serde_json::json!({"records": [bins("a", "2026-09-20"), bins("b", "2026-09-27"), bins("c", "2026-10-01")]}); attach_slip_lines(&definition, Some("Asia/Kolkata"), Some(now), true, &mut answer, cotton_core::records::page::Words::shipped()); let data = &answer["records"][1]["data"]; assert_eq!(data["@slip_foot"], "Sun 27 Sep · 4 days late · missed 2"); assert_eq!(data["@slip_foot_late"], true); assert_eq!(data["@slip_strip"], "4 days late"); assert_eq!(answer["records"][2]["data"]["@slip_strip"], "today"); assert!(answer["records"][2]["data"]["@slip_foot"].is_null()); } #[test] fn resolved_slip_wire_preserves_typed_data_and_absent_records() { let definition = cotton_core::definitions::builtin_table_definitions() .iter().find(|&d| d.id == "email_sender").cloned() .unwrap(); let mut answer = serde_json::json!({"record":{"id":"sender","data":{"address":"someone@example.invalid","email_count":7}},"before":null}); attach_slip_lines(&definition, Some("UTC"), None, true, &mut answer, cotton_core::records::page::Words::shipped()); assert_eq!(answer["record"]["data"]["email_count"], 7); assert_eq!(answer["record"]["data"]["@slip_subtitle"], "someone@example.invalid"); assert!(answer["before"].is_null()); assert!(answer.get("records").is_none()); let mut list = serde_json::json!({"records":[{"id":"sender","data":{"address":"other@example.invalid"}}]}); attach_slip_lines(&definition, Some("UTC"), None, true, &mut list, cotton_core::records::page::Words::shipped()); assert_eq!(list["records"][0]["data"]["@slip_subtitle"], "other@example.invalid"); let mut absent = serde_json::json!({"count":0}); attach_slip_lines(&definition, Some("UTC"), None, true, &mut absent, cotton_core::records::page::Words::shipped()); assert_eq!(absent, serde_json::json!({"count":0})); } /// RULE: every link a record carries says its kind in the format set's words, else its key in words. #[test] fn a_records_links_say_their_kind() { let definition = cotton_core::definitions::builtin_table_definitions().iter().find(|&d| d.id == "todo").cloned().unwrap(); let mut answer = serde_json::json!({"record": {"id": "todo-1", "table": "todo", "data": {"title": "An invented errand", "links": [ {"table": "transaction", "id": "t-1"}, {"table": "session_message", "id": "s-1"}, {"table": "invented_kind", "id": "i-1"}, {"id": "no-table"}, ]}}}); let words = cotton_core::records::page::Words::shipped(); attach_slip_lines(&definition, Some("UTC"), None, true, &mut answer, words); let links = &answer["record"]["data"]["links"]; assert_eq!(links[0]["kind_word"], words.format.say("mark.transaction", &[]).unwrap()); assert_eq!(links[1]["kind_word"], words.format.say("mark.session_message", &[]).unwrap()); assert_eq!(links[2]["kind_word"], cotton_core::definitions::key_as_words("invented_kind")); assert!(links[3].get("kind_word").is_none(), "a link naming no table says no kind"); } /// RULE: A slip's lines from another table go only onto the records of its own table that an answer carries; a null receipt side, another table's record or an answer with no records gains nothing. #[test] fn slip_rows_land_only_on_the_tables_own_records() { let todo = cotton_core::definitions::builtin_table_definitions() .iter().find(|&d| d.id == "todo").cloned() .unwrap(); let mut one = serde_json::json!({"record":{"id":"t1","table":"todo","data":{}},"before":null}); assert_eq!(answered_records(&todo, &mut one).len(), 1); let mut list = serde_json::json!({"records":[{"id":"t1","data":{}},{"id":"t2","table":"todo","data":{}},{"id":"x","table":"note","data":{}}]}); assert_eq!(answered_records(&todo, &mut list).len(), 2); let mut absent = serde_json::json!({"count":0}); assert!(answered_records(&todo, &mut absent).is_empty()); } } #[cfg(test)] mod duration_readings_tests { use super::*; /// RULE: All record answer shapes carry the core duration reading beside the unchanged typed value, so cards never have to format a raw count. #[test] fn every_record_answer_carries_core_duration_words() { let definition = cotton_core::definitions::builtin_table_definition("video").unwrap(); let record = json!({"id":"invented-video", "table":"video", "data":{"duration_ms":4000}}); for mut answer in [ record.clone(), json!({"record":record}), json!({"records":[record]}), json!({"before":record, "after":record}), ] { attach_slip_lines(definition, None, None, true, &mut answer, cotton_core::records::page::Words::shipped()); for row in answered_records(definition, &mut answer) { assert_eq!(row["data"]["duration_ms"], 4000); assert_eq!(row["data"]["@column_words"]["duration_ms"], "4 s"); } } } /// RULE: A date alone asks the core for both slip slots; otherwise a /// surface falls back to its raw ISO value just because the definition /// did not add a reading or unit label. #[test] fn date_only_slip_slots_carry_resolved_metadata() { let mut definition = cotton_core::definitions::builtin_table_definition("note") .unwrap() .clone(); let stamp = definition .columns .iter_mut() .find(|column| column.key == "published_at") .unwrap(); stamp.column_type = cotton_core::definitions::ColumnType::Date; stamp.format = Some(cotton_core::definitions::ColumnFormat::Ago); stamp.reading = None; stamp.units = None; definition.slip.subtitle = Some(cotton_core::definitions::SlipSubtitle::One( "published_at".into(), )); definition.slip.caption = Some(cotton_core::definitions::SlipCaption { columns: Some(vec!["published_at".into()]), status: None, dates: None, fields: None, near: None, date_form: None, form: None, }); let now = chrono::DateTime::parse_from_rfc3339("2026-10-14T10:03:00Z") .unwrap() .with_timezone(&chrono::Utc); let mut answer = json!({"id":"invented-note", "table":"note", "data":{"published_at":"2026-10-14T10:00:00Z"}}); attach_slip_lines(&definition, Some("UTC"), Some(now), true, &mut answer, cotton_core::records::page::Words::shipped()); assert_eq!(answer["data"]["@slip_subtitle"], "3 min ago"); assert_eq!(answer["data"]["@slip_caption"], "3 min ago"); } } #[cfg(test)] mod mac_away_page_guards { use serde_json::{Map, Value}; /// The page's reads as `ClientPages` hands them to the core when the /// serving Mac never answered: every read refused with the transport's /// message. struct Unreached(&'static str); impl cotton_core::records::page::PageSource for Unreached { fn line_rows(&mut self) -> Vec { Vec::new() } fn definition(&mut self, table: &str) -> Option { cotton_core::definitions::builtin_table_definition(table).cloned() } fn record(&mut self, _: &str, _: &str) -> Result, String> { Err(self.0.to_string()) } fn records( &mut self, _: &str, _: &[String], ) -> Result)>, String> { Err(self.0.to_string()) } fn list( &mut self, _: &str, _: &Map, _: usize, ) -> Result<(u64, Vec<(String, Map)>), String> { Err(self.0.to_string()) } fn active_project_slugs(&mut self) -> Vec { Vec::new() } fn read(&mut self, _: &str, _: &Map) -> Result { Err(self.0.to_string()) } } /// RULE: a record's page whose serving Mac never answered (status 0 or a gateway's 502–504) answers the typed could-not-read line `mac_away`, and NOTHING the app receives — code, message or details — carries the transport's words; they go to the log alone. The core's page source carries a refusal as its message only, so the page answers the typed refusal of the read that failed it, never an `unreadable` built from that message (294 walk row G: "no raw transport string on any page"). #[test] fn a_page_whose_mac_never_answered_carries_none_of_the_transports_words() { const WORDS: &str = "synthetic-relay-7f3c.invalid could not be resolved (dns error 9917)"; for status in [0_u64, 502, 503, 504] { let transport = crate::methods::MethodError::new("server_refused", WORDS) .with_details(serde_json::json!({ "status": status })); let reason = cotton_core::records::page::record_page( &mut Unreached(WORDS), "todo", "synthetic-todo", ) .expect_err("a page was made with no read answered"); let _ = cotton_client::replica::take_read_refusal(); let typed = crate::methods::could_not_read( "records.page", super::page_refusal(reason, Some(transport)), ); assert_eq!(typed.code, crate::methods::COULD_NOT_READ, "{status}"); assert_eq!(typed.details["why"], "mac_away", "{status}"); let (said, logged) = typed.for_person(); let answer = said.envelope().to_string(); assert!( !answer.contains(WORDS) && !answer.contains("synthetic-relay") && !answer.contains("9917"), "{answer}" ); assert!( logged.is_some_and(|line| line.contains(WORDS)), "the log lost the transport's words" ); } // A refusal the page made itself keeps its own code. let own = super::page_refusal( "no such page here".into(), Some(crate::methods::MethodError::new( "server_refused", "another read", )), ); assert_eq!(own.code, "unreadable"); } }