//! 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