Cotton code
574 lines · 27.1 KB · RustRaw
//! BOARD definitions — a screen's composition as data (design note 26203e21 §4).//!//! A board names the parts a screen draws, in order, from a CLOSED set//! ([`BOARD_PART_KINDS`]); the app draws each kind once (`BoardSurface`) and//! no part composes others. One row per screen per database//! (`cotton_board_definitions`): `home`, `tools`, `database`, or a tool's id//! for a tool's own landing board. Built-in defaults ship in//! `crates/cotton-core/kits/shell/boards/` and are written into every//! database. A personal row stores id-keyed differences over its shipped//! default (`overlay`); removing that row restores the default. A package//! board without a shipped base stays whole.//!//! A part is kept WHOLE — its kind and every setting as it came — because a//! newer build may add a kind or a setting an older phone cannot draw: the//! phone skips that part and says so once in Feedback, and a Mac relays the//! row untouched. [`BoardDefinition::validate`] refuses only a malformed row//! (a setting this build knows holding the wrong type); [`BoardDefinition::strict`]//! holds an authored board to exactly what this build draws.#[path = "board_overlay.rs"]pub mod overlay;use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use super::tolerant::Unknown;use super::automations::said;use super::{is_valid_id, refusal_words, DefinitionError};use crate::rules::shell_lines;/// Every part kind a board can name, in no particular order — the whole set.pub const BOARD_PART_KINDS: &[&str] = &[    "head", "tools", "asked", "done", "notices", "list", "facts", "about", "recent", "search", "today", "figure", "sync",    "device",];/// The setting a `device` part carries once the catalogue that serves it to/// a device has resolved it: that device's own record id. Never authored and/// never stored; absent where no device is known (a fresh database's/// last-resort answer), where the part draws nothing.pub const THIS_DEVICE_KEY: &str = "device_id";/// The stretches of time a `list` or `figure` part keeps its rows from, by/// the table's own date (`FigurePeriod`, by its wire names).pub const PART_PERIODS: &[&str] = &["this_month", "today", "tomorrow", "next_7_days", "next_day"];/// What a `figure` part does with its rows (`SummaryOp`, by its wire names).pub const FIGURE_OPS: &[&str] = &["count", "sum", "min", "max"];/// What a `notices` part can show, in the order Home draws them when the/// part does not say (`shows`). Each is a notice the app draws once.pub const NOTICE_KINDS: &[&str] = &[    "update", "arriving", "unreadable", "backup", "joinRequests", "workingOn", "readRefusal", "attention", "project",];/// What an `asked` part can show: the Asked of you rows the crate counts/// (`rules::asked_of_you::ASKED_KEYS`, by their wire names), and/// [`RETIRED_ASKED_SHOWS`], which a board saved before may still name.pub const ASKED_SHOWS: &[&str] = &["joinRequests", "assistantsAsked", "invites", "passwords", "aiAccess"];/// Asked of you rows no read answers any more, still a word a saved board/// may name: `assistantsAsked` counted the comment table's open questions,/// held as retired (TABLE DROP 1, 27 Nov 2026), so it is never drawn.pub const RETIRED_ASKED_SHOWS: &[&str] = &["assistantsAsked"];/// What a `done` part can show: the Done for you receipts the crate reads/// (`rules::done_for_you::DoneKind`, by their wire names).pub const DONE_SHOWS: &[&str] = &["filed", "remembered", "couldNotRead", "cityFilled", "junkFiled", "removedFrom"];/// Where an `asked` or `done` part stands: a band on the page, or behind/// the head's tag of the same name (a sheet the tag opens).const BAND_PLACES: &[&str] = &["band", "head"];/// Part kinds no board draws any more, each with the `refusal.definition`/// line a refusal says./// Refused on every read and every write, never relayed as a newer build's:/// removed means removed (owner's ruling, 12 Oct 2026 — Home is tiles, and a/// tile opens its view).pub const REMOVED_BOARD_PARTS: &[(&str, &str)] = &[(    "sections",    "home_draws_no_sections_any_more_each",)];/// The built-in boards: `(id, json)`, compiled in.pub const BUILTIN_BOARD_FILES: &[(&str, &str)] = &[    ("home", include_str!("../../kits/shell/boards/home.json")),    ("tools", include_str!("../../kits/shell/boards/tools.json")),    ("database", include_str!("../../kits/shell/boards/database.json")),    ("settings", include_str!("../../kits/shell/boards/settings.json")),];/// A screen's parts, in the order they are drawn.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct BoardDefinition {    /// The definition format the file is written in ([`super::format`]).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub format_version: Option<u32>,    pub id: String,    pub parts: Vec<BoardPart>,    /// Other part lists for other sizes of screen (`when.size`: `large`,    /// `widest`, `mac`); absent, every size draws `parts`.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub variants: Vec<BoardVariant>,    /// The picture the board's own tile prints when nothing else fills it —    /// Home's tile, which prints the owner's face, before any person is    /// chosen as them (a database just founded, on a phone or a Mac) and in a    /// business app, which has no "you". Home's board always names one: the    /// shipped Home and every manifest's (`declare_home` refuses one without).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub picture: Option<super::ToolPicture>,    /// The content hash of the shipped file a person's row was written    /// against ([`super::format`]); absent on a shipped file.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub base_hash: Option<String>,    #[serde(flatten, default, skip_serializing_if = "Map::is_empty")]    pub unknown: Unknown,    /// The settings [`BoardDefinition::resolved`] fell back on, by path    /// (`parts.1.face`): a newer build's word this build cannot draw, read    /// as its kind's default ([`super::tolerant`]). Never stored.    #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")]    pub fallbacks: Vec<String>,}/// One part: its kind, and its settings as they came.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct BoardPart {    pub kind: String,    #[serde(flatten, default)]    pub settings: Map<String, Value>,}/// The parts a board draws on one size of screen.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct BoardVariant {    pub when: Map<String, Value>,    pub parts: Vec<BoardPart>,}/// What one setting of a known part kind must hold.enum Setting {    Strings,    Id,    Words,    Count,    /// Static record data an engine catalogue reads from this list part.    Rows,    OneOf(&'static [&'static str]),    /// A list of words, each from the set; a word outside it is a newer    /// build's, refused only when authored here.    SomeOf(&'static [&'static str]),    /// Columns and what each must hold (`records::parse_where`'s shape),    /// checked against the table when the part is read.    Where,}/// Each known kind's settings: `(key, what it holds, required)`.fn settings_of(kind: &str) -> Option<&'static [(&'static str, Setting, bool)]> {    use Setting::*;    Some(match kind {        // The database's cap is the frame's (the caps arc), never the head's.        "head" => &[("tags", Strings, false)],        // Home's fan is the app's frame, drawn in code on every page (owner        // with the architect, 16 Oct 2026): no face of a board draws it.        "tools" => &[            ("face", OneOf(&["row", "grid"]), false),            ("columns", Count, false),            ("size", OneOf(&["large", "small"]), false),            // The tools whose tables hold no rows, in the kit's order: the            // object says so on the home board it serves, and the fan deals            // them after Settings (owner, 26 Oct 2026). The object holds every            // row; a phone's copy keeps a window, so it never works this out.            ("empty", Strings, false),            // No `order` and no `default_order`: the fan is alphabetical in            // every database, always (owner, 17 Oct 2026), but for the empty            // tools above. A stored row that still carries either reads with            // it dropped (`without_retired`); an authored one naming either is            // refused (`strict`).        ],        // A table's rows as a section: those `where` holds, kept by the        // table's own date in `period` (a business's Home, 19 Oct 2026).        "list" => &[            ("table", Id, true),            ("heading", Words, false),            ("limit", Count, false),            ("rows", Rows, false),            ("where", Where, false),            ("period", OneOf(PART_PERIODS), false),        ],        // One figure of a table as a section — a tool card's figure        // (`FigureSummary`) with the words it is said in: `many` with the        // total for `{n}`, `one` for a count of exactly one.        "figure" => &[            ("heading", Words, true),            ("table", Id, true),            ("op", OneOf(FIGURE_OPS), true),            ("column", Id, false),            ("where", Where, false),            ("period", OneOf(PART_PERIODS), false),            ("many", Words, true),            ("one", Words, false),        ],        "facts" => &[("source", Id, true)],        // The backup's one line (`records::backup`), said the same on Home,        // the device page and Feedback: how long the Mac has not backed up        // (`{device}`, `{behind}` filled with "3 days"), stopped with no time        // known, half set up, and the button that opens the Mac's page. The        // Mac's own reason is never in the line; it stays on the Mac's page.        "notices" => &[            ("shows", SomeOf(NOTICE_KINDS), false),            ("backup_behind", Words, false),            ("backup_unset", Words, false),            ("backup_open", Words, false),            ("sync_not_answering", Words, false),            ("backup_stopped", Words, false),        ],        "asked" => &[("shows", SomeOf(ASKED_SHOWS), false), ("place", OneOf(BAND_PLACES), false)],        "done" => &[("shows", SomeOf(DONE_SHOWS), false), ("place", OneOf(BAND_PLACES), false)],        "about" => &[("source", OneOf(&["build"]), false)],        // The person's last opens, newest first and one per tool page or        // record (`read.recentVisits`); it never reorders the tiles.        "recent" => &[("heading", Words, false), ("limit", Count, false)],        // Where the board's search is offered: a magnifier in the head that        // turns the head's row into the field, or the field under the head        // (fan3 part 6, owner 15 Oct 2026). A board with no search part        // offers no search.        "search" => &[("face", OneOf(&["field", "icon"]), false)],        // The ready/today agenda: across databases on Personal, otherwise        // only the shown database. The Mac and phone ship this word together.        "today" => &[],        // This device's one sync line (`rules::sync_status`): the core's        // typed state in the shell's words (`kits/shell/lines/sync.json`); a        // tap opens this device's own record page. No setting: the words are        // the lines file's, never the board's.        "sync" => &[],        // This device's own record, drawn by the device tool's own card        // (`device.json`'s `card`: its sync rows done of total, bytes, synced        // at, stalled) — the card Settings › This device draws, read through        // the same `device.facts`, so the two never disagree. First on Home        // while Cotton is in development (owner, 27 Oct 2026: "so we know if        // the app has fully synced or not"). No authored setting: the        // catalogue that hands a board to a device names that device's own        // record on the part ([`THIS_DEVICE_KEY`]), so an authored one is        // refused (`strict`) and a stored one never holds it.        "device" => &[],        _ => return None,    })}/// What a known kind's setting reads as when its part does not say — the ONE/// place a board's defaults live. The catalogue hands every part resolved/// ([`BoardDefinition::resolved`]), so the app draws the core's settings and/// keeps no default of its own./// A notice's default words: the `backup` set's line, kit words.fn notice(words: Option<String>) -> Value {    Value::String(words.unwrap_or_default())}fn default_of(kind: &str, key: &str) -> Option<Value> {    Some(match (kind, key) {        ("head", "tags") => serde_json::json!([]),        ("tools", "face") => serde_json::json!("row"),        ("tools", "columns") => serde_json::json!(4),        ("tools", "size") => serde_json::json!("large"),        ("notices", "shows") => serde_json::json!(NOTICE_KINDS),        ("notices", "backup_behind") => notice(shell_lines::resolve("backup", "notices.behind", &[], &[])),        ("notices", "backup_unset") => notice(shell_lines::resolve("backup", "notices.unset", &[], &[])),        ("notices", "backup_open") => notice(shell_lines::resolve("backup", "notices.open", &[], &[])),        ("notices", "sync_not_answering") => notice(shell_lines::resolve("backup", "notices.not_answering", &[], &[])),        ("notices", "backup_stopped") => notice(shell_lines::resolve("backup", "notices.stopped", &[], &[])),        ("asked", "shows") => serde_json::json!(ASKED_SHOWS),        ("done", "shows") => serde_json::json!(DONE_SHOWS),        ("asked" | "done", "place") => serde_json::json!("band"),        ("about", "source") => serde_json::json!("build"),        ("recent", "heading") => serde_json::json!("Recent"),        ("recent", "limit") => serde_json::json!(30),        ("search", "face") => serde_json::json!("icon"),        _ => return None,    })}/// A stored whole board with what no longer exists dropped: a part whose/// kind this build does not draw, a setting its kind no longer has, a word a/// setting can no longer hold. The seed re-resolves every stored board this/// way on every install, against the shipped shape (dialchrome, 16 Oct/// 2026), so a retired part — Home's `databases`, a `voice` part, the head's/// `cap`, the tools' `fan` face — never lingers in a person's row. Only a row/// an older build wrote is ever handed here: a newer build's part is relayed.pub fn without_retired(board: &Value) -> Value {    fn part(raw: &Value) -> Option<Value> {        let kind = raw.get("kind")?.as_str()?;        let known = settings_of(kind)?;        let mut kept = Map::new();        for (key, value) in raw.as_object()? {            if key == "kind" || key == "id" {                kept.insert(key.clone(), value.clone());                continue;            }            let Some((_, setting, _)) = known.iter().find(|(name, _, _)| name == key) else { continue };            let holds = match (setting, value) {                (Setting::OneOf(values), Value::String(word)) => values.contains(&word.as_str()),                _ => true,            };            if holds {                kept.insert(key.clone(), value.clone());            }        }        Some(Value::Object(kept))    }    fn parts(list: &Value) -> Value {        Value::Array(list.as_array().into_iter().flatten().filter_map(part).collect())    }    let mut board = board.clone();    if let Some(list) = board.get("parts").cloned() {        board["parts"] = parts(&list);    }    if let Some(variants) = board.get_mut("variants").and_then(Value::as_array_mut) {        for variant in variants {            if let Some(list) = variant.get("parts").cloned() {                variant["parts"] = parts(&list);            }        }    }    board}impl BoardPart {    /// This part with each setting its kind defaults that it does not name    /// filled in, and each word this build cannot draw read as its default —    /// the setting's own when its kind has one, else absent; a list keeps the    /// words it can draw, or reads as its default when none is left. Each    /// setting that fell back is named in `fallbacks` under `at`. A kind    /// this build does not know is kept as it came.    pub fn resolved(&self, at: &str, fallbacks: &mut Vec<String>) -> BoardPart {        let mut part = self.clone();        for (key, setting, _) in settings_of(&self.kind).into_iter().flatten() {            let drawable = match (setting, part.settings.get(*key)) {                (Setting::OneOf(values), Some(Value::String(word))) => values.contains(&word.as_str()),                (Setting::SomeOf(values), Some(Value::Array(words))) => {                    let known: Vec<Value> =                        words.iter().filter(|word| word.as_str().is_some_and(|word| values.contains(&word))).cloned().collect();                    let whole = known.len() == words.len();                    if !whole && !known.is_empty() {                        part.settings.insert((*key).to_string(), Value::Array(known));                        fallbacks.push(format!("{at}.{key}"));                        continue;                    }                    whole                }                _ => true,            };            if !drawable {                part.settings.remove(*key);                fallbacks.push(format!("{at}.{key}"));            }            if part.settings.get(*key).is_none_or(Value::is_null) {                if let Some(default) = default_of(&self.kind, key) {                    part.settings.insert((*key).to_string(), default);                }            }        }        part    }}/// The words a `notices` part says when nothing overrides them — the backup/// and sync lines' (`default_of`), read by the engines that word a notice/// (`records::backup`, `rules::sync_state`) whether or not a board names the/// part: Cotton's Home names none (owner, 2 Nov 2026), and the engines stay.pub fn notice_words() -> Map<String, Value> {    BoardPart { kind: "notices".into(), settings: Map::new() }.resolved("notices", &mut Vec::new()).settings}const VARIANT_SIZES: &[&str] = &["large", "widest", "mac"];impl BoardDefinition {    pub fn from_json(json: &str) -> Result<BoardDefinition, DefinitionError> {        serde_json::from_str(json).map_err(|error| DefinitionError::Parse(error.to_string()))    }    /// Every built-in board, in declaration order. A file that does not parse    /// is a build defect the guard test names; here it is a panic.    pub fn builtins() -> Vec<BoardDefinition> {        BUILTIN_BOARD_FILES            .iter()            .map(|(id, json)| {                let file = format!("boards/{id}.json");                serde_json::from_str::<Value>(json)                    .map_err(|error| DefinitionError::Parse(error.to_string()))                    .and_then(|raw| super::format::check_file(&file, &raw))                    .and_then(|_| BoardDefinition::from_json(json))                    .unwrap_or_else(|error| panic!("built-in board {file}: {error}"))            })            .collect()    }    /// The shipped default for `id`, if this build ships one.    pub fn builtin(id: &str) -> Option<BoardDefinition> {        Self::builtins().into_iter().find(|board| board.id == id)    }    /// This board with every part — of every size's list — resolved    /// ([`BoardPart::resolved`]), naming every setting that fell back in    /// `fallbacks`: what the catalogue hands the app.    pub fn resolved(&self) -> BoardDefinition {        let mut board = self.clone();        let mut fallbacks = Vec::new();        board.unknown.remove("fallbacks");        board.parts = board.parts.iter().enumerate().map(|(index, part)| part.resolved(&format!("parts.{index}"), &mut fallbacks)).collect();        for (at, variant) in board.variants.iter_mut().enumerate() {            variant.parts = variant                .parts                .iter()                .enumerate()                .map(|(index, part)| part.resolved(&format!("variants.{at}.parts.{index}"), &mut fallbacks))                .collect();        }        board.fallbacks = fallbacks;        board    }    /// The row is well formed: a valid id, and every setting this build    /// knows holds what it must. Unknown kinds and settings pass — a newer    /// build's row is relayed and drawn in part, never refused.    pub fn validate(&self) -> Result<(), DefinitionError> {        if !is_valid_id(&self.id) {            return Err(DefinitionError::BadId(self.id.clone()));        }        if self.parts.is_empty() {            return Err(DefinitionError::Empty("parts"));        }        let lists = std::iter::once(("parts".to_string(), &self.parts)).chain(            self.variants                .iter()                .enumerate()                .map(|(index, variant)| (format!("variants.{index}.parts"), &variant.parts)),        );        for (at, parts) in lists {            let mut ids = std::collections::BTreeSet::new();            let mut counts = std::collections::BTreeMap::new();            for part in parts {                let count = counts.entry(&part.kind).or_insert(0); *count += 1;                let id = match part.settings.get("id") {                    Some(Value::String(id)) if is_valid_id(id) => id.clone(),                    Some(_) => return Err(DefinitionError::BadSlot { slot: format!("{at}.id"), why: refusal_words("a_part_id_is_a_lowercase_identifier") }),                    None if *count == 1 => part.kind.clone(),                    None => format!("{}#{count}", part.kind),                };                if !ids.insert(id) {                    return Err(DefinitionError::BadSlot { slot: format!("{at}.id"), why: refusal_words("part_ids_must_be_unique_in_their") });                }            }            for (index, part) in parts.iter().enumerate() {                validate_part(&format!("{at}.{index}"), part, false)?;            }        }        Ok(())    }    /// An AUTHORED board: well formed, and naming only the kinds, settings,    /// values and sizes this build draws.    pub fn strict(raw: &Value) -> Result<BoardDefinition, DefinitionError> {        super::format::check_authored(&format!("boards/{}.json", raw["id"].as_str().unwrap_or("board")), raw)?;        let board: BoardDefinition = serde_json::from_value(raw.clone())            .map_err(|error| DefinitionError::Parse(error.to_string()))?;        board.validate()?;        if !board.unknown.is_empty() {            return Err(DefinitionError::UnknownKeys(board.unknown.keys().cloned().collect()));        }        for (index, part) in board.parts.iter().enumerate() {            validate_part(&format!("parts.{index}"), part, true)?;        }        for (index, variant) in board.variants.iter().enumerate() {            let at = format!("variants.{index}");            let mut unknown: Vec<String> =                variant.when.keys().filter(|key| *key != "size").map(|key| format!("{at}.when.{key}")).collect();            match variant.when.get("size").and_then(Value::as_str) {                Some(size) if VARIANT_SIZES.contains(&size) => {}                _ => unknown.push(format!("{at}.when.size")),            }            if !unknown.is_empty() {                return Err(DefinitionError::UnknownKeys(unknown));            }            for (part_index, part) in variant.parts.iter().enumerate() {                validate_part(&format!("{at}.parts.{part_index}"), part, true)?;            }        }        Ok(board)    }}fn validate_part(at: &str, part: &BoardPart, strict: bool) -> Result<(), DefinitionError> {    let bad = |key: &str, why: &str| DefinitionError::BadSlot {        slot: format!("{at}.{key}"),        why: why.to_string(),    };    if !is_valid_id(&part.kind) {        return Err(bad("kind", &refusal_words("a_part_s_kind_is_a_lowercase")));    }    if let Some(at_index) = REMOVED_BOARD_PARTS.iter().position(|(kind, _)| *kind == part.kind) {        // Said once per process: a removed part is refused on every read.        static WHY: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();        let why = WHY.get_or_init(|| REMOVED_BOARD_PARTS.iter().map(|(_, piece)| refusal_words(piece)).collect());        return Err(DefinitionError::RemovedPart { slot: at.to_string(), kind: REMOVED_BOARD_PARTS[at_index].0, why: why[at_index].as_str() });    }    let Some(known) = settings_of(&part.kind) else {        return if strict {            Err(DefinitionError::UnknownKeys(vec![format!("{at}.kind {}", part.kind)]))        } else {            Ok(())        };    };    for (key, setting, required) in known {        let Some(value) = part.settings.get(*key).filter(|value| !value.is_null()) else {            if *required {                return Err(bad(key, "is required"));            }            continue;        };        let holds = match setting {            Setting::Strings => value                .as_array()                .is_some_and(|items| items.iter().all(Value::is_string)),            Setting::Id => value.as_str().is_some_and(is_valid_id),            Setting::Words => value.as_str().is_some_and(|words| !words.trim().is_empty()),            Setting::Count => value.as_u64().is_some_and(|count| count >= 1),            Setting::Rows => value.as_array().is_some_and(|rows| {                let mut ids = std::collections::BTreeSet::new();                rows.iter().all(|row| {                    row["id"].as_str().is_some_and(|id| !id.trim().is_empty() && ids.insert(id))                        && row["data"].is_object()                        // What the row needs to be listed (`needs`): one word.                        && row.get("needs").is_none_or(|need| need.as_str().is_some_and(is_valid_id))                })            }),            // A value outside the known set is a newer build's: well formed            // as long as it is a word, refused only when authored here.            Setting::OneOf(values) => match value.as_str() {                Some(word) if values.contains(&word) => true,                Some(word) => !strict && is_valid_id(word),                None => false,            },            Setting::Where => value.as_object().is_some_and(|columns| !columns.is_empty()),            Setting::SomeOf(values) => value.as_array().is_some_and(|items| {                items.iter().all(|item| match item.as_str() {                    Some(word) => values.contains(&word) || (!strict && !word.trim().is_empty()),                    None => false,                })            }),        };        if !holds {            let why = match setting {                Setting::OneOf(values) => said("must_be_one_of", &[("values", &values.join(", "))]),                _ => refusal_words("holds_the_wrong_kind_of_value"),            };            return Err(bad(key, &why));        }    }    if strict {        let unknown: Vec<String> = part            .settings            .keys()            .filter(|key| key.as_str() != "id" && !known.iter().any(|(known, _, _)| known == key))            .map(|key| format!("{at}.{key}"))            .collect();        if !unknown.is_empty() {            return Err(DefinitionError::UnknownKeys(unknown));        }    }    Ok(())}#[cfg(test)]#[path = "board_tests.rs"]mod tests;