//! A database's tools and its Home, read and written in one place — for the//! phone (`cotton-ffi`'s `read.home`, `read.toolOrder`),//! for an assistant asked to "put Memory on Home" (`arrange_tools`) and for//! Add tool and Remove tool. The rules are//! `cotton_core::rules::home_arrangement`'s; this is where they meet the file://! which tools are installed, which views still exist, and what a tool holds.use cotton_core::rules::home_arrangement::{ home_views, mark_empty, tool_view, view_tool, HomeArrangement, HomeTile, EVERYTHING_VIEW,};use cotton_core::rules::project_page::{ default_order, section_title, section_tool, section_view, section_wears, view_section,};use cotton_core::definitions::ToolDefinition;use cotton_store::driver::{Driver, Row};use rusqlite::types::ValueasSqlValue;use serde_json::{Map, Value};use std::collections::HashSet;usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::common::{insert_row, update_row};usecrate::mcp::handlers::projects::sections::project_sections;usecrate::mcp::protocol::ToolFailure;/// The one row per workspace.pubconst HOME_ARRANGEMENT: &str = "cotton_home_arrangement";fn param(value: &str) -> SqlValue {SqlValue::Text(value.to_string())}fn rows_of(db: &Driver, sql: &str, params: &[SqlValue]) -> Result<Vec<Row>, String> { db.all(sql, params).map_err(|error| error.to_string())}fn owned(row: &Row, column: &str) -> Option<String> { row.text(column).map(str::to_string)}/// Does this database hold the tool `key`? A tool is in a database only by a/// row of its own (72nd amendment, 21 Oct 2026: no tool is built in).pubfn tool_held(db: &Driver, workspace_id: &str, key: &str) -> Result<bool, String> {Ok(db .get("SELECT id FROM cotton_tool_definitions WHERE workspace_id = ? AND id = ?", &[param(workspace_id), param(key)], ) .map_err(|error| error.to_string())? .is_some())}/// The tools installed in this database (`cotton_tool_definitions` ids).pubfn installed(db: &Driver, workspace_id: &str) -> Result<Vec<String>, String> {Ok(rows_of( db,"SELECT id FROM cotton_tool_definitions WHERE workspace_id = ? ORDER BY id", &[param(workspace_id)], )? .iter() .filter_map(|row| owned(row, "id")) .collect())}/// The database's tools, alphabetical by name: exactly the tools it holds by a/// row of its own (`cotton_tool_definitions`), in every database — no tool is/// built in (72nd amendment, tools are records only). `manual` and `personal`/// change nothing about which tools there are./// The shell's own tool on Home: the Bin every delete goes to. Its tile is on/// Home by default and comes off like any tile (a delete's receipt follows/// it, `receipt::binned_said`); it is no package, so no tool row names it.pubconst SHELL_BIN: &str = "bin";pubfn tools(db: &Driver, workspace_id: &str, _manual: Option<&HomeArrangement>, _personal: bool) -> Result<Vec<String>, String> { tools_named(db, workspace_id, &tool_names(&installed_definitions(db, workspace_id)?))}/// [`tools`], the installed tools' names already read.fn tools_named(db: &Driver, workspace_id: &str, names: &[(String, String)]) -> Result<Vec<String>, String> {letmut installed = installed(db, workspace_id)?;if !installed.iter().any(|key| key == SHELL_BIN) { installed.push(SHELL_BIN.to_string()); }Ok(cotton_core::rules::home_arrangement::installed_tools(&installed, |key| tool_name(names, key)))}/// The installed tools' definitions, parsed from their rows once per read: a/// Home read hands this one list to every step (its tools, their names, the/// catalogue) instead of parsing the rows again at each.fn installed_definitions(db: &Driver, workspace_id: &str) -> Result<Vec<ToolDefinition>, String> {Ok(crate::definitions::tool_definitions_from_driver(db, workspace_id) .map_err(|failure| failure.to_string())? .definitions)}/// Each installed tool's name, by id, from its own definition.fn tool_names(installed: &[ToolDefinition]) -> Vec<(String, String)> { installed.iter().map(|tool| (tool.id.clone(), tool.name.clone())).collect()}/// The name a tool's tile is drawn with: its own definition's, else its key.fn tool_name(installed: &[(String, String)], key: &str) -> String { installed .iter() .find(|(id, _)| id == key) .map_or_else(|| if key == SHELL_BIN { "Bin".to_string() } else { key.to_string() }, |(_, name)| name.clone())}/// One view a tile can point at (owner's ruling, 12 Oct 2026: a tile points/// at any view of its tool): a tool's list, one of its tables' own list for a/// tool of several (`<tool>/<table>`), one of its tables' shipped views/// (`ready/today`) or charts (`chart/mood`), a group of one of its tables/// (`<table>/<groupId>`), or Everything, which is no tool's.#[derive(Debug, Clone, PartialEq, Eq)]pubstructHomeView {pub view: String,/// The tool it belongs to — whose picture its tile wears; `None` for Everything.pub tool: Option<String>,/// Its own name ("Today", a group's name); `None` for a tool's list and/// Everything, which the app names.pub name: Option<String>,/// The app path its tile opens, when the view's definition names one/// (`ShippedView::opens`); `None` opens the tool, or the group's list.pub opens: Option<String>,/// The table whose list the tile opens, for a table of a tool with/// several (`<tool>/<table>`, architect 14 Oct 2026: any table of a tool/// can be a tile of its own). Said rather than parsed: the view id has a/// group's shape (`<table>/<groupId>`), and only this field tells them apart.pub table: Option<String>,/// A group the person made: something to show while it exists.pub group: bool,/// A project's section (`project/<section>/<slug>`): whether it holds/// anything now. `None` for every other view.pub holds: Option<bool>,}/// A database's tools and its Home, read once.#[derive(Debug, Clone, PartialEq, Eq)]pubstructHome {/// The database's tools, alphabetical by name.pub tools: Vec<String>,/// Every view Home can show here, by tool in the tools' order, then/// Everything ([`catalogue`]) — on Home or not.pub offered: Vec<HomeView>,/// Home's view ids, alphabetical by the name each tile is drawn with —/// what a write starts from. Membership is the person's; order never is.pub views: Vec<String>,/// Home's tiles in the order they are drawn — the same alphabet, an/// empty one faint in its place.pub tiles: Vec<HomeTile>,}implHome {/// Is this tile on Home?pubfn shows(&self, view: &str) -> bool {self.tiles.iter().any(|tile| tile.id == view) }/// What Home knows of a view it can show.pubfn view(&self, view: &str) -> Option<&HomeView> {self.offered.iter().find(|offered| offered.view == view) }}/// The database's tools and its Home, the faint rule applied.pubfn home(db: &Driver, workspace_id: &str, manual: Option<&HomeArrangement>, personal: bool) -> Result<Home, String> {let installed = installed_definitions(db, workspace_id)?;let names = tool_names(&installed);let tools = tools_named(db, workspace_id, &names)?;let named = manual.map_or(&[][..], |row| row.view_ids.as_slice());let offered = catalogue_of(db, workspace_id, &installed, &tools, named)?;let arriving: Vec<String> = offered .iter() .filter(|offered| offered.holds == Some(true)) .map(|offered| offered.view.clone()) .collect();letmut failure: Option<String> = None;// The alphabet's name of a tile: its own (a group's, a shipped view's, a// section's), else its tool's, else Everything.let tile_name = |view: &str| -> String {let known = offered.iter().find(|offered| offered.view == view);ifletSome(name) = known.and_then(|known| known.name.clone()) {return name; }if view == EVERYTHING_VIEW {return"Everything".to_string(); }match known.and_then(|known| known.tool.as_deref()).or_else(|| view_tool(view)) {Some(key) => tool_name(&names, key),None => view.to_string(), } };let views = home_views(manual, &tools, personal, &arriving, |view| offered.iter().any(|offered| offered.view == view), tile_name);letmut held: Vec<(String, bool)> = Vec::new();letmut holds = |key: &str| -> bool {ifletSome((_, answer)) = held.iter().find(|(tool, _)| tool == key) {return *answer; }let answer = match holds_records(db, workspace_id, key) {Ok(answer) => answer,Err(error) => { failure.get_or_insert(error);false } }; held.push((key.to_string(), answer)); answer };let tiles = mark_empty(views.clone(), |view| {if view == EVERYTHING_VIEW {return tools.iter().any(|key| holds(key)); }match offered.iter().find(|offered| offered.view == view) {// A group the person put on Home: something to show while it exists.Some(HomeView { group: true, .. }) => true,// A project's section: while it holds something.Some(HomeView { holds: Some(holds), .. }) => *holds,// A tool's list, or a view of its tables: what the tool holds.Some(HomeView { tool: Some(key), .. }) => holds(key), _ => view_tool(view).is_some_and(&mut holds), } });match failure {Some(error) => Err(error),None => Ok(Home { tools, offered, views, tiles }), }}/// One view a table ships that Home offers: a shipped view as `ready/<face>`,/// a table's chart as `chart/<table>`.#[derive(Debug, Clone, PartialEq, Eq)]pubstructTableView {pub view: String,/// What the catalogue calls it ("Today", "Payments by week").pub name: String,/// The table it reads.pub table: String,}/// The views this database's tables ship ([`TableView`]): every built-in/// table's shipped view in its faces' order, then the chart of each table a/// tool here holds — a built-in's or a kit's — in the order the tables are/// defined.pubfn table_views( tools: &[ToolDefinition], tables: &crate::definitions::Definitions<cotton_core::definitions::TableDefinition>,) -> Vec<TableView> {letmut ready = Vec::new();for definition in cotton_core::definitions::builtin_table_definitions() {// A chart is offered per table that holds one, below.for view in definition.views.iter().flatten().filter(|view| view.chart.is_none()) {let shipped = TableView { view: format!("ready/{}", view.face.as_str()), name: view.name.clone(), table: definition.id.clone() }; ready.push((view.face, shipped)); } } ready.sort_by_key(|(face, _)| *face);let held: HashSet<&str> = tools.iter().flat_map(|tool| tool.tables.iter().map(String::as_str)).collect();letmut views: Vec<TableView> = ready.into_iter().map(|(_, view)| view).collect();for table in tables.definitions.iter().filter(|table| held.contains(table.id.as_str())) {for view in table.views.iter().flatten().filter(|view| view.chart.is_some()) { views.push(TableView { view: format!("chart/{}", table.id), name: view.name.clone(), table: table.id.clone() }); } } views}/// [`table_views`] of the database a file holds, its definitions read from it.pubfn database_table_views(db: &Driver, workspace_id: &str) -> Result<Vec<TableView>, String> {let tools = crate::definitions::tool_definitions_from_driver(db, workspace_id) .map_err(|failure| failure.to_string())? .definitions;let tables = crate::definitions::shared_table_definitions_from_driver(db, workspace_id) .map_err(|failure| failure.to_string())?;Ok(table_views(&tools, &tables))}/// Every view Home can show in this database, grouped by tool in the tools'/// order — each tool's list, then each of its tables' own list when it has/// several, then its tables' shipped views and charts ([`table_views`]), then/// the groups made of its tables — then each active project's sections no tool here covers/// ([`project_section_views`]), and Everything last. A view two tools' tables/// share is its home tool's (the tool its definition names) when that tool is/// here, else the first tool's. `named` is Home as the person's row has it: a/// section on Home stays offered while it is empty, drawn faint.pubfn catalogue(db: &Driver, workspace_id: &str, tools: &[String], named: &[String]) -> Result<Vec<HomeView>, String> { catalogue_of(db, workspace_id, &installed_definitions(db, workspace_id)?, tools, named)}/// [`catalogue`], the installed tools' definitions already read.fn catalogue_of(db: &Driver, workspace_id: &str, installed: &[ToolDefinition], tools: &[String], named: &[String]) -> Result<Vec<HomeView>, String> {let defined = crate::definitions::shared_table_definitions_from_driver(db, workspace_id) .map_err(|failure| failure.to_string())?;let views = table_views(installed, &defined);let groups: Vec<(String, String, String)> =crate::mcp::handlers::tables::groups::live_groups(db, Some(workspace_id))? .into_iter() .filter_map(|(id, data)| {let table = data.get("table")?.as_str()?.to_string();let name = data.get("name").and_then(Value::as_str).unwrap_or_default().to_string();Some((id, table, name)) }) .collect();letmut out: Vec<HomeView> = Vec::new();let push = |out: &mutVec<HomeView>, view: HomeView| {if !out.iter().any(|known| known.view == view.view) { out.push(view); } };for key in tools {let tables = installed .iter() .find(|tool| &tool.id == key) .map(|tool| tool.tables.clone()) .unwrap_or_default(); push(&mut out, HomeView { view: tool_view(key), tool: Some(key.clone()), name: None, opens: None, table: None, group: false, holds: None });// A tool of several tables is a board of tiles, one per table, and// each table can stand on Home as its own (architect, 14 Oct 2026):// `<tool>/<table>`, named by the table, opening its list. A tool of// one table is that table's tile already.if tables.len() > 1 {for table in &tables {let name = defined.definitions.iter().find(|definition| &definition.id == table).map(|definition| definition.plural.clone());letSome(name) = name else { continue }; push(&mut out, HomeView { view: table_view(key, table), tool: Some(key.clone()), name: Some(name), opens: None, table: Some(table.clone()), group: false, holds: None, }); } }// A table's shipped views and chart are its home tool's (the tool its// definition names) when that tool is here, so a tool that only writes// a table — Meetings adding todos — never takes Todos' Today.let home_elsewhere = |table: &str| { defined .definitions .iter() .find(|definition| definition.id == table) .and_then(|definition| definition.tool.as_ref()?.key.as_deref()) .is_some_and(|home| home != key && tools.iter().any(|tool| tool == home)) };for offer in views.iter().filter(|offer| tables.contains(&offer.table) && !home_elsewhere(&offer.table)) {letSome(face) = offer.view.strip_prefix("ready/").or(offer.view.strip_prefix("chart/").map(|_| "chart")) else {continue; };let opens = defined .definitions .iter() .find(|table| table.id == offer.table) .and_then(|table| table.views.iter().flatten().find(|view| view.face.as_str() == face)) .and_then(|view| view.opens.clone()); push(&mut out, HomeView { view: offer.view.clone(), tool: Some(key.clone()), name: Some(offer.name.clone()), opens, table: None, group: false, holds: None, }); }for (id, table, name) in groups.iter().filter(|(_, table, _)| tables.contains(table) && !home_elsewhere(table)) { push(&mut out, HomeView { view: format!("{table}/{id}"), tool: Some(key.clone()), name: Some(name.clone()), opens: None, table: None, group: true, holds: None, }); } }for view in project_section_views(db, workspace_id, tools, named)? { push(&mut out, view); } push(&mut out, HomeView { view: EVERYTHING_VIEW.to_string(), tool: None, name: None, opens: None, table: None, group: false, holds: None });Ok(out)}/// A table's own view on Home: `<tool>/<table>`.pubfn table_view(tool: &str, table: &str) -> String { format!("{tool}/{table}")}/// The database page is Home (architect, 13 Oct 2026), so what a project's/// sections held are tiles in its project database: for each active project/// in that database, every section that holds something and that no tool covers/// (`project_page::section_tool` — a covered section is that tool's list), as/// the view `project/<section>/<slug>`, wearing a shipped tool's photograph/// (`section_wears`). A section named on Home (`named`) stays offered while/// empty, so its tile turns faint rather than vanishing. Personal holds the/// project directory for switching databases; those entries never offer tiles/// on Personal Home, even if an older arrangement still names one.pubfn project_section_views( db: &Driver, workspace_id: &str, tools: &[String], named: &[String],) -> Result<Vec<HomeView>, String> {if cotton_store::link_rule::file_kind(db).map_err(|error| error.to_string())? != cotton_store::link_rule::FileKind::Shared {returnOk(Vec::new()); }let projects = rows_of( db,"SELECT id, slug, name FROM cotton_memory_projects WHERE workspace_id = ? AND status = 'active' \ ORDER BY created_at, id", &[param(workspace_id)], )?;let several = projects.len() > 1;letmut out = Vec::new();for project in &projects {let (Some(id), Some(slug)) = (owned(project, "id"), owned(project, "slug")) else { continue };let present = project_sections(db, workspace_id, &id) .map_err(|failure| failure.to_string())? .unwrap_or_default();for section in default_order() {if section_tool(section).is_some_and(|tool| tools.iter().any(|held| held == tool)) {continue; }let view = section_view(section, &slug);let holds = present.iter().any(|shown| shown.section == section);if !holds && !named.contains(&view) {continue; }let title = section_title(section);let name = match owned(project, "name").filter(|_| several) {Some(project) => format!("{project} · {title}"),None => title.to_string(), }; out.push(HomeView { view, tool: Some(section_wears(section).to_string()), name: Some(name), opens: None, table: None, group: false, holds: Some(holds), }); } }Ok(out)}/// Add a tile leaves out tools already represented on Home (architect,/// 16 Oct 2026). Project sections remain individual offers: wearing a/// tool's picture does not make a project's section that tool's own tile.pubfn offers(home: &Home) -> Vec<&HomeView> {let shown: HashSet<&str> = home.views.iter().map(String::as_str).collect();let placed: HashSet<&str> = home.offered.iter() .filter(|offered| shown.contains(offered.view.as_str()) && view_section(&offered.view).is_none()) .filter_map(|offered| offered.tool.as_deref()) .collect(); home.offered.iter().filter(|offered| { !shown.contains(offered.view.as_str()) && (view_section(&offered.view).is_some() || offered.tool.as_deref().is_none_or(|tool| !placed.contains(tool))) }).collect()}/// Does this tool hold a record — any row of a table its definition names?/// What draws its tile in colour (owner's ruling, 12 Oct 2026). A tool that/// is no row here holds nothing.pubfn holds_records(db: &Driver, workspace_id: &str, key: &str) -> Result<bool, String> {letSome(definition) = rows_of( db,"SELECT definition FROM cotton_tool_definitions WHERE workspace_id = ? AND id = ?", &[param(workspace_id), param(key)], )? .first() .and_then(|row| owned(row, "definition")) else {returnOk(false); };let definition: Value = serde_json::from_str(&definition) .map_err(|error| format!("cotton_tool_definitions.definition of {key} is not JSON: {error}"))?;for table in definition["tables"].as_array().into_iter().flatten() {letSome(table) = table.as_str() else { continue };// A made table's records are rows of its own table; a name that is// no table id never reaches SQL, and a table this file does not hold// yet holds nothing.if !cotton_core::definitions::is_valid_id(table) {continue; }// A table whose schema is code keeps its rows in its compiled store// table, binned rows included.ifletSome(store) = cotton_core::definitions::builtin_store_table(table) {if has_table(db, store)? && any_row(db, workspace_id, store, "")? {returnOk(true); }continue; }let store = crate::mcp::handlers::tables::made_table(table);if !has_table(db, &store)? {continue; }let found = rows_of( db, &format!("SELECT 1 AS n FROM {store} WHERE workspace_id = ? AND deleted_at IS NULL LIMIT 1"), &[param(workspace_id)], )?;if !found.is_empty() {returnOk(true); } }Ok(false)}/// Is there a row of `table` in this workspace matching `predicate`?fn any_row(db: &Driver, workspace_id: &str, table: &str, predicate: &str) -> Result<bool, String> {let index = crate::mcp::read_db::indexed_by_predicate(table, predicate);letmut sql = format!("SELECT 1 AS n FROM {table}{index} WHERE 1 = 1");letmut params = Vec::new();if has_column(db, table, "workspace_id")? { sql.push_str(" AND workspace_id = ?"); params.push(param(workspace_id)); }if !predicate.is_empty() { sql.push_str(&format!(" AND {predicate}")); } sql.push_str(" LIMIT 1");Ok(!rows_of(db, &sql, ¶ms)?.is_empty())}/// Does this table carry this column? Asked of the FILE, never remembered.fn has_table(db: &Driver, table: &str) -> Result<bool, String> {Ok(!rows_of(db, "SELECT 1 AS n FROM sqlite_master WHERE type = 'table' AND name = ?", &[param(table)])?.is_empty())}fn has_column(db: &Driver, table: &str, column: &str) -> Result<bool, String> {Ok(!rows_of( db,"SELECT name FROM pragma_table_info(?) WHERE name = ?", &[param(table), param(column)], )? .is_empty())}/// A tool joins this database: one of its tools, its list on Home at the end./// Written whole, from what the database holds now.pubfn join(ctx: &mutCtx<'_>, key: &str, personal: bool) -> Result<(), ToolFailure> {let workspace_id = ctx.workspace_id.to_string();let manual = stored(ctx.db(), &workspace_id).map_err(ToolFailure::new)?;let now = home(ctx.db(), &workspace_id, manual.as_ref(), personal).map_err(ToolFailure::new)?;letmut tools = now.tools.clone();if !tools.iter().any(|tool| tool == key) { tools.push(key.to_string()); }letmut view_ids = now.views;let view = tool_view(key);if !view_ids.contains(&view) { view_ids.push(view); }let project_slugs = manual.map(|row| row.project_slugs).unwrap_or_default(); save(ctx, &HomeArrangement { project_slugs, tools, view_ids }).map(drop)}/// A tool leaves this database: no longer one of its tools, and every tile of/// its views off Home. The caller has refused a tool that holds records.pubfn leave(ctx: &mutCtx<'_>, key: &str, personal: bool) -> Result<(), ToolFailure> {let workspace_id = ctx.workspace_id.to_string();let manual = stored(ctx.db(), &workspace_id).map_err(ToolFailure::new)?;let now = home(ctx.db(), &workspace_id, manual.as_ref(), personal).map_err(ToolFailure::new)?;let tools: Vec<String> = now.tools.iter().filter(|tool| *tool != key).cloned().collect();// Every view the tool owns goes with it — its list, its tables' own// tiles, their charts and shipped views, their groups — not only// `tool/<key>`: a table tile left behind would point at nothing.let view_ids: Vec<String> = now .views .iter() .filter(|view| view_tool(view) != Some(key) && now.view(view).and_then(|known| known.tool.as_deref()) != Some(key)) .cloned() .collect();let project_slugs = manual.map(|row| row.project_slugs).unwrap_or_default(); save(ctx, &HomeArrangement { project_slugs, tools, view_ids }).map(drop)}/// What the person keeps on Home, or `None` when they have never arranged it.////// Read by the phone's Home and Tools screens and `arrange_tools`, which/// orders the same band and must not come to hold a second opinion about what/// the row says.////// A row this build cannot parse is refused LOUDLY rather than read as "no/// arrangement" — a silent fallback there would answer the default order and/// the next Done would overwrite the person's real one/// ([prefer-root-cause-fixes-no-silent-fallbacks]).pubfn stored( db: &Driver, workspace_id: &str,) -> Result<Option<HomeArrangement>, String> {letSome(row) = db .get("SELECT project_slugs, tools, view_ids FROM cotton_home_arrangement WHERE workspace_id = ?", &[param(workspace_id)], ) .map_err(|error| error.to_string())?else {returnOk(None); };let list = |column: &str| -> Result<Vec<String>, String> {let raw = row.text(column).unwrap_or("[]"); serde_json::from_str::<Vec<String>>(raw).map_err(|error| { format!("cotton_home_arrangement.{column} is not a list of strings: {error}") }) };Ok(Some(HomeArrangement { project_slugs: list("project_slugs")?, tools: list("tools")?, view_ids: list("view_ids")?, }))}/// Store an arrangement — ONE row per workspace, keyed by the workspace,/// created on the first write and replaced on every one after it. What is/// handed over is stored unfiltered: the rules are the read's/// (`cotton_core::rules::home_arrangement`), but for the project sections Home/// has now been shown, which join `tools` — the row as stored is the answer,/// and what a caller reads Home back from.pubfn save(ctx: &mutCtx<'_>, record: &HomeArrangement) -> Result<HomeArrangement, ToolFailure> {let workspace_id = ctx.workspace_id.to_string();let existing = ctx .db() .get( &format!("SELECT workspace_id FROM {HOME_ARRANGEMENT} WHERE workspace_id = ?"), &[param(&workspace_id)], ) .map_err(|error| ToolFailure::new(error.to_string()))?;// The set Home has been shown names the project sections it offers now,// so one the person took off stays off ([`home_views`]'s `arriving`).letmut shown = record.tools.clone();let before = stored(ctx.db(), &workspace_id).map_err(ToolFailure::new)?;for view in before.iter().flat_map(|row| row.tools.iter()) {if view_section(view).is_some() && !shown.contains(view) { shown.push(view.clone()); } }for view in project_section_views(ctx.db(), &workspace_id, &record.tools, &record.view_ids).map_err(ToolFailure::new)? {if view.holds == Some(true) && !shown.contains(&view.view) { shown.push(view.view); } }letmut patch = Map::new(); patch.insert("project_slugs".into(), Value::from(record.project_slugs.clone())); patch.insert("tools".into(), Value::from(shown.clone())); patch.insert("view_ids".into(), Value::from(record.view_ids.clone()));match existing {Some(_) => update_row(ctx, HOME_ARRANGEMENT, &workspace_id, patch)?,None => insert_row(ctx, HOME_ARRANGEMENT, &workspace_id, patch)?, }Ok(HomeArrangement { tools: shown, ..record.clone() })}/// Optional business tables require their package; People is part of the core.pubfn require_table(db: &Driver, workspace: &str, table: &str) -> Result<(), String> {if !cotton_core::flavor::single_database() { returnOk(()); }let store = cotton_core::definitions::builtin_store_table(table).unwrap_or(table);// Customer identity and every package person link use the core People table.if store == "cotton_people" { returnOk(()); }let key = cotton_core::definitions::builtin_table_definition(table) .and_then(|d| d.tool.as_ref()).and_then(|tool| tool.key.as_deref()) .or_else(|| {let name = cotton_core::rules::home_arrangement::tool_of_store_table(store)?; cotton_core::definitions::builtin_table_definitions().iter() .filter_map(|definition| definition.tool.as_ref()) .find(|tool| tool.name == name).and_then(|tool| tool.key.as_deref()) });ifletSome(key) = key {if !tool_held(db, workspace, key)? { returnErr(format!("no such tool here: {key}")); } }Ok(())}