//! `update_definition` — how a table's records look, written as data from a //! conversation: a built-in's too. The owner asked to change Devices' rows on //! the phone and could not; this is the write the stored-row read draws //! (`crate::definitions::resolve_table`). //! //! It takes only what changes how records LOOK — the slip, the tile, the //! page's sections, the page's style and parts, the picture — the list's //! acts and stacks, a shipped table's columns as its owner keeps them, and //! the instructions. Acts (`links`, `menu`) are the table's own, shown, //! hidden and reordered, never made; a stack keeps where the file keeps its //! groups; and `columns` is every shipped column exactly as shipped (only //! its look his — its engine reads it, so it is never removed or retyped) //! followed by the columns he added, keyed `own_…`, whose values //! `tables::own_values` keeps (`owner::on_shipped`). Everything else a read //! selects or a write reaches (the engine, commands, connections, actions) //! is refused by the fixed-key deny-list. Every present and future look //! key is accepted, then validated on the table. //! //! The owner's phone calls it too (`definitions.saveTable`), on his own //! database: the same write, the same rules. use cotton_core::definitions::owner::{on_shipped, Against}; use cotton_core::definitions::{builtin_table_definitions, leaf_edit_paths, writable_definition_key, TableDefinition, ToolPicture, BUILTIN_DEFINITIONS_HASH, BUILTIN_DEFINITIONS_STAMP}; use serde_json::{json, Map, Value}; use crate::definitions::{definition_rows, TABLE_DEFINITIONS}; use crate::mcp::dispatch::{Ctx, ToolResult}; use crate::mcp::handlers::common::{fail, insert_row, now_iso, update_row}; /// Keep the exact provenance and overlay before an engine updates a theme, /// so undo restores the row rather than composing a new default. pub(super) fn theme_beside(ctx: &Ctx<'_>, id: &str) -> super::Valid { use crate::mcp::{handlers::common::maybe_row, read_db::Query}; let row = maybe_row(ctx, &Query::on(crate::presentation::THEME_DEFINITIONS) .columns(&["definition", "builtin", "builtin_revision", "builtin_hash", "builtin_stamp", "created_at", "updated_at"]) .eq("id", id.to_string()))?; Ok(json!({"@theme_row":row}).as_object().unwrap().clone()) } /// History's inverse carries authored keys, never the resolved display's /// defaults. The beside image retains the exact row, including base_hash, /// for byte-for-byte undo; that bookkeeping is not an authored theme key. pub(super) fn carry_theme_override(beside: &super::Data, before: &mut super::Data) { if !before.contains_key("definition") { return; } let Some(mut raw) = beside.get("@theme_row") .and_then(|row| row.get("definition")) .and_then(Value::as_object) .cloned() else { return; }; raw.remove("base_hash"); before.insert("definition".into(), Value::from(Value::Object(raw).to_string())); } /// Keep the stored board and provenance, including absence, for exact undo. pub(super) fn board_beside(ctx: &Ctx<'_>, id: &str) -> super::Valid { use crate::mcp::{handlers::common::maybe_row, read_db::Query}; let row = maybe_row(ctx, &Query::on(crate::presentation::BOARD_DEFINITIONS) .columns(&["definition", "builtin", "builtin_revision", "builtin_hash", "builtin_stamp", "created_at", "updated_at"]) .eq("id", id.to_string()))?; Ok(json!({"@board_row":row}).as_object().unwrap().clone()) } pub fn update_definition(ctx: &mut Ctx<'_>, args: &Map) -> ToolResult { let table = args .get("table") .and_then(Value::as_str) .map(str::trim) .filter(|table| !table.is_empty()) .ok_or_else(|| crate::mcp::protocol::ToolFailure::new("table is required"))? .to_string(); if let Some(key) = args.keys().find(|key| *key != "table" && !writable_definition_key(key)) { return fail(format!("{key:?} cannot be changed here: column types, engines, commands, connections and table identity stay as the table defines them")); } let mut changed: Vec<&str> = args.keys().map(String::as_str).filter(|key| *key != "table").collect(); changed.sort_by_key(|key| *key != "columns"); // What the table draws today is where the edit starts — and, asked with // the table alone, the answer. let current = super::definition(ctx, &table)?; if changed.is_empty() { return Ok(json!({ "table": table, "definition": writable(¤t)? })); } let row = definition_rows(ctx, Some(&table))?.into_iter().next(); let builtin = row.as_ref().map_or(current.builtin, |row| row.builtin); // A kit table is this build's (its engine's columns are compiled in), so a // person edits it in place like any table here; an engine table the build // does not carry keeps its definition as its package wrote it. let carried = builtin_table_definitions().iter().any(|definition| definition.id == table); if !builtin && !carried && current.engine.is_some() { return fail(format!("table {table:?} is kept by an engine; its definition is not written here")); } // The leaves a person has edited ride every later write. Older rows named // their whole section; `leaf_edit_paths` turns those into the leaves that // actually differ from this build before the next revision carries them. let mut edited: Vec = row .as_ref() .and_then(|row| serde_json::from_str::(&row.definition).ok()) .and_then(|raw| raw.get("edited").cloned()) .and_then(|edited| serde_json::from_value(edited).ok()) .unwrap_or_default(); // Acts and stacks are taken onto what the build ships at this id (a // table a person defined: onto its own definition), refused for anything // it does not offer — an act is shown, hidden or reordered, never made. // A kit table's package row records its edits against the build's copy, // as a built-in's row does, so they ride on the compiled definition. let tracked = builtin || carried; let shipped = tracked .then(|| builtin_table_definitions().iter().find(|definition| definition.id == table)) .flatten(); let offered = shipped.unwrap_or(¤t); let before = writable(¤t)?; let mut merged = serde_json::to_value(¤t).map_err(|error| crate::mcp::protocol::ToolFailure::new(error.to_string()))?; { let object = merged.as_object_mut().expect("a definition is an object"); for key in &changed { let value = match on_shipped(offered, key, &args[*key], Against::Write) { Ok(value) => value, Err(reason) => return fail(format!("the definition is refused: {reason}")), }; match value { Value::Null => { object.remove(*key); } value => { object.insert((*key).to_string(), value); } } } } if tracked { let changed_roots: std::collections::BTreeSet<&str> = changed .iter() .copied() .filter(|key| *key != "instructions") .collect(); // A newly submitted section replaces every old leaf in that section. // Leaves in sections this request did not touch remain precise; old // whole-section markers are normalized against the current file. let mut paths: Vec = edited .iter() .filter(|path| { let root = path.split('.').next().unwrap_or_default(); !changed_roots.contains(root) }) .cloned() .collect(); paths.extend(changed_roots.iter().map(|root| (*root).to_string())); edited = leaf_edit_paths(offered, &merged, &paths); } let object = merged.as_object_mut().expect("a definition is an object"); if tracked && !edited.is_empty() { object.insert("edited".into(), json!(edited)); // The edits sit on this build's copy of the file; an upgrade reads // this to know which shipped copy they were made against. match cotton_core::definitions::format::shipped_hash(&format!("{table}.json")) { Some(hash) => object.insert("base_hash".into(), json!(hash)), None => object.remove("base_hash"), }; } else { object.remove("edited"); object.remove("base_hash"); } let edited: TableDefinition = serde_json::from_value(merged.clone()) .map_err(|error| crate::mcp::protocol::ToolFailure::new(format!("the definition does not read: {error}")))?; let mut visibility_tables=super::made_definitions(ctx)?; visibility_tables.retain(|t|t.id!=edited.id); visibility_tables.push(edited.clone()); cotton_core::definitions::visibility::validate_tables(&visibility_tables).map_err(crate::mcp::protocol::ToolFailure::new)?; if let Err(error) = edited.validate_import() { return fail(format!("the definition is refused: {error}")); } // Changing a column must preserve the rules and capacity binding of its installed package. if changed.contains(&"columns") { for tool in super::super::tool_packages::live_tool_definitions(ctx)? .into_iter().filter(|tool| tool.tables.contains(&table)) { let tables = tool.tables.iter().map(|id| { if id == &table { Ok(edited.clone()) } else { super::definition(ctx, id) } }).collect::>>()?; cotton_core::definitions::automations::validate_tables(&tool, &tables) .map_err(crate::mcp::protocol::ToolFailure::new)?; } } // A word this build cannot draw is a newer device's, kept as it came on // the keys this write leaves alone; one this write sets is refused. let unnamed: Vec<&String> = edited .fallbacks .iter() .filter(|path| changed.iter().any(|key| path.split('.').next() == Some(*key))) .collect(); if !unnamed.is_empty() { return fail(format!("the definition is refused: {} names a word this build does not draw", unnamed.iter().map(|path| path.as_str()).collect::>().join(", "))); } // Resetting uses the build's own offline picture, even before its photo // seed has run in this database. A chosen picture must be held here. if changed.contains(&"picture") && !(shipped.is_some() && args["picture"].is_null()) { picture_held(ctx, edited.picture.as_ref())?; } // The keys a built-in draws from its row are exactly the ones written here, // less the instructions, which its row has always lent. let mut patch = Map::new(); patch.insert("id".into(), Value::from(table.clone())); patch.insert("definition".into(), merged); if builtin { // At this build's revision, so the seed leaves it and every read draws it. 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 changed.contains(&"instructions") { patch.insert("instructions_edited".into(), Value::Bool(true)); } match row { Some(_) => { patch.insert("updated_at".into(), Value::from(now_iso(ctx))); update_row(ctx, TABLE_DEFINITIONS, &table, patch)?; } None => insert_row(ctx, TABLE_DEFINITIONS, &table, patch)?, } // A handler commits its own writes: the transport mints nothing after it. ctx.commit()?; // `before` is what each changed key drew until now — the write that // takes this one back (the phone's Undo). let before: Map = changed.iter().map(|key| ((*key).to_string(), before.get(*key).cloned().unwrap_or(Value::Null))).collect(); Ok(json!({ "table": table, "changed": changed, "before": before, "definition": writable(&edited)? })) } /// A picture set from a conversation draws: a `{"photo": …}` names a photo /// record this database holds, and an `object` is one a built-in ships, with /// that object's own photo — so a card never names bytes no device has. pub(crate) fn picture_held(ctx: &Ctx<'_>, picture: Option<&ToolPicture>) -> Result<(), crate::mcp::protocol::ToolFailure> { let Some(ToolPicture::Photo(picture)) = picture else { return Ok(()) }; if let Some(object) = &picture.object { let shipped = builtin_table_definitions().into_iter().any(|definition| { matches!(&definition.picture, Some(ToolPicture::Photo(theirs)) if theirs.object.as_ref() == Some(object) && theirs.photo == picture.photo) }); if !shipped { return Err(crate::mcp::protocol::ToolFailure::new(format!( "{object:?} with {:?} is no object this build ships; name a built-in's picture as it stands, or a photo alone", picture.photo ))); } } let held = ctx .db() .get( "SELECT id FROM cotton_photos WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[rusqlite::types::Value::Text(ctx.workspace_id.to_string()), rusqlite::types::Value::Text(picture.photo.clone())], ) .map_err(|error| crate::mcp::protocol::ToolFailure::new(error.to_string()))? .is_some(); if held { Ok(()) } else { Err(crate::mcp::protocol::ToolFailure::new(format!( "{:?} is not a photo in this database; list_photos names the ones there are", picture.photo ))) } } /// The keys this tool writes, as `definition` draws them. fn writable(definition: &TableDefinition) -> Result { let all = serde_json::to_value(definition).map_err(|error| crate::mcp::protocol::ToolFailure::new(error.to_string()))?; Ok(Value::Object( all.as_object().expect("a definition is an object").iter().filter(|(key, _)| writable_definition_key(key)).map(|(key, value)| (key.clone(), value.clone())).collect(), )) }