Cotton code
389 lines · 19.4 KB · RustRaw
//! `definitions.catalogue` — every definition a database draws, resolved and//! decoded by the core, handed to the app in one versioned shape.//!//! **One decoder of the definition format (architect, 14 Oct 2026).** Phone//! cut 273 crashed before its first screen: a definition file the core//! accepted failed the app's own Swift decoder. Two decoders of one format are//! two truths. So the core is the only reader of definitions: the app draws//! the tables, boards and themes this answer carries — each the core's typed//! value, serialized — caches it once per database, and asks again only when//! a definitions row moves.//!//! **Every page is the core's.** Each table travels with the page the core//! resolved for it ([`Page`]: its parts and their order, defaults dealt), so//! the app never derives a page itself — a second derivation is a second//! truth exactly as a second decoder is.//!//! Every board part arrives with its settings resolved: a board's defaults//! live in the core (`board::default_of`), never in the app. A `device` part//! arrives naming this device's own record (`board::THIS_DEVICE_KEY`).//!//! **Tools are records only (72nd amendment, 21 Oct 2026).** A database's//! catalogue carries the tables its own definition rows describe and no//! other: a table with no row opens, lists and syncs, and a read that needs a//! definition for it answers `no_tool_draws_this_table` — never a table this//! build bundles. A built-in's stored row the core cannot read is said once//! in the database's Feedback (`fell_back`), as is a board or theme row it//! cannot draw (`passed_over`); never a crash and never a blank screen.//!//! **A table with no face is said, not drawn.** A definition row with no//! slip is a storage table — its rows sync and the engines and the MCP read//! them, and no tool draws it — so the answer leaves it out of `tables` and//! names it in `kept_as_rows` with why ([`KEPT_AS_ROWS`]); the app's reader//! logs every table it was served and did not draw once, by id and reason//! (tables-dropped, 28 Oct 2026: 35 of Personal's 144 rows were left out//! without a word).//!//! **The shape is versioned** ([`CATALOGUE_SHAPE`]): an app whose Swift reads//! another shape than its core answers says so plainly instead of drawing//! half a definition. A change to what this answer carries bumps the number in//! the same commit as the Swift that reads it.//!//! **The last-resort answer is empty of tables** ([`fresh`]): what the app//! draws before any database answers is this build's boards and themes and//! no table at all. A process with no core of its own (the package's tests)//! reads it from the snapshot beside the app's resources ([`SNAPSHOT_PATH`]),//! generated explicitly by `generate_shipped_catalogue`. Its `themes` are//! written beside the look's resources too ([`THEMES_PATH`]): the look//! (`CottonPaper`) draws before any core answers and links none of the//! screens that read the rest.use std::collections::BTreeMap;use cotton_core::definitions::board::BoardDefinition;use cotton_core::definitions::theme::{ThemeDefinition, BUILTIN_THEME_FILES, DEFAULT_THEME};use cotton_core::definitions::{PagePart, PageParts, SlipsLayout, TableDefinition, TableRole, BUILTIN_DEFINITIONS_HASH};use cotton_tools::definitions::Refused;use cotton_tools::presentation::{Drawn, Resolved};use serde::Serialize;use serde_json::{json, Value};use crate::methods::MethodError;use crate::shell::client::ClientController;/// The version of [`Catalogue`]'s shape. The Swift reader names the one it/// reads (`DefinitionCatalogue.shape`) and refuses any other.pub const CATALOGUE_SHAPE: u32 = 10;/// Why a served definition row is in `kept_as_rows` and not in `tables`.pub const KEPT_AS_ROWS: &str = "no slip: a storage table, its rows sync and are read, no tool draws it";/// Where the committed snapshot of a fresh database's answer lives, from the/// repo root.pub const SNAPSHOT_PATH: &str = "apps/cotton/Sources/CottonUI/Resources/Shipped/catalogue.json";/// Where the snapshot's `themes` live for the look (`CottonPaper`'s/// `ShippedThemes`), from the repo root: the same rows, held equal to the/// snapshot's by `the_looks_themes_are_the_snapshots`.pub const THEMES_PATH: &str = "apps/loom/Sources/CottonPaper/Resources/Themes/themes.json";/// Everything a database draws, as the core resolved and decoded it.#[derive(Debug, Clone, Serialize)]pub struct Catalogue {    /// [`CATALOGUE_SHAPE`].    pub shape: u32,    /// The content hash of the definitions folder this build compiled in.    pub revision: &'static str,    /// Every table the database draws: the built-ins in the order the app    /// ships them, then every other synced table by id.    pub tables: Vec<TableDefinition>,    /// Every table's page as the core resolved it, by the table's id.    pub pages: BTreeMap<String, Page>,    /// Tables a person or a package defined that could not be read, with why.    pub refused: Vec<Refused>,    /// Built-ins whose stored row could not be read, drawn as shipped.    pub fell_back: Vec<Refused>,    /// Definition rows with no face (no slip), kept as rows and drawn    /// nowhere, each with [`KEPT_AS_ROWS`].    pub kept_as_rows: Vec<Refused>,    /// Every board by id: the person's row, or this build's default.    pub boards: BTreeMap<String, Resolved>,    /// The theme the database wears.    pub theme: Resolved,    /// Every theme this build ships, by id — what a family is drawn over.    pub themes: BTreeMap<String, ThemeDefinition>,}/// The table a database keeps its face choices in (`face_choices`), and the/// column naming the table each row chooses for (`row_key`).#[derive(Debug, Clone, PartialEq)]pub struct FaceChoiceTable {    pub table: String,    pub row_key: String,}impl FaceChoiceTable {    /// The first of `tables` that keeps face choices and names its key.    pub fn of<'a>(tables: impl IntoIterator<Item = &'a TableDefinition>) -> Option<Self> {        tables.into_iter().find(|table| table.face_choices == Some(true)).and_then(|table| {            table.row_key.as_ref().map(|key| FaceChoiceTable { table: table.id.clone(), row_key: key.clone() })        })    }}/// One table's page as the core resolves it: the parts the app draws/// (`resolved_parts`) in the order it draws them (`resolved_page_parts`).#[derive(Debug, Clone, PartialEq, Serialize)]pub struct Page {    pub parts: PageParts,    pub page_parts: Vec<PagePart>,}/// The page of every table in `tables`, by id, its slips dealt from the/// database table's slips table: every field card arrives with its width and/// its acts.pub fn pages(tables: &[TableDefinition]) -> BTreeMap<String, Page> {    let slips = slips_of(tables);    tables.iter().map(|table| (table.id.clone(), page(table, slips))).collect()}/// What the core says of every table in `tables`, by id: what a shell asks/// of the table itself and never works out.pub fn said(tables: &[TableDefinition]) -> BTreeMap<String, Value> {    tables.iter().map(|table| (table.id.clone(), table_said(table))).collect()}/// `{ "list_takes_capture", "takes_an", "labels": { column: words } }`:/// whether the table's list draws the capture bar (sealed tables and a table/// nothing is typed into never do; `capture` that is not page-only does even/// when its own rows are read-only), whether its name takes "an", and every/// column's name as a person reads it (its own, else its key as words).pub fn table_said(table: &TableDefinition) -> Value {    let sealed = table.sealed == Some(true);    let capture = table.capture.as_ref();    let takes = !sealed && (table.columns.iter().any(|column| column.readonly != Some(true)) || capture.is_some_and(|capture| capture.link.is_some()));    let listed = table.add != Some(false) && (takes || (!sealed && capture.is_some_and(|capture| capture.page_only != Some(true))));    let takes_an = table.name.to_lowercase().starts_with(['a', 'e', 'i', 'o', 'u']);    let labels: BTreeMap<&str, String> = table.columns.iter()        .map(|column| (column.key.as_str(), column.name.clone().unwrap_or_else(|| key_words(&column.key))))        .collect();    json!({ "list_takes_capture": listed, "takes_an": takes_an, "labels": labels })}/// A column key as the words a person reads: the store's endings say how a/// value is kept, not what it is, so they go; the rest reads as one phrase/// with its first letter raised ("balance_minor" is "Balance").fn key_words(key: &str) -> String {    let stem = ["_id", "_at", "_on", "_minor", "_ms"].iter()        .find_map(|ending| key.strip_suffix(ending).filter(|stem| !stem.is_empty()))        .unwrap_or(key)        .replace('_', " ");    let mut letters = stem.chars();    letters.next().map(|first| first.to_uppercase().chain(letters).collect()).unwrap_or_default()}/// The slips table a database deals its pages from: its database table's,/// when its catalogue carries one.pub fn slips_of(tables: &[TableDefinition]) -> Option<&SlipsLayout> {    tables.iter().find(|table| table.role == Some(TableRole::Database)).and_then(|table| table.slips.as_ref())}/// One table's page: its resolved parts with its slips dealt, in its order.pub fn page(table: &TableDefinition, slips: Option<&SlipsLayout>) -> Page {    let mut parts = table.resolved_parts();    if let Some(slips) = slips {        table.deal_slips(&mut parts, slips);    }    Page { parts, page_parts: table.resolved_page_parts() }}/// A board as the app draws it: every part's settings resolved by the core/// (`BoardDefinition::resolved`). A row that does not read as a board passes/// as it came — the app draws this build's own board in its place.fn resolved_board(mut board: Resolved) -> Resolved {    if let Ok(read) = serde_json::from_value::<BoardDefinition>(board.definition.clone()) {        if let Ok(definition) = serde_json::to_value(read.resolved()) {            board.definition = definition;        }    }    board}/// A board as it is served to THIS device: each `device` part, of every/// size's list, names this device's own record (`THIS_DEVICE_KEY`), so the/// app draws the record the core says is this phone's and never works out/// which one itself. No device known yet (no identity), the part names none/// and draws nothing.fn served_to(mut board: Resolved, device: Option<&str>) -> Resolved {    use cotton_core::definitions::board::THIS_DEVICE_KEY;    let Some(device) = device else { return board };    let name = |parts: Option<&mut Value>| {        for part in parts.and_then(Value::as_array_mut).into_iter().flatten().filter(|part| part["kind"] == "device") {            if let Some(settings) = part.as_object_mut() {                settings.insert(THIS_DEVICE_KEY.into(), Value::from(device));            }        }    };    name(board.definition.get_mut("parts"));    for variant in board.definition.get_mut("variants").and_then(Value::as_array_mut).into_iter().flatten() {        name(variant.get_mut("parts"));    }    board}fn shipped_themes() -> BTreeMap<String, ThemeDefinition> {    ThemeDefinition::builtins().into_iter().map(|theme| (theme.id.clone(), theme)).collect()}fn shipped_theme_row(id: &str) -> Value {    let json = BUILTIN_THEME_FILES.iter().find(|(file, _)| *file == id).expect("the default theme ships").1;    serde_json::from_str(json).expect("a shipped theme parses")}/// The last-resort answer, before any database answers: no table, every/// board and the theme at this build's default. Decoded and validated, each/// failure named.pub fn fresh() -> Result<Catalogue, String> {    let mut boards = BTreeMap::new();    for board in BoardDefinition::builtins() {        board.validate().map_err(|error| format!("built-in board {}: {error}", board.id))?;        let definition = serde_json::to_value(board.resolved()).map_err(|error| error.to_string())?;        boards.insert(board.id.clone(), Resolved { definition, drawn: Drawn::Default, passed_over: None });    }    let themes = shipped_themes();    for theme in themes.values() {        theme.validate().map_err(|error| format!("built-in theme {}: {error}", theme.id))?;    }    Ok(Catalogue {        shape: CATALOGUE_SHAPE,        revision: BUILTIN_DEFINITIONS_HASH,        tables: Vec::new(),        pages: BTreeMap::new(),        refused: Vec::new(),        fell_back: Vec::new(),        kept_as_rows: Vec::new(),        boards,        theme: Resolved { definition: shipped_theme_row(DEFAULT_THEME), drawn: Drawn::Default, passed_over: None },        themes,    })}/// The committed snapshot's bytes: a fresh database's answer, pretty-printed,/// one newline at the end.pub fn snapshot() -> Result<String, String> {    let mut text = serde_json::to_string_pretty(&fresh()?).map_err(|error| error.to_string())?;    text.push('\n');    Ok(text)}/// The look's themes file for a snapshot's bytes: its `themes`,/// pretty-printed the same way.pub fn themes_of(snapshot: &str) -> Result<String, String> {    let answer: Value = serde_json::from_str(snapshot).map_err(|error| error.to_string())?;    let mut text = serde_json::to_string_pretty(&answer["themes"]).map_err(|error| error.to_string())?;    text.push('\n');    Ok(text)}/// Answer `definitions.catalogue` for the database the call is scoped to; with/// `{"shipped": true}`, the last-resort answer ([`fresh`]): this build's/// boards and themes, no table.pub fn call(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    if request["shipped"].as_bool() == Some(true) {        let answer = fresh().map_err(|reason| MethodError::new("unreadable", reason))?;        return serde_json::to_value(answer).map_err(|error| MethodError::new("unreadable", error.to_string()));    }    // Home's board is drawn from this answer: every read in it — the    // definitions and the worn theme — is on the read pool's short lane, never    // behind a list or a walk of the file (readpool, 16 Oct 2026).    crate::shell::client::on_short_lane(crate::shell::client::ShortRead::Catalogue, || catalogue_of(client))}fn catalogue_of(client: &ClientController) -> Result<Value, MethodError> {    let reader = client.device_scope().map_err(|reason| MethodError::new("unreadable", reason))?        == cotton_core::device::scope::DeviceScope::Reader;    let this_device = client.self_device_id();    let read = client        .read_rows("definitions.catalogue", &mut |ctx| {            let mut listed = cotton_tools::definitions::table_definitions(ctx).map_err(|failure| failure.to_string())?;            // Rows only: a table no definition row describes is not drawn            // from this build's copy — it has no tool here.            let rows: std::collections::BTreeSet<String> = cotton_tools::definitions::definition_rows(ctx, None)                .map_err(|failure| failure.to_string())?                .into_iter()                .map(|row| row.id)                .collect();            listed.definitions.retain(|definition| rows.contains(&definition.id));            // A table with no face (a storage-only one the object serves) is            // kept as rows and drawn nowhere — named, so the reader says so.            let (faced, faceless): (Vec<_>, Vec<_>) = listed.definitions.into_iter().partition(TableDefinition::has_face);            listed.definitions = faced;            let kept_as_rows: Vec<Refused> =                faceless.into_iter().map(|table| Refused { id: table.id, reason: KEPT_AS_ROWS.to_string() }).collect();            listed.fell_back.retain(|fell| rows.contains(&fell.id));            if reader {                listed.definitions = listed.definitions.into_iter().map(crate::phone::records::resolve_reader_acts).collect();            }            let mut boards = BTreeMap::new();            for id in cotton_tools::presentation::board_ids() {                if let Some(board) = cotton_tools::presentation::board(ctx.read.driver(), ctx.workspace_id, id)? {                    boards.insert(id.to_string(), served_to(resolved_board(board), this_device.as_deref()));                }            }            let catalogue = json!({                "said": said(&listed.definitions),                "pages": pages(&listed.definitions),                "tables": listed.definitions, "refused": listed.refused,                "fell_back": listed.fell_back,                "kept_as_rows": kept_as_rows,                "boards": boards,            });            Ok(json!({ "catalogue": catalogue, "database": ctx.workspace_id }))        })        .map_err(|reason| MethodError::new("unreadable", reason))?;    // The worn theme, as `definitions.theme` answers it: a family this build    // does not ship is said once in Feedback there.    let theme = crate::phone::theme_save::read(client)?;    let mut catalogue = read["catalogue"].clone();    catalogue["shape"] = json!(CATALOGUE_SHAPE);    catalogue["revision"] = json!(BUILTIN_DEFINITIONS_HASH);    catalogue["theme"] = theme;    catalogue["themes"] = serde_json::to_value(shipped_themes()).map_err(|error| MethodError::new("unreadable", error.to_string()))?;    let database = read["database"].as_str().unwrap_or_default().to_string();    // The database the answer is of, so the reader says each database's    // undrawn rows once whichever core asked (scoped or the personal default).    catalogue["database"] = json!(database);    say_fallbacks(client, &database, &catalogue);    Ok(catalogue)}/// Each definition drawn as shipped in place of a stored row, said ONCE per/// database and definition in its Feedback. The read stands whatever the note/// does: a database this device may not write (a guest's) still draws.fn say_fallbacks(client: &ClientController, database_id: &str, catalogue: &Value) {    let mut said: Vec<(String, String, String)> = Vec::new();    for fell in catalogue["fell_back"].as_array().into_iter().flatten() {        let (Some(id), Some(why)) = (fell["id"].as_str(), fell["reason"].as_str()) else { continue };        said.push(("table".into(), id.into(), why.into()));    }    for (id, board) in catalogue["boards"].as_object().into_iter().flatten() {        if let Some(why) = board["passed_over"].as_str() {            said.push(("board".into(), id.clone(), why.into()));        }    }    if said.is_empty() {        return;    }    let name = crate::phone::databases::name_of(client, database_id).ok().flatten().unwrap_or_else(|| database_id.to_string());    for (kind, id, why) in said {        // A table says itself in the definition's words, never the parse        // error (294, walker293); the reason stays in the context.        let words = (kind == "table").then(|| cotton_core::rules::feedback::definition_fallback_line(&id)).flatten();        let note = words.unwrap_or_else(|| format!(            "The {kind} \"{id}\" stored in {name} could not be drawn, so this build drew its own instead: {why}"        ));        let key = format!("definition-fallback:{database_id}:{kind}:{id}");        let context = json!({ "surface": "definitions", "kind": kind, "id": id, "databaseId": database_id, "databaseName": name, "reason": why });        let filed = client.write_rows("definitions.catalogue", &mut |ctx| {            crate::phone::feedback_note::file_once(ctx, &key, &note, context.as_object().cloned().unwrap_or_default())                .map(|wrote| json!({ "filed": wrote }))        });        if let Err(why) = filed {            tracing::warn!(kind, id, why, "definitions: the fallback's Feedback note was not written");        }    }}#[cfg(test)]#[path = "catalogue_tests.rs"]mod tests;