Cotton code
880 lines · 43.0 KB · RustRaw
//! Boards and themes — the presentation kinds beside table and tool//! definitions (design note 26203e21 §4, §6, §7, §8): the ONE read of which//! board a screen draws and which theme a database wears. No start writes//! one (72nd amendment); creation writes the SHELL once ([`write_shell`])://! Home's board, the paper and plain themes and the cap — not a tool.//!//! The read never leaves a screen blank. A row that does not decode or//! lacks a required capability is drawn as this//! build's default, with the reason handed back for the app to say once in//! Feedback; a row a person wrote (`builtin = 0`) overrides the default.use cotton_core::definitions::board::{overlay as board_overlay, BoardDefinition, BUILTIN_BOARD_FILES};use cotton_core::definitions::theme::{ThemeDefinition, BUILTIN_THEME_FILES, DEFAULT_THEME};use cotton_core::definitions::{DefinitionError, BUILTIN_DEFINITIONS_HASH, BUILTIN_DEFINITIONS_STAMP};use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{insert_row, now_iso, update_row};use crate::mcp::protocol::ToolFailure;/// The synced table the boards live in.pub const BOARD_DEFINITIONS: &str = "cotton_board_definitions";/// The synced table the themes live in.pub const THEME_DEFINITIONS: &str = "cotton_theme_definitions";/// A stored row as every read answers it: `base_hash` is the upgrade's/// bookkeeping, never something a screen draws or an assistant writes back.fn without_bookkeeping(text: &str) -> String {    match serde_json::from_str::<Value>(text) {        Ok(Value::Object(mut object)) if object.contains_key("base_hash") => {            object.remove("base_hash");            Value::Object(object).to_string()        }        _ => text.to_string(),    }}/// Where a drawn board or theme came from.#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]#[serde(rename_all = "lowercase")]pub enum Drawn {    /// A row a person wrote in this database.    Row,    /// This build's shipped default.    Default,}/// What a screen or a database draws, as the JSON the app decodes.#[derive(Debug, Clone, PartialEq, serde::Serialize)]pub struct Resolved {    pub definition: Value,    pub drawn: Drawn,    /// Why a row stored here was not drawn, for the app to say once in    /// Feedback; absent when nothing was passed over.    #[serde(skip_serializing_if = "Option::is_none")]    pub passed_over: Option<String>,}struct StoredRow {    id: String,    definition: String,    builtin: bool,}fn stored_rows(db: &Driver, table: &str, workspace: &str, id: Option<&str>) -> Result<Vec<StoredRow>, String> {    let (filter, mut values) = (if id.is_some() { " AND id = ?" } else { " AND builtin = 0" }, vec![SqlValue::Text(workspace.into())]);    if let Some(id) = id {        values.push(SqlValue::Text(id.into()));    }    let rows = db        .all(            &format!(                "SELECT id, definition, builtin FROM {table} WHERE workspace_id = ?{filter} \                 ORDER BY updated_at DESC, id"            ),            &values,        )        .map_err(|error| error.to_string())?;    Ok(rows        .iter()        .map(|row| StoredRow {            id: row.text("id").unwrap_or_default().to_string(),            definition: without_bookkeeping(row.text("definition").unwrap_or_default()),            builtin: row.int("builtin") == Some(1),        })        .collect())}/// Read one stored row tolerantly: its JSON when this build can draw it,/// otherwise why not.fn drawable<T>(row: &StoredRow, decode: impl Fn(&Value) -> Result<T, DefinitionError>) -> Result<Value, String> {    let raw: Value = serde_json::from_str(&row.definition).map_err(|error| error.to_string())?;    decode(&raw).map_err(|error| error.to_string())?;    if raw.get("id").and_then(Value::as_str) != Some(row.id.as_str()) {        return Err("it names another id".into());    }    Ok(raw)}fn resolve_board_row(raw: &Value) -> Value {    match raw["id"].as_str().and_then(|id| base_board(id)) {        Some(base) => board_overlay::resolve(raw, &base),        None => raw.clone(),    }}fn decode_board(raw: &Value) -> Result<BoardDefinition, DefinitionError> {    let board: BoardDefinition =        serde_json::from_value(raw.clone()).map_err(|error| DefinitionError::Parse(error.to_string()))?;    board.validate()?;    Ok(board)}fn decode_theme(raw: &Value) -> Result<ThemeDefinition, DefinitionError> {    let theme = ThemeDefinition::from_json(&raw.to_string())?;    theme.validate()?;    Ok(theme)}/// The board a screen falls back to and a person's board lays itself over:/// this build's shipped one — except Home in a business app, whose manifest/// names its own (`declare_home`).fn base_board(id: &str) -> Option<Value> {    if id == HOME_BOARD {        if let Some(home) = DECLARED_HOME.get() {            return Some(home.clone());        }    }    shipped(BUILTIN_BOARD_FILES, id)}const HOME_BOARD: &str = "home";/// What this app's Settings rows may need (a settings board row's `needs`):/// the facts the app's manifest gives, held for the process at open. Every/// need is met unless the manifest says otherwise, so a manifest that never/// speaks of it — Cotton's — shows every row.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct SettingsReach {    /// More than one database, ever (the Databases row).    pub several_databases: bool,    /// A serving Mac (a row that `needs` `serving`): the process's own fact,    /// `cotton_core::flavor::serving()`, read where the reach is read.    pub serving: bool,    /// A personal object the app backs up to (the Backup and Cotton server    /// rows): a personal app whose manifest names a server — Cotton, not    /// Rigby, whose kit simply lists no such rows (owner, 1 Nov 2026).    pub personal_object: bool,}impl SettingsReach {    pub const EVERY: Self = Self { several_databases: true, serving: true, personal_object: true };    /// THE ONE PLACE a manifest says what the Settings rows may need    /// (architect, 22 Oct 2026: one meaning per key). `"databases": "only"`    /// holds exactly one database ever — no new, no join, no Databases    /// screen (Rigby); `single` only SHOWS one at a time and meets the need.    /// A personal object is a manifest whose genesis is personal (absent is    /// personal) naming a server (`business.server`), as the app reads it    /// (`FlavourManifest.personalObject`).    pub fn of(manifest: &Value) -> Self {        let only = manifest.get("databases").and_then(Value::as_str) == Some("only");        let personal = manifest.get("genesis").and_then(Value::as_str).is_none_or(|genesis| genesis == "personal");        let served = manifest.get("business").and_then(|business| business.get("server")).is_some_and(|server| !server.is_null());        Self { several_databases: !only, personal_object: personal && served, ..Self::EVERY }    }    /// Whether a row needing `need` shows. A need this build does not know is    /// a newer build's: the row shows.    pub fn meets(self, need: &str) -> bool {        match need {            "several_databases" => self.several_databases,            "serving" => self.serving,            "personal_object" => self.personal_object,            _ => true,        }    }}static DECLARED_REACH: std::sync::RwLock<SettingsReach> = std::sync::RwLock::new(SettingsReach::EVERY);/// The app's manifest's reach, held for the process: each open declares it/// (none, every need met).pub fn declare_settings_reach(reach: SettingsReach) {    *DECLARED_REACH.write().unwrap_or_else(std::sync::PoisonError::into_inner) = reach;}pub fn settings_reach() -> SettingsReach {    let declared = *DECLARED_REACH.read().unwrap_or_else(std::sync::PoisonError::into_inner);    SettingsReach { serving: cotton_core::flavor::serving(), ..declared }}static DECLARED_HOME: std::sync::OnceLock<Value> = std::sync::OnceLock::new();/// A business app's Home (owner, 19 Oct 2026: the root page is Home in every/// flavour, drawn from the manifest's home definition): the board its/// manifest's `home` names, held for the process in place of this build's/// shipped Home — the board every database's Home falls back to and every/// person's Home lays itself over. Held to exactly what this build draws/// (`BoardDefinition::strict`) and to the id `home`; a second, different/// declaration is refused, as a flavour's is.pub fn declare_home(raw: &Value) -> Result<(), String> {    let board = BoardDefinition::strict(raw).map_err(|error| format!("the manifest's home definition is not a board this build draws: {error}"))?;    if board.id != HOME_BOARD {        return Err(format!("the manifest's home definition names the board {:?}; it must be {HOME_BOARD:?}", board.id));    }    if board.parts.is_empty() {        return Err("the manifest's home definition draws no sections".into());    }    // Home's tile prints the board's picture where no face is chosen, and a    // business app has no "you": without one its Home tile is a blank square.    if board.picture.is_none() {        return Err("the manifest's home definition names no picture for Home's tile".into());    }    if DECLARED_HOME.get_or_init(|| raw.clone()) != raw {        return Err("this process already holds a different home definition".into());    }    Ok(())}fn shipped(files: &[(&str, &str)], id: &str) -> Option<Value> {    files        .iter()        .find(|(file, _)| *file == id)        .map(|(_, json)| serde_json::from_str(json).expect("a built-in presentation file parses"))}/// The shell a new database is created with (architect, 21 Oct 2026: the/// shell is not a tool): Home's board — a business app's own Home where its/// manifest declares one ([`declare_home`]), else the kit's — the paper and/// plain themes from `kits/shell/`, and the cap its id assigns. Written once,/// through ordinary signed receipts, into a file whose workspace row is/// seeded; no tool, table or toolkit row./// The shell's tables, `kits/shell/tables/`: the Bin every delete goes to, the/// two its board and theme rows are drawn through, and the serving Mac's daily/// copies (`backup`, drawn by Settings and This Mac), the shell's words/// (`lines`), and the devices that hold the database (`device`: pairing,/// approval, removal and sync exist in every database from creation, like the/// Bin, and are never installed by hand), and the sync engine's two (`copy`:/// each device holding the database, which Home's sync line, the Mac-away/// line and the Databases screen read; `schema_move`: what Home's move line/// opens), and the Settings list (`settings`: the settings board's rows, the/// one way in to This device, About, Classic lists and Debug; Rigby build 4/// found it undefined in every new database), and the face each table wears/// (`face_settings`: every deck reads it on open; a Cotton started on the/// phone found it undefined, 1 Nov 2026), and the person's voice settings/// (`voice_settings`: voice.plan reads it before every dictation) — the shell/// kit's own tables (kits/shell/kit.json); written at creation and carried/// into existing ones.pub const SHELL_TABLES: [&str; 12] =    ["bin", "board", "theme", "backup", "lines", "device", "copy", "schema_move", "settings", "everything", "face_settings", "voice_settings"];pub fn write_shell(    db: &Driver,    now: chrono::DateTime<chrono::Utc>,    random: std::sync::Arc<dyn crate::random::Random>,    held: cotton_store::mint::Held,) -> Result<(), ToolFailure> {    write_shell_with(db, now, random, held, true)}/// [`write_shell`] for a device's copy (TRIM, 21 Nov 2026): no shell line is/// written as a row. A copy says the kit's words for every line it holds no/// row of (`shell_lines::resolved` lays rows over the kit), so a row that/// only repeats the kit's words is 6,116 rows and their receipts of nothing,/// in every app's copy, and one an earlier build wrote keeps that build's/// words over a later build's. A row is a rewording: it comes from the/// object, or from the person's own edit.pub fn write_shell_for_a_copy(    db: &Driver,    now: chrono::DateTime<chrono::Utc>,    random: std::sync::Arc<dyn crate::random::Random>,    held: cotton_store::mint::Held,) -> Result<(), ToolFailure> {    write_shell_with(db, now, random, held, false)}fn write_shell_with(    db: &Driver,    now: chrono::DateTime<chrono::Utc>,    random: std::sync::Arc<dyn crate::random::Random>,    held: cotton_store::mint::Held,    lines: bool,) -> Result<(), ToolFailure> {    let fail = |error: cotton_store::StoreError| ToolFailure::new(error.to_string());    let file = cotton_store::file_identity::read_file_identity(db)        .map_err(fail)?        .ok_or_else(|| ToolFailure::new("the new database has no identity yet"))?;    let owner = db        .get("SELECT owner_id FROM _meta", &[])        .map_err(fail)?        .and_then(|row| row.text("owner_id").map(str::to_string))        .unwrap_or_default();    let services = crate::mcp::dispatch::ToolServices::none();    let audit = |_: &str, _: &str| {};    let actor = cotton_store::mint::Actor::DeviceJob(cotton_store::mint::JobName::named("shell").map_err(fail)?);    let mut ctx = Ctx::for_worker(db, &file, &owner, actor, "shell", now, random, &services, &audit).held_as(held);    let home = base_board(HOME_BOARD).ok_or_else(|| ToolFailure::new("the kit's shell has no Home board"))?;    // The shell's tables first, so its board and themes are drawn and written.    let mut rows = Vec::new();    for id in SHELL_TABLES {        let (definition, builtin) = shell_table(id);        rows.push((crate::definitions::TABLE_DEFINITIONS, id, definition, builtin));    }    rows.push((BOARD_DEFINITIONS, HOME_BOARD, home, true));    for (id, _) in BUILTIN_THEME_FILES {        rows.push((THEME_DEFINITIONS, id, shipped(BUILTIN_THEME_FILES, id).expect("a shell theme parses"), true));    }    for (table, id, definition, builtin) in rows {        insert_row(&mut ctx, table, id, shell_row(id, definition, builtin))?;    }    let workspace = ctx.workspace_id.to_string();    let caps = cotton_core::records::page::assign_caps(std::slice::from_ref(&workspace));    set_cap_colour(&mut ctx, caps.get(&workspace).copied())?;    ctx.commit()?;    if !lines {        return Ok(());    }    write_lines(&mut ctx)}/// The definition the shell kit ships for its table `id`, and whether it is/// a built-in this build compiles: a built-in is written with the build's/// hash and stamp; a plain kit table (`face_settings`) is written as data, as/// the object serves it.pub fn shell_table(id: &str) -> (Value, bool) {    let (_, file) = cotton_core::kit::shell::SHELL_KIT_TABLES        .iter()        .find(|(table, _)| *table == id)        .expect("the shell's table is in its kit");    let builtin = cotton_core::definitions::BUILTIN_DEFINITION_FILES.iter().any(|(table, _)| *table == id);    (serde_json::from_str(file).expect("a shell table parses"), builtin)}/// A shell definition row: a built-in carries the build's hash and stamp, a/// plain kit table its definition alone.fn shell_row(id: &str, definition: Value, builtin: bool) -> Map<String, Value> {    let mut patch = Map::new();    patch.insert("id".into(), Value::from(id));    patch.insert("definition".into(), definition);    if builtin {        patch.insert("builtin".into(), Value::Bool(true));        patch.insert("builtin_hash".into(), Value::from(BUILTIN_DEFINITIONS_HASH));        patch.insert("builtin_stamp".into(), Value::from(BUILTIN_DEFINITIONS_STAMP));    }    patch}/// Carry the shell's add-only tables and rows into a database made before/// them (architect, 21 Oct 2026: the Mac's pass at start, so the owner's/// Personal gets `backup` and the sync lines with no hand step): each of/// [`SHELL_TABLES`] the file has no definition row for is written as this/// build ships it, then every shell line it has no row for. ADD-ONLY: a row/// already here — the owner's overlay, a rewording — is never written over./// Answers the tables it wrote.pub fn carry_shell(ctx: &mut Ctx<'_>) -> Result<Vec<&'static str>, ToolFailure> {    let fail = |error: cotton_store::StoreError| ToolFailure::new(error.to_string());    let mut wrote = Vec::new();    for id in SHELL_TABLES {        let held = ctx            .read            .driver()            .get(&format!("SELECT 1 AS here FROM {} WHERE id = ?", crate::definitions::TABLE_DEFINITIONS), &[SqlValue::Text(id.into())])            .map_err(fail)?            .is_some();        if held {            continue;        }        let (definition, builtin) = shell_table(id);        insert_row(ctx, crate::definitions::TABLE_DEFINITIONS, id, shell_row(id, definition, builtin))?;        wrote.push(id);    }    ctx.commit()?;    write_lines(ctx)?;    Ok(wrote)}/// The rows of the `lines` shell table (`rules::shell_lines`), stored in/// `cotton_lines`, the table its definition derives.pub const LINES: &str = "cotton_lines";/// Write every shell line this database has no row for — the rows a new/// database is made with, and the ones a later build adds. ADD-ONLY: a row/// already here (a person's rewording) is never written over.pub fn write_lines(ctx: &mut Ctx<'_>) -> Result<(), ToolFailure> {    let fail = |error: cotton_store::StoreError| ToolFailure::new(error.to_string());    // The definition row is committed; the file steps to the table it derives.    let _span = cotton_store::spans::span("presentation::write_lines");    let (_, refused) = cotton_store::schema::package_shape::step_file(ctx.read.driver()).map_err(fail)?;    if let Some((_, why)) = refused.iter().find(|(id, _)| id == cotton_core::rules::shell_lines::TABLE) {        return Err(ToolFailure::new(format!("the shell's lines cannot take their table: {why}")));    }    let held: std::collections::BTreeSet<String> = ctx        .read        .driver()        .all(&format!("SELECT id FROM {LINES} WHERE workspace_id = ?"), &[SqlValue::Text(ctx.workspace_id.to_string())])        .map_err(fail)?        .iter()        .filter_map(|row| row.text("id").map(str::to_string))        .collect();    let stamp = now_iso(ctx);    for row in cotton_core::rules::shell_lines::shipped_lines() {        let id = row.id();        if held.contains(&id) {            continue;        }        let mut patch = Map::new();        patch.insert("id".into(), Value::from(id.clone()));        patch.insert("set".into(), Value::from(row.set.as_str()));        patch.insert("line".into(), Value::from(row.line.as_str()));        patch.insert("words".into(), Value::from(row.words.as_str()));        patch.insert("created_at".into(), Value::from(stamp.clone()));        patch.insert("updated_at".into(), Value::from(stamp.clone()));        insert_row(ctx, LINES, &id, patch)?;    }    // Every line as one batch of rows: the same receipts, each its own, with    // the file's shape read once for the 3,727 of them.    let _commit = cotton_store::spans::span("presentation::write_lines commit");    ctx.commit_batch()}/// The shell lines this database holds; empty when it has none (a database/// made before its lines were written), so the kit's words are said.pub fn line_rows(db: &Driver, workspace: &str) -> Vec<cotton_core::rules::shell_lines::LineRow> {    let held = db        .get("SELECT 1 AS here FROM sqlite_master WHERE type = 'table' AND name = ?", &[SqlValue::Text(LINES.into())])        .ok()        .flatten()        .is_some();    if !held {        return Vec::new();    }    db.all(        &format!("SELECT \"set\", line, words FROM {LINES} WHERE workspace_id = ? AND deleted_at IS NULL"),        &[SqlValue::Text(workspace.into())],    )    .unwrap_or_default()    .iter()    .filter_map(|row| {        Some(cotton_core::rules::shell_lines::LineRow {            set: row.text("set")?.into(),            line: row.text("line")?.into(),            words: row.text("words")?.into(),        })    })    .collect()}/// The id of the theme row a database writes for itself when it has none of/// its own yet: with no `family`, it wears `paper` with what it names laid over.pub const OWN_THEME: &str = "database";/// The cap enamel the database's theme names; `None` leaves it to the one the/// database's id assigns.pub fn cap_colour(db: &Driver, workspace: &str) -> Result<Option<String>, String> {    Ok(theme(db, workspace)?.definition["cap"]["colour"].as_str().map(str::to_string))}/// Set or clear the cap enamel on the theme the database wears — its own/// row, made at [`OWN_THEME`] when it has none — and answer the one before./// The cap's colour is the theme's (design note 26203e21 §6): the database/// page's recolour writes it here and nowhere else.pub fn set_cap_colour(ctx: &mut Ctx<'_>, colour: Option<&str>) -> Result<Option<String>, ToolFailure> {    let failure = |error: String| ToolFailure::new(error);    let worn = theme(ctx.read.driver(), ctx.workspace_id).map_err(failure)?;    let before = worn.definition["cap"]["colour"].as_str().map(str::to_string);    let (id, mut definition, exists) = if worn.drawn == Drawn::Row {        let raw = theme_overrides(ctx.read.driver(), ctx.workspace_id).map_err(failure)?.expect("the worn theme has a raw row");        let id = raw["id"].as_str().unwrap_or(OWN_THEME).to_string();        (id, raw, true)    } else {        let stored = stored_rows(ctx.read.driver(), THEME_DEFINITIONS, ctx.workspace_id, Some(OWN_THEME)).map_err(failure)?;        let kept = stored            .first()            .and_then(|row| serde_json::from_str::<Value>(&row.definition).ok())            .filter(Value::is_object);        (OWN_THEME.to_string(), kept.unwrap_or_else(|| serde_json::json!({ "id": OWN_THEME })), !stored.is_empty())    };    if !definition["cap"].is_object() {        definition["cap"] = Value::Object(Map::new());    }    let cap = definition["cap"].as_object_mut().expect("an object");    match colour {        Some(colour) => {            cap.insert("colour".into(), Value::from(colour));        }        None => {            cap.remove("colour");        }    }    let mut patch = Map::new();    patch.insert("id".into(), Value::from(id.clone()));    patch.insert("definition".into(), definition);    patch.insert("builtin".into(), Value::Bool(false));    if exists {        patch.insert("updated_at".into(), Value::from(now_iso(ctx)));        update_row(ctx, THEME_DEFINITIONS, &id, patch)?;    } else {        insert_row(ctx, THEME_DEFINITIONS, &id, patch)?;    }    Ok(before)}/// The screens that draw a board, by board id — the shipped defaults' ids./// A board for any other id would be drawn by no screen.pub fn board_ids() -> impl Iterator<Item = &'static str> {    BUILTIN_BOARD_FILES.iter().map(|(id, _)| *id)}/// Write a person's board for a screen (`builtin = 0`): AUTHORED, so held to/// exactly the parts, settings and values this build draws/// (`BoardDefinition::strict`), and only for a screen that draws one/// (`board_ids`) — a row for any other id would sync to every device and be/// drawn by none. Answers the person's board it replaced, if the screen had/// one — `None` means it drew the default.pub fn save_board(ctx: &mut Ctx<'_>, raw: &Value) -> Result<Option<Value>, ToolFailure> {    let board = BoardDefinition::strict(raw).map_err(|error| ToolFailure::new(format!("That board cannot be saved: {error}")))?;    if !board_ids().any(|id| id == board.id) {        return Err(ToolFailure::new(format!(            "There is no board {:?}: the screens that draw one are {}.",            board.id,            board_ids().collect::<Vec<_>>().join(", ")        )));    }    validate_board_sources(ctx, &board)?;    write_board(ctx, raw, &board)}/// A list or facts part must name a table the database can actually read.fn validate_board_sources(ctx: &Ctx<'_>, board: &BoardDefinition) -> Result<(), ToolFailure> {    let definitions = crate::definitions::table_definitions(ctx)?.definitions;    for part in board.parts.iter().chain(board.variants.iter().flat_map(|variant| &variant.parts)) {        let key = match part.kind.as_str() { "list" => "table", "facts" => "source", _ => continue };        let source = part.settings[key].as_str().expect("strict board validates source ids");        if !definitions.iter().any(|definition| definition.id == source) {            return Err(ToolFailure::new(format!("That board cannot be saved: {}.{key} names {source:?}, which no table definition names", part.kind)));        }    }    Ok(())}/// Read the whole board that this database draws, including the core's defaults.pub fn get_board_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> crate::mcp::dispatch::ToolResult {    let id = args.get("id").and_then(Value::as_str).ok_or_else(|| ToolFailure::new("id is required"))?;    let resolved = board(ctx.db(), ctx.workspace_id, id).map_err(ToolFailure::new)?        .ok_or_else(|| ToolFailure::new(format!("There is no board {id:?}")))?;    let definition = decode_board(&resolved.definition).map_err(|why| ToolFailure::new(why.to_string()))?.resolved();    Ok(serde_json::json!({"id":id,"definition":definition,"default":resolved.drawn == Drawn::Default,"passed_over":resolved.passed_over}))}/// Preview and save use the same validation; the record writer owns history.pub fn update_board_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> crate::mcp::dispatch::ToolResult {    let id = args.get("id").and_then(Value::as_str).ok_or_else(|| ToolFailure::new("id is required"))?;    let raw = args.get("definition").filter(|value| value.is_object()).ok_or_else(|| ToolFailure::new("definition must be a whole board object"))?;    let board = BoardDefinition::strict(raw).map_err(|why| ToolFailure::new(format!("That board cannot be saved: {why}")))?;    if board.id != id { return Err(ToolFailure::new("The board definition must name the same id")); }    if !board_ids().any(|known| known == id) { return Err(ToolFailure::new(format!("There is no board {id:?}"))); }    validate_board_sources(ctx, &board)?;    if args.get("dry_run").and_then(Value::as_bool) == Some(true) {        let before = self::board(ctx.db(), ctx.workspace_id, id).map_err(ToolFailure::new)?.expect("shipped board").definition;        let keys: std::collections::BTreeSet<_> = before.as_object().into_iter().flatten().map(|(key, _)| key)            .chain(raw.as_object().into_iter().flatten().map(|(key, _)| key)).collect();        let changes: Vec<Value> = keys.into_iter().filter(|key| before.get(*key) != raw.get(*key))            .map(|key| serde_json::json!({"key":key,"old":before.get(key),"new":raw.get(key)})).collect();        return Ok(serde_json::json!({"id":id,"dry_run":true,"valid":true,"changes":changes}));    }    crate::mcp::handlers::tables::update_record(ctx, serde_json::json!({"table":"board","id":id,"patch":{"definition":raw.to_string()}}).as_object().expect("object"))}/// A package carries only its own board, atomically with its definitions.pub(crate) fn install_tool_board(ctx: &mut Ctx<'_>, tool: &str, board: &BoardDefinition) -> Result<(), ToolFailure> {    if board.id != tool { return Err(ToolFailure::new("package board names another tool")); }    let raw = serde_json::to_value(board).map_err(|why| ToolFailure::new(why.to_string()))?;    let board = BoardDefinition::strict(&raw).map_err(|why| ToolFailure::new(why.to_string()))?;    write_board(ctx, &raw, &board).map(|_| ())}fn write_board(ctx: &mut Ctx<'_>, raw: &Value, board: &BoardDefinition) -> Result<Option<Value>, ToolFailure> {    let stored = stored_rows(ctx.read.driver(), BOARD_DEFINITIONS, ctx.workspace_id, Some(&board.id)).map_err(ToolFailure::new)?;    let before = stored        .first()        .filter(|row| !row.builtin)        .and_then(|row| serde_json::from_str::<Value>(&row.definition).ok())        .map(|raw| resolve_board_row(&raw));    let mut patch = Map::new();    patch.insert("id".into(), Value::from(board.id.clone()));    let definition = match base_board(&board.id) {        Some(base) => {            let previous = stored.first().and_then(|row| serde_json::from_str::<Value>(&row.definition).ok()).unwrap_or(Value::Null);            board_overlay::difference_preserving(raw, &base, &previous)        },        None => raw.clone(), // A package board has no shipped base.    };    patch.insert("definition".into(), definition.clone());    patch.insert("builtin".into(), Value::Bool(false));    patch.insert("builtin_hash".into(), Value::Null);    // On a person's row, the build that wrote it: an older build's upgrade    // leaves it as it came.    patch.insert("builtin_stamp".into(), Value::from(BUILTIN_DEFINITIONS_STAMP));    if stored.is_empty() {        insert_row(ctx, BOARD_DEFINITIONS, &board.id, patch)?;    } else {        patch.insert("updated_at".into(), Value::from(now_iso(ctx)));        update_row(ctx, BOARD_DEFINITIONS, &board.id, patch)?;    }    Ok(before)}/// Put a screen back on this build's default board: the row becomes the/// shipped default again (`builtin = 1`), so a later build's seed moves it/// on as it does every default. Answers the person's board it replaced.pub fn reset_board(ctx: &mut Ctx<'_>, id: &str) -> Result<Option<Value>, ToolFailure> {    let Some(default) = base_board(id) else {        return Err(ToolFailure::new(format!("There is no board {id:?} to put back.")));    };    let stored = stored_rows(ctx.read.driver(), BOARD_DEFINITIONS, ctx.workspace_id, Some(id)).map_err(ToolFailure::new)?;    let before = stored        .first()        .filter(|row| !row.builtin)        .and_then(|row| serde_json::from_str::<Value>(&row.definition).ok())        .map(|raw| resolve_board_row(&raw));    let mut patch = Map::new();    patch.insert("id".into(), Value::from(id));    patch.insert("definition".into(), default);    patch.insert("builtin".into(), Value::Bool(true));    patch.insert("builtin_hash".into(), Value::from(BUILTIN_DEFINITIONS_HASH));    patch.insert("builtin_stamp".into(), Value::from(BUILTIN_DEFINITIONS_STAMP));    if stored.is_empty() {        insert_row(ctx, BOARD_DEFINITIONS, id, patch)?;    } else {        patch.insert("updated_at".into(), Value::from(now_iso(ctx)));        update_row(ctx, BOARD_DEFINITIONS, id, patch)?;    }    Ok(before)}/// The board `id` draws in this database: a person's row when it stands,/// otherwise this build's default (a stored built-in row is always drawn as/// this build's own default — what an older or newer build seeded is theirs)./// `None` only for an id with neither a row nor a default.pub fn board(db: &Driver, workspace: &str, id: &str) -> Result<Option<Resolved>, String> {    let default = base_board(id);    let mut passed_over = None;    for row in stored_rows(db, BOARD_DEFINITIONS, workspace, Some(id))? {        if row.builtin && default.is_some() {            break;        }        let resolved = serde_json::from_str::<Value>(&row.definition).map(|raw| resolve_board_row(&raw));        let row = StoredRow { id: row.id, builtin: row.builtin, definition: resolved.map(|raw| raw.to_string()).unwrap_or(row.definition) };        match drawable(&row, decode_board) {            Ok(definition) => return Ok(Some(Resolved { definition, drawn: Drawn::Row, passed_over: None })),            Err(why) => passed_over = Some(format!("the board {id:?} stored here is not drawn: {why}")),        }    }    Ok(default.map(|definition| Resolved { definition, drawn: Drawn::Default, passed_over }))}/// The themes a database can hold a row for, by id: the shipped ones and its/// own ([`OWN_THEME`], the row the cap's colour lives on). A theme row for/// any other id would be one no screen offers.pub fn theme_ids() -> impl Iterator<Item = &'static str> {    BUILTIN_THEME_FILES.iter().map(|(id, _)| *id).chain(std::iter::once(OWN_THEME))}/// What a theme id is when the database holds no row of its own for it: the/// shipped file, or — its own theme — a theme naming nothing, which wears/// `paper` exactly as no row does.fn theme_default(id: &str) -> Option<Value> {    shipped(BUILTIN_THEME_FILES, id).or_else(|| (id == OWN_THEME).then(|| serde_json::json!({ "id": OWN_THEME })))}/// One theme id as the `theme` table answers it: the same resolved overlay/// the app draws, and whether it is the theme the database wears.pub struct ThemeEntry {    pub id: &'static str,    pub definition: Value,    pub drawn: Drawn,    pub worn: bool,}/// Every theme id ([`theme_ids`]) resolved exactly as the app draws it.pub fn themes(db: &Driver, workspace: &str) -> Result<Vec<ThemeEntry>, String> {    let worn = theme(db, workspace)?;    let worn_id = match worn.drawn {        Drawn::Row => worn.definition["id"].as_str().map(str::to_string),        Drawn::Default => Some(DEFAULT_THEME.to_string()),    };    let mut entries = Vec::new();    for id in theme_ids() {        let own = stored_rows(db, THEME_DEFINITIONS, workspace, Some(id))?            .into_iter()            .find(|row| !row.builtin)            .and_then(|row| drawable(&row, decode_theme).ok());        let (raw, drawn) = match own {            Some(definition) => (definition, Drawn::Row),            None => (theme_default(id).expect("each theme has a default"), Drawn::Default),        };        let definition = decode_theme(&raw).expect("a drawable theme decoded").resolved();        entries.push(ThemeEntry { id, definition, drawn, worn: worn_id.as_deref() == Some(id) });    }    Ok(entries)}/// Write a person's theme (`builtin = 0`) — AUTHORED, so held to exactly/// what this build draws (`ThemeDefinition::strict`), and only for a theme id/// the database knows ([`theme_ids`]). The newest own row is the one worn, so/// the database wears it from the next read. Answers the person's row it/// replaced, if there was one.pub fn save_theme(ctx: &mut Ctx<'_>, raw: &Value) -> Result<Option<Value>, ToolFailure> {    let theme = validate_theme(raw)?;    if !theme_ids().any(|id| id == theme.id) {        return Err(ToolFailure::new(format!(            "There is no theme {:?}: the themes are {}.",            theme.id,            theme_ids().collect::<Vec<_>>().join(", ")        )));    }    let stored = stored_rows(ctx.read.driver(), THEME_DEFINITIONS, ctx.workspace_id, Some(&theme.id)).map_err(ToolFailure::new)?;    let before = stored        .first()        .filter(|row| !row.builtin)        .and_then(|row| serde_json::from_str::<Value>(&row.definition).ok());    let mut patch = Map::new();    patch.insert("id".into(), Value::from(theme.id.clone()));    patch.insert("definition".into(), theme.overrides());    patch.insert("builtin".into(), Value::Bool(false));    patch.insert("builtin_hash".into(), Value::Null);    patch.insert("builtin_stamp".into(), Value::from(BUILTIN_DEFINITIONS_STAMP));    if stored.is_empty() {        insert_row(ctx, THEME_DEFINITIONS, &theme.id, patch)?;    } else {        patch.insert("updated_at".into(), Value::from(now_iso(ctx)));        update_row(ctx, THEME_DEFINITIONS, &theme.id, patch)?;    }    Ok(before)}/// An authored theme, held to what this build draws and to every number's/// range in the core ([`ThemeDefinition::strict`], `THEME_SCALE_TOKENS`); a/// refusal names each key, its value and its range. Reads stay tolerant so a/// newer device's row is relayed unchanged.pub fn validate_theme(raw: &Value) -> Result<ThemeDefinition, ToolFailure> {    ThemeDefinition::strict(raw).map_err(|error| ToolFailure::new(format!("That theme cannot be saved: {error}")))}/// The preview and the write share validation and the record writer; there is/// no theme-specific history to disagree with records.undo.pub fn save_theme_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> crate::mcp::dispatch::ToolResult {    let raw = args.get("definition").filter(|raw| raw.is_object()).ok_or_else(|| ToolFailure::new("save_theme takes a theme definition object"))?;    let id = raw["id"].as_str().unwrap_or(OWN_THEME);    let mut raw = raw.clone();    raw["id"] = Value::from(id);    if args.get("dry_run").and_then(Value::as_bool) == Some(true) {        return preview_theme(ctx, &raw);    }    validate_theme(&raw)?;    crate::mcp::handlers::tables::update_record(ctx, serde_json::json!({"table":"theme","id":id,"patch":{"definition":raw.to_string()}}).as_object().expect("object"))}pub fn preview_theme(ctx: &Ctx<'_>, raw: &Value) -> Result<Value, ToolFailure> {    fn leaves(value: &Value, path: Vec<String>, out: &mut std::collections::BTreeMap<Vec<String>, Value>) {        if let Some(object) = value.as_object().filter(|object| !object.is_empty()) {            for (key, value) in object {                let mut path = path.clone(); path.push(key.clone());                leaves(value, path, out);            }        } else { out.insert(path, value.clone()); }    }    let id = raw["id"].as_str().unwrap_or(OWN_THEME);    let before = themes(ctx.read.driver(), ctx.workspace_id).map_err(ToolFailure::new)?.into_iter().find(|theme| theme.id == id).map(|theme| theme.definition).unwrap_or(Value::Null);    let mut old = std::collections::BTreeMap::new();    let mut new = std::collections::BTreeMap::new();    leaves(&before, vec![], &mut old); leaves(raw, vec![], &mut new);    // Preview the values that will be drawn, while refusals below inspect    // every authored leaf (including ones resolution would discard).    let mut drawn = std::collections::BTreeMap::new();    let candidate = validate_theme(raw).map(|theme| theme.resolved()).unwrap_or_else(|_| raw.clone());    leaves(&candidate, vec![], &mut drawn);    let keys: std::collections::BTreeSet<_> = old.keys().chain(drawn.keys()).cloned().collect();    let changes: Vec<Value> = keys.into_iter().filter(|key| old.get(key) != drawn.get(key)).map(|key| serde_json::json!({"key":key.join("."),"old":old.get(&key),"new":drawn.get(&key)})).collect();    // Every number outside its range, with its value and the range, from    // the core's one list; then whatever else each key gets wrong.    let mut refused: Vec<Value> = ThemeDefinition::out_of_range(raw).into_iter().map(|outside| serde_json::json!({        "key": outside.key, "value": outside.value, "range": outside.range, "reason": format!("That theme cannot be saved: {outside}"),    })).collect();    let ranged: Vec<String> = refused.iter().filter_map(|refusal| refusal["key"].as_str().map(str::to_string)).collect();    for (path, value) in &new {        let key = path.join(".");        if ranged.iter().any(|at| *at == key || at.starts_with(&format!("{key}."))) { continue; }        let mut candidate = serde_json::json!({"id":id});        if raw["family"].as_str().is_some_and(|family| cotton_core::definitions::theme::THEME_FAMILIES.contains(&family)) { candidate["family"] = raw["family"].clone(); }        // Validate each leaf independently so one bad key cannot hide another.        let mut at = &mut candidate;        for key in &path[..path.len().saturating_sub(1)] {            if !at[key].is_object() { at[key] = Value::Object(Map::new()); }            at = &mut at[key];        }        if let Some(key) = path.last() { at[key] = value.clone(); }        if let Err(why) = validate_theme(&candidate) { refused.push(serde_json::json!({"key":key,"value":value,"reason":why.message()})); }    }    if !theme_ids().any(|known| known == id) { refused.push(serde_json::json!({"key":"id","reason":"The theme id must be paper, plain or database"})); }    let error = validate_theme(raw).err().map(|why| why.message().to_string());    Ok(serde_json::json!({"dry_run":true,"changes":changes,"refused":refused,"valid":error.is_none() && refused.is_empty(),"error":error}))}/// The last theme edit that can still be undone: its record-history id and/// when it was made.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]pub struct ThemeChange {    pub id: String,    pub at: String,}/// The last theme edit's existing record-history row, if it can still be undone.pub fn last_theme_change(db: &Driver, workspace: &str) -> Result<Option<ThemeChange>, String> {    let row = db.get("SELECT c.id, c.created_at FROM cotton_changes c WHERE c.workspace_id = ? AND c.table_id = 'theme' AND c.verb = 'update' AND NOT EXISTS (SELECT 1 FROM cotton_undos u WHERE u.change_id = c.id) AND NOT EXISTS (SELECT 1 FROM cotton_undos u WHERE u.undo_change_id = c.id) ORDER BY c._hlc DESC, c.id DESC LIMIT 1", &[SqlValue::Text(workspace.into())]).map_err(|why| why.to_string())?;    Ok(row.and_then(|row| Some(ThemeChange {        id: row.text("id")?.to_string(),        at: row.text("created_at").unwrap_or_default().to_string(),    })))}/// Put a theme id back on its default: the row becomes the shipped file/// again (`builtin = 1`, so a later build's seed moves it on), or — the/// database's own theme — a built-in row naming nothing, so the database/// wears what it wore before it had one. Answers the person's row it/// replaced; `None` when there was none (nothing is written then).pub fn reset_theme(ctx: &mut Ctx<'_>, id: &str) -> Result<Option<Value>, ToolFailure> {    let Some(default) = theme_default(id) else {        return Err(ToolFailure::new(format!("There is no theme {id:?} to put back.")));    };    let stored = stored_rows(ctx.read.driver(), THEME_DEFINITIONS, ctx.workspace_id, Some(id)).map_err(ToolFailure::new)?;    let Some(before) = stored        .first()        .filter(|row| !row.builtin)        .map(|row| serde_json::from_str::<Value>(&row.definition).unwrap_or(Value::Null))    else {        return Ok(None);    };    let shipped_here = shipped(BUILTIN_THEME_FILES, id).is_some();    let mut patch = Map::new();    patch.insert("id".into(), Value::from(id));    patch.insert("definition".into(), default);    patch.insert("builtin".into(), Value::Bool(true));    patch.insert("builtin_stamp".into(), if shipped_here { Value::from(BUILTIN_DEFINITIONS_STAMP) } else { Value::Null });    patch.insert("builtin_hash".into(), if shipped_here { Value::from(BUILTIN_DEFINITIONS_HASH) } else { Value::Null });    patch.insert("updated_at".into(), Value::from(now_iso(ctx)));    update_row(ctx, THEME_DEFINITIONS, id, patch)?;    Ok(Some(before))}/// The newest drawable person's row, kept sparse for authoring and undo./// No row means the database wears the shipped theme.pub fn theme_overrides(db: &Driver, workspace: &str) -> Result<Option<Value>, String> {    for row in stored_rows(db, THEME_DEFINITIONS, workspace, None)? {        if let Ok(raw) = drawable(&row, decode_theme) {            return Ok(Some(raw));        }    }    Ok(None)}/// The worn theme, with missing tokens supplied by its shipped family.pub fn theme(db: &Driver, workspace: &str) -> Result<Resolved, String> {    let mut passed_over = None;    for row in stored_rows(db, THEME_DEFINITIONS, workspace, None)? {        match drawable(&row, decode_theme) {            Ok(raw) => {                let definition = decode_theme(&raw).expect("a drawable theme decoded").resolved();                return Ok(Resolved { definition, drawn: Drawn::Row, passed_over });            }            Err(why) => {                passed_over.get_or_insert(format!("the theme {:?} stored here is not drawn: {why}", row.id));            }        }    }    let definition = shipped(BUILTIN_THEME_FILES, DEFAULT_THEME).expect("the default theme ships");    Ok(Resolved { definition, drawn: Drawn::Default, passed_over })}