Cotton code
743 lines · 36.6 KB · RustRaw
//! A tool's ordered views. The list is definition data; counts belong to its reads.use super::automations::said;use super::{is_valid_id, refusal_words, DefinitionError, ListSort, SlipLayout, TableDefinition, TileLayout};use serde::{Deserialize, Serialize};use serde_json::{Map, Value};#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct ToolView {    pub id: String,    pub label: String,    /// Old definitions remain private until their author explicitly publishes them.    #[serde(default = "owner_visibility")]    pub visibility: String,    #[serde(default)]    pub is_default: bool,    /// Arguments of records.list, without paging or the reader's clock.    pub read: Map<String, Value>,    /// The link column of the read's table that names the record the view    /// is drawn for: a partitioned view is one record's list ("Between us    /// with <name>"), opened from that record's act (`RecordCommand::view`),    /// never a slip of the tool's ring on its own and never its default.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub partition: Option<String>,    /// The view's own order, slip and tile over its table's, for this view    /// alone: a Birthdays view over people orders by the next birthday and    /// says "in 12 days · turns 34" while People keeps its name order and    /// its own slip. Absent, the table's stand.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub sort: Option<ListSort>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub slip: Option<SlipLayout>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub tile: Option<TileLayout>,    /// How the list draws this view: "list" as slips one under another even    /// where the table's own face is a stack or a grid (Birthdays over    /// People's polaroids), "grid" as the table's cards, "cards" as the deck    /// of the table's (or this view's) `card`, one record in front, "script"    /// as the whole current story laid out as a screenplay to read (Cotton    /// Story's Script, `story.script`), "meetings" as Cotton Meetings' first    /// screen (record in one tap, every meeting's card with where it stands).    /// Absent, the deck where the table    /// carries a card, else the table's own layout.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub face: Option<String>,    /// A partitioned view's line under the record's head while the ring    /// stands on it, in the slip caption's form over the RECORD's columns    /// ("you owe 200" on a person under Between us).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub head_line: Option<super::SlipCaption>,    /// The view's own card over its table's (`card::CardFace`), for this view    /// alone: Birthdays draws a birthday face over People's person card. A    /// face a newer build wrote reads as none, the table's card standing.    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "super::card::face_or_absent")]    pub card: Option<super::card::CardFace>,    /// The section this view's whole read leads with, over its table's    /// `upcoming` (`ListUpcoming::lead`): the All deck leads with the late.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub lead: Option<String>,    /// The acts of its tool this view offers (`ToolAct`, by id): an act a    /// view names stands on that view's deck alone — its cards' fans and its    /// empty placeholder's — and one no view names on every deck of the tool    /// (Cotton Books' On this phone carries Sign in, Back up now and Sign    /// out; owner, 4 Nov 2026).    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub acts: Vec<String>,    /// The line over the view's deck that counts its rows in a stretch of    /// time ([`ViewHead`]): Finished says "12 of 24 this year".    #[serde(default, skip_serializing_if = "Option::is_none")]    pub head: Option<ViewHead>,    /// The tool's lists (its tables' groups) stand on its ring just before    /// this view; where no view says so, after the last.    #[serde(default, skip_serializing_if = "std::ops::Not::not")]    pub lists_before: bool,    /// The painted object the view's fan tile carries, one of    /// [`VIEW_PICTURES`]: the picture is the whole tile face, a card with    /// its object at the head, and the fan types the view's name and count    /// live beneath it (Cotton Books' seven, Round 17, 5 Nov 2026). Absent,    /// the tile is the plain cream card with the words alone.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub picture: Option<String>,    /// What this view narrows and orders by once its rows are open on the    /// device ([`OpenedRead`]): a sealed table's view of its sealed columns    /// (Health's Sleep, its nights' stages), read and ordered by its clear    /// columns on the object alone.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub opened: Option<OpenedRead>,    /// The one record of another table this view's rows belong to, chosen by    /// the person elsewhere in the app ([`CurrentOf`]): Story's Scenes,    /// Characters, Places, Notes and Script show the current story's rows    /// alone. Absent, the view reads its table as its `read` says.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub current: Option<CurrentOf>,}/// RULE (Cotton Story contract, 17 Nov 2026): a view may show only the rows/// of the CURRENT record of another table — the story a person is writing —/// where that record is the one most lately chosen. `column` is the link/// column of the view's table naming it (`story` on a scene); `by` is the/// clear moment column of the linked table written when a person chooses a/// record (`chosen_at` on a story). The current record is the linked/// table's row with the latest `by`; while none holds one, its newest row./// The core narrows the view's rows to `column` = that record's id wherever/// it reads the view; with no row at all the view is empty.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct CurrentOf {    pub column: String,    pub by: String,}/// RULE (coordinator, 12 Nov 2026: Health's views read sealed columns and the/// Worker refused them): a sealed table's view narrows and orders by its/// sealed columns only on the device, after its rows open. The object reads/// the view by its clear `read` and `sort` alone (a Health day by its day);/// `where` narrows the opened rows further and `tie` orders the rows the/// view's sort holds alike (a day's measures by their name, a day's/// workouts by their start). The Worker never reads this block, so a sealed/// column named here never reaches it; a list of the view on the object/// that would need `where` is refused by name, never widened.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct OpenedRead {    #[serde(default, rename = "where", skip_serializing_if = "Map::is_empty")]    pub where_: Map<String, Value>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub tie: Option<String>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub tie_descending: Option<bool>,}/// Kit schema: the closed vocabulary of painted view tiles, each kept in the/// app's catalogue as `view-<name>` (`scripts/import-books-materials.py/// views`). Books' seven (Round 17, 5 Nov 2026): an open book (Reading), a/// gold ribbon marker (Want to read), a closed book under a cream band/// (Finished), a closed book caught on a slip (Stopped), a pencil beside a/// marked strip (Highlights), a keypad phone (On this phone), a pile of/// books (All).pub const VIEW_PICTURES: &[&str] = &[    "open_book", "ribbon", "banded_book", "slipped_book", "pencil", "keypad_phone", "book_pile",];/// What a view's head line counts: the view's own rows whose table date/// falls in `period` (the list read's `period`, from the person's own day),/// said in `line`, a line of the `reading` set filled with `{n}`; with a/// `goal`, the count against the number one row holds, said in the goal's/// line with `{n}` and `{goal}` — the goal's line only while that number is/// above nought. Or, in place of a period, `here` ([`HereHead`]): what this/// device keeps of the view's rows.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct ViewHead {    #[serde(default, skip_serializing_if = "Option::is_none")]    pub period: Option<super::FigurePeriod>,    pub line: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub goal: Option<ViewGoal>,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub here: Option<HereHead>,}/// A head said of this device (Books' On this phone, 4 Nov 2026): the view's/// rows, the bytes of their files kept here, and whether this phone is/// backed up. `line` is said while it is, with `{n}`, `{size}` and `{ago}`;/// `not_backed_up` while it is not (never signed in, or no pass yet), with/// `{n}` and `{size}`. Each is a pair of the `reading` set, `.one` and/// `.other`, chosen by `{n}`.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct HereHead {    pub not_backed_up: String,}/// The number a head counts against: one row's number column, the row by/// its id (`face_settings`' `reader` row's `year_goal`).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(deny_unknown_fields)]pub struct ViewGoal {    pub table: String,    pub row: String,    pub column: String,    pub line: String,}/// The set a view head's lines are said from.pub const HEAD_LINES: &str = "reading";impl ToolView {    /// The table as this view reads it: its order, slip and tile in place of    /// the table's where the view declares them.    pub fn over(&self, table: &TableDefinition) -> TableDefinition {        let mut table = table.clone();        if let Some(sort) = &self.sort {            table.sort = Some(sort.clone());        }        if let Some(slip) = &self.slip {            table.slip = slip.clone();        }        if let Some(tile) = &self.tile {            table.tile = tile.clone();        }        if let Some(card) = &self.card {            table.card = Some(card.clone());        }        if let (Some(lead), Some(upcoming)) = (&self.lead, table.upcoming.as_mut()) {            upcoming.lead = Some(lead.clone());        }        // The opened rows' own order within the clear sort's (`OpenedRead`).        if let (Some(opened), Some(sort)) = (&self.opened, table.sort.as_mut()) {            if let Some(tie) = &opened.tie {                sort.tie = Some(tie.clone());                sort.tie_descending = opened.tie_descending;            }        }        table    }    /// The list read this view makes of `asked`: the view's `read.where`    /// narrows it, a key both name reading the asked value, and a view that    /// reads the archive (`read.archived`) reads it unless the read says    /// otherwise. Every list read that names a view goes through here — the    /// phone sends the same `where` itself, so the two reads are one.    pub fn narrow(&self, asked: &Map<String, Value>) -> Map<String, Value> {        let mut read = asked.clone();        if let Some(archived) = self.read.get("archived").filter(|archived| archived.is_boolean()) {            read.entry("archived").or_insert_with(|| archived.clone());        }        let opened = self.opened.as_ref().map(|opened| opened.where_.clone()).unwrap_or_default();        let own = match self.read.get("where") {            Some(Value::Object(own)) => own.clone(),            _ if opened.is_empty() => return read,            _ => Map::new(),        };        // The opened rows' narrowing (`OpenedRead`) after the clear read's:        // this device holds them open.        let own: Map<String, Value> = own.into_iter().chain(opened).collect();        // A column this device answers (an episode's `on_phone`) is never        // stored: the phone has read it into the rows it names already        // (`cotton_ffi::phone::episodes::narrow_where`), so the store never        // narrows by it again.        let table = self.read.get("table").and_then(Value::as_str).unwrap_or_default();        let mut filter: Map<String, Value> =            own.iter().filter(|(key, _)| !super::is_device_answered_column(table, key)).map(|(k, v)| (k.clone(), v.clone())).collect();        match asked.get("where") {            None | Some(Value::Null) => {}            Some(Value::Object(more)) => filter.extend(more.clone()),            // A filter of another form is the caller's whole say.            Some(_) => return read,        }        read.insert("where".into(), Value::Object(filter));        read    }    fn overrides(&self) -> bool {        self.sort.is_some() || self.slip.is_some() || self.tile.is_some() || self.card.is_some() || self.lead.is_some() || self.opened.is_some()    }}fn owner_visibility() -> String {    "owner".into()}fn private_record(id: &str) -> bool {    id.split('_').any(|word| {        matches!(            word,            "person"                | "people"                | "member"                | "customer"                | "student"                | "lead"                | "booking"                | "order"                | "payment"                | "transaction"                | "device"                | "credential"        )    })}/// A column a public page never carries: a person, booking, payment or/// device, or a contact or secret. The server's projection and the phone that/// draws it judge by this one rule.pub fn private_field(key: &str) -> bool {    private_record(key)        || matches!(key, "phone" | "email" | "password" | "token" | "amount" | "public_key" | "private_key")}/// Resolve view reads against their table definitions at every load/import/// boundary: a view's own order, slip and tile pass the checks the table's/// own get (on the table as the view reads it), and a public view reads a/// table safe to publish.pub fn validate_public_reads(    views: &[ToolView],    tables: &[super::TableDefinition],) -> Result<(), DefinitionError> {    for view in views.iter().filter(|view| view.overrides()) {        let Some(table) = tables.iter().find(|table| Some(table.id.as_str()) == view.read["table"].as_str()) else {            continue;        };        // A lead orders a day plan; a table read otherwise has none to lead.        if view.lead.is_some() && table.upcoming.is_none() {            return Err(DefinitionError::BadSlot {                slot: format!("tool.views.{}", view.id),                why: refusal_words("a_view_leads_with_late_today_later"),            });        }        let mut read = view.over(table);        // The views are checked here, not again inside the table's check.        read.tool = None;        read.validate().map_err(|error| DefinitionError::BadSlot {            slot: format!("tool.views.{}", view.id),            why: error.to_string(),        })?;    }    // What a view reads once its rows are open belongs to a sealed table, and    // names that table's columns: it narrows by them and its sort holds a tie    // for its order (`OpenedRead`).    for view in views.iter() {        let Some(opened) = &view.opened else { continue };        let Some(table) = tables.iter().find(|table| Some(table.id.as_str()) == view.read["table"].as_str()) else {            continue;        };        let column = |key: &str| table.columns.iter().any(|column| column.key == key);        let sorted = view.sort.as_ref().or(table.sort.as_ref()).is_some();        let named = opened.where_.keys().all(|key| column(key)) && opened.tie.as_deref().is_none_or(column);        if table.seal.is_none() || !named || (opened.tie.is_some() && !sorted) || (opened.where_.is_empty() && opened.tie.is_none()) {            return Err(DefinitionError::BadSlot {                slot: format!("tool.views.{}.opened", view.id),                why: refusal_words("a_view_opened_narrows_a_sealed_tables_open_rows"),            });        }    }    // A head counts the rows by their table's date: a table with none    // keeps no period. A head of this device's keeping counts no period.    for view in views.iter().filter(|view| view.head.as_ref().is_some_and(|head| head.period.is_some())) {        let Some(table) = tables.iter().find(|table| Some(table.id.as_str()) == view.read["table"].as_str()) else {            continue;        };        if table.date.is_none() {            return Err(DefinitionError::BadSlot {                slot: format!("tool.views.{}.head", view.id),                why: refusal_words("a_view_head_counts_its_rows_in_a_period"),            });        }    }    for view in views.iter().filter(|view| view.visibility == "public") {        let table = tables            .iter()            .find(|table| Some(table.id.as_str()) == view.read["table"].as_str());        let safe = table.is_some_and(|table| {            table.visibility.as_deref() == Some("public")                && table.source.is_none()                && table.engine.is_none()                && !private_record(&table.id)                && !table.columns.iter().any(|column| {                    private_field(&column.key)                        || column.link_to.as_deref().is_some_and(private_record)                })        });        if !safe {            return Err(DefinitionError::BadSlot { slot: "tool.views.visibility".into(),                why: said("public_view_must_read_a_public_table", &[("view", &format!("{:?}", view.id))]) });        }    }    Ok(())}/// The views of a package that carries no table, against the tables the/// database has: each reads one of them, and passes the checks/// [`validate_public_reads`] puts to any view.pub fn validate_reads_beside(    views: &[ToolView],    tables: &[super::TableDefinition],) -> Result<(), DefinitionError> {    for view in views {        let table = view.read["table"].as_str().unwrap_or_default();        if !tables.iter().any(|held| held.id == table) {            return Err(DefinitionError::UnknownTable { slot: format!("tool.views.{}", view.id), table: table.into() });        }    }    validate_public_reads(views, tables)}/// The tables as a package's views will read them once it is installed: each/// carries the columns `tool` contributes to it (`own_<tool>__<key>`), so a/// view may name its own tool's column on the first import, in the same/// check as every other column. A table already holding the key keeps its own.pub fn with_contributions(    tables: &[TableDefinition],    tool: &super::ToolDefinition,) -> Result<Vec<TableDefinition>, DefinitionError> {    let mut tables = tables.to_vec();    for (at, contribution) in tool.contributes.iter().enumerate() {        let bad = |why: String| DefinitionError::BadSlot { slot: format!("tool.contributes.{at}"), why };        let Some(table) = tables.iter_mut().find(|table| table.id == contribution.table) else { continue };        let entry = super::owner::contributed_column(&tool.id, &contribution.column).map_err(bad)?;        let column: super::Column = serde_json::from_value(entry).map_err(|error| bad(error.to_string()))?;        if table.column(&column.key).is_none() {            table.columns.push(column);        }    }    Ok(tables)}pub fn validate(views: &[ToolView]) -> Result<(), DefinitionError> {    let bad = |why: &str| DefinitionError::BadSlot {        slot: "tool.views".into(),        why: refusal_words(why),    };    // An absent list is supported for older and imported definitions.    if views.is_empty() {        return Ok(());    }    if views.iter().filter(|view| view.is_default).count() != 1 {        return Err(bad("has_exactly_one_default_view"));    }    let mut seen = std::collections::BTreeSet::new();    for view in views {        if !matches!(            view.visibility.as_str(),            "public" | "customer" | "staff" | "owner"        ) || view.visibility == "public"            && view.read["table"].as_str().is_some_and(private_record)        {            return Err(bad("visibility_is_public_customer_staff_or_owner"));        }        if !is_valid_id(&view.id) || !seen.insert(&view.id) || view.label.trim().is_empty() {            return Err(bad("each_view_has_its_own_id_and"));        }        if !view            .read            .get("table")            .and_then(Value::as_str)            .is_some_and(is_valid_id)        {            return Err(bad("each_view_reads_a_table"));        }        if view.face.as_deref().is_some_and(|face| !matches!(face, "list" | "grid" | "cards" | "script" | "meetings")) {            return Err(bad("a_view_s_face_is_list_grid"));        }        if view.partition.as_deref().is_some_and(|column| !is_valid_id(column) || view.is_default) {            return Err(bad("a_partitioned_view_names_its_link_column"));        }        if view.current.as_ref().is_some_and(|current| !is_valid_id(&current.column) || !is_valid_id(&current.by) || view.partition.is_some()) {            return Err(bad("a_current_view_names_its_link_and_moment"));        }        if view.lead.as_deref().is_some_and(|lead| !matches!(lead, "late" | "today" | "later" | "undated")) {            return Err(bad("a_view_leads_with_late_today_later"));        }        if view.read.keys().any(|key| {            !matches!(                key.as_str(),                "table" | "where" | "section" | "archived" | "period" | "empty"            )        }) {            return Err(bad(                "a_view_declares_its_list_filter_never",            ));        }        if let Some(head) = &view.head {            validate_head(view, head)?;        }        if view.partition.is_some() && (view.lists_before || !view.acts.is_empty()) {            return Err(bad("a_partitioned_view_is_no_slip_of_the_ring"));        }        if view.picture.as_deref().is_some_and(|picture| !VIEW_PICTURES.contains(&picture)) {            return Err(bad("a_known_view_picture"));        }    }    if views.iter().filter(|view| view.lists_before).count() > 1 {        return Err(bad("one_view_says_where_the_lists_stand"));    }    Ok(())}/// A head names its line, a period the read itself keeps none of, and a goal/// by ids; the lines are the `reading` set's, said where they are drawn.fn validate_head(view: &ToolView, head: &ViewHead) -> Result<(), DefinitionError> {    let bad = |why: &str| DefinitionError::BadSlot { slot: format!("tool.views.{}.head", view.id), why: refusal_words(why) };    let line = |line: &str| !line.is_empty() && line.split('.').all(is_valid_id);    if let Some(here) = &head.here {        if !line(&head.line) || !line(&here.not_backed_up) || head.period.is_some() || head.goal.is_some() {            return Err(bad("a_view_head_of_this_device_counts_no_period"));        }        return Ok(());    }    if !line(&head.line) || view.read.contains_key("period") || head.period.is_none_or(|period| period == super::FigurePeriod::NextDay) {        return Err(bad("a_view_head_counts_its_rows_in_a_period"));    }    if let Some(goal) = &head.goal {        if !is_valid_id(&goal.table) || !is_valid_id(&goal.column) || goal.row.trim().is_empty() || !line(&goal.line) {            return Err(bad("a_view_head_s_goal_names_a_row_s_number"));        }    }    Ok(())}/// Every act a view offers is one its tool declares (`acts`), named once.pub fn validate_acts(views: &[ToolView], acts: &[super::ToolAct]) -> Result<(), DefinitionError> {    for view in views {        let mut seen = std::collections::BTreeSet::new();        if view.acts.iter().any(|id| !acts.iter().any(|act| &act.id == id) || !seen.insert(id)) {            return Err(DefinitionError::BadSlot {                slot: format!("tool.views.{}.acts", view.id),                why: refusal_words("a_view_offers_its_tool_s_own_acts"),            });        }    }    Ok(())}#[cfg(test)]mod tests {    use super::*;    use crate::definitions::builtin_table_definitions;    use serde_json::json;    // RULE: a view's painted tile is one of the kit's closed vocabulary; an unknown picture is refused, never drawn as a blank card.    #[test]    fn a_view_picture_is_a_closed_kit_vocabulary() {        let view = |picture: &str| -> ToolView {            serde_json::from_value(json!({"id": "reading", "label": "Reading", "is_default": true, "read": {"table": "book"}, "picture": picture})).unwrap()        };        for picture in VIEW_PICTURES {            validate(&[view(picture)]).unwrap_or_else(|error| panic!("{picture}: {error}"));        }        for picture in ["", "act-stamp", "view-open_book", "unknown"] {            assert!(validate(&[view(picture)]).is_err(), "{picture}");        }        let plain: ToolView = serde_json::from_value(json!({"id": "all", "label": "All", "is_default": true, "read": {"table": "book"}})).unwrap();        assert_eq!(plain.picture, None);        assert!(!serde_json::to_value(&plain).unwrap().as_object().unwrap().contains_key("picture"), "a view with no picture says none");    }    // RULE: Cotton Books' seven views each carry their painted tile (Round 17, 5 Nov 2026); every other personal tool's views carry none, so Cotton's and Rigby's other tiles stay the plain cream card.    #[test]    fn books_views_carry_their_painted_tiles_and_no_other_tool_does() {        let tools = cotton_store::manifest_dir().join("kits/personal/tools");        let mut seen = 0;        for entry in std::fs::read_dir(tools).expect("the personal kit's tools") {            let manifest = entry.expect("a kit tool").path().join("manifest.json");            let Ok(text) = std::fs::read_to_string(&manifest) else { continue };            let tool: serde_json::Value = serde_json::from_str(&text).expect("a manifest reads");            let views: Vec<ToolView> = serde_json::from_value(tool["views"].clone()).unwrap_or_default();            let pictures: Vec<(String, Option<String>)> = views.into_iter().map(|view| (view.id, view.picture)).collect();            if tool["id"] == "books" {                let expected = [                    ("reading", "open_book"), ("want_to_read", "ribbon"), ("finished", "banded_book"), ("stopped", "slipped_book"),                    ("highlights", "pencil"), ("on_phone", "keypad_phone"), ("all", "book_pile"),                ];                let expected: Vec<(String, Option<String>)> = expected.iter().map(|(id, picture)| (id.to_string(), Some(picture.to_string()))).collect();                assert_eq!(pictures, expected);            } else {                assert!(pictures.iter().all(|(_, picture)| picture.is_none()), "{}: {pictures:?}", manifest.display());            }            seen += 1;        }        assert!(seen > 1, "the kit's tools were read");    }    // RULE: a head of this device (On this phone) names its two lines and counts no period and no goal; a head with neither a period nor `here` is refused.    #[test]    fn a_head_of_this_device_counts_no_period() {        let view = |head: serde_json::Value| -> ToolView {            serde_json::from_value(json!({"id": "on_phone", "label": "On this phone", "is_default": true, "read": {"table": "book"}, "head": head})).unwrap()        };        let checked = |head: serde_json::Value| validate(&[view(head)]);        assert!(checked(json!({"line": "list.on_phone", "here": {"not_backed_up": "list.on_phone_not_backed_up"}})).is_ok());        assert!(checked(json!({"line": "list.on_phone", "here": {"not_backed_up": ""}})).is_err());        assert!(checked(json!({"period": "this_year", "line": "list.on_phone", "here": {"not_backed_up": "list.on_phone_not_backed_up"}})).is_err());        assert!(checked(json!({"line": "list.on_phone", "here": {"not_backed_up": "list.on_phone_not_backed_up"},            "goal": {"table": "face_settings", "row": "reader", "column": "year_goal", "line": "list.this_year_of_goal"}})).is_err());        assert!(checked(json!({"line": "list.this_year"})).is_err(), "a head counts a period or this device");    }    // RULE: Publishing a view cannot publish identity, booking, payment or device rows,    // even when a package author labels the underlying table public or renames it.    #[test]    fn the_loader_refuses_public_views_of_private_records() {        for id in [            "person",            "device",            "yoga_member",            "yoga_booking",            "yoga_payment",            "kitchen_customer",            "kitchen_order",        ] {            let raw = json!({"id":"public","label":"Public","is_default":true,"visibility":"public","read":{"table":id}});            let views = vec![serde_json::from_value::<ToolView>(raw).unwrap()];            assert!(validate(&views).is_err(), "{id}");        }        let package = crate::toolkits::shipped_kit_tools()            .into_iter()            .find(|p| p.tool.id == "yoga")            .unwrap();        let mut table = package            .tables            .iter()            .find(|t| t.id == "yoga_member")            .unwrap()            .clone();        table.id = "renamed".into();        table.visibility = Some("public".into());        let view: ToolView = serde_json::from_value(json!({"id":"all","label":"All","is_default":true,"visibility":"public","read":{"table":"renamed"}})).unwrap();        assert!(validate_public_reads(&[view], &[table]).is_err());    }    fn health_day() -> TableDefinition {        serde_json::from_str(include_str!("../../kits/personal/tables/health_day.json")).expect("health_day reads")    }    // RULE (coordinator, 12 Nov 2026): a sealed table's view narrows and orders by its sealed columns only once its rows are open on the device (`OpenedRead`): the clear read and sort are what the object reads, the opened where narrows after them and the opened tie orders a day's rows.    #[test]    fn a_sealed_views_opened_block_narrows_and_orders_its_open_rows() {        let sleep: ToolView = serde_json::from_value(json!({"id":"sleep","label":"Sleep","is_default":false,            "read":{"table":"health_day"},"sort":{"column":"day","descending":true},            "opened":{"where":{"metric":["sleep_deep","sleep_rem"]},"tie":"metric","tie_descending":false}})).unwrap();        let asked = json!({"table":"health_day","where":{"day":"2026-11-12"}});        assert_eq!(sleep.narrow(asked.as_object().unwrap())["where"], json!({"metric":["sleep_deep","sleep_rem"],"day":"2026-11-12"}));        let read = sleep.over(&health_day());        let sort = read.sort.expect("a sort");        assert_eq!((sort.column.as_str(), sort.descending, sort.tie.as_deref(), sort.tie_descends()), ("day", Some(true), Some("metric"), false));        validate_public_reads(&[sleep.clone()], &[health_day()]).expect("a sealed table's opened view stands");        // The opened block never reaches the clear read: the object's list reads the view by day alone.        assert!(sleep.read.get("where").is_none());        // A view with no opened block narrows as before.        let today: ToolView = serde_json::from_value(json!({"id":"today","label":"Today","is_default":true,            "read":{"table":"health_day","where":{"day":{"on":"today"}}},"sort":{"column":"day"},"opened":{"tie":"metric"}})).unwrap();        assert_eq!(today.narrow(json!({"table":"health_day"}).as_object().unwrap())["where"], json!({"day":{"on":"today"}}));    }    // RULE: an opened block is a sealed table's alone, names its columns, and orders only under a sort; one that says nothing is refused.    #[test]    fn an_opened_block_is_refused_off_a_sealed_table_or_off_its_columns() {        let view = |table: &str, opened: Value| -> ToolView {            serde_json::from_value(json!({"id":"v","label":"V","is_default":false,"read":{"table":table},"opened":opened})).unwrap()        };        let mut open = health_day();        open.seal = None;        let refused = |view: ToolView, table: TableDefinition| {            validate_public_reads(&[view], &[table]).expect_err("refused");        };        refused(view("health_day", json!({"tie":"metric"})), open);        refused(view("health_day", json!({"where":{"glucose":1}})), health_day());        refused(view("health_day", json!({"tie":"nowhere"})), health_day());        refused(view("health_day", json!({})), health_day());        assert!(serde_json::from_value::<ToolView>(json!({"id":"v","label":"V","read":{"table":"health_day"},"opened":{"sort":"metric"}})).is_err(), "an opened block says where and tie alone");    }    // RULE: A view that reads the archive reads it on every list that names it, unless the read says otherwise; its `where` still narrows it.    #[test]    fn a_view_of_the_archive_reads_the_archive() {        let view: ToolView = serde_json::from_value(json!({"id":"archived","label":"Archived","is_default":false,            "read":{"table":"memory","where":{"status":"archived"},"archived":true}})).unwrap();        let asked = json!({"table":"memory","limit":1});        let read = view.narrow(asked.as_object().unwrap());        assert_eq!(Value::Object(read), json!({"table":"memory","limit":1,"archived":true,"where":{"status":"archived"}}));        let asked = json!({"table":"memory","archived":false});        assert_eq!(view.narrow(asked.as_object().unwrap())["archived"], json!(false));        let live: ToolView = serde_json::from_value(json!({"id":"all","label":"All","is_default":true,"read":{"table":"memory"}})).unwrap();        assert!(!live.narrow(json!({"table":"memory"}).as_object().unwrap()).contains_key("archived"));    }    // RULE: A view's `where` on a column the device answers (a film's `on_phone`) never narrows the store: the phone reads it into the rows it names, and those stand.    #[test]    fn a_view_never_narrows_the_store_by_a_device_answered_column() {        let view: ToolView = serde_json::from_value(json!({"id":"downloaded","label":"Downloaded","is_default":false,            "read":{"table":"film","where":{"on_phone":"kept","played":"started"}}})).unwrap();        let asked = json!({"table":"film","where":{"audio_url":["https://example.test/ep1.mp3"]}});        assert_eq!(view.narrow(asked.as_object().unwrap())["where"],                   json!({"played":"started","audio_url":["https://example.test/ep1.mp3"]}));    }    // RULE: A shipped tool always opens one declared view; two defaults would let surfaces disagree.    #[test]    fn every_shipped_tool_has_exactly_one_default_view() {        for table in builtin_table_definitions() {            if let Some(tool) = &table.tool {                assert_eq!(                    tool.views.iter().filter(|view| view.is_default).count(),                    1,                    "{}",                    table.id                );                validate(&tool.views).unwrap();                assert!(                    tool.views.iter().all(|view| view.visibility != "public"),                    "Cotton tools keep personal data private"                );            }        }        for (table, default) in [            ("todo", "today"),            ("person", "all"),            ("email_thread", "today"),            ("event", "today"),            ("media", "all"),        ] {            let tool = builtin_table_definitions()                .iter()                .find(|definition| definition.id == table)                .unwrap()                .tool                .as_ref()                .unwrap();            assert_eq!(                tool.views.iter().find(|view| view.is_default).unwrap().id,                default            );        }        let shipped = crate::toolkits::shipped_kit_tools();        // A package that carries no table reads the tables the others bring.        let brought: Vec<TableDefinition> = shipped.iter().flat_map(|package| package.tables.iter().cloned()).collect();        for package in &shipped {            assert_eq!(                package                    .tool                    .views                    .iter()                    .filter(|view| view.is_default)                    .count(),                1,                "{}",                package.tool.id            );            validate(&package.tool.views).unwrap();            let tables = if package.tables.is_empty() { &brought } else { &package.tables };            validate_public_reads(&package.tool.views, tables).unwrap();        }        for count in [0, 2] {            let views: Vec<ToolView> = serde_json::from_value(json!([                {"id":"a","label":"A","is_default":count > 0,"read":{"table":"todo"}},                {"id":"b","label":"B","is_default":count > 1,"read":{"table":"todo"}}            ]))            .unwrap();            assert!(validate(&views).is_err());        }    }}