Cotton code
1311 lines · 60.5 KB · RustRaw
//! Tool packages write the shared synced definitions, never executable extensions.use super::common::{insert_row, update_row};use crate::mcp::writer::Retract;use crate::mcp::{    dispatch::{Ctx, HandlerGroup, ToolResult},    protocol::ToolFailure,};use base64::{engine::general_purpose::STANDARD, Engine};use cotton_core::definitions::{    builtin_table_definitions,    computed::{validate_beside, AbsentTable, Computed},    package::{decode_package, encode_package, ToolPackage},    key_as_words, Column, DefinitionError, TableDefinition, ToolContribution, ToolDefinition,};use cotton_store::driver::Driver;use cotton_store::protocol::derived_id::tool_asset_id;use cotton_store::link_rule::FileKind;use rusqlite::types::Value as SqlValue;use cotton_core::rules::source_absent;use serde_json::{json, Map, Value};use std::collections::{BTreeMap, BTreeSet};const TOOL: &str = crate::definitions::TOOL_DEFINITIONS;const TABLE: &str = crate::definitions::TABLE_DEFINITIONS;// A package's pictures are payload, not definitions: one core-table row per// picture (137), which no record verb addresses.use crate::tool_pictures::TOOL_ASSETS;fn fail(error: impl std::fmt::Display) -> ToolFailure {    ToolFailure::new(error.to_string())}fn text<'a>(args: &'a Map<String, Value>, key: &str) -> Result<&'a str, ToolFailure> {    args.get(key)        .and_then(Value::as_str)        .filter(|s| !s.is_empty())        .ok_or_else(|| fail(format!("{key} is required")))}pub fn handlers() -> HandlerGroup {    &[        ("export_tool", export_tool),        ("import_tool", import_tool),        ("list_tools", list_tools),        ("remove_tool", remove_tool),        ("add_tool", add_tool),        ("list_toolkits", list_toolkits),        ("save_toolkit", save_toolkit),        ("update_toolkit", update_toolkit),        ("delete_toolkit", delete_toolkit),    ]}/// The kits a database can be made from, as the personal database keeps them/// (`cotton_toolkits`). Each tool is summarised — a built-in by its key, a/// carried package by its tool's id, name, picture and tables — unless `id`/// names one kit, which is answered whole, packages and all.pub fn list_toolkits(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    if ctx.file_kind()? != cotton_store::link_rule::FileKind::Personal {        return Err(fail("toolkits are kept in your personal database; ask it there"));    }    let only = super::common::optional_string(args, "id");    let kits = crate::toolkits::read(ctx.db(), ctx.workspace_id).map_err(fail)?;    if let Some(id) = only {        let kit = kits            .into_iter()            .find(|kit| kit.id == id)            .ok_or_else(|| fail(format!("no toolkit {id:?}; list_toolkits names them")))?;        return Ok(json!({ "toolkit": kit }));    }    let kits: Vec<Value> = kits.iter().map(kit_summary).collect();    Ok(json!({ "toolkits": kits }))}/// One part of a stored definition this build cannot draw (architect, 20 Oct/// 2026): THAT command, view or column is left out of what the catalogue/// answers — never the whole package, never the database's list, the/// tolerance the app has for a definition (it never throws on one). `part` is/// `whole` for an entry the start's scan found unreadable altogether.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]pub struct LostPart {    pub entry: String,    #[serde(rename = "key")]    pub part: String,    pub reason: String,}/// The part a refusal names, as `(collection, key)`, when it is one command,/// view or column a reader can do without.fn part_of(error: &DefinitionError) -> Option<(String, String)> {    use DefinitionError::*;    let slot = match error {        UnknownColumn { slot, .. } | WrongColumnType { slot, .. } | RemovedPart { slot, .. }        | UnknownChoice { slot, .. } | Requires { slot, .. } | Conflict { slot, .. }        | TooSmall { slot, .. } | UnknownCommand { slot, .. } | BadSlot { slot, .. } => slot,        _ => return None,    };    let mut parts = slot.split('.');    let (collection, key) = (parts.next()?, parts.next()?);    matches!(collection, "commands" | "views" | "columns").then(|| (collection.to_string(), key.to_string()))}/// Leave `key` out of the definition's `collection`, a list of parts by id/// or key, or a map by key. Answers whether anything went.fn without_part(definition: &mut Value, collection: &str, key: &str) -> bool {    match definition.get_mut(collection) {        Some(Value::Array(items)) => {            let before = items.len();            items.retain(|item| item["id"] != key && item["key"] != key);            items.len() != before        }        Some(Value::Object(map)) => map.remove(key).is_some(),        _ => false,    }}fn validate_entry(kind: &str, definition: &Value) -> Result<(), DefinitionError> {    let parse = |error: serde_json::Error| DefinitionError::Parse(error.to_string());    if kind == TOOL {        serde_json::from_value::<ToolDefinition>(definition.clone()).map_err(parse)?.validate()    } else {        serde_json::from_value::<TableDefinition>(definition.clone()).map_err(parse)?.validate()    }}fn decode_entry(kind: &str, id: &str, raw: &str, lost: &mut Vec<LostPart>) -> Result<Value, ToolFailure> {    let mut definition: Value = serde_json::from_str(raw).map_err(fail)?;    if definition["id"].as_str() != Some(id) {        return Err(fail("stored definition names another id"));    }    // Each round leaves one part out, so it ends.    while let Err(error) = validate_entry(kind, &definition) {        match part_of(&error) {            Some((collection, name)) if without_part(&mut definition, &collection, &name) => lost.push(LostPart {                entry: format!("{kind}.{id}"),                part: format!("{collection}.{name}"),                reason: error.to_string(),            }),            _ => return Err(fail(error)),        }    }    if kind == TOOL {        let tool: ToolDefinition = serde_json::from_value(definition.clone()).map_err(fail)?;        let mut entry = cotton_core::definitions::package::Signature::of(&tool).fields();        entry.insert("definition".into(), definition);        Ok(Value::Object(entry))    } else {        Ok(json!({"definition":definition}))    }}/// Every stored entry of `kind`, each with the parts this build cannot draw/// left out and named in `lost`. An entry that is not a definition at all —/// not JSON, another id — is corruption, not a part: it refuses the read,/// unless `skip_unreadable` (the start's Feedback scan) names it in `lost`.fn catalog_entries(    db: &Driver,    workspace: &str,    kind: &str,    lost: &mut Vec<LostPart>,    skip_unreadable: bool,) -> Result<Vec<Value>, ToolFailure> {    let rows: Vec<(String, String)> = if kind == TABLE {        let shipped = builtin_table_definitions();        crate::definitions::definition_rows_from_driver(db, workspace, None)?            .into_iter()            .filter(|row| !crate::definitions::retired_builtin(row, shipped.iter().find(|table| table.id == row.id)))            .map(|row| {                // Built-ins draw as this build ships them, with the same                // owner edits as definitions.catalogue. Decoding yesterday's                // raw native definition first can drop a retired command but                // leave its acts reference, refusing the entire tool list.                let definition = if row.builtin {                    let compiled = shipped.iter().find(|table| table.id == row.id);                    let resolved = crate::definitions::resolve_table_on_file(                        db, &row.id, compiled, Some(&row),                    )?;                    serde_json::to_string(&resolved).map_err(fail)?                } else {                    row.definition                };                Ok((row.id, definition))            })            .collect::<Result<_, ToolFailure>>()?    } else {        db.all(            &format!("SELECT id, definition FROM {kind} WHERE workspace_id = ? ORDER BY id"),            &[SqlValue::Text(workspace.into())],        )        .map_err(fail)?        .into_iter()        .map(|row| {            let id = row.text("id").ok_or_else(|| fail("definition id is missing"))?;            let raw = row.text("definition").ok_or_else(|| fail("definition is missing"))?;            Ok((id.to_string(), raw.to_string()))        })        .collect::<Result<_, ToolFailure>>()?    };    let mut entries = Vec::with_capacity(rows.len());    for (id, raw) in rows {        match decode_entry(kind, &id, &raw, lost) {            Ok(entry) => entries.push(entry),            Err(error) if skip_unreadable => lost.push(LostPart { entry: format!("{kind}.{id}"), part: "whole".into(), reason: error.0 }),            Err(error) => return Err(fail(format!("{kind}.{id}: {}", error.0))),        }    }    Ok(entries)}/// Each stored tool's id and the tables it lists, as [`read_entries`] of the/// tools would answer them — and refusing as it would on an entry that is/// not a definition — remembered by the entry's exact text: a package's/// preflight asks it of every tool already held, so a kit of twenty-one/// tools decoded and validated some two hundred definitions over.fn tools_and_tables(db: &Driver, workspace: &str) -> Result<Vec<(String, Vec<String>)>, ToolFailure> {    type Memo = std::collections::HashMap<(String, String), Result<(String, Vec<String>), String>>;    static MEMO: std::sync::LazyLock<std::sync::Mutex<Memo>> = std::sync::LazyLock::new(Default::default);    // Bounded: a long-lived process that sees tools edited many times starts again.    const KEPT: usize = 1024;    let rows = db        .all(&format!("SELECT id, definition FROM {TOOL} WHERE workspace_id = ? ORDER BY id"), &[SqlValue::Text(workspace.into())])        .map_err(fail)?;    let mut out = Vec::with_capacity(rows.len());    for row in rows {        let id = row.text("id").ok_or_else(|| fail("definition id is missing"))?;        let raw = row.text("definition").ok_or_else(|| fail("definition is missing"))?;        let key = (id.to_owned(), raw.to_owned());        let known = MEMO.lock().unwrap_or_else(std::sync::PoisonError::into_inner).get(&key).cloned();        let answer = known.unwrap_or_else(|| {            let answer = decode_entry(TOOL, id, raw, &mut Vec::new())                .map(|entry| {                    let definition = &entry["definition"];                    let tables = definition["tables"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();                    (definition["id"].as_str().unwrap_or_default().to_owned(), tables)                })                .map_err(|error| error.0);            let mut memo = MEMO.lock().unwrap_or_else(std::sync::PoisonError::into_inner);            if memo.len() >= KEPT {                memo.clear();            }            memo.insert(key, answer.clone());            answer        });        out.push(answer.map_err(|error| fail(format!("{TOOL}.{id}: {error}")))?);    }    Ok(out)}fn read_entries(db: &Driver, workspace: &str, kind: &str) -> Result<Vec<Value>, ToolFailure> {    catalog_entries(db, workspace, kind, &mut Vec::new(), false)}/// The rollup columns whose source tool is absent, each as `{table, words}`:/// the source table id and the field problem the page draws, worded by the/// `everything` definition (`rules::source_absent`) over the source's name./// Table definitions survive removal, so existence alone cannot answer/// availability, and the surviving definition still names the table.pub fn computed_unavailable(    db: &Driver,    workspace: &str,    definition: &TableDefinition,) -> Result<BTreeMap<String, Value>, ToolFailure> {    if !definition.columns.iter().any(|column| column.computed.as_ref().and_then(Computed::rollup).is_some()) {        return Ok(BTreeMap::new());    }    let mut present: BTreeSet<String> = builtin_table_definitions().iter().map(|table| table.id.clone()).collect();    for row in read_entries(db, workspace, TOOL)? {        present.extend(row["definition"]["tables"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned));    }    let absent: Vec<(&str, &str)> = definition.columns.iter().filter_map(|column| {        let rollup = column.computed.as_ref().and_then(Computed::rollup)?;        (!present.contains(rollup.table)).then(|| (column.key.as_str(), rollup.table))    }).collect();    if absent.is_empty() {        return Ok(BTreeMap::new());    }    let tables = crate::definitions::table_definitions_from_driver(db, workspace)?.definitions;    let find = |id: &str| tables.iter().find(|table| table.id == id);    let wording = find(source_absent::WORDING_TABLE);    Ok(absent.into_iter().map(|(column, table)| {        let words = wording.and_then(|wording| source_absent::line(wording, &source_absent::source_name(find(table), table)));        (column.to_owned(), json!({ "table": table, "words": words }))    }).collect())}fn pictures(    db: &Driver,    workspace: &str,    id: &str,) -> Result<BTreeMap<String, String>, ToolFailure> {    let pictures = crate::tool_pictures::package_pictures(db, workspace, id).map_err(fail)?;    // A held picture whose bytes do not read is corruption, not a package    // without that picture.    for (name, bytes) in &pictures {        STANDARD            .decode(bytes)            .map_err(|error| fail(format!("tool {id:?}: picture {name:?} cannot be read: {error}")))?;    }    Ok(pictures)}/// Make tool `tool_id`'s pictures the package's set `pictures` (name →/// base64): each picture one row of its own, a changed one rewritten, and/// one the package no longer carries retracted — so installing a package/// replaces the tool's pictures, and `{}` takes them all away.pub(crate) fn replace_pictures(    ctx: &mut Ctx<'_>,    tool_id: &str,    pictures: &BTreeMap<String, String>,) -> Result<(), ToolFailure> {    let held = pictures_of(ctx, tool_id)?;    for (name, bytes) in pictures {        if held.get(name) == Some(bytes) {            continue;        }        let id = tool_asset_id(tool_id, name);        let mut patch = json!({"tool_id": tool_id, "name": name, "bytes": bytes})            .as_object()            .unwrap()            .clone();        if held.contains_key(name) {            patch.insert("updated_at".into(), Value::from(super::common::now_iso(ctx)));            update_row(ctx, TOOL_ASSETS, &id, patch)?;        } else {            insert_row(ctx, TOOL_ASSETS, &id, patch)?;        }    }    for name in held.keys().filter(|name| !pictures.contains_key(*name)) {        ctx.writer()?            .retract(TOOL_ASSETS, &tool_asset_id(tool_id, name), Retract::Relation);    }    Ok(())}/// `pictures` added to tool `tool_id`'s carried pictures where it holds none/// of that name: nothing it holds is replaced or taken away (the kit keep,/// laying a held tool's new pictures beside the person's).pub(crate) fn add_pictures(    ctx: &mut Ctx<'_>,    tool_id: &str,    pictures: &BTreeMap<String, String>,) -> Result<(), ToolFailure> {    let held = pictures_of(ctx, tool_id)?;    for (name, bytes) in pictures.iter().filter(|(name, _)| !held.contains_key(*name)) {        let patch = json!({"tool_id": tool_id, "name": name, "bytes": bytes}).as_object().unwrap().clone();        insert_row(ctx, TOOL_ASSETS, &tool_asset_id(tool_id, name), patch)?;    }    Ok(())}fn pictures_of(ctx: &Ctx<'_>, tool_id: &str) -> Result<BTreeMap<String, String>, ToolFailure> {    pictures(ctx.read.driver(), ctx.workspace_id, tool_id)}/// A table a package may own: no engine, and not one of the shell's own tables/// (`lines` has no engine but belongs to the shell, so no tool lists it and it/// is never an orphan).fn package_table(row: &Value) -> bool {    row["definition"]["engine"].is_null()        && !row["definition"]["id"].as_str().is_some_and(|id| crate::presentation::SHELL_TABLES.contains(&id))}/// Records reads this list including orphaned tables; Tools reads only live tools.////// Orphan status is derived from the live tools, never from the record bin.pub fn stored_table_definitions(db: &Driver, workspace: &str) -> Result<Vec<Value>, ToolFailure> {    let referenced: BTreeSet<String> = read_entries(db, workspace, TOOL)?        .iter()        .flat_map(|row| {            row["definition"]["tables"]                .as_array()                .into_iter()                .flatten()                .filter_map(Value::as_str)                .map(str::to_owned)        })        .collect();    Ok(read_entries(db, workspace, TABLE)?        .into_iter()        .filter(package_table)        .map(|mut row| {            row["orphaned"] = Value::Bool(                !referenced.contains(                    row["definition"]["id"]                        .as_str()                        .expect("validated definition id"),                ),            );            row        })        .collect())}/// A shipped upgrade keeps the owner's overlay and avoids minting unchanged rows.fn write_package_entry(ctx: &mut Ctx<'_>, kind: &str, id: &str, mut definition: Value, shipped: bool) -> Result<(), ToolFailure> {    let held = ctx.db().get(&format!("SELECT definition, instructions_edited FROM {kind} WHERE workspace_id = ? AND id = ?"),        &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(id.into())]).map_err(fail)?;    let mut instructions_edited = false;    if let Some(row) = &held {        let previous: Value = serde_json::from_str(row.text("definition").ok_or_else(|| fail("definition is missing"))?).map_err(fail)?;        if shipped {            instructions_edited = row.int("instructions_edited") == Some(1);            if kind == TABLE {                let base: TableDefinition = serde_json::from_value(definition.clone()).map_err(fail)?;                let edited: Vec<String> = serde_json::from_value(previous.get("edited").cloned().unwrap_or(json!([]))).map_err(fail)?;                definition = serde_json::to_value(cotton_core::definitions::with_edits(&base, &previous, &edited).0).map_err(fail)?;            } else {                // Unknown keys include the tool's arrangement and edit metadata.                let tool: ToolDefinition = serde_json::from_value(previous.clone()).map_err(fail)?;                for (key, value) in tool.unknown { definition[&key] = value; }                for key in previous["edited"].as_array().into_iter().flatten().filter_map(Value::as_str) {                    if matches!(key, "name" | "purpose" | "picture" | "card_stock") {                        definition[key] = previous[key].clone();                    }                }            }            if instructions_edited { definition["instructions"] = previous["instructions"].clone(); }        }        if previous == definition && row.int("instructions_edited") == Some(i64::from(instructions_edited)) { return Ok(()); }    }    let patch = json!({"id":id,"definition":definition,"builtin":false,"instructions_edited":instructions_edited}).as_object().unwrap().clone();    if held.is_some() { update_row(ctx, kind, id, patch) } else { insert_row(ctx, kind, id, patch) }}fn tool_entries(ctx: &Ctx<'_>) -> Result<Vec<Value>, ToolFailure> {    read_entries(ctx.read.driver(), ctx.workspace_id, TOOL)}/// Validated live imported tools, shared by the briefing and data automation interpreter.pub fn live_tool_definitions(ctx: &Ctx<'_>) -> Result<Vec<ToolDefinition>, ToolFailure> {    tool_entries(ctx)?        .into_iter()        .map(|row| serde_json::from_value(row["definition"].clone()).map_err(fail))        .collect()}/// JSON carries zip bytes as standard base64, for MCP and cotton_call alike.pub fn import_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let encoded = text(args, "bytes")?;    if encoded.len() > 24 * 1024 * 1024 {        return Err(fail("bytes exceeds the package size limit"));    }    let bytes = STANDARD        .decode(encoded)        .map_err(|_| fail("bytes is not base64"))?;    let with_samples = super::common::optional_boolean(args, "with_samples")?.unwrap_or(false);    let imported = decode_package(&bytes).map_err(fail)?;    install_package(ctx, &imported.package, Door::Import, with_samples)}/// The door a package came in by, which decides what of it is written.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Door {    /// A package someone imported or a toolkit carried: its own tables, with    /// any table Cotton carries swapped for this build's.    Import,    /// A kit revision Cotton ships: it keeps the pictures the database holds    /// and writes over the shipped definitions' overlay.    Kit,    /// Cotton's own carried tables, written as they come.    Cotton,}/// Install one decoded package: its tables, its tool row, its pictures and,/// when asked, its sample rows — the whole of `import_tool` after the zip.////// Its own function because a package does not only arrive as bytes an/// assistant pasted: a bridge that reads a service into a tool it carries/// (`crate::connections::domains`) installs that tool the same way, through/// the same checks, so a built-in table or another tool's table is refused/// identically whichever door the package came in by.pub fn install_package(    ctx: &mut Ctx<'_>,    package: &ToolPackage,    door: Door,    with_samples: bool,) -> ToolResult {    let own = own_tables(package, door);    let package = own.as_ref().unwrap_or(package);    preflight(ctx, package)?;    let _span = cotton_store::spans::span("tool_packages::write_package");    write_package(ctx, package, door, with_samples)}/// What a revision the database could not take left behind: the reason, and/// the tables it would have dropped (empty when it refused for another cause).#[derive(Debug, Clone, PartialEq, Eq)]pub struct RefusedRevision {    pub reason: String,    pub drops: Vec<String>,}/// A table Cotton itself carries is always THIS BUILD'S: a kit somebody/// saved, or any other door that is not Cotton's own install, may list/// Domains, and what is written for its table is the definition the build/// ships — its commands included — never the one that came in the package.fn own_tables(package: &ToolPackage, door: Door) -> Option<ToolPackage> {    if door == Door::Cotton        || !package.tables.iter().any(|table| crate::connections::domains::carried_table(&table.id).is_some())    {        return None;    }    let mut shipped = package.clone();    for table in &mut shipped.tables {        if let Some(carried) = crate::connections::domains::carried_table(&table.id) {            *table = carried;        }    }    Some(shipped)}/// The tool definition this database holds under `id`, if any.fn held_tool(ctx: &Ctx<'_>, id: &str) -> Result<Option<ToolDefinition>, ToolFailure> {    let Some(row) = ctx.db().get(&format!("SELECT definition FROM {TOOL} WHERE workspace_id = ? AND id = ?"),        &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(id.into())]).map_err(fail)? else { return Ok(None) };    ToolDefinition::from_json(row.text("definition").ok_or_else(|| fail("definition is missing"))?).map(Some).map_err(fail)}/// Every check a package passes before its first write: a refusal imports nothing./// A retired built-in's commands come only from the database: a package may/// carry for such a table exactly the commands and `on_open` the database's/// own row holds, and nothing else/// ([`cotton_core::definitions::package::commands_held_by_the_database`]).fn held_commands(ctx: &Ctx<'_>, package: &ToolPackage) -> Result<(), ToolFailure> {    for table in package.tables.iter().filter(|table| cotton_core::definitions::package::commands_held_by_the_database(table)) {        if table.commands.is_none() && table.on_open.is_none() {            continue;        }        let held = crate::definitions::definition_rows(ctx, Some(&table.id))?            .into_iter()            .next()            .and_then(|row| serde_json::from_str::<Value>(&row.definition).ok());        let holds = |key: &str, carried: Value| held.as_ref().and_then(|row| row.get(key)).filter(|value| !value.is_null()).cloned() == Some(carried).filter(|value| !value.is_null());        let commands = serde_json::to_value(&table.commands).map_err(fail)?;        let on_open = serde_json::to_value(&table.on_open).map_err(fail)?;        if !holds("commands", commands) || !holds("on_open", on_open) {            return Err(fail(cotton_core::definitions::package::commands_not_held(&table.id)));        }    }    Ok(())}fn preflight(ctx: &mut Ctx<'_>, package: &ToolPackage) -> Result<(), ToolFailure> {    let _span = cotton_store::spans::span("tool_packages::preflight");    let part = cotton_store::spans::span("preflight validate");    package.tool.validate().map_err(fail)?;    held_commands(ctx, package)?;    drop(part);    let part = cotton_store::spans::span("preflight views");    // The views read the tables with what this package contributes to them:    // a view naming its own contributed column passes on the first import.    // A package that carries no table reads the tables this database has, and    // its public views are judged on those (a kitchen's Plans over the    // kitchen's own tables).    let read = if package.tables.is_empty() {        let held: Vec<TableDefinition> = crate::definitions::definition_rows(ctx, None)?            .iter()            .filter_map(|row| crate::definitions::parsed(&row.id, &row.definition))            .map(|definition| (*definition).clone())            .collect();        let held = cotton_core::definitions::tool_views::with_contributions(&held, &package.tool).map_err(fail)?;        cotton_core::definitions::tool_views::validate_reads_beside(&package.tool.views, &held).map_err(|error| match error {            DefinitionError::UnknownTable { table, .. } => fail(format!(                "This tool reads the {} table. Install its tool first.", key_as_words(&table)            )),            error => fail(error),        })?;        held    } else {        cotton_core::definitions::tool_views::with_contributions(&package.tables, &package.tool).map_err(fail)?    };    cotton_core::definitions::tool_views::validate_public_reads(&package.tool.views, &read).map_err(fail)?;    drop(part);    let part = cotton_store::spans::span("preflight contributions+tables");    for contribution in &package.tool.contributes {        let carried = package.tables.iter().find(|table| table.id == contribution.table);        contribution_fits(ctx, &package.tool.id, contribution, carried)?;    }    cotton_core::definitions::visibility::validate_tables(&package.tables).map_err(fail)?;    cotton_core::definitions::automations::validate_tables(&package.tool, &package.tables).map_err(fail)?;    for definition in &package.tables { definition.validate_import().map_err(fail)?; }    // No tool is built in (72nd amendment): a tool row of the same id is a    // revision of it, held to adding only.    if let Some(previous) = held_tool(ctx, &package.tool.id)? {        for id in &previous.tables {            if !package.tables.iter().any(|table| &table.id == id) {                return Err(fail(format!("a package revision may only add: it drops the table {id}")));            }        }    }    let builtins: BTreeSet<_> = builtin_table_definitions()        .iter()        .map(|d| d.id.clone())        .collect();    // A table another live tool lists is that tool's: a package may not    // redefine it. One this tool lists already (an upgrade) or one no tool    // lists (orphaned by a removal, re-attached now) takes the package's    // definition, provided the revision only ADDS to the tables it owns    // (GUARD 3, `package_shape::check_add_only`): a column is never dropped,    // renamed or narrowed — one no longer wanted is marked retired — because    // every device takes the new shape by data, in place. Views, pages, sort,    // group and defaults change freely.    drop(part);    let part = cotton_store::spans::span("preflight others");    let listed_by_others: BTreeSet<String> = tools_and_tables(ctx.read.driver(), ctx.workspace_id)?        .into_iter()        .filter(|(id, _)| *id != package.tool.id)        .flat_map(|(_, tables)| tables)        .collect();    drop(part);    let part = cotton_store::spans::span("preflight each table");    for definition in &package.tables {        // A built-in table travels as itself — its schema and engine are        // code, checked when the package was read; a package's own table        // may not take a built-in's name.        if (builtins.contains(&definition.id) || cotton_core::definitions::is_builtin_table(&definition.id)) && !definition.builtin {            return Err(fail(format!(                "table {:?} has the name of a table Cotton has built in; give the package's table a name of its own",                definition.id            )));        }        // A retired built-in's row (`definitions::retired_builtin`) is no        // definition: the package's own takes its id.        if crate::definitions::definition_rows(ctx, Some(&definition.id))?            .iter()            .all(|row| row.builtin)        {            continue;        }        let existing = super::tables::definition(ctx, &definition.id)?;        if existing == *definition {            continue;        }        if listed_by_others.contains(&definition.id) {            return Err(fail(format!(                "table {:?} belongs to another tool and the package defines it differently",                definition.id            )));        }        let (had, next) = (            existing.physical_tables().map_err(fail)?,            definition.physical_tables().map_err(fail)?,        );        cotton_store::schema::package_shape::check_add_only(&had, &next)            .map_err(|refused| fail(format!("table {:?}: {}", definition.id, refused)))?;    }    // A computed column reads what THIS database has: the package's tables,    // the tables other installed tools brought, and the built-ins. A rollup    // over another tool's table (Customers counting the Orders tool's    // orders) installs once that tool is here and is refused, naming the    // table, while it is not; and an upgrade may not take away what an    // installed rollup reads.    drop(part);    let _part = cotton_store::spans::span("preflight installed");    let installed: Vec<std::sync::Arc<TableDefinition>> = crate::definitions::definition_rows(ctx, None)?        .iter()        .filter_map(|row| crate::definitions::parsed(&row.id, &row.definition))        .filter(|definition| definition.engine.is_none())        .collect();    let builtin_tables = builtin_table_definitions();    let own: Vec<&TableDefinition> = package.tables.iter().collect();    let beside: Vec<&TableDefinition> = installed.iter().map(|definition| &**definition).chain(builtin_tables.iter()).collect();    validate_beside(&own, &beside, AbsentTable::Refuse).map_err(|error| match error {        // The phone's failure renderer hides definition paths and raw ids.        // Name the missing table in words so the refusal stays actionable        // through both the MCP and phone paths.        DefinitionError::UnknownTable { table, .. } => fail(format!(            "This tool needs the {} table. Install its tool first.", key_as_words(&table)        )),        error => fail(error),    })?;    Ok(())}/// A column a tool adds may go on a table this database has, or the package/// itself carries (Cotton Pages' page, laid with the tool that adds its/// star), that keeps added columns (a kit table), and only at a key free of/// any other column — or the same column, written there by this tool before.fn contribution_fits(ctx: &Ctx<'_>, tool: &str, contribution: &ToolContribution, carried: Option<&TableDefinition>) -> Result<(), ToolFailure> {    let table = &contribution.table;    let words = key_as_words(table);    if carried.is_none() && crate::definitions::definition_rows(ctx, Some(table))?.is_empty() {        return Err(fail(format!("This tool adds a column to the {words} table. Install its tool first.")));    }    if !builtin_table_definitions().iter().any(|definition| &definition.id == table) {        return Err(fail(format!("This tool adds a column to the {words} table, which takes no added columns.")));    }    let wanted: Column = serde_json::from_value(        cotton_core::definitions::owner::contributed_column(tool, &contribution.column).map_err(fail)?,    )    .map_err(fail)?;    let held = match carried {        Some(carried) => carried.clone(),        None => super::tables::definition(ctx, table)?,    };    if let Some(column) = held.column(&wanted.key) {        if column.column_type != wanted.column_type {            return Err(fail(format!(                "The {words} table already has a column {:?} of another type.", contribution.column.label()            )));        }    }    Ok(())}/// The table's columns as `update_definition` takes them back: every one it/// draws today, in order.fn columns_of(ctx: &mut Ctx<'_>, table: &str) -> Result<Vec<Value>, ToolFailure> {    let answer = super::tables::definition_writes::update_definition(ctx, json!({"table": table}).as_object().expect("an object"))?;    Ok(answer["definition"]["columns"].as_array().cloned().unwrap_or_default())}/// Add a contributed column to its table, hidden in the table's own look,/// through the owner's own column write; one already there (the tool was/// here before) is left as the owner keeps it.fn contribute(ctx: &mut Ctx<'_>, tool: &str, contribution: &ToolContribution) -> Result<(), ToolFailure> {    let column = cotton_core::definitions::owner::contributed_column(tool, &contribution.column).map_err(fail)?;    let mut columns = columns_of(ctx, &contribution.table)?;    if columns.iter().any(|held| held["key"] == column["key"]) {        return Ok(());    }    columns.push(column);    super::tables::definition_writes::update_definition(ctx, json!({"table": contribution.table, "columns": columns}).as_object().expect("an object"))?;    Ok(())}/// Hide a contributed column in its table's own look (the owner may have/// shown it there); its values are never touched.fn hide_contribution(ctx: &mut Ctx<'_>, tool: &str, contribution: &ToolContribution) -> Result<(), ToolFailure> {    if crate::definitions::definition_rows(ctx, Some(&contribution.table))?.is_empty() {        return Ok(());    }    let key = cotton_core::definitions::owner::contributed_key(tool, &contribution.column.key);    let mut columns = columns_of(ctx, &contribution.table)?;    let Some(column) = columns.iter_mut().find(|held| held["key"] == key.as_str()) else { return Ok(()) };    if column["hidden"] == true {        return Ok(());    }    column["hidden"] = Value::Bool(true);    super::tables::definition_writes::update_definition(ctx, json!({"table": contribution.table, "columns": columns}).as_object().expect("an object"))?;    Ok(())}/// Write a package [`preflight`] passed./// Each of `ids` that this copy holds no definition of, laid from the kit's shipped file (`kit::table_file`) as a/// package's table is laid: a kit table no tool draws (Sites' `site`, Post's `email_account`). A built-in table is/// the build's and is skipped, as is one a copy already holds (its keep is `kit_keep`'s). No tool is written, so/// nothing new is listed to an assistant. Answers the ids laid.pub fn lay_kit_tables(ctx: &mut Ctx<'_>, ids: &[String]) -> Result<Vec<String>, ToolFailure> {    let mut laid = Vec::new();    for id in ids {        // ONLY A KIT-OWN TABLE (review of GENESIS KITS, 26 Nov 2026): a kit's other tables are its tools' to lay, and a        // table neither compiled in nor on that list is never made here.        if !cotton_core::kit::kit_own_tables().any(|own| own == id) {            continue;        }        if cotton_core::definitions::builtin_store_table(id).is_some() || cotton_core::definitions::is_builtin_table(id) {            continue;        }        let held = ctx.db().get(&format!("SELECT id FROM {TABLE} WHERE workspace_id = ? AND id = ?"),            &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(id.clone())]).map_err(fail)?.is_some();        if held {            continue;        }        let Some(bytes) = cotton_core::kit::table_file(id) else { continue };        let definition: Value = serde_json::from_slice(bytes).map_err(fail)?;        write_package_entry(ctx, TABLE, id, definition, true)?;        laid.push(id.clone());    }    if !laid.is_empty() {        ctx.commit()?;    }    Ok(laid)}fn write_package(ctx: &mut Ctx<'_>, package: &ToolPackage, door: Door, with_samples: bool) -> ToolResult {    // A tool already installed under this id is upgraded in place: its row    // and its tables take the package's definitions (checked above).    let shipped = door == Door::Kit;    for definition in &package.tables {        write_package_entry(ctx, TABLE, &definition.id, serde_json::to_value(definition).map_err(fail)?, shipped)?;    }    let mut pictures = if shipped { pictures_of(ctx, &package.tool.id)? } else { BTreeMap::new() };    pictures.extend(package.pictures.iter().map(|(name, bytes)| (name.clone(), STANDARD.encode(bytes))));    write_package_entry(ctx, TOOL, &package.tool.id, serde_json::to_value(&package.tool).map_err(fail)?, shipped)?;    if let Some(board) = &package.board {        // Package boards have no shipped-base overlay yet. An installed board        // is the owner's arrangement; only seed it when it is absent.        let held = ctx.db().get("SELECT id FROM cotton_board_definitions WHERE workspace_id = ? AND id = ?",            &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(board.id.clone())]).map_err(fail)?.is_some();        if !shipped || !held { crate::presentation::install_tool_board(ctx, &package.tool.id, board)?; }    }    replace_pictures(ctx, &package.tool.id, &pictures)?;    ctx.commit()?;    for contribution in &package.tool.contributes {        contribute(ctx, &package.tool.id, contribution)?;    }    // Sample rows come after the definitions have landed, each its own    // create (defaults, checks, automations, byline "sample"); a row the    // table refuses after all — a link to nothing — stops the rest and says    // which, with the tool itself installed.    // A sample may link an earlier sample by `sample:<table>#<n>` (a trip's    // ticket its trip), answered by the id that sample was made under.    let mut samples = 0usize;    if with_samples {        let mut made: BTreeMap<String, Vec<String>> = BTreeMap::new();        for (table, rows) in cotton_core::definitions::package::sample_order(&package.samples) {            for (at, row) in rows.iter().enumerate() {                let row = cotton_core::definitions::package::resolve_sample_refs(row, &made)                    .map_err(|why| fail(format!("sample rows records/{table}.json[{at}]: {why}")))?;                let written = super::tables::create_sample_record(ctx, table, &row).map_err(|why| {                    fail(format!("sample rows records/{table}.json[{at}]: {}", why.0))                })?;                made.entry(table.clone()).or_default().push(written["record"]["id"].as_str().unwrap_or_default().to_string());                samples += 1;            }        }    }    let mut answer = cotton_core::definitions::package::Signature::of(&package.tool).fields();    answer.insert("tool_id".into(), Value::from(package.tool.id.clone()));    answer.insert("sample_records".into(), Value::from(samples));    Ok(Value::Object(answer))}pub fn list_tools(ctx: &mut Ctx<'_>, _args: &Map<String, Value>) -> ToolResult {    let mut lost = Vec::new();    let mut tools = catalog_entries(ctx.read.driver(), ctx.workspace_id, TOOL, &mut lost, false)?;    let tables = catalog_entries(ctx.read.driver(), ctx.workspace_id, TABLE, &mut lost, false)?;    let referenced: BTreeSet<_> = tools        .iter()        .flat_map(|row| {            row["definition"]["tables"]                .as_array()                .into_iter()                .flatten()                .filter_map(Value::as_str)        })        .collect();    let tables: Vec<_> = tables        .into_iter()        .filter(package_table)        .map(|mut row| {            row["orphaned"] = Value::Bool(                !referenced.contains(                    row["definition"]["id"]                        .as_str()                        .expect("validated definition id"),                ),            );            row        })        .collect();    for tool in &mut tools {        let id = tool["definition"]["id"]            .as_str()            .expect("validated definition id");        tool["pictures"] = serde_json::to_value(pictures(ctx.read.driver(), ctx.workspace_id, id)?)            .map_err(fail)?;    }    let mut answer = json!({"tools":tools,"table_definitions":tables});    if !lost.is_empty() {        answer["lost"] = serde_json::to_value(&lost).map_err(fail)?;    }    Ok(answer)}pub fn export_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = text(args, "tool_id")?;    let mut package = crate::tool_export::package(ctx.read.driver(), ctx.workspace_id, id)?;    let signer = ctx.services.tool_signer.as_ref()        .ok_or_else(|| fail("this device has no signing key for tools"))?;    package.tool.author = signer.author.clone();    let mut sign_error = None;    let bytes = encode_package(&package, |payload| match (signer.sign)(payload) {        Ok(sig) => sig,        Err(error) => {            sign_error = Some(error);            [0; 64]        }    });    if let Some(error) = sign_error {        return Err(fail(error));    }    let bytes = bytes.map_err(fail)?;    Ok(json!({"tool_id":id,"bytes":STANDARD.encode(bytes)}))}/// Add a kit tool (`cotton_core::kit`) or a business package a flavour's/// manifest names (`cotton_core::toolkits::shipped_kit_tools`: yoga, kitchen)/// to this database on purpose, through the same install `import_tool` runs,/// with no sample rows — or Domains, which this crate carries for the/// Cloudflare connection, added with no connection. No tool is built in (72nd/// amendment): any other tool arrives with `import_tool`. Adding it again/// changes nothing.pub fn add_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = text(args, "tool_id")?;    let here_span = cotton_store::spans::span("tool_packages::add_tool here");    let here = tools_and_tables(ctx.read.driver(), ctx.workspace_id)?.iter().any(|(held, _)| held == id);    drop(here_span);    // Domains is carried by this crate for the connection that fills it    // (`crate::connections::domains`); its rows are written by hand.    if id == crate::connections::domains::TOOL_ID {        crate::connections::domains::add(ctx)?;        return Ok(json!({"tool_id":id,"added":!here}));    }    if let Some(package) = cotton_core::toolkits::kit_packages().iter().find(|package| package.tool.id == id) {        if here {            return Ok(json!({"tool_id":id,"added":false}));        }        let carried = crate::toolkits::carried_package("shipped", package)?;        install_package(ctx, &carried, Door::Kit, false)?;        { let _span = cotton_store::spans::span("tool_packages::commit"); ctx.commit()?; }        return Ok(json!({"tool_id":id,"added":true}));    }    let decoding = cotton_store::spans::span("tool_packages::kit decoded");    let decoded = cotton_core::kit::decoded(id);    drop(decoding);    let Some(package) = decoded else {        let business: Vec<String> = cotton_core::toolkits::kit_packages().iter().map(|package| package.tool.id.clone()).collect();        return Err(fail(format!(            "{id:?} is not a tool to add: the tools Cotton offers are {}, the business packages {} and {}; any other tool arrives with import_tool",            cotton_core::kit::ids().join(", "),            business.join(", "),            crate::connections::domains::TOOL_ID        )));    };    if here {        return Ok(json!({"tool_id":id,"added":false}));    }    let package = package.map_err(fail)?;    let _span = cotton_store::spans::span("tool_packages::install_package");    install_package(ctx, &package.package, Door::Import, false)?;    { let _span = cotton_store::spans::span("tool_packages::commit"); ctx.commit()?; }    Ok(json!({"tool_id":id,"added":true}))}/// Take a tool out of this database: its row and its cards on Home go, and/// its tables, its data and every engine on them stay untouched (72nd/// amendment) — so a tool holding records is removed like any other, and/// importing it again draws what is there.pub fn remove_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = text(args, "tool_id")?;    let entries = tool_entries(ctx)?;    let entry = entries        .iter()        .find(|row| row["definition"]["id"] == id)        .ok_or_else(|| fail(format!("there is no tool {id:?}")))?;    let personal = !matches!(ctx.file_kind()?, FileKind::Shared);    crate::home_arrangement::leave(ctx, id, personal)?;    let tool: ToolDefinition = serde_json::from_value(entry["definition"].clone()).map_err(fail)?;    let shared: BTreeSet<String> = entries        .iter()        .filter(|row| row["definition"]["id"] != id)        .flat_map(|row| {            row["definition"]["tables"]                .as_array()                .into_iter()                .flatten()                .filter_map(Value::as_str)                .map(str::to_string)        })        .collect();    ctx.writer()?.retract(TOOL, id, Retract::Relation);    replace_pictures(ctx, id, &BTreeMap::new())?;    // The definitions remain in their own synced table. No deletion stamp    // puts them into the record bin, and every replica derives the same mark.    // Tables no other tool here lists: they stay, with their data, undrawn.    let orphaned: Vec<_> = tool        .tables        .iter()        .filter(|table| !shared.contains(*table))        .cloned()        .collect();    ctx.commit()?;    // Its columns on other tools' tables are hidden there, never taken out:    // their values stay, and the tool imported again draws them.    for contribution in &tool.contributes {        hide_contribution(ctx, id, contribution)?;    }    Ok(json!({"tool_id":id,"orphaned_tables":orphaned}))}/// One kit as `list_toolkits` lists it: each tool summarised.fn kit_summary(kit: &crate::toolkits::KitRow) -> Value {    use cotton_core::toolkits::KitTool;    let tools: Vec<Value> = kit        .tools        .iter()        .map(|tool| match tool {            KitTool::Kit(key) => json!({"key": key, "kit": true}),            KitTool::Package { package } => json!({                "key": package.tool.id,                "kit": false,                "name": package.tool.name,                "picture": package.tool.picture,                "tables": package.tables.iter().map(|table| &table.id).collect::<Vec<_>>(),                "with_samples": package.with_samples,            }),        })        .collect();    json!({        "id": kit.id,        "name": kit.name,        "description": kit.description,        "picture": kit.picture,        "shipped": kit.shipped,        "tools": tools,    })}const KITS: &str = crate::toolkits::TOOLKITS;fn personal_only(ctx: &Ctx<'_>) -> Result<(), ToolFailure> {    if ctx.file_kind()? != cotton_store::link_rule::FileKind::Personal {        return Err(fail("toolkits are kept in your personal database; ask it there"));    }    Ok(())}fn stored_kit(ctx: &Ctx<'_>, id: &str) -> Result<Option<crate::toolkits::KitRow>, ToolFailure> {    Ok(crate::toolkits::read(ctx.db(), ctx.workspace_id).map_err(fail)?.into_iter().find(|kit| kit.id == id))}/// A kit's tools, checked whole before anything is written: a built-in by a/// key Home knows, each carried tool valid with exactly the tables it lists,/// and no key twice.fn checked_tools(value: &Value) -> Result<Vec<cotton_core::toolkits::KitTool>, ToolFailure> {    use cotton_core::toolkits::KitTool;    let tools: Vec<KitTool> = serde_json::from_value(value.clone()).map_err(|error| {        fail(format!("tools is a list of kit tool ids (\"todos\") or {{\"package\": …}} entries: {error}"))    })?;    let mut seen = BTreeSet::new();    // The tables the kit's tools bring, in kit order: a package that carries    // no table reads Cotton's kit tables and those of the packages before it.    let mut brought: Vec<TableDefinition> = builtin_table_definitions().to_vec();    for tool in &tools {        if !seen.insert(tool.key().to_string()) {            return Err(fail(format!("tool {:?} is in the kit twice", tool.key())));        }        match tool {            KitTool::Kit(tool_id) => {                if !cotton_core::kit::ids().contains(&tool_id.as_str()) {                    return Err(fail(format!("{tool_id:?} is not a kit tool; carry it as a package")));                }            }            KitTool::Package { package } => {                package.tool.validate().map_err(fail)?;                // A kit is checked without a database: a package that carries                // no table reads the tables the kit's tools before it bring.                let read = if package.tables.is_empty() {                    let kit = cotton_core::definitions::tool_views::with_contributions(&brought, &package.tool).map_err(fail)?;                    cotton_core::definitions::tool_views::validate_reads_beside(&package.tool.views, &kit).map_err(fail)?;                    kit                } else {                    cotton_core::definitions::tool_views::with_contributions(&package.tables, &package.tool).map_err(fail)?                };                cotton_core::definitions::tool_views::validate_public_reads(&package.tool.views, &read).map_err(fail)?;                brought.extend(package.tables.iter().cloned());                for table in &package.tables {                    table.validate_import().map_err(fail)?;                }                let builtin_ids: BTreeSet<String> = builtin_table_definitions().iter().map(|table| table.id.clone()).collect();                let carried: Vec<&String> = package.tables.iter().map(|table| &table.id).collect();                if carried.iter().any(|id| builtin_ids.contains(*id)) {                    return Err(fail(format!("tool {:?} carries a built-in table; list it without carrying it", package.tool.id)));                }                let own: Vec<&String> = package.tool.tables.iter().filter(|id| !builtin_ids.contains(*id)).collect();                if carried != own {                    return Err(fail(format!(                        "tool {:?} lists its own tables {own:?} and carries {carried:?}",                        package.tool.id                    )));                }            }        }    }    Ok(tools)}/// Write one kit row the person made or changed: `shipped` is false from/// here, so the launch seed leaves it as they left it.fn write_kit(    ctx: &mut Ctx<'_>,    id: &str,    fields: Map<String, Value>,    existing: Option<&crate::toolkits::KitRow>,) -> Result<(), ToolFailure> {    let mut patch = fields;    patch.insert("id".into(), json!(id));    patch.insert("shipped".into(), Value::Bool(false));    match existing {        Some(_) => {            patch.insert("updated_at".into(), json!(super::common::now_iso(ctx)));            update_row(ctx, KITS, id, patch)?;        }        None => {            let next = crate::toolkits::read(ctx.db(), ctx.workspace_id)                .map_err(fail)?                .iter()                .map(|kit| kit.position + 1)                .max()                .unwrap_or(0);            patch.entry("position").or_insert(json!(next));            insert_row(ctx, KITS, id, patch)?;        }    }    ctx.commit()}fn kit_answer(ctx: &Ctx<'_>, id: &str) -> ToolResult {    let kit = stored_kit(ctx, id)?.ok_or_else(|| fail(format!("toolkit {id:?} was not written")))?;    Ok(json!({ "toolkit": kit_summary(&kit) }))}/// A fresh id for a person's kit named `name`: the name's slug, suffixed/// when a kit (shipped, kept or deleted) holds it.fn fresh_kit_id(ctx: &Ctx<'_>, name: &str) -> Result<String, ToolFailure> {    let slug = crate::toolkits::kit_id(name);    if slug.is_empty() {        return Err(fail("name has no letters or digits to make the kit's id from"));    }    let taken = crate::toolkits::taken_ids(ctx.db(), ctx.workspace_id).map_err(fail)?;    Ok(crate::toolkits::fresh_id(&slug, &taken))}/// Save a database's Home as a kit: the tools on its Home, in order — its/// built-ins by key, every tool installed there carried whole — under/// `name`, in the personal database, at an id of its own. `replace: true`/// overwrites the person's own kit at the name's id; a shipped kit is never/// overwritten (11 Oct: a save took home-kitchen and the shipped kit was lost).pub fn save_toolkit(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    personal_only(ctx)?;    let from = text(args, "from")?;    let name = text(args, "name")?.trim().to_string();    let replace = match args.get("replace") {        None | Some(Value::Null) => false,        Some(Value::Bool(replace)) => *replace,        Some(_) => return Err(fail("replace is true or false")),    };    let slug = crate::toolkits::kit_id(&name);    if slug.is_empty() {        return Err(fail("name has no letters or digits to make the kit's id from"));    }    let mine = if replace {        if crate::toolkits::is_shipped_id(&slug) {            return Err(fail(format!(                "{slug:?} is a kit Cotton ships and is never replaced; save without replace for a kit of your own"            )));        }        stored_kit(ctx, &slug)?    } else {        None    };    let id = match &mine {        Some(kit) => kit.id.clone(),        None => fresh_kit_id(ctx, &name)?,    };    let rail = ctx        .services        .kit_source        .clone()        .ok_or_else(|| fail("this server cannot read another database for a kit"))?;    let tools = rail(from).map_err(fail)?;    let existing = mine;    let mut fields = Map::new();    fields.insert("name".into(), json!(name));    fields.insert("tools".into(), json!(tools));    if let Some(description) = super::common::optional_string(args, "description") {        fields.insert("description".into(), json!(description));    }    write_kit(ctx, &id, fields, existing.as_ref())?;    kit_answer(ctx, &id)}/// A kit's tools as a call writes them: the list form list_toolkits answers,/// or — as the generic record verbs take a kit, a text column — a line (or/// comma) per tool, each a kit tool's id or name, or the name or id of a/// tool one of the person's kits already carries (`current` first).fn kit_tools(ctx: &Ctx<'_>, value: &Value, current: Option<&crate::toolkits::KitRow>) -> Result<Vec<cotton_core::toolkits::KitTool>, ToolFailure> {    use cotton_core::toolkits::KitTool;    let Value::String(words) = value else { return checked_tools(value) };    let kits = crate::toolkits::read(ctx.db(), ctx.workspace_id).map_err(fail)?;    let carried: Vec<&cotton_core::toolkits::KitPackage> = current        .into_iter()        .chain(kits.iter())        .flat_map(|kit| kit.tools.iter())        .filter_map(|tool| match tool {            KitTool::Package { package } => Some(package),            KitTool::Kit(_) => None,        })        .collect();    let mut tools = Vec::new();    for word in words.split(['\n', ',']).map(str::trim).filter(|word| !word.is_empty()) {        if let Some(key) = crate::toolkits::kit_key(word) {            tools.push(KitTool::Kit(key));        } else if let Some(package) = carried.iter().find(|package| package.tool.id == word || package.tool.name.eq_ignore_ascii_case(word)) {            tools.push(KitTool::Package { package: (*package).clone() });        } else {            return Err(fail(format!("{word:?} is neither a kit tool nor a tool one of your kits carries")));        }    }    if tools.is_empty() {        return Err(fail("tools names at least one tool"));    }    checked_tools(&json!(tools))}/// A kit's picture as a call writes it: none, or a photo the personal/// database holds — `"<photo id>"` or `{"photo": "<photo id>"}` (a shipped/// picture is held as photo:<sha256>) — never a free string the chooser/// cannot draw.fn kit_picture(ctx: &Ctx<'_>, value: &Value) -> Result<Value, ToolFailure> {    use cotton_core::definitions::{ToolPhoto, ToolPicture};    let picture = match value {        Value::Null => return Ok(Value::Null),        Value::String(photo) => ToolPicture::Photo(ToolPhoto { photo: photo.trim().to_string(), object: None, link_object: None }),        other => serde_json::from_value::<ToolPicture>(other.clone())            .map_err(|_| fail("picture is a photo: its id, or {\"photo\": id}"))?,    };    if !matches!(picture, ToolPicture::Photo(_)) {        return Err(fail("picture is a photo: its id, or {\"photo\": id}"));    }    super::tables::definition_writes::picture_held(ctx, Some(&picture))?;    Ok(json!(picture))}/// A kit made whole from its parts — `create_record { table: "toolkit" }`,/// the ordinary create: `name`, `tools` (built-in keys or `{"package": …}`/// entries, as list_toolkits answers them), `description` and `picture` —/// at an id of its own, never a shipped kit's. Answers `{id}`.pub fn make_toolkit(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    personal_only(ctx)?;    let name = text(args, "name")?.trim().to_string();    let tools = kit_tools(ctx, args.get("tools").ok_or_else(|| fail("tools is required: the kit's tools, in order"))?, None)?;    let id = fresh_kit_id(ctx, &name)?;    let mut fields = Map::new();    fields.insert("name".into(), json!(name));    fields.insert("tools".into(), json!(tools));    if let Some(description) = args.get("description") {        fields.insert("description".into(), description.clone());    }    if let Some(picture) = args.get("picture") {        fields.insert("picture".into(), kit_picture(ctx, picture)?);    }    write_kit(ctx, &id, fields, None)?;    Ok(json!({ "id": id }))}/// Change a kit: each of `name`, `description`, `picture`, `tools` given/// replaces that part whole. A shipped kit is never changed in place: the/// change is saved as the person's copy at an id of its own, and answered.pub fn update_toolkit(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    personal_only(ctx)?;    let id = text(args, "id")?;    let existing = stored_kit(ctx, id)?.ok_or_else(|| fail(format!("no toolkit {id:?}; list_toolkits names them")))?;    let mut fields = Map::new();    if let Some(name) = args.get("name") {        let name = name.as_str().map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| fail("name is a non-empty string"))?;        fields.insert("name".into(), json!(name));    }    if let Some(tools) = args.get("tools") {        fields.insert("tools".into(), json!(kit_tools(ctx, tools, Some(&existing))?));    }    if let Some(description) = args.get("description") {        fields.insert("description".into(), description.clone());    }    if let Some(picture) = args.get("picture") {        fields.insert("picture".into(), kit_picture(ctx, picture)?);    }    if fields.is_empty() {        return Err(fail("say what to change: name, description, picture or tools"));    }    if existing.shipped || crate::toolkits::is_shipped_id(id) {        for (key, value) in [            ("name", json!(existing.name)),            ("description", json!(existing.description)),            ("picture", json!(existing.picture)),            ("tools", json!(existing.tools)),        ] {            fields.entry(key).or_insert(value);        }        let copy = fresh_kit_id(ctx, fields["name"].as_str().unwrap_or(&existing.name))?;        write_kit(ctx, &copy, fields, None)?;        return kit_answer(ctx, &copy);    }    write_kit(ctx, id, fields, Some(&existing))?;    kit_answer(ctx, id)}/// Delete a kit. A shipped kit deleted stays deleted: the launch seed never/// writes it again.pub fn delete_toolkit(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    personal_only(ctx)?;    let id = text(args, "id")?;    let existing = stored_kit(ctx, id)?.ok_or_else(|| fail(format!("no toolkit {id:?}; list_toolkits names them")))?;    ctx.writer()?.retract("cotton_toolkits", id, Retract::Verb("delete_toolkit"));    ctx.commit()?;    Ok(json!({ "deleted": existing.id, "name": existing.name }))}#[cfg(test)]mod failure_tests {    use super::*;    // RULE: A refusal accepts any Display value and preserves its formatted message.    #[test]    fn failure_formats_display_values() {        assert_eq!(fail(42).0, "42");        assert_eq!(            fail(format_args!("package {} is invalid", "lesson")).0,            "package lesson is invalid"        );    }}