//! Toolkits: the starter kits a database is made from. A kit is a row of the//! personal database (`cotton_toolkits`) — its tools, each a built-in key or//! a tool package carried inline; this module holds that row's form and the//! kits this build seeds (`toolkits/shipped.json`).usecrate::definitions::{TableDefinition, ToolDefinition, ToolPicture};use serde::{Deserialize, Serialize};/// One entry of a kit row's `tools` (`cotton_toolkits.tools`): the id of a/// kit tool (`crate::kit`), installed from the kit's package, or a tool/// package carried inline. No tool is built in (72nd amendment).#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]#[serde(untagged)]pubenumKitTool {Kit(String),Package { package: KitPackage },}implKitTool {/// The key the database's Home arranges it by: the kit tool's id, or the/// carried tool's id.pubfn key(&self) -> &str {matchself {KitTool::Kit(key) => key,KitTool::Package { package } => &package.tool.id, } }}/// A tool package as a kit carries it: the parsed `.cottontool` — its tool,/// the tables it works with and its sample rows. Its pictures are photo/// records in the personal database, named by the tool's `picture`.#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]pubstructKitPackage { #[serde(default, skip_serializing_if = "Option::is_none")]pub board: Option<crate::definitions::board::BoardDefinition>,pub tool: ToolDefinition,pub tables: Vec<TableDefinition>,/// Sample rows by table id, made only when `with_samples` says so. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]pub samples: std::collections::BTreeMap<String, Vec<serde_json::Value>>, #[serde(default)]pub with_samples: bool,/// The package's carried pictures, by their name beneath `pictures/`, as/// standard base64 — the form its asset record keeps them in. A shipped/// kit's pictures ship in the build, so it carries none. #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]pub pictures: std::collections::BTreeMap<String, String>,}/// One `cotton_toolkits` row as this build seeds it.#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]pubstructShippedToolkit {pub id: String,pub name: String,pub description: Option<String>,pub picture: Option<ToolPicture>,pub tools: Vec<KitTool>,pub position: i64,}/// The kits this build ships, as the rows the launch seed writes into the/// personal database (`toolkits/shipped.json`, in the row form the/// `cotton_toolkits` table keeps): from then on a kit is that database's/// data, and this file is only where a new database's first rows come from.pubfn shipped() -> Vec<ShippedToolkit> { shipped_kits().to_vec()}/// [`shipped`], parsed once per process and shared: an install asks for the/// shipped packages once per table it checks (copy-installer-cpu, 7 Nov 2026).pubfn shipped_kits() -> &'static [ShippedToolkit] {static PARSED: std::sync::OnceLock<Vec<ShippedToolkit>> = std::sync::OnceLock::new(); PARSED.get_or_init(parse_shipped)}fn parse_shipped() -> Vec<ShippedToolkit> {letmut kits: serde_json::Value = serde_json::from_str(include_str!("../toolkits/shipped.json")).expect("validated shipped toolkits");for tool in kits.as_array_mut().into_iter().flatten().flat_map(|kit| kit["tools"].as_array_mut().into_iter().flatten()) {ifletSome(id) = tool.get("package").and_then(serde_json::Value::as_str) { *tool = serde_json::json!({"package": shipped_package(id)}); } } serde_json::from_value(kits).expect("validated shipped toolkits")}// A package a kit names by id (`{"package": "yoga"}`) ships as files in its// app's kit (`kits/<app>/`): its tool's manifest (`tools/<id>/manifest.json`)// and one definition file per table it names (`tables/<id>.json`), so a// business's package is written and read as data like every other definition// rather than inline in the kit. build.rs compiles every kit but the personal// one and the shell into `SHIPPED_PACKAGES`, in each kit.json's order.include!(concat!(env!("OUT_DIR"), "/kit_packages.rs"));fn shipped_package(id: &str) -> serde_json::Value {let (_, tool, tables) = SHIPPED_PACKAGES .iter() .find(|(shipped, _, _)| *shipped == id) .unwrap_or_else(|| panic!("a kit names package {id:?}, which ships no files"));let parse = |text: &str| serde_json::from_str::<serde_json::Value>(text).expect("shipped package file"); serde_json::json!({"tool": parse(tool), "tables": tables.iter().map(|t| parse(t)).collect::<Vec<_>>()})}/// Every tool a shipped kit carries as a package, once each, in kit order —/// what `add_tool` installs on purpose into any database (a kit tool shipped/// in two kits is the same tool, so the first carries it).pubfn shipped_kit_tools() -> Vec<KitPackage> { kit_packages().to_vec()}/// [`shipped_kit_tools`], built once per process and shared.pubfn kit_packages() -> &'static [KitPackage] {static PACKAGES: std::sync::OnceLock<Vec<KitPackage>> = std::sync::OnceLock::new(); PACKAGES.get_or_init(|| {letmut seen = std::collections::BTreeSet::new(); shipped_kits() .iter() .flat_map(|kit| kit.tools.iter()) .filter_map(|tool| match tool {KitTool::Package { package } => Some(package.clone()),KitTool::Kit(_) => None, }) .filter(|package| seen.insert(package.tool.id.clone())) .collect() })}#[cfg(test)]mod tests {usesuper::*;// RULE: Business reservation picks carry their own labels; other acts keep the scalar pick contract, so adding quantity never changes cash or renewal calls. #[test]fn business_quantity_picks_keep_labels_and_other_acts_scalar() {for package in shipped_kit_tools().into_iter().filter(|package| matches!(package.tool.id.as_str(), "yoga" | "kitchen")) {for table in &package.tables {for act in table.acts.iter().flatten() {if act.verb.as_deref() == Some("reserve_record") { assert!(act.pick.is_none());let picks = act.picks.as_ref().expect("reservation asks in order");for pick in picks { assert!(pick.label.as_ref().is_some_and(|label| !label.trim().is_empty()),"{}.{} needs definition words for {}", table.id, act.id, pick.argument); }// The shared core gives the renderer exactly the definition's// labels, including when an author changes the wording.letmut edited = act.clone(); edited.picks.as_mut().unwrap()[0].label = Some("Synthetic author's question".into());let decoded: crate::definitions::RecordCommand = serde_json::from_value(serde_json::to_value(&edited).unwrap()).unwrap(); assert_eq!(decoded.ordered_picks(), edited.picks.as_ref().unwrap()); } else { assert!(act.picks.is_none(), "{}.{} keeps its scalar contract", table.id, act.id);ifletSome(pick) = &act.pick { assert_eq!(act.ordered_picks(), std::slice::from_ref(pick)); } } } } } }fn packages(kit: &ShippedToolkit) -> implIterator<Item = &KitPackage> { kit.tools.iter().filter_map(|tool| match tool {KitTool::Package { package } => Some(package),KitTool::Kit(_) => None, }) }/// RULE: Every kit tool photo reference resolves to an asset shipped by the build, so installing any kit cannot leave a dangling picture. #[test]fn the_shipped_kit_tools_name_pictures_the_build_ships() {usecrate::definitions::pictures::BUILTIN_TOOL_PICTURES;for kit in shipped() {for package in packages(&kit) {letSome(ToolPicture::Photo(picture)) = &package.tool.picture else { continue };let sha = picture.photo.strip_prefix("photo:").expect("photo:<sha256>"); assert!(BUILTIN_TOOL_PICTURES.iter().any(|(shipped, _)| *shipped == sha), "{}: {sha} is not shipped", package.tool.id); } } }/// RULE: a kit's own picture is what the chooser draws, so a shipped kit names none or a/// photo:<sha256> this build ships — never a free string (architect, 11 Oct); a person's/// kit is held to a photo the personal database holds when it is written. #[test]fn a_shipped_kits_picture_is_a_picture_the_build_ships() {usecrate::definitions::pictures::BUILTIN_TOOL_PICTURES;for kit in shipped() {letSome(picture) = &kit.picture else { continue };letToolPicture::Photo(picture) = picture else { panic!("{}: a kit's picture is a photo, not a word", kit.id) };let sha = picture.photo.strip_prefix("photo:").unwrap_or_else(|| panic!("{}: photo:<sha256>", kit.id)); assert!(BUILTIN_TOOL_PICTURES.iter().any(|(shipped, _)| *shipped == sha), "{}: {sha} is not shipped", kit.id); } }/// Every carried tool shipped in a kit — the picture guard walks them. #[test]fn a_kit_tool_shipped_twice_is_the_same_tool() {letmut seen: std::collections::BTreeMap<String, KitPackage> = Default::default();for kit in shipped() {for package in packages(&kit) {ifletSome(before) = seen.insert(package.tool.id.clone(), package.clone()) { assert_eq!(&before, package, "{} differs between kits", package.tool.id); } } } }/// RULE: The business packages Cotton ships as files share no table but person, so one business's package never needs another's to install and no edit to one moves the other's rows. #[test]fn shipped_business_packages_share_no_table_but_person() {let packages: Vec<KitPackage> = SHIPPED_PACKAGES .iter() .map(|(id, _, _)| serde_json::from_value(shipped_package(id)).expect("a shipped package reads")) .collect();letmut owner: std::collections::BTreeMap<String, String> = Default::default();for package in &packages { assert_eq!(package.tables.iter().map(|t| &t.id).collect::<Vec<_>>(), package.tool.tables.iter().collect::<Vec<_>>(), "{}", package.tool.id);for table in &package.tables { assert!(owner.insert(table.id.clone(), package.tool.id.clone()).is_none(), "{} is in two packages", table.id); } }for package in &packages {for table in &package.tables {for column in table.columns.iter().filter(|c| c.link_to.is_some()) {let to = column.link_to.as_deref().unwrap(); assert!(to == "person" || owner.get(to) == Some(&package.tool.id), "{}.{} links to {to}, outside {} and not person", table.id, column.key, package.tool.id); } } }// Each is carried by a kit, so add_tool and a business manifest can name it.let carried: Vec<String> = shipped_kit_tools().into_iter().map(|p| p.tool.id).collect();for (id, _, _) in SHIPPED_PACKAGES { assert!(carried.iter().any(|c| c == id), "no kit carries {id}"); } }/// RULE: Every table a business package ships says who sees it — public, staff, or/// mine(<column>) — and a mine is one hop (architect, 19 Oct): the column links to/// person, or to a table of the same package that is itself mine(<a link to person>)./// The judge resolves mine once; a deeper chain is refused at save, so a package/// carrying one would install a table nobody but staff could ever see. #[test]fn every_business_package_table_says_who_sees_it_in_one_hop() {for (id, _, _) in SHIPPED_PACKAGES {let package = shipped_package(id);let tables = package["tables"].as_array().unwrap();let link = |table: &serde_json::Value, key: &str| -> Option<String> { table["columns"].as_array()?.iter().find(|c| c["key"] == key && c["type"] == "link")?["link_to"].as_str().map(str::to_string) };let mine = |table: &serde_json::Value| -> Option<String> {let visibility = table["visibility"].as_str()?;Some(visibility.strip_prefix("mine(")?.strip_suffix(')')?.to_string()) };for table in tables {let name = table["id"].as_str().unwrap();match table["visibility"].as_str() {Some("public") | Some("staff") => continue,Some(_) => {}None => panic!("{id}: {name} says nobody's visibility"), }let column = mine(table).unwrap_or_else(|| panic!("{id}: {name}'s visibility is not public, staff or mine(<column>)"));let to = link(table, &column).unwrap_or_else(|| panic!("{id}: {name} is mine({column}), which is no link column"));if to == "person" { continue; }let target = tables.iter().find(|t| t["id"] == to.as_str()).unwrap_or_else(|| panic!("{id}: {name}.{column} links outside the package"));let hop = mine(target).unwrap_or_else(|| panic!("{id}: {name} is mine({column}) but {to} is not mine")); assert_eq!(link(target, &hop).as_deref(), Some("person"), "{id}: {name} is mine({column}) → {to} mine({hop}), two hops"); } } }}/// The personal object's tables as the phone stores them/// (`kits/personal/storage.json`, which `pnpm -s personal-tables`/// in `apps/business` writes from schema 141): for each object table, the Rust/// table it fills, that table's key, whether its rows carry `workspace_id`, and/// each object column's own column there. The phone reads the object's rows into/// its typed tables through this, and posts its own writes back through it.pubconst PERSONAL_STORAGE: &str = include_str!("../kits/personal/storage.json");