Cotton code
713 lines · 40.0 KB · RustRaw
//! The kit: the tools Cotton offers as `.cottontool` packages — the tools the//! personal kit ships (`crates/cotton-core/kits/personal/kit.json`, each in//! `kits/personal/tools/<id>/`), compiled in so `import_tool` can be handed//! one by id and a synthetic household can be given them. No database is//! made with them (72nd amendment, 21 Oct 2026).//!//! The kit is the personal kit's packages: the eight, Documents and Web pages//! (views over Documents' table). None is written at a database's creation —//! a database is made with the shell only (owner, 21 Oct 2026); each tool is//! added by hand with add_tool or import_tool.use crate::definitions::package::{archive_files, decode_files, ImportedPackage, PackageError};use std::collections::BTreeMap;include!(concat!(env!("OUT_DIR"), "/kit_files.rs"));// `CORE_KIT`: the one kit this core was built for, whose tools' pictures and// the shell's are the only ones it carries (`crate::kit_pictures`,// `COTTON_CORE_KIT` at build time); none is the whole object's core.include!(concat!(env!("OUT_DIR"), "/core_kit.rs"));/// Whether a core built for `core` serves a manifest that names `named`:/// the whole core serves any, and a kit's core serves that kit alone. Any/// other app would hold tools whose pictures are not in it.pub fn core_serves(core: Option<&str>, named: Option<&str>) -> Result<(), String> {    match core {        Some(core) if named != Some(core) => Err(format!(            "this core was built for kit {core:?} and carries only its pictures; the manifest names {}",            named.map_or("no kit (the whole object)".to_string(), |kit| format!("kit {kit:?}"))        )),        _ => Ok(()),    }}/// The shell kit's tables (`kits/shell/kit.json`), `(id, json)`: the ones/// every database is made with, wherever each is defined — `face_settings`/// is the personal kit's file, a plain table no tool draws.pub mod shell {    include!(concat!(env!("OUT_DIR"), "/shell_kit_tables.rs"));}/// The kit's tool ids, in name order.pub fn ids() -> Vec<&'static str> {    let mut ids: Vec<&str> = KIT_FILES.iter().map(|(id, _, _)| *id).collect();    ids.dedup();    ids}/// What the kit and the shell ARE, as sixteen hex characters: every kit/// package's files, and the shell's tables, boards and themes a database is/// created with, by set, name and bytes. A test fixture built from them/// (cotton-tools' harness) is cached under it, so a changed file names a new/// fixture and a stale one is never reused.pub fn fingerprint() -> String {    // The kit's files by their digest, worked out at build (build.rs `KIT_FILES_DIGEST`, the same parts in the same    // order as `fingerprint_of`); the shell's few definition files are hashed here.    fingerprint_over(KIT_FILES_DIGEST, &fingerprinted()[KIT_FILES.len()..])}/// The fingerprint of the kit's files by their digest ([`digest_of`]) and the shell's files whole.pub fn fingerprint_over(kit_digest: &str, shell: &[(&str, &str, &[u8])]) -> String {    let mut files = vec![("kit", "digest", kit_digest.as_bytes())];    files.extend_from_slice(shell);    fingerprint_of(&files)}/// The SHA-256 of these files as build.rs works out `KIT_FILES_DIGEST`: each part length-first, in order, in hex.pub fn digest_of(files: &[(&str, &str, &[u8])]) -> String {    use sha2::{Digest, Sha256};    let mut hasher = Sha256::new();    for (tool, name, bytes) in files {        for part in [tool.as_bytes(), name.as_bytes(), bytes] {            hasher.update((part.len() as u64).to_le_bytes());            hasher.update(part);        }    }    hex::encode(hasher.finalize())}/// The files [`fingerprint`] reads: the kit's, then the shell's by set.pub fn fingerprinted() -> Vec<(&'static str, &'static str, &'static [u8])> {    let shell = [        ("shell/tables", crate::definitions::BUILTIN_DEFINITION_FILES),        ("shell/boards", crate::definitions::board::BUILTIN_BOARD_FILES),        ("shell/themes", crate::definitions::theme::BUILTIN_THEME_FILES),    ];    KIT_FILES.iter().copied()        .chain(shell.into_iter().flat_map(|(set, files)| files.iter().map(move |(name, text)| (set, *name, text.as_bytes()))))        .collect()}/// [`fingerprint`] of these files.pub fn fingerprint_of(files: &[(&str, &str, &[u8])]) -> String {    use sha2::{Digest, Sha256};    let mut hasher = Sha256::new();    for (tool, name, bytes) in files {        for part in [tool.as_bytes(), name.as_bytes(), bytes] {            hasher.update((part.len() as u64).to_le_bytes());            hasher.update(part);        }    }    hex::encode(hasher.finalize())[..16].to_string()}/// The kit package `id` as the archive `import_tool` takes, or `None` for an/// id the kit does not hold.pub fn archive(id: &str) -> Option<Result<Vec<u8>, PackageError>> {    Some(archive_files(&files(id)?))}/// The kit package `id`'s files by name, as its archive holds them: the/// compiled files and the manifest's instructions as `instructions.md`.fn files(id: &str) -> Option<BTreeMap<String, Vec<u8>>> {    let mut files: BTreeMap<String, Vec<u8>> = KIT_FILES.iter()        .filter(|(tool, _, _)| *tool == id)        .map(|(_, name, bytes)| (name.to_string(), bytes.to_vec()))        .collect();    let manifest = files.get("manifest.json")?;    let instructions = serde_json::from_slice::<serde_json::Value>(manifest).ok()        .and_then(|manifest| manifest["instructions"].as_str().map(str::to_owned)).unwrap_or_default();    files.insert("instructions.md".to_string(), instructions.into_bytes());    Some(files)}/// The kit package `id`, decoded as an import decodes it.pub fn package(id: &str) -> Option<Result<ImportedPackage, PackageError>> {    Some(decoded(id)?.cloned())}/// The kit package `id` as [`package`] decodes it, decoded once per process/// and shared: the compiled kit never changes while it runs, and a fresh/// copy's 21 genesis tools each asked for a whole archive-and-decode of/// theirs (copy-installer-cpu, 7 Nov 2026).pub fn decoded(id: &str) -> Option<Result<&'static ImportedPackage, PackageError>> {    type Decoded = BTreeMap<&'static str, std::sync::OnceLock<Result<ImportedPackage, String>>>;    static PACKAGES: std::sync::OnceLock<Decoded> = std::sync::OnceLock::new();    let packages = PACKAGES.get_or_init(|| ids().into_iter().map(|id| (id, std::sync::OnceLock::new())).collect());    let (id, slot) = packages.get_key_value(id)?;    let decoded = slot.get_or_init(|| {        decode_files(&files(id).expect("a kit id holds its files")).map_err(|error| error.0)    });    Some(decoded.as_ref().map_err(|error| PackageError(error.clone())))}/// The table `id` as a kit package ships it, read from its file rather than/// by decoding the package: a decode asks this for a built-in table's shipped/// engine and commands, so it may not decode in turn.pub fn table(id: &str) -> Option<crate::definitions::TableDefinition> {    shipped_table(id).cloned()}/// [`table`], parsed once per process and shared: every package decode and/// install check asks for it per table it reads.pub fn shipped_table(id: &str) -> Option<&'static crate::definitions::TableDefinition> {    type Parsed = BTreeMap<&'static str, Option<crate::definitions::TableDefinition>>;    static TABLES: std::sync::OnceLock<Parsed> = std::sync::OnceLock::new();    TABLES.get_or_init(|| {        let mut tables = Parsed::new();        for (name, bytes) in KIT_FILES.iter().map(|(_, name, bytes)| (*name, *bytes)) {            let Some(id) = name.strip_prefix("tables/").and_then(|name| name.strip_suffix(".json")) else { continue };            // The first file under a name is the kit's, as `table_file` reads it.            tables.entry(id).or_insert_with(|| std::str::from_utf8(bytes).ok().and_then(|json| crate::definitions::TableDefinition::from_json(json).ok()));        }        tables    }).get(id)?.as_ref()}/// The bytes of the table `id`'s file as a kit package ships it — the/// kit's one definition of it (`kits/personal/tables`): what an unchanged/// table is written back as, so a package's own table (Books' book) keeps/// the file a person reads and edits, as a built-in does.pub fn table_file(id: &str) -> Option<&'static [u8]> {    let file = format!("tables/{id}.json");    KIT_FILES        .iter()        .find(|(_, name, _)| *name == file)        .map(|(_, _, bytes)| *bytes)        .or_else(|| KIT_OWN_TABLES.iter().find(|(name, _)| *name == id).map(|(_, bytes)| *bytes))}/// The personal kit's tables a phone's copy may need with no tool of its own laying them: one a phone's copy keeps kit/// columns on (Days' people on an event, 22 Nov 2026), Sites' `site` (no tool, and closed to every assistant by/// `seal::agent::CLOSED`), and Post's `email_account` (now also drawn by the `personal/messages` tool, mail-design row/// 11, so a copy holding that tool lays it there and this list skips it as held; what an assistant may read of it is/// that tool's, not this list's). Found by [`table_file`] like a package's, and laid on a phone's own copy by genesis/// and at every open (`cotton_tools::kit::lay_kit_tables`, 25 Nov 2026; only these, GENESIS KITS 2).const KIT_OWN_TABLES: &[(&str, &[u8])] = &[    ("event_attendee", include_bytes!("../kits/personal/tables/event_attendee.json")),    ("site", include_bytes!("../kits/personal/tables/site.json")),    ("email_account", include_bytes!("../kits/personal/tables/email_account.json")),    // Contacts' own (PEOPLE BUILD 1b, CONTACTS): kept by the core for every app that names people, with no tool of    // their own: a number several contacts share, each contact's sources, its kind, Close pin and merges, the apps'    // per-person lines, why a group was made, and his Same person? answers.    ("shared_handle", include_bytes!("../kits/personal/tables/shared_handle.json")),    ("person_source", include_bytes!("../kits/personal/tables/person_source.json")),    ("person_state", include_bytes!("../kits/personal/tables/person_state.json")),    ("person_fact", include_bytes!("../kits/personal/tables/person_fact.json")),    ("group_origin", include_bytes!("../kits/personal/tables/group_origin.json")),    ("person_pair", include_bytes!("../kits/personal/tables/person_pair.json")),    // A number's or an address's own label (Mobile, Work, his word), one row per handle (CONTACT KINDS).    ("handle_label", include_bytes!("../kits/personal/tables/handle_label.json")),];/// The ids of [`KIT_OWN_TABLES`]: tables a copy may hold with no tool drawing them.pub fn kit_own_tables() -> impl Iterator<Item = &'static str> {    KIT_OWN_TABLES.iter().map(|(id, _)| *id)}/// The tables whose rows are the person's face choices, among those every/// database is made with (`shell::SHELL_KIT_TABLES`) and the kit's tools/// ship, as each table's definition says (`face_choices`), never a list of/// ids kept here.pub fn face_choice_tables() -> &'static [String] {    static TABLES: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();    TABLES.get_or_init(|| {        let shell = shell::SHELL_KIT_TABLES.iter().map(|(_, json)| *json);        let kit = KIT_FILES.iter()            .filter(|(_, name, _)| name.starts_with("tables/"))            .filter_map(|(_, _, bytes)| std::str::from_utf8(bytes).ok());        let mut tables: Vec<String> = shell.chain(kit)            .map(|json| crate::definitions::TableDefinition::from_json(json).expect("a shipped table definition"))            .filter(|table| table.face_choices == Some(true))            .map(|table| table.id)            .collect();        tables.sort();        tables.dedup();        tables    })}include!(concat!(env!("OUT_DIR"), "/app_kits.rs"));/// What an app keeps to (coordinator, 5 Nov 2026): the kit its manifest names/// (`"kit": "books"`, `kits/books/kit.json`). Signed in to the owner's object,/// the app draws only the kit's tools and pulls only the kit's tables and the/// shell's; an app that names no kit (Cotton) keeps to the whole object, the/// tools a person made included. Cotton Books on the owner's phone drew his/// whole Cotton and synced every table before this.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]pub struct AppKit {    pub id: String,    /// The kit's tools, by id, in the kit's order.    pub tools: Vec<String>,    /// The kit's tables, by id, in the kit's order.    pub tables: Vec<String>,    /// Tools the app holds but draws inside its first tool, never as tools of    /// their own ([`AppKit::fold`]): Cotton People's Birthdays, a tool of    /// views over People's person, is People's Birthday wishes and Everyone    /// (owner, 11 Nov 2026). A folded tool is born with the copy and kept on    /// it, so the columns it adds (`own_birthdays__wish`) are there for its    /// views; Cotton draws it as its own tool as before.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub folds: Vec<String>,    /// The cards that stand LEFT of the app's first card, nearest first    /// (owner, 11 Nov 2026): the fan opens on its first view in the centre,    /// and what a person reaches for less often lives to its left. The kit    /// says which, by id; the core knows how each is answered    /// ([`ACCOUNT_CARD`], and a FAQ or terms card when one comes).    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub aside: Vec<String>,    /// The table whose rows ARE the app's fan, where its records and not its    /// tool's views are what a person chooses between (Cotton Story: one tile    /// a screenplay, owner on build 4, 18 Nov 2026). Read from the kit this    /// build ships ([`AppKit::named`]), never a copy saved by an older build.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub fan_of: Option<String>,    /// The account acts the app lays over its first tool, the one it opens on, where the tool's own    /// definition names none ([`AppKit::lay_acts`]): Sign in, Back up now and    /// Sign out, in the app's own pictures. Money in Cotton names no account    /// act, Cotton keeping its account on its own Settings card; the kit    /// lays them, and Money's definition stays the one Cotton draws. They    /// stand on the Account card alone.    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub acts: Vec<crate::definitions::ToolAct>,    /// The face the app's records are to stand in before Loom draws it    /// ([`KitFace`]): a kit names the real object and its ground in data, a    /// Mac lane paints it, and until then its cards keep the face their    /// table names (a card may name only a face the app draws).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub face: Option<KitFace>,    /// Whether the app's Cotton chats say more than delivery (`signals`):    /// read receipts and typing, sent and drawn, each behind the person's own    /// switch. Absent, they do not (owner, 15 Nov 2026): the phone sends no    /// read receipt and no typing, draws neither, and offers no switch for    /// them. The code and the columns stay; `"signals": true` in the kit    /// turns them back on.    #[serde(default, skip_serializing_if = "is_false")]    pub signals: bool,    /// Of a table the kit pulls, only the rows whose clear column holds one of    /// these values (owner, 21 Nov 2026: Words keeps the documents that are an    /// assistant's web pages, never every document): `{"document": {"mime":    /// ["text/html"]}}`, sent with each pass as `only=` and kept by the object.    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]    pub only: std::collections::BTreeMap<String, std::collections::BTreeMap<String, Vec<String>>>,    /// Of a dated table the kit pulls, only the newest days (MAIL.md, 21 Nov    /// 2026: Comms keeps 90 days of mail, `{"email": 90, "email_thread": 90}`),    /// sent with each pass as `window=` beside the shell's own; what is older    /// stays on the object, paged by `GET /v1/older` and found by `GET /v1/blind`.    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]    pub window: std::collections::BTreeMap<String, u32>,    /// MAIL ALL ON PHONE (owner via the coordinator, 24 Nov 2026; MAIL.md "All mail on the phone"): the tables of    /// `window` this kit keeps whole after all, its switch. Comms ships it empty (the 90 days stand); naming    /// `email` and `email_thread` here takes all his mail's text to the phone. A copy pulled with the window owes    /// those tables whole on its next pass (`again=`), never the whole object ([`AppKit::copy_mark`]).    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub all_history: Vec<String>,    /// The tables the kit's `first` names `late` (Comms' mail, f09ef54d2f): the object serves their rows behind the    /// others' on a first pull, and a phone opens the rows it parked for want of the key in the same order, the    /// others first (`cotton_client`'s object transport, `reopened`).    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub late: Vec<String>,}fn is_false(value: &bool) -> bool { !*value }/// The face a kit asks for, named before it is painted (owner, 12 Nov 2026:/// each app is its own remembered real object on its own ground): the face's/// id, the object it is, the card slots it draws from, and the ground it/// stands on, a `FaceGround` id once its tile is painted.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]#[serde(deny_unknown_fields)]pub struct KitFace {    pub id: String,    /// The object, in words a painter reads ("a newspaper clipping on a bulldog clip").    pub object: String,    /// The slots it draws, each a card slot this build knows.    pub slots: Vec<crate::definitions::card::CardSlot>,    pub ground: String,}/// What a view laid on the kit's first tool is to its own tool ([`AppKit::unfolded`]).#[derive(Debug, Clone, PartialEq, Eq)]pub enum Unfolded {    /// Its own tool's view, by that tool's name for it (`birthdays/wishes`).    Named(String),    /// No view of its tool's: the tool's home table whole.    Whole,}/// The Account card ([`AppKit::aside`]): this phone's sign-in and sync, one/// card (`shell.account`). On the fan it is a view of the kit's one tool by/// this id, left of the first; no deck reads it.pub const ACCOUNT_CARD: &str = "account";/// This phone's account acts, which stand on the Account card alone.pub const ACCOUNT_ACTS: &[&str] = &["account_sign_in", "account_back_up", "account_sign_out"];const APP_KIT_FILE: &str = "app_kit.json";/// The contacts the shell kit pulls into every app only so a number is named by who holds it (PEOPLE BUILD 1, C7):/// kept and pulled everywhere, shown only by an app whose own kit lists them ([`AppKit::deals_table`]).pub const NAMING_TABLES: &[&str] = &["person", "person_handle", "shared_handle"];impl AppKit {    /// What your Claude may read, in the groups a person knows, as the kit    /// `id` this build ships names them (`reads`: Comms' Chats, Mail, Photos,    /// Calls, Contacts and Files, you-grouped.html, 22 Nov 2026): each group's    /// id and its tables, in the kit's order. A kit that names none answers none,    /// and Your Claude lists every sealed table as before.    pub fn reads_of(id: &str) -> Vec<(String, Vec<String>)> {        let Some((_, text)) = APP_KITS.iter().find(|(kit, _)| *kit == id) else { return Vec::new() };        let kit: serde_json::Value = serde_json::from_str(text).expect("a shipped kit.json");        kit["reads"]            .as_array()            .into_iter()            .flatten()            .filter_map(|group| {                let tables = group["tables"].as_array()?.iter().filter_map(serde_json::Value::as_str).map(str::to_string).collect();                Some((group["id"].as_str()?.to_string(), tables))            })            .collect()    }    /// The tables the kit `id` this build ships names, as ids, the personal    /// kit's too (Cotton's whole object): what a former object's copy sends    /// whole into a new object (`cotton_ffi::phone::adopt`). A table held as    /// retired is never named, though its file may still ship (TABLE DROP 1).    pub fn tables_of(id: &str) -> Vec<String> {        let Some((_, text)) = APP_KITS.iter().find(|(kit, _)| *kit == id) else { return Vec::new() };        let kit: serde_json::Value = serde_json::from_str(text).expect("a shipped kit.json");        kit["tables"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str).map(|entry| entry.rsplit('/').next().unwrap_or(entry).to_string()).filter(|table| !crate::retired::is_gone_table(table)).collect()    }    /// The kit `id` this build ships, its entries as ids (`personal/book` is    /// `book`). The personal and shell kits are no app's to keep to: Cotton's    /// whole object is no kit at all.    pub fn named(id: &str) -> Option<AppKit> {        if id == "personal" || id == "shell" {            return None;        }        let (_, text) = APP_KITS.iter().find(|(kit, _)| *kit == id)?;        let kit: serde_json::Value = serde_json::from_str(text).expect("a shipped kit.json");        let ids = |key: &str| -> Vec<String> {            kit[key].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str)                .map(|entry| entry.rsplit('/').next().unwrap_or(entry).to_string()).collect()        };        let acts: Vec<crate::definitions::ToolAct> = kit.get("acts").map(|acts| serde_json::from_value(acts.clone()).expect("a shipped kit's acts are tool acts")).unwrap_or_default();        let tools = ids("tools");        let folds = ids("folds");        let aside = ids("aside");        assert!(acts.is_empty() || aside.iter().any(|card| card == ACCOUNT_CARD), "kits/{id}: account acts stand on the Account card, which the kit's aside names");        let face = kit.get("face").map(|face| serde_json::from_value(face.clone()).expect("a shipped kit's face names its id, object, card slots and ground"));        let late: Vec<String> = kit["first"].as_object().into_iter().flatten().filter(|(_, how)| how["late"] == serde_json::Value::Bool(true)).map(|(table, _)| table.clone()).collect();        Some(AppKit {            late, id: id.to_string(), tools, tables: ids("tables").into_iter().filter(|table| !crate::retired::is_gone_table(table)).collect(), folds, aside, fan_of: kit["fan_of"].as_str().map(str::to_string), acts, face, signals: kit["signals"].as_bool().unwrap_or(false), only: kit.get("only").map(|only| serde_json::from_value(only.clone()).expect("a shipped kit's only names table, column and values")).unwrap_or_default(), window: kit.get("window").map(|window| serde_json::from_value(window.clone()).expect("a shipped kit's window names tables and days")).unwrap_or_default(), all_history: kit.get("all_history").map(|all| serde_json::from_value(all.clone()).expect("a shipped kit's all_history names tables")).unwrap_or_default() })    }    /// The tools this app draws inside its first tool, in the fan's order:    /// every other tool its kit lists, then the ones it folds    /// ([`AppKit::folds`]). RULE (owner, 11 Nov 2026: "the fan menu is just    /// views, and a view can be of a specific tool"): a Cotton app's fan has    /// no tools tier; its one top tier holds every view of every tool the    /// kit lists, in kit order. The tools stay in the data as they are.    pub fn folded(&self) -> Vec<&String> {        self.tools.iter().skip(1).chain(&self.folds).collect()    }    /// Whether the app draws any tool inside its first ([`AppKit::folded`]).    pub fn folds_any(&self) -> bool {        self.tools.len() > 1 || !self.folds.is_empty()    }    /// The views a tool declares, as stored: its home table's where the    /// table heads it with views of its own, else its definition's.    fn views_of<'a>(tool: &'a crate::definitions::ToolDefinition, tables: &'a [crate::definitions::TableDefinition]) -> &'a [crate::definitions::tool_views::ToolView] {        tables.iter().filter_map(|table| table.tool.as_ref().filter(|home| home.key.as_deref().unwrap_or(&table.id) == tool.id && !home.views.is_empty())).next()            .map(|home| home.views.as_slice()).unwrap_or(&tool.views)    }    /// The view `named` (`<tool>/<id>`) by the name its own tool gives it,    /// where it is a view [`AppKit::fold`] laid on the kit's first tool:    /// People's `people/wishes` is Birthdays' `birthdays/wishes`, Keys'    /// `keys/passwords__all` is Passwords' `passwords/all`, read as their own    /// tool reads them (its added columns drawn); a tool that declares no    /// view is its table's whole list (`money/subscriptions`). Any other    /// name is its own, and so is every name in an app that folds nothing.    /// `tables` and `tools` are the database's, as stored.    pub fn unfolded(&self, named: &str, tables: &[crate::definitions::TableDefinition], tools: &[crate::definitions::ToolDefinition]) -> Option<Unfolded> {        let (tool, id) = named.split_once('/')?;        if !self.folds_any() || self.tools.first().map(String::as_str) != Some(tool) {            return None;        }        let first = tools.iter().find(|found| found.id == tool)?;        if Self::views_of(first, tables).iter().any(|view| view.id == id) {            return None;        }        let folded: Vec<&crate::definitions::ToolDefinition> = self.folded().into_iter().filter_map(|id| tools.iter().find(|found| &found.id == id)).collect();        if let Some((owner, own)) = id.split_once("__") {            if folded.iter().any(|found| found.id == owner && Self::views_of(found, tables).iter().any(|view| view.id == own)) {                return Some(Unfolded::Named(format!("{owner}/{own}")));            }        }        if let Some(found) = folded.iter().find(|found| Self::views_of(found, tables).iter().any(|view| view.id == id)) {            return Some(Unfolded::Named(format!("{}/{id}", found.id)));        }        folded.iter().any(|found| found.id == id).then_some(Unfolded::Whole)    }    /// The tools a copy for this app is born with and keeps: the kit's, then    /// the ones it folds ([`AppKit::folds`]).    pub fn held(&self) -> Vec<String> {        self.tools.iter().chain(&self.folds).cloned().collect()    }    /// `tables` and `tools` as this app draws them ([`AppKit::folded`]): each    /// folded tool's views laid after the kit's first tool's own (on the    /// table that heads it, where one does, else on its definition), in the    /// kit's order, none of them its default; its tables the first tool's;    /// and the folded tool gone from `tools`. Its acts stay its own: an act    /// is offered and run on the tool of the view in view, read from the    /// tools as stored (`cotton_ffi::phone::tool_acts`), so two tools may    /// each define an act of one id. A kit tool that    /// declares no view is one view of its home table, under its own name    /// (Subscriptions, Machines). A kit tool's view whose id is taken is    /// `<tool>__<id>`; a tool the kit `folds` keeps the first tool's own, as    /// before. Where two tools say a view by the same name (All), each says    /// whose it is: its tool's name where it is the view the tool opens on    /// or its only one, else the tool's name with it (line    /// `fan.view_of_tool`). Read where the phone reads its views, never    /// written to the copy: the object's definitions stay the ones Cotton    /// draws, each tool its own there.    pub fn fold(&self, tables: &mut [crate::definitions::TableDefinition], tools: &mut Vec<crate::definitions::ToolDefinition>) {        use crate::definitions::tool_views::ToolView;        let Some(into) = self.tools.first().filter(|_| self.folds_any()) else { return };        // Each view with the tool that declared it, whether it is that tool's opening or only view, and whether a kit tool's.        struct Laid { view: ToolView, tool: String, heads: bool }        let whose = |views: &[ToolView], tool: &crate::definitions::ToolDefinition| -> Vec<Laid> {            let shown = views.iter().filter(|view| view.partition.is_none()).count();            views.iter().map(|view| Laid { view: view.clone(), tool: tool.name.clone(), heads: view.is_default || shown == 1 }).collect()        };        let Some(first) = tools.iter().find(|tool| &tool.id == into) else { return };        let mut laid = whose(Self::views_of(first, tables), first);        let mut held_tables = Vec::new();        for id in self.folded() {            let Some(at) = tools.iter().position(|tool| &tool.id == id) else { continue };            let tool = tools.remove(at);            let listed = self.tools.contains(id);            let mut views = whose(Self::views_of(&tool, tables), &tool);            if listed && !views.iter().any(|laid| laid.view.partition.is_none()) {                if let Some(home) = tool.tables.first() {                    let view: ToolView = serde_json::from_value(serde_json::json!({"id": tool.id, "label": tool.name, "read": {"table": home}})).expect("a view of a table");                    views.push(Laid { view, tool: tool.name.clone(), heads: true });                }            }            for mut next in views {                next.view.is_default = false;                if laid.iter().any(|held| held.view.id == next.view.id) {                    if !listed { continue }                    next.view.id = format!("{}__{}", tool.id, next.view.id);                }                laid.push(next);            }            held_tables.extend(tool.tables);        }        // Two tools' views under one name each say whose they are.        let said: Vec<(String, String)> = laid.iter().filter(|laid| laid.view.partition.is_none()).map(|laid| (laid.view.label.to_lowercase(), laid.tool.clone())).collect();        for next in laid.iter_mut().filter(|laid| laid.view.partition.is_none()) {            let label = next.view.label.to_lowercase();            if said.iter().any(|(other, tool)| *other == label && *tool != next.tool) {                next.view.label = if next.heads { next.tool.clone() } else {                    crate::rules::shell_lines::resolve("boot", "fan.view_of_tool", &[], &[("tool", &next.tool), ("view", &next.view.label)]).unwrap_or_else(|| format!("{} {}", next.tool, next.view.label))                };            }        }        let views: Vec<ToolView> = laid.into_iter().map(|laid| laid.view).collect();        let home = tables.iter_mut().filter_map(|table| {            let key = table.tool.as_ref()?.key.clone().unwrap_or_else(|| table.id.clone());            (&key == into).then_some(table)        }).find_map(|table| table.tool.as_mut().filter(|home| !home.views.is_empty()));        if let Some(home) = home { home.views = views.clone(); }        let Some(first) = tools.iter_mut().find(|tool| &tool.id == into) else { return };        if first.views.is_empty() && tables.iter().any(|table| table.tool.as_ref().is_some_and(|home| home.key.as_deref().unwrap_or(&table.id) == into.as_str() && !home.views.is_empty())) {            // The table heads the tool: its views stand there alone.        } else {            first.views = views;        }        for table in held_tables { if !first.tables.contains(&table) { first.tables.push(table); } }    }    /// `tools` as this app offers their acts: the kit's account acts laid    /// over its first tool where the tool defines none of that id    /// ([`AppKit::acts`]). They stand on the Account card alone    /// ([`ACCOUNT_CARD`], `cotton_ffi::phone::tool_acts`), never on a deck.    /// Read where the phone reads its tools' acts, never written to the    /// copy: the object's definition stays the one every app shares.    pub fn lay_acts(&self, tools: &mut [crate::definitions::ToolDefinition]) {        let Some(tool) = tools.iter_mut().find(|tool| self.tools.first() == Some(&tool.id)) else { return };        for act in &self.acts {            if !tool.acts.iter().any(|held| held.id == act.id) {                tool.acts.push(act.clone());            }        }    }    /// The manifest's `kit`: none is the whole object. A kit this build does    /// not ship, or one named beside a `tools` list (one source only: the kit    /// names the tools), refuses the manifest.    pub fn of(manifest: Option<&serde_json::Value>) -> Result<Option<AppKit>, String> {        let Some(named) = manifest.and_then(|manifest| manifest.get("kit")) else {            core_serves(CORE_KIT, None)?;            return Ok(None);        };        let id = named.as_str().ok_or("a manifest's kit is a kit's id")?;        core_serves(CORE_KIT, Some(id))?;        if manifest.is_some_and(|manifest| manifest.get("tools").is_some()) {            return Err(format!("the manifest names kit {id:?} and a tools list: the kit names the tools"));        }        let mut kit = AppKit::named(id).ok_or_else(|| format!("the manifest names kit {id:?}, which this build does not ship as an app's kit"))?;        // The app's switch for its windows (MAIL ALL ON PHONE, 24 Nov 2026): `"all_history": ["email", "email_thread"]`        // in Comms' flavour.json keeps those tables whole. Only a table the kit windows can be named.        if let Some(all) = manifest.and_then(|manifest| manifest.get("all_history")) {            let all: Vec<String> = serde_json::from_value(all.clone()).map_err(|_| "a manifest's all_history is a list of tables")?;            if let Some(table) = all.iter().find(|table| !kit.window.contains_key(*table)) {                return Err(format!("the manifest keeps {table:?} whole, which kit {id:?} keeps no window of"));            }            kit.all_history = all;        }        Ok(Some(kit))    }    /// Whether the app holds the tool `id`: its own, or one it folds.    pub fn keeps_tool(&self, id: &str) -> bool {        self.tools.iter().chain(&self.folds).any(|tool| tool == id)    }    /// Whether the app keeps the table `id`: the kit's, or the shell's own    /// (the device the phone files itself under, face choices), or one the    /// shell answers in every app (the unlock window's request, grant and    /// read log: `rules::unlock::SHELL_TABLES`).    pub fn keeps_table(&self, id: &str) -> bool {        self.tables.iter().any(|table| table == id) || shell::SHELL_KIT_TABLES.iter().any(|(table, _)| *table == id) || crate::rules::unlock::SHELL_TABLES.contains(&id)    }    /// Whether the app deals a view reading `table` (owner, 11 Nov 2026): a    /// view over a table the kit does not keep is another app's, never a    /// tile here. Messages' Agents view reads the session table, which the    /// messages kit leaves to Cotton Developer: the Messages app deals    /// Messages without it, and Cotton, keeping the whole object, deals it.    pub fn deals_view(&self, table: Option<&str>) -> bool {        table.is_none_or(|table| self.deals_table(table))    }    /// Whether the app shows `table` as its own (its views, a link to one of its rows): what it keeps, except the    /// contacts every app keeps only to name a number ([`NAMING_TABLES`], PEOPLE BUILD 1b), which an app whose own    /// kit does not list them never shows. Pulling them changed no look.    pub fn deals_table(&self, id: &str) -> bool {        self.tables.iter().any(|table| table == id) || (self.keeps_table(id) && !NAMING_TABLES.contains(&id))    }    /// The tables a pull asks the object for, by id, sorted: the kit's, the    /// shell's, the unlock window's (its card stands from the shell in every    /// app, ruling R4) and the seal keys.    pub fn pulled(&self) -> Vec<String> {        // Every app opens and seals with the database's data key, so every        // app pulls the seal keys.        let mut tables: Vec<String> = self            .tables            .iter()            .cloned()            .chain(shell::SHELL_KIT_TABLES.iter().map(|(table, _)| table.to_string()))            .chain(crate::rules::unlock::SHELL_TABLES.iter().map(|table| table.to_string()))            .chain(std::iter::once(crate::seal::SEAL_KEY_TABLE.to_string()))            .collect();        tables.sort();        tables.dedup();        tables    }    /// The kit's `only` as a pass asks it (`document.mime:text/html,…`), or    /// none: each value escaped, several values of one column joined by `|`.    pub fn only_query(&self) -> Option<String> {        let escape = |value: &str| url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>();        let parts: Vec<String> = self            .only            .iter()            .flat_map(|(table, columns)| columns.iter().map(move |(column, values)| format!("{table}.{column}:{}", values.iter().map(|value| escape(value)).collect::<Vec<_>>().join("|"))))            .collect();        (!parts.is_empty()).then(|| parts.join(","))    }    /// Keep this launch's kit (or none) for the paths handed only a data folder.    pub fn keep(kit: Option<&AppKit>, root: &std::path::Path) -> Result<(), String> {        std::fs::create_dir_all(root).map_err(|error| error.to_string())?;        std::fs::write(root.join(APP_KIT_FILE), serde_json::to_vec(&kit).unwrap()).map_err(|error| error.to_string())    }    /// The kit this data folder's app keeps to; none kept is the whole object.    pub fn at(root: &std::path::Path) -> Result<Option<AppKit>, String> {        match std::fs::read(root.join(APP_KIT_FILE)) {            Ok(bytes) => serde_json::from_slice(&bytes).map_err(|error| format!("the app's kit does not read: {error}")),            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),            Err(error) => Err(error.to_string()),        }    }    /// What a copy pulled for this kit is marked with: the kit's id, or    /// `whole` for the whole object.    pub fn mark(kit: Option<&AppKit>) -> &str {        kit.map_or("whole", |kit| kit.id.as_str())    }    /// What a copy pulled for this kit is marked with beside it: the kit's id    /// and the tables its pulls asked for ([`AppKit::pulled`]), or `whole`.    /// A kit that gains a table (Cotton Money taking Subscriptions, 11 Nov    /// 2026) marks its copies anew, so a copy pulled before is made again on    /// the kit as it ships, rows written before its cursor included, never    /// pulled on from a cursor that skipped them.    pub fn copy_mark(kit: Option<&AppKit>) -> String {        kit.map_or_else(            || "whole".to_string(),            |kit| {                // The tables kept whole past their window (`all_history`) follow the tables, after a space: a mark                // without them is the same as before this word, so a copy pulled with the window keeps its mark.                let whole = kit.whole_past_window();                let mark = format!("{} {}", kit.id, kit.pulled().join(","));                if whole.is_empty() { mark } else { format!("{mark} all:{}", whole.join(",")) }            },        )    }    /// The days this kit keeps of each dated table it pulls: its `window`, less the tables its switch keeps whole.    pub fn windows(&self) -> std::collections::BTreeMap<String, u32> {        self.window.iter().filter(|(table, _)| !self.all_history.contains(table)).map(|(table, days)| (table.clone(), *days)).collect()    }    /// The tables of `window` the switch keeps whole, in name order.    pub fn whole_past_window(&self) -> Vec<String> {        let mut whole: Vec<String> = self.window.keys().filter(|table| self.all_history.contains(table)).cloned().collect();        whole.sort();        whole    }    /// A copy mark's parts: the kit's id, the tables it pulled, and the tables it kept whole past their window.    pub fn read_copy_mark(mark: &str) -> (String, Vec<String>, Vec<String>) {        let mut parts = mark.split(' ');        let id = parts.next().unwrap_or_default().to_string();        let list = |text: &str| text.split(',').filter(|t| !t.is_empty()).map(str::to_string).collect::<Vec<_>>();        let tables = parts.next().map(list).unwrap_or_default();        let whole = parts.find_map(|part| part.strip_prefix("all:")).map(list).unwrap_or_default();        (id, tables, whole)    }}/// An ISO 8601 instant as a clock reads it in `zone` (an IANA name; UTC when/// it names none), in chrono's `format`: the Account card's times.pub fn local_clock(iso: &str, zone: &str, format: &str) -> Option<String> {    let at = chrono::DateTime::parse_from_rfc3339(iso).ok()?;    let zone: chrono_tz::Tz = zone.parse().unwrap_or(chrono_tz::UTC);    Some(at.with_timezone(&zone).format(format).to_string())}#[cfg(test)]#[path = "kit_tests.rs"]mod tests;