//! Table and tool DEFINITIONS — a table's shape and its faces as data. //! //! A [`TableDefinition`] says what a table holds (its columns and their //! types), which column is its title, its date, its project and its manual //! order, and how it is drawn at each size: the slip (one row), the tile (the //! board's face) and the page (one record). A [`ToolDefinition`] names the //! tables one tool works with. Both are records in their own synced tables //! (`cotton_table_definitions`, `cotton_tool_definitions`), stored as the JSON //! these types round-trip, so a definition written on one device reaches every //! other one under the same who-wins rule as any record. //! //! The JSON is a SHARED FORMAT: the app draws from exactly these field names, //! so the serde attributes below are the contract, not a convenience. READING //! is tolerant and AUTHORING is strict (design note 26203e21 §8, [`tolerant`]): //! a row a newer device wrote decodes here with the keys this build cannot //! name kept in `unknown` (top level) or passed over (deeper), so an older Mac //! relays it and an older phone draws what it knows; a definition authored //! here (a package, a built-in file) is refused for any key this build does //! not name, through [`tolerant::unknown_keys`] — the guard that replaced //! `deny_unknown_fields`. //! //! The kit tools' tables are compiled in from //! `crates/cotton-core/kits/personal/tables/` and `kits/shell/tables/` ([`builtin_table_definitions`]), //! one definition per table: the one the object serves. //! No launch writes one into a database (72nd amendment): a stored //! definition is a record a tool's import wrote. This crate opens nothing. use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; pub mod automations; pub mod acts; pub mod board; pub mod card; pub mod reserve; mod commands; mod import_validation; pub mod computed; pub mod contributors; pub mod fileable; pub mod fan_tile; pub mod format; pub mod owner; pub mod package; pub mod parts; pub mod record_page; pub mod pictures; pub mod spoken; pub mod theme; pub mod tolerant; pub mod tool_views; pub mod seal; pub use seal::SealSpec; pub use commands::{CommandDoes, CommandKind, CommandLands, CommandList, CommandOutcome, CommandPick, PickKind, RecordCommand, ACT_OBJECTS, CARRIED_COMMAND_TABLES, COMMAND_BINDINGS, COMMAND_METHODS, COPY_SEALED, COUNT_BINDING, COUNT_WORD, GENERIC_DELETE, RECEIPT_NAME, RECEIPT_PICKED, RECORD_ID}; pub(crate) use commands::when_not; pub use record_page::{record_views, RecordView, OVERVIEW, PageGroup, PageOpens, PageViewRef, GroupColumns, GroupReach, GroupReads, DEFAULT_PEEK, GROUP_COLUMNS}; pub use parts::{slip_kind, PagePart, PageParts, PageShape, PLAIN_PAGE, PartsActs, PartsHead, PartsList, PartsMatch, PartsRead, ReadFormat, ReadLine, SlipWidth, SlipsLayout, PAGE_READS, SHORT_HASH, SLIP_ACTS, SLIP_DESTROYS, SLIP_OTHER}; /// The part a table plays that the app asks for by name, from a fixed /// vocabulary: where the board's sentence goes by what it guesses (`todo`, /// `event`, `note`, `person`), the people and the projects a sentence's /// names are matched against, and where a sentence filed nowhere is kept /// (`thought`). The app asks for the table playing a role, never for a /// table by its id (architect, 13 Oct 2026). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum TableRole { Todo, Event, Note, Person, Project, Thought, /// The database's tools, in Home's order. Tools, /// The databases this device holds, each its own record ("Name and /// picture"). Database, /// Every device's copy of a database, how far behind each is: what a /// database's sync page lists. Copies, /// The people admitted to the database, and what a customer reads when /// signing in to it is refused. Members, } /// The read that answers a record's projects and memberships: the kind the /// link verbs name the record by, the read (`read.`, or `record` with /// the kind), and the screen families it draws. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ProjectsRead { pub kind: String, pub read: String, pub families: Vec, } /// What a bin's rows hold: the column naming each record's own table, and /// the values a Restore writes to the row. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct BinnedRows { pub from: String, pub restore: std::collections::BTreeMap, } /// How a record of this table says its date where it is listed outside its /// own tool ("Also linked"): the words around `{when}` for a day it is due or /// starts (`scheduled`) and for the day it was made (`made`). A table naming /// neither reads "due {when}" and "added {when}". #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LinkedWhen { #[serde(default, skip_serializing_if = "Option::is_none")] pub scheduled: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub made: Option, } /// A list drawn as people's stories: pictures grouped by who posted them, /// the print's words on the list (`picture`) and on the page (`page`), and /// the rows whose picture plays (`video`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct StoriesLayout { pub picture: PolaroidLayout, pub page: PolaroidLayout, pub video: ValueMatch, } /// The columns a queued message row is written with: the link to the /// conversation's record and the words. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ConversationQueue { pub link: String, pub body: String, } /// A view the app stands above a table's list. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum ListHead { /// The next alarm this device will ring, counting down. NextAlarm, } /// Column types in the shared format's spelling. /// `url` (round six) is a web address: text that opens on tap and is edited /// as text. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ColumnType { Text, /// A stored account identifier whose public value is only its ending. #[serde(rename = "account_number")] AccountNumber, Longtext, Date, Time, Number, Bytes, Amount, Choice, Link, Photo, File, Bool, Url, Place, } impl ColumnType { pub const ALL: [ColumnType; 15] = [ ColumnType::Text, ColumnType::AccountNumber, ColumnType::Longtext, ColumnType::Date, ColumnType::Time, ColumnType::Number, ColumnType::Bytes, ColumnType::Amount, ColumnType::Choice, ColumnType::Link, ColumnType::Photo, ColumnType::File, ColumnType::Bool, ColumnType::Url, ColumnType::Place, ]; } /// A place keeps the person's text beside the selected stable dataset/record id. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PlaceColumns { pub id: String, pub country: String, pub zone: String, /// The picked place's coordinates and the published version it was read /// at, copied in beside its id (14 Nov 2026), where a definition names them. #[serde(default, skip_serializing_if = "Option::is_none")] pub lat: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub lng: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option, } /// One typed column. `name` falls back to the key where it is absent; /// `required` and `indexed` are absent rather than `false` unless the source /// said so, so a definition round-trips byte for byte. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Column { pub key: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option, #[serde(rename = "type")] pub column_type: ColumnType, /// A balance marker: automations cannot mutate stored counters. #[serde(default, skip_serializing_if = "Option::is_none")] pub counter: Option, /// Companion columns written atomically when a place is chosen. #[serde(default, skip_serializing_if = "Option::is_none")] pub place: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub required: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub link_to: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub choices: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub indexed: Option, /// No person edits it: the page draws it and opens no editor for it, and /// no patch writes it. Its engine keeps it, or else the table's declared /// producer, or else the app fills it as it makes the record (a /// highlight's passage and place); `records::authored_column` is the rule. #[serde(default, skip_serializing_if = "Option::is_none")] pub readonly: Option, /// An engine's current value. Editable settings come from their owner /// reader; a declared live read may overlay readonly facts only. #[serde(default, skip_serializing_if = "Option::is_none")] pub live: Option, /// A field of the facts sentence, only with an explicit reading. #[serde(default, skip_serializing_if = "Option::is_none")] pub fact: Option, /// Sentence template: {value} is a human scalar, {date} a day and month, /// {datetime} a local weekday, day and time. #[serde(default, skip_serializing_if = "Option::is_none")] pub reading: Option, /// How many decimals a number's {value} shows, half-up /// (`cotton_rules::computed::figure`); absent: at most 2. The stored /// value is never rounded, only the reading. #[serde(default, skip_serializing_if = "Option::is_none")] pub decimals: Option, /// Separator before this fact; absent is the sentence's middle dot. #[serde(default, skip_serializing_if = "Option::is_none")] pub fact_join: Option, /// Choice values which fill a field card's toggle object. #[serde(default, skip_serializing_if = "Option::is_none")] pub toggle_on: Option>, /// A read-only column the person may still edit while another column /// holds one of `values`: a thought's words until it is filed. #[serde(default, skip_serializing_if = "Option::is_none")] pub editable_when: Option, /// The word a face reads when the column holds nothing ("Once"). #[serde(default, skip_serializing_if = "Option::is_none")] pub placeholder: Option, /// A date column's name once its day has gone ("Was" for "By"). #[serde(default, skip_serializing_if = "Option::is_none")] pub past_name: Option, /// A latitude column's longitude column: together they are a place. #[serde(default, skip_serializing_if = "Option::is_none")] pub pair: Option, /// A number column's count words ("1 order", "6 orders", "Sold out"). #[serde(default, skip_serializing_if = "Option::is_none")] pub units: Option, /// How a value is read out, beyond what its type says. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub format: Option, /// A choice column's stamps: the choice value, and the stamp it wears. #[serde(default, skip_serializing_if = "Option::is_none")] pub stamps: Option>, /// A choice column's allowed moves: from each value, the values it may go /// to. Absent: any choice, any time. #[serde(default, skip_serializing_if = "Option::is_none")] pub moves: Option>>, /// What choosing a value also means, one sentence per value. #[serde(default, skip_serializing_if = "Option::is_none")] pub hints: Option>, /// A drawn object per choice value, overriding the theme's type object. /// Missing entries use the ordinary column object; names belong to the theme. #[serde(default, skip_serializing_if = "Option::is_none")] pub objects: Option>, /// A choice column holding SEVERAL of its choices: its value is a list. #[serde(default, skip_serializing_if = "Option::is_none")] pub multiple: Option, /// A several-choice column of the week's seven days, Monday first. #[serde(default, skip_serializing_if = "Option::is_none")] pub week: Option, /// A date column whose value is a MONTH (a card's expiry): read as the /// month and year, never a day or a clock. #[serde(default, skip_serializing_if = "Option::is_none")] pub month: Option, /// The page draws the column only while another column holds one of /// `values`. #[serde(default, skip_serializing_if = "Option::is_none")] pub shown_when: Option, /// A text value written blind: typed in a secure field, answered masked. #[serde(default, skip_serializing_if = "Option::is_none")] pub secret: Option, /// Values drawn in red where a face shows them ("missed"). #[serde(default, skip_serializing_if = "Option::is_none")] pub red_when: Option>, // Round 2 (1 Oct 2026): every key below is optional and absent unless the // source said so, appended so a definition written before them // round-trips unchanged. /// A face of its own the value is drawn with, beyond its type. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub presentation: Option, /// A column of this record holding the list of choices it offers (an /// import's candidate senders); a choice column naming one needs no /// `choices` of its own. #[serde(default, skip_serializing_if = "Option::is_none")] pub choices_from: Option, /// Words for each choice or text value. Repeat-rule text maps preset /// identifiers (including `custom`); app-name text maps provider ids. #[serde(default, skip_serializing_if = "Option::is_none")] pub labels: Option>, /// The same as `labels` — the Settings spelling ("API key" for /// "api_key"). The two builders named it apart; both are read. #[serde(default, skip_serializing_if = "Option::is_none")] pub choice_names: Option>, /// A date column's last day: the two read as one range. #[serde(default, skip_serializing_if = "Option::is_none")] pub until: Option, /// A picture's width and height columns, so it is drawn at its own /// proportion. #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option>, /// A picture's words: the column handwritten in its margin. #[serde(default, skip_serializing_if = "Option::is_none")] pub caption: Option, /// A picture's words when its `caption` column says nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub caption_fallback: Option, /// On a several-record link: columns of plain names, one a line, drawn /// in the same list as its tags, before and after them. #[serde(default, skip_serializing_if = "Option::is_none")] pub plain_before: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub plain_after: Option, /// A picture or a read-only text whose tap opens another record (a /// duplicate's two sides; a todo's Repeats, its repeat rule). #[serde(default, skip_serializing_if = "Option::is_none")] pub opens: Option, /// A file column's still (a photo column): with one it plays as a film, /// without as a recording. #[serde(default, skip_serializing_if = "Option::is_none")] pub poster: Option, /// A text column holding an IANA time zone, read as the clock there. #[serde(default, skip_serializing_if = "Option::is_none")] pub zone: Option, /// What a date column says on a day's line for a row that names its day /// and no hour ("due today", "all day"), never the midnight it is stored /// as. Date only. #[serde(default, skip_serializing_if = "Option::is_none")] pub untimed: Option, /// A date that comes round every year (a birthday; "--MM-DD" with no /// year). #[serde(default, skip_serializing_if = "Option::is_none")] pub yearly: Option, /// A text column whose values are ways to reach someone. #[serde(default, skip_serializing_if = "Option::is_none")] pub reach: Option, /// Who wrote a long text and when, in pencil under it. #[serde(default, skip_serializing_if = "Option::is_none")] pub provenance: Option, /// An amount's words for which way it runs, read with the figure /// unsigned. #[serde(default, skip_serializing_if = "Option::is_none")] pub signs: Option, /// The ISO currency text or money_account link read with an amount. #[serde(default, skip_serializing_if = "Option::is_none")] pub currency: Option, /// Whether the amount keeps its sign; explicit false stays false. #[serde(default, skip_serializing_if = "Option::is_none")] pub signed: Option, /// A readonly link whose destination table follows a choice column. #[serde(default, skip_serializing_if = "Option::is_none")] pub link_by: Option, /// The policy for copying a secret; decoding never reveals its value. #[serde(default, skip_serializing_if = "Option::is_none")] pub reveal: Option, /// A choice stamp's ink, one tone per choice value. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::known_words::<_, StampTone, _>")] pub tones: Option>, /// A long text drawn as Markdown. #[serde(default, skip_serializing_if = "Option::is_none")] pub markdown: Option, /// The value a new record gets when its data leaves this column out (or /// null): a value of the column's own type, a choice among its choices; /// never on a link, photo or file, which name something that must exist. /// A patch never applies it — clearing a column clears it. #[serde(default, skip_serializing_if = "Option::is_none")] pub default: Option, /// What the core works the value out from (`computed.rs`): nobody writes /// it, and it is stored in no synced column. #[serde(default, skip_serializing_if = "Option::is_none")] pub computed: Option, /// A link column's say in what it contributes to the page of the record /// it points at (`contributors.rs`): `false`, or the words of its list. #[serde(default, skip_serializing_if = "Option::is_none")] pub contributes: Option, /// The OWNER'S, never a shipped file's (`owner.rs`): a column he put /// out of the look. No page draws it; its values stay where they are and /// its engine reads and writes it as before. #[serde(default, skip_serializing_if = "Option::is_none")] pub hidden: Option, /// A link column whose values are edges, not a value of the row: a /// link adds the record it names, or takes it off when it is there /// already, one at a time (a record's people; `link_records`). #[serde(default, skip_serializing_if = "Option::is_none")] pub edges: Option, /// A link to the picture or file the record shows or is about (a /// person's avatar) — never a parent the record belongs to. #[serde(default, skip_serializing_if = "Option::is_none")] pub media: Option, /// A choice column's families: each member choice and the choice it is /// one of (an event's `dinner` is a `meal`), one level deep — a family /// is never itself a member. What an engine falls back to when it is /// sure of the family and not the member. #[serde(default, skip_serializing_if = "Option::is_none")] pub families: Option>, /// A choice column's exemplars: short phrases a record of each choice /// is said with ("Leg day" for `gym`), which an engine that fills the /// column compares a record's words with. Data, never code. #[serde(default, skip_serializing_if = "Option::is_none")] pub examples: Option>>, /// The columns a record is said with when an engine fills this choice /// from its exemplars (an event's `title`, `notes` and `location`): the /// first alone, then all of them together. Each a column of the table. #[serde(default, skip_serializing_if = "Option::is_none")] pub says: Option>, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ColumnLinkBy { pub column: String, pub tables: OrderedMap, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SecretReveal { pub once: bool, pub expires: u32, } /// A slip can name a link column directly or carry the shared opens object. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum SlipOpens { Column(String), Record(RecordOpens), } /// A face of its own a column's value is drawn with — each belongs to the /// types it names. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ColumnPresentation { /// A story's sources list. Text or long text. Sources, /// The file viewer (a continuous PDF, an image). File only. File, /// Typed blind and shown masked. Text only. Password, /// A message's shared media. File only. Attachments, /// What was said, a turn each under its clock time; a turn plays the /// record's recording from there. Long text only. Turns, /// A scene's heading: stored as typed, read in capitals wherever it is /// drawn. Text only. Heading, /// A version's changes, as their JSON: each field's /// label, then the word-level spans of changed prose — removed struck in /// red, added underlined — or the value before struck and the value after /// underlined. Long text only. Changes, } impl ColumnPresentation { /// The column types this presentation draws, and the words a refusal says. pub fn types(self) -> (&'static [ColumnType], &'static str) { match self { ColumnPresentation::Sources => ( &[ColumnType::Text, ColumnType::Longtext], "a_text_or_a_long_text", ), ColumnPresentation::File | ColumnPresentation::Attachments => { (&[ColumnType::File], "a file") } ColumnPresentation::Password | ColumnPresentation::Heading => { (&[ColumnType::Text], "a text") } ColumnPresentation::Turns | ColumnPresentation::Changes => (&[ColumnType::Longtext], "a long text"), } } } /// Where a tap goes when a row or a picture stands for another record: the /// record whose id `column` holds, in `table`, else in the table /// `table_column`'s value names, else in the column's own `link_to`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RecordOpens { pub column: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub table: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub table_column: Option, } /// What a `reach` column's values are: the word alone, or the word and the /// column holding the channel a conversation with them runs over. Either /// form round-trips as it was written. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum ColumnReach { Kind(ReachKind), Detailed(ReachDetail), } impl ColumnReach { pub fn kind(&self) -> ReachKind { match self { ColumnReach::Kind(kind) => *kind, ColumnReach::Detailed(detail) => detail.kind, } } pub fn channel(&self) -> Option<&str> { match self { ColumnReach::Kind(_) => None, ColumnReach::Detailed(detail) => detail.channel.as_deref(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ReachKind { Phone, Email, Instagram, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ReachDetail { pub kind: ReachKind, #[serde(default, skip_serializing_if = "Option::is_none")] pub channel: Option, } /// Who wrote a long text (`by`), when (`at`, a date), and what has arrived /// since (`since`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ColumnProvenance { pub by: String, pub at: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub since: Option, } /// An amount's words above nothing, below it, and at nothing at all. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AmountSigns { pub positive: String, pub negative: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub zero: Option, } /// An object of names to values that keeps the order it was written in, so a /// definition round-trips byte for byte, and refuses a name given twice /// (which a JSON object can carry and a definition cannot mean). #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct OrderedMap(pub Vec<(String, V)>); impl OrderedMap { pub fn get(&self, key: &str) -> Option<&V> { self.0 .iter() .find(|(name, _)| name == key) .map(|(_, value)| value) } pub fn keys(&self) -> impl Iterator { self.0.iter().map(|(name, _)| name) } pub fn iter(&self) -> impl Iterator { self.0.iter().map(|(name, value)| (name, value)) } pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl Serialize for OrderedMap { fn serialize(&self, serializer: S) -> Result { use serde::ser::SerializeMap; let mut map = serializer.serialize_map(Some(self.0.len()))?; for (name, value) in &self.0 { map.serialize_entry(name, value)?; } map.end() } } impl<'de, V: Deserialize<'de>> Deserialize<'de> for OrderedMap { fn deserialize>(deserializer: D) -> Result { struct Entries(std::marker::PhantomData); impl<'de, V: Deserialize<'de>> serde::de::Visitor<'de> for Entries { type Value = OrderedMap; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("an object") } fn visit_map>( self, mut access: A, ) -> Result { let mut entries: Vec<(String, V)> = Vec::new(); while let Some((name, value)) = access.next_entry::()? { if entries.iter().any(|(held, _)| *held == name) { return Err(serde::de::Error::custom(refusal_said("is_named_twice", &[("name", format!("{:?}", name))]))); } entries.push((name, value)); } Ok(OrderedMap(entries)) } } deserializer.deserialize_map(Entries(std::marker::PhantomData)) } } /// A count's words: the number, then `one` or `other`; a zero reads as `zero` /// alone when there is one, and an empty `zero` says nothing at all. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ColumnUnits { pub one: String, pub other: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub zero: Option, } /// Fields a unit template reads. `{n}` is the number; other fields are /// declared text columns of the same row, never arbitrary expressions. pub fn unit_fields(template: &str) -> Option> { let mut fields = Vec::new(); let mut rest = template; while let Some((before, tail)) = rest.split_once('{') { if before.contains('}') { return None; } let (field, tail) = tail.split_once('}')?; if field.is_empty() || field.contains('{') { return None; } fields.push(field); rest = tail; } (!rest.contains('}')).then_some(fields) } /// How a value is read out — each format belongs to the types it names. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum ColumnFormat { /// A number of SECONDS read as a duration ("1 h 4 min"). Number only. Duration, /// A number of MILLISECONDS read as a length ("0:42"). Number only. #[serde(rename = "duration_ms")] DurationMs, /// A slug read as plain words ("needs_action" → "Needs action"). Text or /// choice. Words, /// A recurrence rule read as its preset's name ("Weekly"). Text only. RepeatRule, /// An app's identifier read as its name ("FaceTime"). Text only. AppName, /// A size in bytes ("2.1 MB"). Number only. Bytes, /// A width read with its `pair` as the height ("4032 × 3024"). Number /// only. Dimensions, /// A date said against now ("2 min ago", "yesterday"), its `units` a /// template around it ("read {n}"). Date only. Ago, /// A calendar date and 12-hour time in words, without a weekday. Date only. CalendarDatetime, /// An instant ahead counted down from NOW ("2 h 24 min", "2 d 23 h"), /// its `units.other` the template around it ("resets in {n}") and its /// `units.zero` what it says once the instant has passed ("has reset") — /// never a negative, and never a countdown frozen at an older reading. /// Date only, holding the instant itself. Countdown, /// One text fact read as a primary figure and small "of …" denominator. CountedPair, } impl ColumnFormat { /// The column types this format reads, and the words a refusal says. /// /// `duration` is seconds (Meetings, Calls); `duration_ms` milliseconds /// (Videos) — one word per unit, so no face guesses which it holds. pub fn types(self) -> (&'static [ColumnType], &'static str) { match self { ColumnFormat::Duration | ColumnFormat::DurationMs | ColumnFormat::Dimensions => { (&[ColumnType::Number], "a number") } ColumnFormat::Bytes => (&[ColumnType::Number, ColumnType::Bytes], "a_number_or_bytes"), ColumnFormat::Words => ( &[ColumnType::Text, ColumnType::Choice], "a_text_or_a_choice", ), ColumnFormat::RepeatRule | ColumnFormat::AppName | ColumnFormat::CountedPair => (&[ColumnType::Text], "a text"), ColumnFormat::Ago | ColumnFormat::CalendarDatetime | ColumnFormat::Countdown => (&[ColumnType::Date], "a date"), } } } /// A stamp's original state words or another Mac's arbitrary display words. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Stamp { Done, Dropped, Words(String), } impl Stamp { pub fn words(&self) -> &str { match self { Self::Done => "done", Self::Dropped => "dropped", Self::Words(words) => words, } } } impl Serialize for Stamp { fn serialize(&self, serializer: S) -> Result { serializer.serialize_str(self.words()) } } impl<'de> Deserialize<'de> for Stamp { fn deserialize>(deserializer: D) -> Result { let words = String::deserialize(deserializer)?; Ok(match words.as_str() { "done" => Self::Done, "dropped" => Self::Dropped, _ => Self::Words(words), }) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum StampTone { Red, Amber, Green, } /// The records whose `column` holds one of `values`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ValueMatch { pub column: String, pub values: Vec, } /// A slip's paper stock. A table may name its plain stock, or map a declared /// record state to meaningful paper without deriving colour from table id. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SlipStock { Plain, Rose, Sage } /// How a page offers its search (fan3 part 6, owner 15 Oct 2026): a /// magnifier in the page head that turns the head's row into the field /// (`icon`, what a list with no word draws), or the field itself standing /// on the page under the title (`field`). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SearchFace { Field, Icon } /// Paper selected from one record field. The field belongs to the table, so a /// reader can explain meaningful paper from row data rather than from a /// screen-specific tint. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipStockBy { pub column: String, #[serde(deserialize_with = "crate::definitions::tolerant::known_words::<_, SlipStock, _>")] pub values: BTreeMap, } /// A slip: one record as a row. Every slot names a column, or is null. /// /// `player` and `trailing_picture` (added 30 Sep 2026) are OPTIONAL keys — /// absent rather than null unless the source said so, so every definition /// written before them round-trips unchanged. `player` is the column the round /// play button and the waveform stand for (the Meetings slip); /// `trailing_picture` is the column a picture on the right is drawn from (the /// Locations slip's map picture, drawn from the coordinates). #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipLayout { pub title: String, /// Each subtitle value is followed by its column's name in the core. #[serde(default, skip_serializing_if = "Option::is_none")] pub with_names: Option, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub stock: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub stock_by: Option, /// One column, or several read in turn (`SlipSubtitle`). pub subtitle: Option, pub trailing: Option, pub photo: Option, pub toggle: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub player: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub trailing_picture: Option, /// True when the subtitle reads the first of its columns holding a value /// instead of joining them (a password's site, else its service). #[serde(default, skip_serializing_if = "Option::is_none")] pub subtitle_first: Option, /// A column naming one of the app's photographed objects, drawn at the /// slip's left (the Tools screen's rows, Spec 9.1). #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option, /// Read in the title's place when the title's column holds nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub title_fallback: Option, /// Read in the subtitle's place when the subtitle's column holds nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub subtitle_fallback: Option, /// The values of a choice toggle that draw it on. #[serde(default, skip_serializing_if = "Option::is_none")] pub toggle_on: Option>, /// How the toggle is drawn; absent is the check. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub toggle_style: Option, /// The words along the slip's foot in place of `trailing`. #[serde(default, skip_serializing_if = "Option::is_none")] pub caption: Option, /// The form each column the slip draws is said in, by column key /// (contract 6): `{"due_at": "late", "balance": "money_signed"}`. A /// column with none is said by its type. #[serde(default, skip_serializing_if = "Option::is_none")] pub forms: Option>, /// A figure typed at the foot's end (an order's total). #[serde(default, skip_serializing_if = "Option::is_none")] pub figure: Option, /// A date column drawn on a stub torn from the slip's leading edge. #[serde(default, skip_serializing_if = "Option::is_none")] pub stub: Option, /// A line at the foot saying who named part of the record. #[serde(default, skip_serializing_if = "Option::is_none")] pub byline: Option, /// A glyph at the foot while a column holds a value. #[serde(default, skip_serializing_if = "Option::is_none")] pub badge: Option, /// The record's place in its list, in pencil at the leading edge. #[serde(default, skip_serializing_if = "Option::is_none")] pub ordinal: Option, /// Typed verbs answering the question the slip asks ("Same as …?"). #[serde(default, skip_serializing_if = "Option::is_none")] pub answers: Option, /// The column that wears the red unread dot: a date holding nothing, or /// a choice holding `unread`. #[serde(default, skip_serializing_if = "Option::is_none")] pub unread: Option, /// The slip's edge: the receipt's torn foot. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub edge: Option, /// The table's dye, one of the theme's (`THEME_DYES`): on a record page, /// where several kinds meet, a slip takes its table's dye so colour says /// kind. Absent, cream. #[serde(default, skip_serializing_if = "Option::is_none")] pub dye: Option, /// A column whose words are written under the slip as its state. #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub opens: Option, // Round 3 (1 Oct 2026), optional and absent unless the source said so. /// The record's links as hand links under the slip ("Todo ›"), each /// opening its record, less the tables `except` names. #[serde(default, skip_serializing_if = "Option::is_none")] pub links: Option, /// Rows of another table that link to the record, one line each under /// the slip, each said as that table's own slip says it (an order's /// items: "Chicken biryani · 1 · ₹560"). The core resolves the lines. #[serde(default, skip_serializing_if = "Option::is_none")] pub lines: Option, // Round 4 (1 Oct 2026), optional and absent unless the source said so. /// The slip's answer in the owner's own words ("Answer"), offered while /// its question is open (`SlipReply`). #[serde(default, skip_serializing_if = "Option::is_none")] pub reply: Option, /// The person's name beside the slip: their photo when present, the /// existing full-name card when its bytes are absent. Independent of title. #[serde(default, skip_serializing_if = "Option::is_none")] pub photo_name: Option, /// How many lines of the title the slip shows: absent is the face's own /// (two on a list), 0 is the whole title — a memory IS its sentence, so /// cutting it leaves nothing (12 Oct 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub title_lines: Option, /// The `copy` command a tap on the slip runs in place of opening the /// record: a clip is tapped to copy it (Clips, 14 Oct 2026). Its page /// still opens from the slip's own Open. Only a copy is taken — a tap /// that wrote or destroyed would be an act with no look first. #[serde(default, skip_serializing_if = "Option::is_none")] pub tap: Option, } /// A slip's answer in the owner's own words: the text or long text `column` /// the words are written to, the verb's words (`label`, absent "Answer") and /// the field's words (`placeholder`). Words in that column answer the slip's /// question, so the record leaves its list as an answered one does. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipReply { pub column: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub placeholder: Option, } /// A slip drawn by a choice column's value (architect, 11 Oct 2026: Records /// slips typed by kind). For a record whose `column` holds one of `slips`' /// values, that variant's words — title, subtitle, trailing, caption — are /// drawn in place of the slip's, a slot the variant leaves out drawn empty; /// everything else about the slip (its badge, its unread dot, its edge) stays. /// A value with no variant, and an empty column, draw the slip as declared. /// The choice is the definition's, never the app's: any table may declare one. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipBy { pub column: String, pub slips: OrderedMap, } /// One value's words on a [`SlipBy`] slip. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipVariant { pub title: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub subtitle: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub trailing: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub caption: Option, } impl SlipLayout { /// No slip was stated: a stated slip always names its title column. pub fn is_absent(&self) -> bool { self.title.is_empty() } /// This slip with `variant`'s words in place of its own: the title, /// subtitle, trailing and caption are the variant's (a slot it leaves out /// is empty), the rest is this slip's — and the slip's own title is read /// when the variant's holds nothing, so a record is never a blank slip. pub fn with_variant(&self, variant: &SlipVariant) -> SlipLayout { SlipLayout { title: variant.title.clone(), subtitle: variant.subtitle.clone(), trailing: variant.trailing.clone(), caption: variant.caption.clone(), title_fallback: (variant.title != self.title).then(|| self.title.clone()), subtitle_fallback: None, ..self.clone() } } /// Every subtitle column, first to last. pub fn subtitles(&self) -> &[String] { match &self.subtitle { None => &[], Some(SlipSubtitle::One(key)) => std::slice::from_ref(key), Some(SlipSubtitle::Several(keys)) => keys, } } } /// A slip's subtitle: one column, or a list of them (the Passwords slip reads /// the first holding a value, the People slip joins those that do). Each form /// round-trips as it was written. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum SlipSubtitle { One(String), Several(Vec), } /// The edges a slip can be drawn with. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SlipEdge { Receipt, } /// The ink a hand-written word is drawn in: red for one not to miss. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Ink { Red, Pencil, } /// Typed verbs, each writing its value into one choice `column`: the words /// each value is offered as, the values in which the question is still open /// (`when`; a blank value always is), whether an answered record leaves its /// lists (`leaves`, absent true), and the agreeing answer offered first /// (`primary`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RecordAnswers { pub column: String, pub values: OrderedMap, #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub leaves: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub primary: Option, } /// How a slip's toggle is drawn. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ToggleStyle { Check, Switch, } /// A slip's foot as a sentence: some columns as they read, a status word, /// then the first of some date columns holding a day; `fields` are typed /// values appended after. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipCaption { #[serde(default, skip_serializing_if = "Option::is_none")] pub columns: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub dates: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub fields: Option>, /// How many days either side a date under `dates` is said as a count /// ("in 5 days", "5 days ago"); beyond, the weekday date. Absent: seven. #[serde(default, skip_serializing_if = "Option::is_none")] pub near: Option, /// How the date under `dates` that leads is said: `"relative"` as a /// count all the way ("in 2 months", "3 months ago"), never the weekday /// date; `"age"` as the years completed by the reader's day ("34"); /// `"turns"`, on a yearly date, its next day then the age it comes round /// to ("in 12 days · turns 35") — `records::DateAge`, said by the core. #[serde(default, skip_serializing_if = "Option::is_none")] pub date_form: Option, /// The form the leading date under `dates` is said in (contract 6); /// `date_form` is its older name and means the same. One of the two. #[serde(default, skip_serializing_if = "Option::is_none")] pub form: Option
, } impl SlipCaption { /// The leading date's form, by either name. pub fn leading_form(&self) -> Option { self.form.or_else(|| self.date_form.as_deref().and_then(Form::named)) } } /// HOW A DRAWN COLUMN IS SAID (transforms contract 6, lane T1): a definition /// names a form, never a format, and the core says the value in it through /// the database's line sets. Each form reads one column type, checked when /// the definition is saved ([`Form::fits`]). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Form { /// A date against today, counted all the way ("in 2 months", "3 days ago"). Relative, /// A date as its short weekday date ("Thu 23 Oct"). WeekdayDate, /// A date with its weekday's whole name ("Tuesday 27 Oct"), its year /// after it outside the reader's year. WeekdayNameDate, /// A date as its short weekday date with its year always ("Sat 3 Oct /// 2026"). WeekdayDateYear, /// A date's years completed by today ("34"). Age, /// A yearly date's next day and the age it comes round to ("in 12 days · turns 35"). Turns, /// An instant ahead as the time left ("in 2 h 30 min"). Countdown, /// A date gone as how late ("4 days late"); a day to come as its relative day. Late, /// A yearly date as the next time it comes round ("in 12 days"). NextOccurrence, /// A date as the whole weeks gone since it ("3 weeks", "1 week"); under /// a week, its relative day. The span alone: the phrase around it ("not /// reached in …") is the reading tool's own line, never the form's. Since, /// An amount in its currency ("$4,999.00"). Money, /// An amount with its sign said ("+$12.00", "−$4.50"). MoneySigned, /// A whole number grouped ("1,204"). Count, /// A number of seconds as a length of time ("1 h 4 min"). Duration, /// A number of seconds as a player's clock ("3:42", "1:04:05"). Clock, /// An instant gone, as how long ago ("5 min ago", "3 h ago"), else its day. Ago, /// A date as its year alone ("2022"). Year, /// A date as its day and month ("18 Oct"), its year after it outside the /// reader's year ("18 Oct 2025"). DayMonth, /// A record id as its four-character Crockford reference, said through /// the `ident` set ("#7KQ2"): `transforms::short_ref`. ShortRef, } impl Form { /// The form a `date_form` word names. pub fn named(word: &str) -> Option { serde_json::from_value(serde_json::Value::String(word.to_string())).ok() } /// Whether `column` holds what this form reads; the refusal names what /// it needs. pub fn fits(self, column: &Column) -> Result<(), &'static str> { let date = column.column_type == ColumnType::Date; let yearly = date && column.yearly == Some(true); let fits = match self { Form::Relative | Form::WeekdayDate | Form::WeekdayNameDate | Form::WeekdayDateYear | Form::Age | Form::Countdown | Form::Late | Form::Since | Form::Ago | Form::Year | Form::DayMonth => date, Form::Turns | Form::NextOccurrence => yearly, Form::Money | Form::MoneySigned => column.column_type == ColumnType::Amount, Form::Count | Form::Duration | Form::Clock => column.column_type == ColumnType::Number, Form::ShortRef => matches!(column.column_type, ColumnType::Text | ColumnType::Link), }; if fits { return Ok(()); } Err(match self { Form::Relative | Form::WeekdayDate | Form::WeekdayNameDate | Form::WeekdayDateYear | Form::Age | Form::Countdown | Form::Late | Form::Since | Form::Ago | Form::Year | Form::DayMonth => "a date column", Form::Turns | Form::NextOccurrence => "a yearly date column", Form::Money | Form::MoneySigned => "an amount column", Form::Count | Form::Duration | Form::Clock => "a number column", Form::ShortRef => "a column holding a record id (text or a link)", }) } } /// Who named part of a record: `column`'s value, and the words for it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipByline { pub column: String, pub words: OrderedMap, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub ink: Option, } /// A glyph (an SF symbol name) at the foot while `column` holds a value — or, /// with `values`, one of those. A yes/no holds one only while it is yes: the /// star on a starred email is its mark, never a row reading On or Off. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipBadge { pub column: String, pub symbol: String, pub spoken: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub values: Option>, } /// The board faces a table's tile can take. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum TileFace { #[default] SlipList, PolaroidGrid, CapGrid, CardGrid, Month, SectionList, /// The tall tinted card grid the Reader draws (added 30 Sep 2026). CoverGrid, /// The receipt: the paper card with the torn bottom edge, for a step in /// progress or just finished (added 30 Sep 2026). Receipt, /// One number over the last days, as a thin ink line on the paper with /// its last value and nothing else; `tile.sparkline` names what it draws /// (added 11 Oct 2026). Sparkline, /// Bars or a line of the table's amounts, numbers or counts by month, /// week or day; `tile.chart` names what it draws (added 12 Oct 2026). Chart, } #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct TileLayout { #[serde(deserialize_with = "crate::definitions::tolerant::word")] pub face: TileFace, /// Figures the tile shows over the whole table, in order — a count, a /// sum, the earliest or latest of a column — each over the rows its /// `where` keeps. Computed once by `records::summarize`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub summary: Vec, /// What counts as current for the table's section on the database page; /// absent is the face's own rule (a slip list: what its list shows, less /// the finished; any other face: any record). #[serde(default, skip_serializing_if = "Option::is_none")] pub current: Option, /// What the sparkline face draws; present exactly when the face is one. #[serde(default, skip_serializing_if = "Option::is_none")] pub sparkline: Option, /// What the chart face draws; present exactly when the face is one. #[serde(default, skip_serializing_if = "Option::is_none")] pub chart: Option, } /// A chart of this table's records by period: `{ "kind": "bar", "x": /// "occurred_on", "y": "amount_minor", "by": "month" }` — each record placed /// in the period its `x` date falls in, and each period's `y` summed (an /// amount or number column) or its records counted (`"y": "count"`), over /// the last `periods` periods ending today (12 months, 12 weeks or 30 days /// when absent). `where` keeps the records it holds for, read the way /// `list_records` reads it. The same definition draws on a tile /// and for an assistant; the series is worked out once, by `records::chart`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ChartFace { #[serde(deserialize_with = "crate::definitions::tolerant::word")] pub kind: ChartKind, pub x: String, pub y: String, #[serde(deserialize_with = "crate::definitions::tolerant::word")] pub by: ChartPeriod, /// Optional numeric civil hour beside x's date, for split date/hour records. #[serde(default, skip_serializing_if = "Option::is_none")] pub hour: Option, /// Timezone of civil hours; timestamp values still identify absolute instants. #[serde(default, skip_serializing_if = "Option::is_none")] pub timezone: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub periods: Option, #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] pub where_: Option>, /// Only the values on one side of zero: `negative` keeps money out of an /// amount kept from the owner's side, `positive` money in. A sum alone. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub sign: Option, } /// Which side of zero a chart keeps. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ChartSign { Negative, Positive, } /// How a chart draws its periods. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ChartKind { #[default] Bar, Line, } /// The period a chart's records are gathered by. A week starts on Monday. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ChartPeriod { #[default] Month, Week, Day, Hour, } impl ChartFace { /// `y` when it counts records rather than summing a column. pub const COUNT: &'static str = "count"; /// The most periods a chart is drawn over. pub const MAX_PERIODS: u32 = 366; pub fn counts(&self) -> bool { self.y == Self::COUNT } pub fn periods(&self) -> u32 { self.periods.unwrap_or(match self.by { ChartPeriod::Month | ChartPeriod::Week => 12, ChartPeriod::Day => 30, ChartPeriod::Hour => 48, }) } } /// A line of one number over time: `{ "table": "quota_reading", "value": /// "week_pct", "at": "sampled_at", "days": 7 }` — the `value` number of each /// record of `table` (this table or another), placed by its `at` date, over /// the last `days` days (7 when absent). On a record's page (`PageSection`) /// `link` names the column of `table` that holds the page's record, so the /// line is that record's readings; a tile's line has no record to link. /// The points are worked out once, by `records::sparkline`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Sparkline { pub table: String, pub value: String, pub at: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub days: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option, } impl Sparkline { /// The window when the definition names none. pub const DAYS: u32 = 7; /// The longest window a line is drawn over. pub const MAX_DAYS: u32 = 366; pub fn days(&self) -> u32 { self.days.unwrap_or(Self::DAYS) } } /// A record is current while the date in `column` is no more than `days` /// days behind today: `{ "column": "captured_at", "days": 2 }`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TileCurrent { pub column: String, pub days: u32, } /// What a tile figure does with its rows. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SummaryOp { /// How many rows there are; takes no column. Count, /// The total of a number or amount column. Sum, /// The smallest of a date, number or amount column — the next renewal. Min, /// The largest of a date, number or amount column. Max, } /// One figure on a board tile: `{ "op": "sum", "column": "amount", /// "where": { "status": "active" }, "label": "a month" }`. `where` is read /// the way `list_records` reads it; `label` is the words drawn after the /// figure. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TileSummary { pub op: SummaryOp, #[serde(default, skip_serializing_if = "Option::is_none")] pub column: Option, #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] pub where_: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, } /// One section of a record's page, top to bottom: an optional heading over /// the columns it shows — or over another table's records (`list`), or the /// live web page a column addresses (`web`, which draws no columns). /// /// `columns` may be absent (a list or web section), and stays absent. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PageSection { pub heading: Option, /// Under a list (`lists`): drawn before the list's own slips rather /// than after them — the Code list's repositories stand above its /// sessions. Read nowhere else; a page section carrying it is refused. #[serde(default, skip_serializing_if = "Option::is_none")] pub above: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub columns: Option>, /// A column whose picture heads the section: a photo, a file, or a /// latitude with its `pair` (a map). #[serde(default, skip_serializing_if = "Option::is_none")] pub picture: Option, /// A text column holding a web address, drawn as the live page. #[serde(default, skip_serializing_if = "Option::is_none")] pub web: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub list: Option, /// Drawn only while the record holds this. #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option, /// One sentence by hand at the section's head. #[serde(default, skip_serializing_if = "Option::is_none")] pub note: Option, /// The note's ink; absent, pencil. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub ink: Option, /// One handwritten line under the section's picture. #[serde(default, skip_serializing_if = "Option::is_none")] pub hand: Option, /// Typed verbs under the section, the slip's `answers` shape. #[serde(default, skip_serializing_if = "Option::is_none")] pub answers: Option, /// Typed verbs that are not one choice: set some columns, or delete. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::available::<_, SectionAction, _>")] pub actions: Option>, /// The engine's own verbs drawn under the section, by id: each offered /// while it applies to the record, by its own label. #[serde(default, skip_serializing_if = "Option::is_none")] pub commands: Option>, /// The record's other links, every table but those `except` names. #[serde(default, skip_serializing_if = "Option::is_none")] pub links: Option, /// The amount at the head of this section, in integer minor units. #[serde(default, skip_serializing_if = "Option::is_none")] pub figure: Option, /// What the section IS on the page: its one `main` body, the `facts` /// said in a line under the title, or a `side` list reached by a link. /// Absent, a section among the others. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub role: Option, /// One number of a linked table over the last days, drawn as a thin ink /// line with its last value (`Sparkline`; its `link` names this record). #[serde(default, skip_serializing_if = "Option::is_none")] pub sparkline: Option, } /// A page section's part: `main` is what the page is for (a script, a /// transcript), at most one a page; `facts` are a few values said in one /// line under the title; `side` is a list reached from the page's row of /// links, or columns kept behind its Details link. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SectionRole { Main, Facts, Side, } /// A section drawn only while `column` holds one of `values`, or (with /// `present`) holds anything at all. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SectionWhen { pub column: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub values: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub present: Option, } /// One handwritten line: some columns' words joined, each entry a column key /// or words naming columns as `{key}` — or one sentence naming them so. Each /// form round-trips as it was written. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum PageHand { Columns(Vec), Sentence(String), } impl PageHand { /// The columns the line reads, in order. pub fn keys(&self) -> Vec<&str> { match self { PageHand::Columns(entries) => entries .iter() .flat_map(|entry| { if entry.contains('{') { braced(entry) } else { vec![entry.as_str()] } }) .collect(), PageHand::Sentence(sentence) => braced(sentence), } } } /// Every `{key}` a line of words names. fn braced(text: &str) -> Vec<&str> { let mut keys = Vec::new(); let mut rest = text; while let Some(open) = rest.find('{') { let after = &rest[open + 1..]; let Some(close) = after.find('}') else { break }; keys.push(&after[..close]); rest = &after[close + 1..]; } keys } /// A typed verb on a page section: `sets` writes those columns, `delete` /// deletes the record after asking. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SectionAction { pub label: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub sets: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub delete: Option, /// The object its act card stands, by name, as a command's `object`. #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option, /// What it does to the record, as a command's `does`: its card's colour. #[serde(default, skip_serializing_if = "Option::is_none")] pub does: Option, } /// The rows of `table` whose `relation` column links to the record, at most /// `limit` of them (absent: [`SlipLines::DEFAULT_LIMIT`]). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SlipLines { pub table: String, pub relation: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option, } impl SlipLines { pub const DEFAULT_LIMIT: u32 = 6; /// How many rows the slip says, never none. pub fn rows(&self) -> usize { self.limit.unwrap_or(Self::DEFAULT_LIMIT).max(1) as usize } } /// The record's other links (what the engine answers as its `links`), less /// the tables named. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LinkedSection { #[serde(default, skip_serializing_if = "Option::is_none")] pub except: Option>, } impl PageSection { /// The columns the section draws; none when the key is absent. pub fn columns(&self) -> &[String] { self.columns.as_deref().unwrap_or_default() } } /// Another table's records as a section: those whose `link` column names the /// page's record, or with no link the whole table's. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SectionList { pub table: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option, /// What the section says with no records; absent, it is left out. #[serde(default, skip_serializing_if = "Option::is_none")] pub empty: Option, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub face: Option, /// Only the archived records, drawn faded. #[serde(default, skip_serializing_if = "Option::is_none")] pub archived: Option, /// How many records the section draws, its heading counting them /// against the whole. #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option, /// The records drawn this many across. #[serde(default, skip_serializing_if = "Option::is_none")] pub columns: Option, /// Other tables' records linked the same way, merged in. #[serde(default, skip_serializing_if = "Option::is_none")] pub with: Option>, /// The words of the row opening a blank record ("Add photos"). #[serde(default, skip_serializing_if = "Option::is_none")] pub add: Option, /// Filters over columns of the section's target table, as a list read's /// `where` takes them: a value, or a list of values meaning any one of /// them. The read is made with them. #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] pub where_: Option>, /// The words of the row under a `limit`ed section that opens the whole /// list ("All movements"); absent, the row reads "All n". #[serde(default, skip_serializing_if = "Option::is_none")] pub whole: Option, } /// An empty list section's words: one sentence, or a title and the sentence /// under it. Each form round-trips as it was written. /// /// On a PAGE section the words may name the page's record: `{title}` is /// replaced, where the words are drawn, by the words heading that page ("No /// movements in {title} yet" on Insurance's page reads "No movements in /// Insurance yet"). A top-level `lists` entry has no record to name, so its /// words never hold `{title}` (validated). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum SectionEmpty { Sentence(String), Titled(SectionEmptyWords), } /// The placeholder a page section's empty words name the page's record by. pub const PAGE_TITLE_PLACEHOLDER: &str = "{title}"; impl SectionEmpty { /// Whether the words name the page's record (`{title}`). pub fn names_the_page(&self) -> bool { match self { SectionEmpty::Sentence(words) => words.contains(PAGE_TITLE_PLACEHOLDER), SectionEmpty::Titled(words) => { words.title.contains(PAGE_TITLE_PLACEHOLDER) || words.message.as_deref().is_some_and(|message| message.contains(PAGE_TITLE_PLACEHOLDER)) } } } } /// A list section's empty words: a title and the sentence under it. A /// section has no search of its own, so no `search` words either. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SectionEmptyWords { pub title: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, } /// Another table's records a list section merges in: those whose `link` /// column names the page's record. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct SectionLink { pub table: String, pub link: String, } /// How a list section draws its records: as slips (absent) or each as its own /// page, read straight through. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SectionFace { Slip, Page, } /// The list's order when nothing is dragged into place. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListSort { pub column: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub descending: Option, /// The column that orders records `column` holds alike (newest message /// below the pins). #[serde(default, skip_serializing_if = "Option::is_none")] pub tie: Option, /// Order by the NEXT time a yearly day comes round from the reader's day /// (birthdays, anniversaries, renewals), not by the stored date: today /// first, then the days ahead, the ones already past this year last; /// rows with no date after them all. Only on a `yearly` date column. #[serde(default, skip_serializing_if = "Option::is_none")] pub next: Option, /// The tie's own direction where it is not the sort's: people reached /// most recently first, and those alike by name A to Z (`false`). /// Absent, the sort's. #[serde(default, skip_serializing_if = "Option::is_none")] pub tie_descending: Option, } impl ListSort { /// Whether the tie orders largest first. pub fn tie_descends(&self) -> bool { self.tie_descending.unwrap_or(self.descending == Some(true)) } } /// A list split into sections by one choice column's value — or, with no /// `sections`, one unheaded section per run of any column's value as the /// list reads (a duplicate's copies under the picture they copy). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListGrouping { pub column: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub sections: Option>, /// Figures each group's head says over that group's rows, in the shape a /// tile's are (`TileSummary`; architect's ruling 09:15 IST 17 Oct 2026): /// Months' in, out and net for a period, Owed's total for a person. The /// core works them out and says the lines (`records::group_heads`); the /// app draws the lines it is given. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub summary: Vec, } /// One section of a grouped list: the choice values it holds, under an /// optional heading, with an optional sentence under it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListGroup { pub heading: Option, pub values: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] pub note: Option, /// Drawn closed — its heading and count — until the heading is tapped. #[serde(default, skip_serializing_if = "Option::is_none")] pub closed: Option, /// The section split by when its records are due (open goals: Overdue, /// This month, Later, No date), each part under its own heading. #[serde(default, skip_serializing_if = "Option::is_none")] pub due: Option, } /// A group section split by a date column: what is owed from a day gone, /// what falls due by the end of this month, what comes after, and what has /// no date — each part's heading, in that order. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct GroupDue { pub column: String, pub late: String, pub soon: String, pub later: String, pub undated: String, } /// The list split by the day each record is next due — the latest of /// `dates` — soonest first; `undated` heads the records with none. `late` /// heads ONE closed section, after today, holding every record owed from a /// day gone, newest first (absent, they fold into today). `series` names the /// column a repeating record's occurrences share: the late ones of one series /// stand as one record, the latest, counting the days it was missed. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListUpcoming { #[serde(default, skip_serializing_if = "Option::is_none")] pub dates: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub undated: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub late: Option, /// The heading of ONE closed section after the days to come, holding every /// record due beyond `horizon` days ("Later"); absent, every day by name. #[serde(default, skip_serializing_if = "Option::is_none")] pub later: Option, /// How many days ahead stand under their own heading (absent: seven). #[serde(default, skip_serializing_if = "Option::is_none")] pub horizon: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub series: Option, /// The section a whole read leads with, ahead of today ("late": the All /// deck, owed before coming); absent, today leads and the late follow the /// undated. A view sets it for itself (`ToolView::lead`). #[serde(default, skip_serializing_if = "Option::is_none")] pub lead: Option, } /// The `count` records latest in `column`, above a list longer than `over`. /// Absent, `count` is 2 and `over` is 3. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RecentLayout { pub column: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub over: Option, } /// How many records stand across a list drawn as `cards` or as the contact /// sheet: its one layout's count, so nothing names a second grid. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListGrid { pub columns: u32, } /// The ONE way a list draws its records, chosen by the definition; the person /// never switches it (owner, 15 Oct 2026). Absent is `list`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ListLayout { /// Each record as its card: a cover, a polaroid, a postcard or a small slip. Cards, /// The borderless contact sheet of pictures, `grid.columns` across. Sheet, /// The records as slips, one under another. List, } /// A row of a several-choice column's words over the list; saving makes a /// record holding them and `sends` (column → value) besides. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ChipRow { pub column: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub sends: Option>, /// The words over the row that say a tap makes a record ("Log a mood"): /// chips with no label read as decoration (walker 604bcce6). #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, } /// The list's Paste button: the column a pasted text is written to. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListPaste { pub column: String, } /// The cover face's footer columns and whether it is drawn as a bound script. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CoverLayout { #[serde(default, skip_serializing_if = "Option::is_none")] pub footer: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub bound: Option, } /// The empty list's own words. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct EmptyWords { pub title: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, /// What a search that matches nothing says. #[serde(default, skip_serializing_if = "Option::is_none")] pub search: Option, } /// A title and the sentence under it, said when a search finds nothing. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct NoMatchWords { pub title: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option, } /// The list's "+": a blank page under `label`, holding today in `dated`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListCreate { pub label: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub dated: Option, /// An app route the "+" opens in place of a blank page ("/people/import"). #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option, /// A phone method the "+" calls at once, with nothing asked, in place of /// a blank page: one of [`commands::COMMAND_METHODS`], whose answer's /// platform action the shell follows. Cotton Story's New scene is /// `story.scene.new`: a scene in the current story, opened in the writer /// (17 Nov 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option, /// An act at the person's object the "+" sends its words to in place of /// making a record here: Podcasts' Plus types a show's name, and the object /// finds the show and writes it (`subscribe_podcast { query }`); the row /// comes back by sync. #[serde(default, skip_serializing_if = "Option::is_none")] pub act: Option, /// The ways in, when there is more than one: the "+" opens a choice tier /// at the hub, one tile per door, in this order, and the table's empty /// deck offers the same tier as its acts. Books' Plus is Find a book (the /// name typed, `find_book`), Add a file (EPUB or PDF, from Files) and /// Bring Goodreads in (the export, from Files) (coordinator, 4 Nov 2026). /// A create with doors is the doors alone: no `act`, `path` or `dated`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub doors: Vec, } /// The object act a list's "+" sends its typed words to: `name`, with the /// words as `args[argument]`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateAct { pub name: String, pub argument: String, /// The key of the act's answer that names the record of this table it /// made or found (`find_book` answers `{ book }`): the app stands on that /// record once sync brings it. Absent, the act lands nowhere. #[serde(default, skip_serializing_if = "Option::is_none")] pub lands: Option, /// What the shell says, in place of asking for the words, on a phone not /// signed in to the object the act asks ("Sign in to find books by /// name"); the tier offers Sign in beside it. Absent, the words are asked /// and the object's refusal is said. #[serde(default, skip_serializing_if = "Option::is_none")] pub signed_out: Option, } /// One way into a table from its "+" choice tier ([`ListCreate::doors`]): /// its word and its picture, and what a tap does — either words typed in /// the shell's short-text input and sent to an object act (`act`, as a /// single-door "+" does), or files chosen in the system's picker and handed /// to the share sheet's own intake (`files`), which files each by what it /// is, exactly as a share of it would. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateDoor { pub id: String, pub label: String, /// The door's bare picture, one of [`commands::ACT_OBJECTS`], as an /// act's. #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub act: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub files: Option, /// Pictures taken in through the system's own picture doors (`pick`): /// the photo picker, which hands over only what the person chose and /// never asks for the whole library, or the camera. What comes back goes /// to the same intake a door's files do. #[serde(default, skip_serializing_if = "Option::is_none")] pub pick: Option, /// A new record of this table written in the shell's own inputs, one /// column after another (`draft`): begun with the draft's `values`, its /// `dated` column today, each of its `asks` columns asked in its own /// editor (an amount in the amount input) and then its title, which makes /// it. Money's Add a spend: the amount, then what it was (coordinator, /// 12 Nov 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub draft: Option, /// What this device keeps of the person read into its tables (`reads`): /// Cotton Health's Read Apple Health, read-only, the system asked for /// access at this tap and never before (13 Nov 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub reads: Option, } /// What a reading door reads from the device ([`CreateDoor::reads`]). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum DeviceReads { /// Apple Health on an iPhone, through HealthKit: the person's days, /// workouts and measurements, never written back (`health.land`). AppleHealth, } /// What a door that writes a new record by hand begins it with and asks /// ([`CreateDoor::draft`]). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateDraft { /// The values the record is begun with, by column. #[serde(default, skip_serializing_if = "OrderedMap::is_empty")] pub values: OrderedMap, /// The date column that holds today. #[serde(default, skip_serializing_if = "Option::is_none")] pub dated: Option, /// The columns asked before the title, in order. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub asks: Vec, /// The money account column the record is written against: the person's /// usual account, else their cash wallet (a spend written by hand). #[serde(default, skip_serializing_if = "Option::is_none")] pub account: Option, } /// Where a picture door takes its pictures from ([`CreateDoor::pick`]), what /// kinds it takes, and whether several may be chosen at once. Cotton Photos' /// Plus: Choose photos (the picker, photos and videos, many) and Take a photo /// (the camera, one at a time) (owner, 12 Nov 2026). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CreatePick { pub source: PickSource, pub kinds: Vec, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub many: bool, } /// The system's picture door a [`CreatePick`] opens. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PickSource { /// The photo picker: the person's own choice, out of process; Cotton is /// handed those pictures and is never granted the library. Library, /// The camera: one picture or film, taken now. Camera, } /// What a picture door takes. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PictureKind { Photo, Video, } /// The files a door's picker offers: their uniform types /// (`org.idpf.epub-container`, `com.adobe.pdf`), and whether several may be /// chosen at once. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CreateFiles { pub types: Vec, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub many: bool, } /// The media types a door's uniform type is on a system that picks files by /// media type (Android's document picker): the shell hands these to its picker /// and maps nothing itself. `None` for a type Cotton does not know, which no /// kit may name ([`validate_doors`]). A folder is `inode/directory`: the shell /// picks a tree, not a file. pub fn file_type_mimes(kind: &str) -> Option<&'static [&'static str]> { Some(match kind { "org.idpf.epub-container" => &["application/epub+zip"], "com.adobe.pdf" => &["application/pdf"], "public.comma-separated-values-text" => &["text/csv", "text/comma-separated-values"], // OPML, a podcast app's subscription list. Apple declares no OPML // type; `org.opml.opml` (conforming to public.xml) is the one // NetNewsWire and the readers declare, so an app that names it // imports it in its Info.plist. Android's media store knows no // `.opml` and files it as `application/octet-stream`, which a picker // handed only the XML types greys out (the Android walk, 12 Nov // 2026): it is named too, and `import_opml` refuses in its own words // a file that is no OPML. "org.opml.opml" => &["text/x-opml", "text/xml", "application/xml", "application/octet-stream"], "public.audio" => &["audio/*"], // An album ZIP (a Bandcamp download) is one album in Music. "public.zip-archive" => &["application/zip"], // Apple Health's export, a bare export.xml (Cotton Health's Bring in // an export; its zip is the album ZIP's type above). "public.xml" => &["text/xml", "application/xml"], "public.mpeg-4" => &["video/mp4"], "com.apple.quicktime-movie" => &["video/quicktime"], "public.avi" => &["video/x-msvideo"], "org.matroska.mkv" => &["video/x-matroska"], "public.folder" => &["inode/directory"], // Cotton Photos' Files door: any picture or any film. "public.image" => &["image/*"], "public.movie" => &["video/*"], _ => return None, }) } /// The file name extensions a door's uniform type is known by, lower-case: /// what a file shared into an app is read by when its provider names it /// only `application/octet-stream` (Android's media store knows no `.mkv`, /// `.opml` or `.epub` on many phones). Empty for a type no file name says /// (a folder). pub fn file_type_extensions(kind: &str) -> &'static [&'static str] { match kind { "org.idpf.epub-container" => &["epub"], "com.adobe.pdf" => &["pdf"], "public.comma-separated-values-text" => &["csv"], "org.opml.opml" => &["opml"], "public.audio" => &["mp3", "m4a", "m4b", "aac", "flac", "ogg", "oga", "opus", "wav", "aif", "aiff"], "public.zip-archive" => &["zip"], "public.xml" => &["xml"], "public.mpeg-4" => &["mp4", "m4v"], "com.apple.quicktime-movie" => &["mov"], "public.avi" => &["avi"], "org.matroska.mkv" => &["mkv"], "public.image" => &["jpg", "jpeg", "png", "heic", "heif", "gif", "webp"], "public.movie" => &crate::films::VIDEO_EXTENSIONS, _ => &[], } } /// The types Cotton knows, each once: what [`file_type_takes`] reads a file /// name's extension against. pub const FILE_TYPES: [&str; 14] = [ "org.idpf.epub-container", "com.adobe.pdf", "public.comma-separated-values-text", "org.opml.opml", "public.audio", "public.zip-archive", "public.xml", "public.mpeg-4", "com.apple.quicktime-movie", "public.avi", "org.matroska.mkv", "public.image", "public.movie", "public.folder", ]; /// Whether a file, by its media type and its name, is of the door type /// `kind`. A name whose extension some known type claims is read by that /// extension alone (an `.epub` its provider calls `application/zip` is a /// book, never an album ZIP); else by the media type, a `audio/*` pattern /// taking every audio type. `application/octet-stream`, or none, says /// nothing. pub fn file_type_takes(kind: &str, mime: Option<&str>, name: Option<&str>) -> bool { let extension = name.and_then(|name| name.rsplit_once('.')).map(|(_, extension)| extension.to_ascii_lowercase()); if let Some(extension) = extension.filter(|extension| FILE_TYPES.iter().any(|known| file_type_extensions(known).contains(&extension.as_str()))) { return file_type_extensions(kind).contains(&extension.as_str()); } let Some(mime) = mime.map(|mime| mime.split(';').next().unwrap_or_default().trim().to_ascii_lowercase()).filter(|mime| !mime.is_empty() && mime != "application/octet-stream") else { return false; }; file_type_mimes(kind).unwrap_or_default().iter().any(|takes| match takes.strip_suffix("/*") { Some(family) => mime.split_once('/').is_some_and(|(of, _)| of == family), None => *takes == mime, }) } /// Where the list's one input writes: the words typed on this table's list /// make a record of `table` instead of one of its own. The Accounts list is /// the case — nobody types a new account there; they say what moved, and that /// is a transaction. `placeholder` is what the empty input says. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListCapture { pub table: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub placeholder: Option, /// The link column of `table` that takes the id of the record whose /// PAGE the input is on: said on an account's page, a movement is that /// account's. #[serde(default, skip_serializing_if = "Option::is_none")] pub link: Option, /// On a record's page, the input captures only while this holds of the /// page's record (a column of this table, the one the page is of); else /// the page's bar asks, as it would with no capture. The list's own /// input is not held to it. #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option, /// The capture is the PAGE's alone: the list's own input still makes the /// list's own record (a new story), and a sentence said on one's page /// makes the captured record there (a scene of it). #[serde(default, skip_serializing_if = "Option::is_none")] pub page_only: Option, } /// Who keeps a record in step from outside the person's hands: `when` names /// the column that, holding a value, marks such a record, and `says` is the /// one pencil line its page wears — "Kept in step with Gmail", "Kept by your /// assistant". A record that is only read-only (a binned password, a closed /// pull, a call) names no keeper and its page says nothing. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct KeptBy { pub when: String, pub says: String, } /// A text column the page menu hands out as `.<extension>`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RecordExport { pub label: String, pub column: String, pub extension: String, } /// A safe handoff to the OS: `column`'s value opened under `scheme`, or under /// `schemes[value of scheme_column]` when that names one. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PageAction { pub label: String, pub column: String, pub scheme: ActionScheme, /// Bare act picture, from commands::ACT_OBJECTS. #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scheme_column: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub schemes: Option<OrderedMap<ActionScheme>>, } /// The only URL schemes a page action may open. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum ActionScheme { Mailto, Tel, Sms, Facetime, FacetimeAudio, } /// A thread's messages for the conversation page: records of `table` whose /// `links` name the thread, their words and moment, which are the owner's, /// and what a message sent from the page is written with. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ConversationLayout { pub table: String, pub links: Vec<String>, pub body: String, pub at: String, pub mine: ValueMatch, /// The message column whose words are the note's when `body` is blank — /// a review that left only its verdict says the verdict as its words. #[serde(default, skip_serializing_if = "Option::is_none")] pub blank_body: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, /// This table's date column that, once set, ends the conversation. #[serde(default, skip_serializing_if = "Option::is_none")] pub ended: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sends: Option<OrderedMap<serde_json::Value>>, /// Columns drawn as a header — and the builders mean two things by it: /// on Messages, MESSAGE columns drawn above each note; on Sessions, THIS /// (thread) table's columns written under the title, one line each, what /// the thread is doing now. Either way only their form is checked here. #[serde(default, skip_serializing_if = "Option::is_none")] pub header: Option<Vec<String>>, /// Message columns drawn below each note — several (Messages), or one /// whose words are the whole line under the note (Sessions). #[serde(default, skip_serializing_if = "Option::is_none")] pub footer: Option<MessageColumns>, /// The message column holding its shared media. #[serde(default, skip_serializing_if = "Option::is_none")] pub media: Option<String>, /// The message column that, set, makes it a system line. #[serde(default, skip_serializing_if = "Option::is_none")] pub system: Option<String>, /// The message column whose value picks a note's paper. #[serde(default, skip_serializing_if = "Option::is_none")] pub color_by: Option<String>, /// Present when words said into the conversation are queued as a new /// message row for the engine to deliver: the columns that row is written /// with (architect, 13 Oct 2026 — never read from the table's name). #[serde(default, skip_serializing_if = "Option::is_none")] pub queue: Option<ConversationQueue>, /// The message column holding its sender's picture, drawn beside the /// first note of a run of theirs in a group. A photo or nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub photo: Option<String>, /// THIS table's column holding the message the page opens on. #[serde(default, skip_serializing_if = "Option::is_none")] pub anchor: Option<String>, /// Whether the page offers the input; absent, it does. Either fixed for /// every record, or the name of THIS table's bool column that says it /// per record (a WhatsApp chat on a linked number sends; an iMessage one /// does not). #[serde(default, skip_serializing_if = "Option::is_none")] pub can_send: Option<CanSend>, /// Mail is paper: every message a page-wide sheet, the newest open and /// the older ones folded to one line (who, when, its first words) that /// opens on a tap. Absent, the messages are a chat's notes. #[serde(default, skip_serializing_if = "Option::is_none")] pub folds: Option<bool>, // Round 3 (1 Oct 2026), optional and absent unless the source said so. /// Message envelope columns drawn above each body, in order — the Email /// conversion's spelling of what Messages calls `header`. #[serde(default, skip_serializing_if = "Option::is_none")] pub header_columns: Option<Vec<String>>, /// The thread's opening line, handwritten first. #[serde(default, skip_serializing_if = "Option::is_none")] pub started: Option<ConversationStarted>, /// The input's words before anything is typed. #[serde(default, skip_serializing_if = "Option::is_none")] pub placeholder: Option<String>, /// Other tables merged into the stream by their own moment (a session's /// turns beside its messages). Read only: nothing is sent into them. #[serde(default, skip_serializing_if = "Option::is_none")] pub also: Option<Vec<ConversationSource>>, } /// Whether a conversation page offers its input: `true`/`false` for every /// record, or a bool column of the thread table read per record. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum CanSend { Always(bool), Column(String), } impl CanSend { /// Whether this record's page offers the input. A column the record does /// not carry, or carries as anything but `true`, says no. pub fn for_record(&self, data: &serde_json::Map<String, serde_json::Value>) -> bool { match self { CanSend::Always(sends) => *sends, CanSend::Column(column) => data.get(column).and_then(serde_json::Value::as_bool) == Some(true), } } } /// A conversation's message columns: one, or several. Each form round-trips /// as it was written. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum MessageColumns { One(String), Several(Vec<String>), } impl MessageColumns { /// Every column named, first to last. pub fn columns(&self) -> &[String] { match self { MessageColumns::One(key) => std::slice::from_ref(key), MessageColumns::Several(keys) => keys, } } } /// The thread's opening line: THIS table's date column `at`, and the /// columns read before the time ("mac-b", "owner@…"). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ConversationStarted { pub at: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub words: Option<Vec<String>>, } /// A second table read into a conversation: its records whose `links` name /// the thread, drawn by `at` — as notes (absent) carrying `body`, or as their /// own table's slips, which need neither `body` nor `mine`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ConversationSource { pub table: String, pub links: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub body: Option<String>, pub at: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub mine: Option<ValueMatch>, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub face: Option<ConversationFace>, } /// How an `also` table's records are drawn in the stream. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ConversationFace { Note, Slip, } /// A column a package retired: its key and the type it was stored as. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct RetiredColumn { pub key: String, #[serde(rename = "type")] pub column_type: ColumnType, } /// A table: its columns, its keys and its faces. /// Provider prices in currency units per million tokens, preserved as the /// exact JSON numbers a definition carries. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TokenPrices { pub input: serde_json::Number, pub output: serde_json::Number, pub cache_read: serde_json::Number, pub cache_write: serde_json::Number, #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")] pub unknown: serde_json::Map<String, serde_json::Value>, } /// Whose records a table holds (`TableDefinition::scope`). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum TableScope { /// The shown database's. Database, /// The person's own, read from their own database whichever is shown. Personal, } /// Authenticated MCP token identity, including its home-file prefix when carried. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct TableProducer { pub token_id: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(remote = "Self")] pub struct TableDefinition { /// The definition format the file is written in ([`format`]); every /// shipped file names it, a stored row may not. #[serde(default, skip_serializing_if = "Option::is_none")] pub format_version: Option<u32>, /// Physical tables owned by this package; absent on imports derives them from columns. #[serde(default, skip_serializing_if = "Option::is_none")] pub tables: Option<Vec<cotton_store::schema::package_tables::PackageTable>>, /// Columns a person no longer wants: never drawn, never written, KEPT in /// storage with every value they hold, because a package revision only /// adds (tools as packages, GUARD 3). A column leaves `columns` for here. #[serde(default, skip_serializing_if = "Option::is_none")] pub retired: Option<Vec<RetiredColumn>>, pub id: String, pub name: String, pub plural: String, /// A required text column whose value is the record id. Creates at the /// same key update that record; the key never changes. Absent, minted ids. #[serde(default, skip_serializing_if = "Option::is_none")] pub row_key: Option<String>, /// The table's rows are face choices: each, keyed by `row_key` naming a /// table, chooses the face that table wears from its card's `offers`, and /// the object stamps `chosen_at` when it takes one. An engine knows such /// a table by this, never by its id (coordinator, 2 Nov 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub face_choices: Option<bool>, /// Customer reads: public, mine(person_column), staff (the default), or /// owner (the personal database's own rows, read by its one person). #[serde(default, skip_serializing_if = "Option::is_none")] pub visibility: Option<String>, /// The card's picture: an object the app ships (`tool-todos`) or a photo /// record (`{"photo": "photo:<sha256>"}`) the database holds. pub picture: Option<ToolPicture>, /// App-seeded provenance, used only by the seed/overlay lifecycle and /// import/write validation; it never grants an engine or a storage home. /// Absent is false: a storage-only table the object serves says nothing. #[serde(default)] pub builtin: bool, /// The compiled rule set that keeps this table's storage and verbs; null /// for a data-only table. The JSON key stays `engine` (the data format is /// unchanged). pub engine: Option<String>, /// Only this authenticated token may author this table's readonly facts, /// on create and patch alike; the app then fills none of them. #[serde(default, skip_serializing_if = "Option::is_none")] pub producer: Option<TableProducer>, /// At most one optional live read enriches a record page. The synced /// record remains the page's normal source; this declares the one bounded /// host read and the fields it may replace. #[serde(default, skip_serializing_if = "Option::is_none")] pub live_read: Option<LiveRead>, /// Built-in engine view: derived values are answered by the engine on read. pub columns: Vec<Column>, /// The column a record is called by; a table with no face may name none. #[serde(default, skip_serializing_if = "String::is_empty")] pub title: String, /// Plain names to feed on-device dictation. Data-only tables default to their text title; [] opts out. #[serde(default, skip_serializing_if = "Option::is_none")] pub voice_words: Option<Vec<String>>, pub date: Option<String>, pub project: Option<String>, pub order: Option<String>, /// Native manual ordering is independent of editing a derived position field. #[serde(default, skip_serializing_if = "Option::is_none")] pub reorder: Option<bool>, /// The table's face: how a record is drawn in a list, as a tile and on its /// page. A table that states no slip has no face ([`TableDefinition::has_face`]): /// a storage-only table the object serves (an email's participants, an /// OAuth code) is kept as rows and drawn nowhere. #[serde(default, skip_serializing_if = "SlipLayout::is_absent")] pub slip: SlipLayout, #[serde(default)] pub tile: TileLayout, #[serde(default)] pub page: Vec<PageSection>, /// The page's parts in order, from the fixed vocabulary the app draws /// ([`PagePart`]); absent is a plain page, [`PLAIN_PAGE`], supplied by /// [`TableDefinition::resolved_page_parts`] (architect, 13 Oct 2026). A key /// of its own beside `page`, which stays the array of sections. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::known_words::<_, PagePart, _>")] pub page_parts: Option<Vec<PagePart>>, // Every key below is OPTIONAL and absent unless the source said so, so a // definition written before it round-trips unchanged. /// A date or bool column that, once set, archives the record. #[serde(default, skip_serializing_if = "Option::is_none")] pub archived: Option<String>, /// A column that, holding a value, makes the whole record read-only. #[serde(default, skip_serializing_if = "Option::is_none")] pub readonly_when: Option<String>, /// A column a record must hold a value in to be listed. #[serde(default, skip_serializing_if = "Option::is_none")] pub listed_when: Option<String>, /// Who keeps a record in step, and the line its page says of it. #[serde(default, skip_serializing_if = "Option::is_none")] pub kept_by: Option<KeptBy>, /// False on a table nothing is added to by typing (chats, email, calls, /// duplicates, imports): its list draws no bar. #[serde(default, skip_serializing_if = "Option::is_none")] pub add: Option<bool>, /// True on a table whose records are secrets: they are never said into /// the bar nor kept as a thought, and never cached on a device's disk /// (architect, 13 Oct 2026: a definition key, never a table's name). #[serde(default, skip_serializing_if = "Option::is_none")] pub sealed: Option<bool>, /// The table's rows are sealed on the object: the clear columns, the /// blind ones and the exact ones ([`seal::SealSpec`], sealing plan §2.2). #[serde(default, skip_serializing_if = "Option::is_none")] pub seal: Option<SealSpec>, /// What a send of one of this table's records carries to one of the /// owner's people ([`cotton_rules::send::SendSpec`]): absent, its records /// are never sent; a table of secrets (`sealed: true`) declares none, /// while one sealed on the object (`seal`) may (ruling R5). #[serde(default, skip_serializing_if = "Option::is_none")] pub send: Option<cotton_rules::send::SendSpec>, /// The view stood above the table's list, from the fixed vocabulary the /// app draws (`next_alarm`: the next alarm this device will ring) — a /// list head is named by the definition, never by its engine's name. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub list_head: Option<ListHead>, /// The column whose value is the project scope a link to one of this /// table's records opens (a project's `slug`): following such a link /// changes the scope rather than opening a page (architect, 13 Oct 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub scope_by: Option<String>, /// Present on a table whose rows stand for records put in the bin: a /// row opens its record's own page, read only, and Restore writes /// `restore` to the row (architect, 13 Oct 2026 — never the bin's name). #[serde(default, skip_serializing_if = "Option::is_none")] pub binned: Option<BinnedRows>, /// Present on a table whose list is drawn as people's stories, grouped /// by who posted them (architect, 13 Oct 2026 — never the table's name). #[serde(default, skip_serializing_if = "Option::is_none")] pub stories: Option<StoriesLayout>, /// The screen a record of this table opens at, when it is not the /// table's page: an app route pattern with one parameter, filled with /// the record's id (`/messages/[thread]`) — never a table-to-screen map /// in the app (architect, 13 Oct 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub record_route: Option<String>, /// The screen this table's LIST opens at, when it is not the generic /// `/lists/[table]`: an app route with no parameter (`/devices`) — never /// a table-to-screen map in the app. #[serde(default, skip_serializing_if = "Option::is_none")] pub list_route: Option<String>, /// Whose records these are: `personal`, the person's own, read from /// their own database whichever one is shown (their assistants, their /// Macs' runners); absent or `database`, the shown database's. #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<TableScope>, /// Part of how the app is set up (devices, members, runners): no thought /// is filed into it by its words and the filing picker never offers it. #[serde(default, skip_serializing_if = "Option::is_none")] pub setup: Option<bool>, /// The words a record of this table says its date in where it is listed /// outside its own tool — never a table's id in the app (pagestyles2, /// 14 Oct 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub linked_when: Option<LinkedWhen>, /// The kind the core's record read and comments know this table's /// records by (`note` for a journal page, a row of the notes) — absent /// on a table the generic read does not answer. #[serde(default, skip_serializing_if = "Option::is_none")] pub record_kind: Option<String>, /// True on a table whose records take pictures as pins: attachments /// filed on the record, each with a conversation of its own. #[serde(default, skip_serializing_if = "Option::is_none")] pub pins: Option<bool>, /// Where the table stands among those a thought is filed into: the /// ranked first, lowest first; the rest by name after them. #[serde(default, skip_serializing_if = "Option::is_none")] pub filing_rank: Option<u32>, /// True on a table a thought is made into by its own verb (Make a todo), /// whatever links its record carries. #[serde(default, skip_serializing_if = "Option::is_none")] pub made_by_verb: Option<bool>, /// The part this table plays that the app asks for by name. #[serde(default, skip_serializing_if = "Option::is_none")] pub role: Option<TableRole>, /// True on a list whose records ARE the files the "+" picks (Photos, /// Videos, Documents). #[serde(default, skip_serializing_if = "Option::is_none")] pub takes_files: Option<bool>, /// The screen family a sync names when this table's rows move, so an /// open list or page of it reads again (the app's `ScreenFamily`). #[serde(default, skip_serializing_if = "Option::is_none")] pub screen_family: Option<String>, /// True on a table whose rows move under an open list without a sync /// saying so: the list reads again on a beat while it is on screen. #[serde(default, skip_serializing_if = "Option::is_none")] pub polled: Option<bool>, /// The read that answers a record's projects, so its page offers /// Projects… — absent on a table whose records are filed under none. #[serde(default, skip_serializing_if = "Option::is_none")] pub projects_read: Option<ProjectsRead>, /// The sections the owner's OWN record of this table adds to its page /// (Me's voice words and devices) — on no other record. #[serde(default, skip_serializing_if = "Option::is_none")] pub owner_sections: Option<Vec<PageSection>>, /// True on a Settings table whose put-away records are the core's /// archived read, not its source's (the comments' archive). #[serde(default, skip_serializing_if = "Option::is_none")] pub archived_in_core: Option<bool>, /// True on a Settings table a link to which may hold the core's own /// record id rather than its source's (a native pull request or issue): /// such a link is titled through the core's records. #[serde(default, skip_serializing_if = "Option::is_none")] pub core_links: Option<bool>, /// True on a table whose create with a record's day adds to that record /// (a journal day): a plain sentence in the page's bar is added to it. #[serde(default, skip_serializing_if = "Option::is_none")] pub append: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sort: Option<ListSort>, /// How many whole months ahead a Money runway view reads from the reader /// day (absent: three). An explicit `to` in the read still wins. #[serde(default, skip_serializing_if = "Option::is_none")] pub horizon: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub group: Option<ListGrouping>, /// A date column the list is split by, one section per day. #[serde(default, skip_serializing_if = "Option::is_none")] pub by_day: Option<String>, /// A date column a long list is split by, one run per month. #[serde(default, skip_serializing_if = "Option::is_none")] pub by_month: Option<String>, /// A date column the list's days are grouped by. #[serde(default, skip_serializing_if = "Option::is_none")] pub day_grouping: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub upcoming: Option<ListUpcoming>, #[serde(default, skip_serializing_if = "Option::is_none")] pub recent: Option<RecentLayout>, /// Records drawn faded on a list. #[serde(default, skip_serializing_if = "Option::is_none")] pub dimmed: Option<ValueMatch>, /// The one layout the list draws in (absent: `list`). #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub layout: Option<ListLayout>, #[serde(default, skip_serializing_if = "Option::is_none")] pub grid: Option<ListGrid>, #[serde(default, skip_serializing_if = "Option::is_none")] pub chips: Option<ChipRow>, /// The system's Paste button at the head of the list: what is pasted /// becomes a record with the text in `column` (Clips, 14 Oct 2026). The /// platform's own button, because it reads the clipboard without asking. #[serde(default, skip_serializing_if = "Option::is_none")] pub paste: Option<ListPaste>, #[serde(default, skip_serializing_if = "Option::is_none")] pub cover: Option<CoverLayout>, /// Other tables' lists under this table's list, each a section with a /// `list`. #[serde(default, skip_serializing_if = "Option::is_none")] pub lists: Option<Vec<PageSection>>, /// A date column the page stamps on first open; blank is unread. #[serde(default, skip_serializing_if = "Option::is_none")] pub opened: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub empty: Option<EmptyWords>, #[serde(default, skip_serializing_if = "Option::is_none")] pub create: Option<ListCreate>, /// The table the list's one input writes into, when it is not this one. #[serde(default, skip_serializing_if = "Option::is_none")] pub capture: Option<ListCapture>, #[serde(default, skip_serializing_if = "Option::is_none")] pub exports: Option<Vec<RecordExport>>, /// A link column naming a record's siblings: the page offers the /// previous and next of them. #[serde(default, skip_serializing_if = "Option::is_none")] pub pager: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::available::<_, PageAction, _>")] pub actions: Option<Vec<PageAction>>, /// The messages a `conversation` page draws; on no other style. #[serde(default, skip_serializing_if = "Option::is_none")] pub conversation: Option<ConversationLayout>, /// The page carries a composer of its own (lane inplace, 16 Oct 2026): /// while it is open on the phone the fan, the caps and the record button /// are put away and the page's composer stands at the foot; closing the /// page brings them back as they were. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub composer: bool, // Round 2 (1 Oct 2026), optional and absent unless the source said so. /// A text column the list is indexed by (the A–Z rail). #[serde(default, skip_serializing_if = "Option::is_none")] pub index: Option<String>, /// The columns a search reads, by any part of a word. #[serde(default, skip_serializing_if = "Option::is_none")] pub search: Option<Vec<String>>, /// False on a table its engine only archives: no Delete anywhere. #[serde(default, skip_serializing_if = "Option::is_none")] pub delete: Option<bool>, /// On a table whose engine deletes some records and refuses others: a /// record offers Delete only while this holds of it as read — a column /// the engine answers, never a rule the page keeps. #[serde(default, skip_serializing_if = "Option::is_none")] pub delete_when: Option<SectionWhen>, /// A row standing for another record: a tap opens THAT record. #[serde(default, skip_serializing_if = "Option::is_none")] pub opens: Option<RecordOpens>, /// The polaroid face's words. #[serde(default, skip_serializing_if = "Option::is_none")] pub polaroid: Option<PolaroidLayout>, /// A row of typed words over the list narrowing it by one column. #[serde(default, skip_serializing_if = "Option::is_none")] pub filter: Option<ListFilter>, /// How a count of records is said, by one column's value. #[serde(default, skip_serializing_if = "Option::is_none")] pub count_words: Option<CountWords>, /// When `by_month` splits the list, and what heads the undated. #[serde(default, skip_serializing_if = "Option::is_none")] pub months: Option<ListMonths>, /// Records never listed (their page still opens). #[serde(default, skip_serializing_if = "Option::is_none")] pub hidden: Option<ValueMatch>, /// The list's own records: those matching this, in a list read's `where` /// shape, unless the read names its own `where` on that column. The core /// applies it to every read of the list, so its pages and its count are /// of these records alone. #[serde(default, skip_serializing_if = "Option::is_none")] pub shows: Option<OrderedMap<serde_json::Value>>, /// A VIEW (architect's ruling 03:55 IST 17 Oct 2026): this definition /// holds no records of its own — its rows are another table's, those its /// `where` keeps, read the way that table's own list reads them, under /// this definition's sort, group and computed columns. Money's So far and /// Ahead are two views of the one transaction table. A record opened from /// a view is the source's record. #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<ViewSource>, /// The list's Select: records ticked, then acted on together. #[serde(default, skip_serializing_if = "Option::is_none")] pub select: Option<ListSelect>, /// The words Delete asks with. #[serde(default, skip_serializing_if = "Option::is_none")] pub deletion: Option<DeletionWords>, /// Other lists the list's menu opens, each with its count. #[serde(default, skip_serializing_if = "Option::is_none")] pub links: Option<Vec<ListLink>>, /// The list's own links drawn as ONE row of tiles, each with its count, /// after its first `after` records (owner, 12 Oct 2026: a list may carry /// one row of view tiles); absent, they stand in a row of links. #[serde(default, skip_serializing_if = "Option::is_none")] pub link_tiles: Option<LinkTiles>, /// Lines of the list's menu that open an app screen, uncounted (the /// Tools screen's About, Spec 9.1). #[serde(default, skip_serializing_if = "Option::is_none")] pub menu: Option<Vec<MenuLine>>, /// The list's search field's words. #[serde(default, skip_serializing_if = "Option::is_none")] pub search_placeholder: Option<String>, /// How the list offers its search: the head's magnifier (no word) or /// the field on the page ([`SearchFace`]). #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub search_face: Option<SearchFace>, /// A record opens in the full-screen viewer — the picture, the film or /// the document itself — rather than on its page, which the viewer's /// details button raises. `words` are the viewer's own lines. #[serde(default, skip_serializing_if = "Option::is_none")] pub viewer: Option<TableViewer>, /// The record button's toast after a spoken line on a fan Home. The /// thought table carries them: what the button keeps is a thought. #[serde(default, skip_serializing_if = "Option::is_none")] pub voice: Option<VoiceWords>, /// Lines the app says about a database's own reads; the database table /// carries them (`could_not_read`). #[serde(default, skip_serializing_if = "Option::is_none")] pub words: Option<TableWords>, /// Other tables' records the page and list menu reach. #[serde(default, skip_serializing_if = "Option::is_none")] pub related: Option<Vec<RelatedRecords>>, /// What the page offers to do, each one of the four kinds in `commands.rs`. Run only for a built-in. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::available::<_, RecordCommand, _>")] pub commands: Option<Vec<RecordCommand>>, /// Whole-record package acts over the shared reserve and rules engines. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::available::<_, RecordCommand, _>")] pub acts: Option<Vec<RecordCommand>>, /// The id of one of `commands`, run after the page reads. #[serde(default, skip_serializing_if = "Option::is_none")] pub on_open: Option<String>, // Round 3 (1 Oct 2026), optional and absent unless the source said so. /// A record whose links hold exactly one record opens as that record. #[serde(default, skip_serializing_if = "Option::is_none")] pub hand_over: Option<RecordHandOver>, /// The strip under the page, written from the page. #[serde(default, skip_serializing_if = "Option::is_none")] pub attachments: Option<AttachmentsLayout>, /// One act under the list erasing every record it holds. #[serde(default, skip_serializing_if = "Option::is_none")] pub clear: Option<ListClear>, /// How often the list and pages read again while on screen. #[serde(default, skip_serializing_if = "Option::is_none")] pub live: Option<LiveReading>, /// Built-in records projected by an engine rather than read from storage. #[serde(default, skip_serializing_if = "Option::is_none")] pub derived: Option<bool>, /// A slip per value of one choice column (`SlipBy`), in place of the /// slip's words for a record holding that value (added 11 Oct 2026). #[serde(default, skip_serializing_if = "Option::is_none")] pub slip_by: Option<SlipBy>, /// What an assistant reads about the table. Every built-in says /// something here (a guard holds it); a definition may leave it out, as /// the Swift decoder reads it, and it then stays out. #[serde(default, skip_serializing_if = "Option::is_none")] pub instructions: Option<String>, /// An AI tool's price data; the client performs the arithmetic. #[serde(default, skip_serializing_if = "Option::is_none")] pub prices: Option<std::collections::BTreeMap<String, TokenPrices>>, /// `false`: a record's page gathers nothing that links to it (a secret, /// a device). Absent: every table linking here contributes its list. #[serde(default, skip_serializing_if = "Option::is_none")] pub contributions: Option<bool>, /// The table's records can be gathered into named groups a person picks /// by hand, drawn as a row of stacks above its list. Absent: no groups. #[serde(default, skip_serializing_if = "Option::is_none")] pub groups: Option<Groups>, /// The views of this table Home can show without anyone making them: /// Today on Todos, Next up on the Calendar, a chart. Each names a face; /// the list of them is data, so Home's catalogue is built from the /// definitions and the groups a person made, never from a list in the /// app. Absent: none. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::known_faces::<_, ShippedView, ViewFace>")] pub views: Option<Vec<ShippedView>>, /// The record drawn alone as a card above the strip (`card::CardFace`). #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "card::face_or_absent")] pub card: Option<card::CardFace>, /// The marks drawn over a card at rest that run one of the table's /// commands on its record, by the mark's name (`card::MARKS`): a /// check on a todo runs `done`. Absent, a mark there does nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub marks: Option<std::collections::BTreeMap<String, String>>, /// Said on the home table of a tool that holds more than this one table: /// the tool's name and every table it holds, this one first. The tool's /// home list is headed by the tool's name, not this table's plural. #[serde(default, skip_serializing_if = "Option::is_none")] pub tool: Option<ToolHome>, /// The column whose words head this record's page, where they are not /// its slip's title ("September 2026 · Everyday" over a statement whose /// slip says "September 2026"). #[serde(default, skip_serializing_if = "Option::is_none")] pub heads: Option<String>, /// The record page's five parts and its shape (Spec 11); absent, the /// default every table gets (`resolved_parts`). A key of its own beside /// `page`, which stays the array of sections. #[serde(default, skip_serializing_if = "Option::is_none")] pub parts: Option<PageParts>, /// The record page's slips table: each kind's width and acts, and their /// words. The database table carries it ([`SlipsLayout`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub slips: Option<SlipsLayout>, /// The writable definition keys a person edited on a built-in's row. /// A revision bump keeps each one whose value still draws on the new /// shipped shape (the columns it names are still there) and drops the /// rest; absent, the row is the shipped definition as seeded. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub edited: Vec<String>, /// The content hash ([`format::file_hash`]) of the shipped file the /// `edited` keys were made against, so an upgrade knows which shipped /// copy the person's edits sit on; absent while nothing is edited. #[serde(default, skip_serializing_if = "Option::is_none")] pub base_hash: Option<String>, /// Keys this build cannot name, kept as they came so a row a newer /// device wrote is relayed and rewritten whole ([`tolerant`]). #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")] pub unknown: serde_json::Map<String, serde_json::Value>, /// The paths of the drawing words this read fell back on: a newer /// build's, read as each key's shipped default ([`tolerant`]). Filled /// by every read, never stored; empty when the row reads as it came. #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")] pub fallbacks: Vec<String>, /// The acts this read left out as unavailable — each holding a word /// that decides what it does (a kind, a class, a scheme) this build does /// not name, by its id ([`tolerant::available`]). Every other act draws. /// Filled by every read, never stored. #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")] pub unavailable: Vec<String>, } /// The single bounded live read a table's record page may make. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LiveRead { pub method: String, pub bindings: OrderedMap<String>, pub fields: Vec<String>, } /// Definition keys fixed by storage, execution or table identity. Columns /// pass through `owner::on_shipped`, which keeps shipped types fixed while /// allowing look overlays and the owner's added columns. pub const FIXED_DEFINITION_KEYS: &[&str] = &[ "id", "builtin", "tables", "retired", "engine", "commands", "acts", "connections", "actions", "reorder", "edited", // Which format the file is and which shipped copy the edits sit on: the // build's bookkeeping, never a look a person sets. "format_version", "base_hash", // Whose database a table is read from, whether words are filed into it, // and the screen its list is: what the table IS, never how it looks. "scope", "setup", "list_route", // What the table's rows are to an engine (face choices). "face_choices", // Which columns the object holds only inside a device's seal: the kit's // to say, never a look, so no edit unseals a table or seals one under // rows the object holds clear. "seal", // What a record carries when it is sent, and what never leaves: the // kit's to say, never a look an edit could widen. "send", ]; /// Every present or future look key is the owner's unless explicitly fixed. pub fn writable_definition_key(key: &str) -> bool { !FIXED_DEFINITION_KEYS.contains(&key) } /// The paths where `from` differs from the shipped `base`, limited to the /// top-level definition keys a person edited. Objects and equally sized lists /// split into their named children; changing a list's membership or order is /// one edit because its position is its meaning. /// /// Old rows named a whole top-level section. Reading those markers through /// this function upgrades them in memory to their actual changed leaves, /// which lets a later shipped sibling join the section. pub fn leaf_edit_paths(base: &TableDefinition, from: &serde_json::Value, edited: &[String]) -> Vec<String> { use std::collections::BTreeSet; let Ok(base) = serde_json::to_value(base) else { return Vec::new() }; let mut paths = BTreeSet::new(); for path in edited { let root = path.split('.').next().unwrap_or_default(); if writable_definition_key(root) { if path.contains('.') { paths.insert(path.clone()); } else { differing_paths(root, base.get(root), from.get(root), &mut paths); } } } paths.into_iter().collect() } fn differing_paths(path: &str, base: Option<&serde_json::Value>, from: Option<&serde_json::Value>, paths: &mut std::collections::BTreeSet<String>) { if path == "columns" { // Shipped column identity and type are fixed. Only authored look // leaves and whole owner-added columns belong to the overlay. for column in from.and_then(serde_json::Value::as_array).into_iter().flatten() { let Some(column_name) = column["key"].as_str() else { continue }; let shipped = base.and_then(serde_json::Value::as_array).into_iter().flatten().find(|column| column["key"] == column_name); match shipped { Some(shipped) => { for look in owner::COLUMN_LOOK_KEYS { differing_paths(&format!("columns.{column_name}.{look}"), shipped.get(*look), column.get(*look), paths); } } None if owner::is_own_column(column_name) => { paths.insert(format!("columns.{column_name}")); } None => {} } } return; } match (base, from) { (Some(serde_json::Value::Object(base)), Some(serde_json::Value::Object(from))) => { let mut properties = std::collections::BTreeSet::new(); properties.extend(base.keys()); properties.extend(from.keys()); for property in properties { differing_paths(&format!("{path}.{property}"), base.get(property), from.get(property), paths); } } (Some(serde_json::Value::Array(base)), Some(serde_json::Value::Array(from))) if !["columns", "links", "menu", "groups"].contains(&path) && base.len() == from.len() && !reordered(base, from) && !moved_ids(base, from) => { for (index, (base, from)) in base.iter().zip(from).enumerate() { differing_paths(&format!("{path}.{index}"), Some(base), Some(from), paths); } } (base, from) if base != from => { paths.insert(path.to_string()); } _ => {} } } /// RULE: a list whose items name themselves (`id`) and stand in another order is ONE edit, kept whole: split by position, a reordered list of views kept the shipped ids in place and moved their labels and default onto other views (Todos' "Everything to do" landed on Done; lane ringviews, 21 Oct 2026). fn moved_ids(base: &[serde_json::Value], from: &[serde_json::Value]) -> bool { let ids = |values: &[serde_json::Value]| values.iter().map(|value| value.get("id").cloned()).collect::<Vec<_>>(); let (base_ids, from_ids) = (ids(base), ids(from)); base_ids.iter().any(Option::is_some) && base_ids != from_ids } fn reordered(base: &[serde_json::Value], from: &[serde_json::Value]) -> bool { if base.len() != from.len() || base == from { return false; } let mut unmatched = from.to_vec(); for value in base { let Some(index) = unmatched.iter().position(|other| other == value) else { return false }; unmatched.remove(index); } unmatched.is_empty() } fn path_value(value: &serde_json::Value, path: &[&str]) -> Option<serde_json::Value> { path.iter() .try_fold(value, |value, key| match value { serde_json::Value::Object(_) => value.get(*key), serde_json::Value::Array(values) => key.parse::<usize>().ok().and_then(|index| values.get(index)) .or_else(|| values.iter().find(|value| value.get("key").and_then(serde_json::Value::as_str) == Some(*key))), _ => None, }) .cloned() } fn set_path(value: &mut serde_json::Value, path: &[&str], replacement: Option<serde_json::Value>) -> bool { let Some((last, parents)) = path.split_last() else { return false }; let mut object = value; for key in parents { let Some(next) = (match object { serde_json::Value::Object(_) => object.get_mut(*key), serde_json::Value::Array(_) => key.parse::<usize>().ok().and_then(|index| object.get_mut(index)), _ => None, }) else { return false }; object = next; } match object { serde_json::Value::Object(object) => match replacement { Some(replacement) => { object.insert((*last).to_string(), replacement); } None => { object.remove(*last); } }, serde_json::Value::Array(array) => { let Ok(index) = last.parse::<usize>() else { return false }; let Some(slot) = array.get_mut(index) else { return false }; match replacement { Some(replacement) => *slot = replacement, None => return false, } } _ => return false, } true } fn set_column_edit(columns: &mut serde_json::Value, path: &[&str], source: &serde_json::Value) -> bool { let Some((key, tail)) = path.split_first() else { return false }; let Some(columns) = columns.as_array_mut() else { return false }; let supplied = source.as_array().into_iter().flatten().find(|column| column["key"] == *key); let existing = columns.iter().position(|column| column["key"] == *key); if tail.is_empty() { // Only a whole owner-added column may be introduced. The shared // owner validator checks its allowed types and namespace below. let Some(supplied) = supplied.filter(|_| owner::is_own_column(key)) else { return false }; match existing { Some(index) => columns[index] = supplied.clone(), None => columns.push(supplied.clone()) } return true; } let (Some(index), Some(supplied)) = (existing, supplied) else { return false }; let replacement = path_value(supplied, tail); set_path(&mut columns[index], tail, replacement) } /// `base` with each of `edited`'s keys taken from `from` (null removes it), /// keeping only the keys whose value still validates on `base` — the rule an /// owner's edit survives a revision bump by. An act or a stack is first taken /// onto `base` ([`owner::on_shipped`]): an act the new file no longer offers /// is dropped from the person's list (and a list with none left is dropped /// whole, so the shipped acts come back), and a stack whose `kept_in` the new /// file changed is dropped; added columns always ride, and a hidden flag /// rides while its column still ships. Answers the definition and the keys /// kept. /// Add every key `from` has that `into` lacks, at every depth, never replacing /// one `into` has. No reader of a definition fails on a missing key: a stored /// row or a served build's base file from before this build added a word /// takes this build's shipped value for it (architect, 16 Oct 2026, after /// `viewer.words.fetching` refused every cut and would have refused the /// media table on every phone). pub fn fill_missing_keys(into: &mut serde_json::Value, from: &serde_json::Value) { let (serde_json::Value::Object(into), serde_json::Value::Object(from)) = (into, from) else { return }; // A different photo is a different asset, not an incomplete copy of // the shipped one. Its bundled object and link style must not travel // onto an owner's photo (definitions_seed's database-isolation guard). if into.get("photo").and_then(serde_json::Value::as_str).is_some_and(|photo| { photo.starts_with("photo:") && from.get("photo").and_then(serde_json::Value::as_str) != Some(photo) }) { return; } for (key, value) in from { match into.get_mut(key) { Some(held) => fill_missing_keys(held, value), None => { into.insert(key.clone(), value.clone()); } } } } pub fn with_edits(base: &TableDefinition, from: &serde_json::Value, edited: &[String]) -> (TableDefinition, Vec<String>) { let mut drawn = base.clone(); let mut kept = Vec::new(); let mut fallbacks = base.fallbacks.clone(); // Columns first, so later look keys can name the owner's additions. let mut paths = leaf_edit_paths(base, from, edited); paths.sort_by_key(|path| { let mut parts = path.split('.'); let column = parts.next() == Some("columns"); let key = parts.next(); let position = from["columns"].as_array().and_then(|columns| columns.iter().position(|column| column["key"].as_str() == key)).unwrap_or(usize::MAX); (!column, if column { position } else { 0 }) }); for path in paths { let mut split = path.split('.'); let key = split.next().expect("leaf paths have a root"); let tail: Vec<&str> = split.collect(); let Ok(mut value) = serde_json::to_value(&drawn) else { continue }; let Some(object) = value.as_object_mut() else { continue }; let mut root = object.get(key).cloned().unwrap_or(serde_json::Value::Null); let source = from.get(key).unwrap_or(&serde_json::Value::Null); // Stack identity is checked against the original stored section, // before merging its look leaves onto the new file's location. if key == owner::STACKS_KEY && owner::on_shipped(base, key, source, owner::Against::Upgrade).is_err() { continue; } // A picture, for example, may ship as a photo object in one build // and an asset string in another. The person's selected form wins; // a leaf cannot be written into the shipped form of another type. if !tail.is_empty() && std::mem::discriminant(&root) != std::mem::discriminant(source) { root = source.clone(); } if tail.is_empty() { root = from.get(key).cloned().unwrap_or(serde_json::Value::Null); } else if key == "columns" { if !set_column_edit(&mut root, &tail, source) { continue; } } else if !set_path(&mut root, &tail, path_value(source, &tail)) { continue; } let Ok(root) = owner::on_shipped(base, key, &root, owner::Against::Upgrade) else { continue }; match root { serde_json::Value::Null => { object.remove(key); } root => { object.insert(key.to_string(), root); } } let Ok(candidate) = serde_json::from_value::<TableDefinition>(value) else { continue }; if candidate.validate().is_ok() { fallbacks.extend(candidate.fallbacks.iter().cloned()); drawn = candidate; kept.push(path); } } fallbacks.sort(); fallbacks.dedup(); drawn.fallbacks = fallbacks; drawn.edited = kept.clone(); (drawn, kept) } /// [`with_edits`], answering each edit the new `base` could not carry: its /// key, what `base` draws there now, and the person's value that went. pub fn with_edits_reported(base: &TableDefinition, from: &serde_json::Value, edited: &[String]) -> (TableDefinition, Vec<format::DroppedEdit>) { let (drawn, kept) = with_edits(base, from, edited); let shipped = serde_json::to_value(base).unwrap_or_default(); let dropped = leaf_edit_paths(base, from, edited) .iter() .filter(|key| !kept.contains(key)) .map(|key| { let path: Vec<&str> = key.split('.').collect(); format::DroppedEdit { key: key.clone(), kept: path_value(&shipped, &path).unwrap_or(serde_json::Value::Null), dropped: path_value(from, &path).unwrap_or(serde_json::Value::Null), } }) .collect(); (drawn, dropped) } /// The tool a home table heads (design note 26203e21 §5): what Home, the /// Tools screen and the database page draw as its card — built-in and /// imported tools alike, from this key and nothing else. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolHome { /// Views in ring order, with exactly one default when declared. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub views: Vec<tool_views::ToolView>, /// The card's name. pub name: String, /// Plain words describing what the tool is for in the tool picker. #[serde(default, skip_serializing_if = "Option::is_none")] pub purpose: Option<String>, /// A tool of several tables: every one, this home table first. Absent, /// the tool is this one table. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tables: Vec<String>, /// The key Home's arrangement orders and puts away the tool by (`todos`, /// `accounts`); absent, the table's id. #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<String>, /// The card's glyph, a kebab-case icon name (`circle-check`). #[serde(default, skip_serializing_if = "Option::is_none")] pub icon: Option<String>, /// The paper the card is printed on; absent, the plainest stock. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub card_stock: Option<CardStock>, /// Where a tap on the card goes, as an app path (`/todos`); absent, the /// table's own list. #[serde(default, skip_serializing_if = "Option::is_none")] pub route: Option<String>, /// The card's figure: each a named read Home answers, in words, joined /// with " · "; a read at zero (or false) says nothing. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub figures: Vec<ToolFigure>, /// True on a built-in a database holds only on purpose: off every /// default, held where a `cotton_tool_definitions` row of its key says so /// — never a list of keys in code. No built-in sets it since Screenplays /// left (owner, 17 Nov 2026). #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub held_only: bool, /// What a built-in's rows need the person's Cotton server for /// ([`ToolServer`]): the Calls card, whose rows the Mac importer brings. #[serde(default, skip_serializing_if = "Option::is_none")] pub server: Option<ToolServer>, } /// One figure on a tool's card: the read it counts and the words it is said /// in — `many` with `{n}` for the count (or alone, for a read that is a flag), /// `one` when the count is exactly one. /// /// A figure the definition works out itself (`summary` or `formula`) names /// its own `read`, a word none of [`TOOL_FIGURE_READS`] is: Home answers it /// as the core's line, its total said for `{n}` — an amount in its own /// currency — or nothing at zero. A `term` is said by no card: it is there /// for another figure's formula (money in over all time, for net worth). A /// lowest or highest (`min`/`max`) may say `{date}` too: the day of the row /// that holds it, by the table's `date` (Ahead's "Lowest ₹… on 20 Oct"). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolFigure { pub read: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub one: Option<String>, pub many: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub summary: Option<FigureSummary>, #[serde(default, skip_serializing_if = "Option::is_none")] pub formula: Option<FigureFormula>, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub term: bool, } /// A figure over one table's rows (`{"table": "transaction", "op": "sum", /// "column": "amount_minor", "where": {"direction": "in"}, "period": /// "this_month"}`): counted or summed by an indexed read — or, for a column /// an engine or the evaluator works out (an account's balance), added over /// the rows the evaluator reads. A `min` or `max` is the lowest or highest /// of a column over those rows (a running balance's lowest point). `where` is a list's where over the table's STORED columns; `period` /// keeps the rows whose date (the table's `date`) falls in it, the month the /// person is in. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FigureSummary { pub table: String, pub op: SummaryOp, #[serde(default, skip_serializing_if = "Option::is_none")] pub column: Option<String>, #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] pub where_: Option<OrderedMap<serde_json::Value>>, #[serde(default, skip_serializing_if = "Option::is_none")] pub period: Option<FigurePeriod>, } /// The stretch of time a figure keeps its rows from. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum FigurePeriod { /// The calendar month the person is in, by their own day. ThisMonth, /// The person's own day. Today, /// The day after the person's own: what a kitchen cooks next. Tomorrow, /// The person's day and the six after it — a business's "this week". #[serde(rename = "next_7_days")] Next7Days, /// The first day after the person's own on which the rows hold any: a /// studio's next class day ("Monday" on a Friday), read from the rows. NextDay, /// The calendar year the person is in, by their own day: the books /// finished this year. ThisYear, } /// A figure made of the tool's other figures: the totals of `plus` less the /// totals of `minus`, each named by its `read` (net worth: what the accounts /// hold, plus what people owe, less what is owed to them). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct FigureFormula { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub plus: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub minus: Vec<String>, } /// The reads a tool's figure can name: the counts Home answers /// (`read.home`'s `counts`). Two are flags, said when true. pub const TOOL_FIGURE_READS: &[&str] = &[ "unreadMessages", "openTodos", "eventsLeftToday", "liveAlarms", "notes", "people", "locations", "unreadPages", "journalUnwritten", "lockedDocuments", "freshEdition", "activeProjects", "runningSessions", "waitingSessions", ]; /// The figure reads that are flags, not counts. pub const TOOL_FIGURE_FLAGS: &[&str] = &["journalUnwritten", "freshEdition"]; /// A table whose records a person gathers into named groups: `stack` names /// which of the existing faces a group's pile above the list is drawn with. /// `kept_in`, when present, says the groups are another table's records — /// the photo list's are its albums — and not rows of their own. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Groups { #[serde(deserialize_with = "crate::definitions::tolerant::word")] pub stack: StackFace, #[serde(default, skip_serializing_if = "Option::is_none")] pub kept_in: Option<GroupsKeptIn>, } /// Where a table's groups are kept when they are another table's records: /// `table`, whose every record is one group — its list the groups' list, its /// page a group's page — and `items`, whose records are a group's members. /// Only a pair the core writes groups through is named /// ([`GROUPS_KEPT_IN`]); a group verb on the table is that pair's own write. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct GroupsKeptIn { pub table: String, pub items: String, } /// The tables groups can be kept in, each with its members' table: albums /// and their pictures (Spec 10 G, item 3 — "albums are groups"). pub const GROUPS_KEPT_IN: &[(&str, &str)] = &[("album", "album_item")]; /// A view a table ships (`TableDefinition::views`): a face Home draws and the /// name its catalogue gives it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ShippedView { /// The face it is drawn with, and its key among the table's views. #[serde(deserialize_with = "crate::definitions::tolerant::word")] pub face: ViewFace, /// What Home's catalogue calls it: "Today", "Next up". pub name: String, /// What a chart view draws — this table's records by period, worked out /// by `records::chart`; present exactly when the face is `chart`. #[serde(default, skip_serializing_if = "Option::is_none")] pub chart: Option<ChartFace>, /// The app path a tile pointing at this view opens (`/calendar/month`); /// absent, the tile opens its tool. #[serde(default, skip_serializing_if = "Option::is_none")] pub opens: Option<String>, /// The kind of database it stands in (`{"database": "project"}`); /// absent, every database. A database of the other kind never reads it. #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option<DatabaseWhen>, } /// The table a view's rows are, and which of them (`TableDefinition::source`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ViewSource { pub table: String, #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] pub where_: Option<OrderedMap<serde_json::Value>>, } /// Where a link or a view stands (`when: {"database": "project"}`): only in a /// database of this kind — Money's Months, a profit and loss by the month an /// invoice is for, means something in a project's database and nothing in /// the personal one. The core drops a link or view whose `when` does not hold /// from the definitions it resolves for a file, so the app and an assistant /// never see it there ([`TableDefinition::for_database`]). #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct DatabaseWhen { pub database: DatabaseKind, } /// The two kinds of database: the person's own, and a project's (which may /// be shared). A file whose kind is not yet written reads as personal. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum DatabaseKind { Personal, Project, } /// The faces a shipped view can name. Their order here is the order Home's /// catalogue gives them. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum ViewFace { /// Today's todos and events, of one database. #[default] Today, /// The todos due in the next seven days. Upcoming, /// The next events. NextUp, /// The month, and beside it what today and the days after it hold. Month, /// The chats last written in. Chats, /// A table's records by period, as bars or a line (`ShippedView::chart`) /// — any table may ship one, a kit's too, so it is offered per table. Chart, } impl ViewFace { /// The face's name as a definition spells it. pub fn as_str(self) -> &'static str { match self { ViewFace::Today => "today", ViewFace::Upcoming => "upcoming", ViewFace::NextUp => "nextUp", ViewFace::Month => "month", ViewFace::Chats => "chats", ViewFace::Chart => "chart", } } } /// The faces a group's stack is drawn with — existing ones, named, never drawn here. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum StackFace { /// The table's polaroids, one on another (People). Polaroids, /// The table's paper slips, one on another (Todos). #[default] Slips, /// The table's covers, one on another (Documents, Reader). Covers, } impl StackFace { /// The face as a definition spells it. pub fn as_str(self) -> &'static str { match self { Self::Polaroids => "polaroids", Self::Slips => "slips", Self::Covers => "covers", } } } /// A record that opens as the one record it links to — while `when` holds, /// or always without it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RecordHandOver { #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option<SectionWhen>, } /// A record's strip of pictures, written from its page (absent `editable` is /// true), a picture added from each of `sources` in order. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct AttachmentsLayout { #[serde(default, skip_serializing_if = "Option::is_none")] pub editable: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::known_words::<_, AttachmentSource, _>")] pub sources: Option<Vec<AttachmentSource>>, } /// Where a picture added to a strip comes from. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AttachmentSource { Library, Camera, } /// One act under the list that erases every record it holds, after one /// question: the verb `label` and its `note` by hand, the question `title` /// (absent, the label) and `message` (`{count}` the number), its buttons, and /// the receipt's `done`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListClear { pub label: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub note: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub confirm: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub cancel: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub done: Option<String>, } /// A table whose records move while on screen: read again every `every` /// seconds. Kept as the number written, so it round-trips as written. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LiveReading { pub every: serde_json::Number, } impl LiveReading { /// The fastest a table may ask to be read again, in seconds. pub const FLOOR: u32 = 1; /// The slowest: a day. pub const CEILING: u32 = 86_400; } /// The polaroid face's words, each a column. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PolaroidLayout { #[serde(default, skip_serializing_if = "Option::is_none")] pub caption: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subtitle: Option<String>, } /// A typed word row narrowing the list by `column`: `all` first, then each /// value's word in `order`, and each value's empty words. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListFilter { pub column: String, /// False hides the controls while retaining value narrowing; absent is true. #[serde(default, skip_serializing_if = "Option::is_none")] pub tabs: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub all: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub words: Option<OrderedMap<String>>, #[serde(default, skip_serializing_if = "Option::is_none")] pub order: Option<Vec<String>>, #[serde(default, skip_serializing_if = "Option::is_none")] pub empty: Option<OrderedMap<EmptyWords>>, } /// A count said by `column`'s value: "40 photos · 2 videos". /// How a table's records open in the full-screen viewer (`viewer`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TableViewer { /// The viewer's lines. The media table carries them; the viewer reads /// them from there for whatever it shows. #[serde(default, skip_serializing_if = "Option::is_none")] pub words: Option<ViewerWords>, } /// Every line the record button's toast says (smooth, owner 16 Oct 2026: no /// live transcript — one toast after the words are taken that says what /// happened; architect 21:05 IST 16 Oct 2026: no caption under the fan). /// `{name}` is filled with what a spoken line opened. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct VoiceWords { /// The words were kept as a thought. pub saved: String, pub undo: String, pub undone: String, /// "Opened {name}" — a tool, a record or a database. pub opened: String, /// The record on top came down. pub back: String, /// A spoken command ran. pub ran: String, /// The microphone heard no words. pub nothing: String, /// The person refused the microphone or speech: the one slip, with /// `settings` as its act. pub denied: String, pub settings: String, } /// Lines a table's definition says about reads, filled with `{database}`, /// the database's name. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct TableWords { #[serde(default, skip_serializing_if = "Option::is_none")] pub could_not_read: Option<CouldNotReadWords>, } /// What a read the core cut says (`could_not_read`, `details.why`): the /// read pool was busy, or the read ran past its deadline (architect's /// rulings 21:00 (4) and 22:03 IST 16 Oct 2026). Drawn instead of the core's /// own sentence on Home, a list and a page. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CouldNotReadWords { pub busy: String, pub too_long: String, /// The read needed the serving Mac and the transport never reached it: /// said instead of the transport's own text, which carries an address /// and a resolver's words (architect's offline-truth ruling, 17 Oct /// 2026). A file that lacks it takes the shipped line. #[serde(default, skip_serializing_if = "Option::is_none")] pub mac_away: Option<String>, /// Any other read that failed: said instead of the error's own text, so /// no transport or engine words reach a page (walker 294 row G, 17 Oct /// 2026). A file that lacks it takes the shipped line. #[serde(default, skip_serializing_if = "Option::is_none")] pub other: Option<String>, /// The read's facts live only on the serving Mac (AI usage: metering /// never leaves it) and the Mac is not heard now, so the read answers at /// once instead of waiting on it (295 rule 15, walker294). `{heard}` is /// the Mac's last-heard instant said as an age, `{what}` the table /// definition's plural. A file that lacks it takes the shipped line. #[serde(default, skip_serializing_if = "Option::is_none")] pub on_the_mac: Option<String>, /// The read met a table whose background move is not done (its computed /// index rebuilt after the open): it shows by itself when the move is /// done, so no Try again (passivemove rule 3). `{what}` is the table /// definition's plural; no version number is said. A file that lacks it /// takes the shipped line. #[serde(default, skip_serializing_if = "Option::is_none")] pub moving: Option<String>, } /// Every line the full-screen viewer says. `{n}` and `{count}` are filled /// with a place and a total. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ViewerWords { pub close: String, pub details: String, pub more: String, pub share: String, /// "{n} of {count}" — the place in the set. pub position: String, pub absent: String, pub removed: String, pub fetch: String, /// While a fetch the person asked for runs. pub fetching: String, /// A place's map with no snapshot kept on this phone. pub map_absent: String, pub play: String, pub pause: String, pub mute: String, pub unmute: String, pub picture_in_picture: String, pub search: String, pub no_match: String, /// "Page {n} of {count}". pub page: String, pub go_to_page: String, pub go: String, pub pin_press: String, pub pin_hint: String, pub pin_placeholder: String, pub cancel: String, pub save: String, pub saving: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CountWords { pub column: String, pub units: OrderedMap<ColumnUnits>, #[serde(default, skip_serializing_if = "Option::is_none")] pub order: Option<Vec<String>>, } /// `by_month`'s threshold (more than `over` records) and the undated's /// heading. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListMonths { #[serde(default, skip_serializing_if = "Option::is_none")] pub over: Option<u32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub undated: Option<String>, } /// The list's Select mode and the verb it ends in; absent, delete. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListSelect { #[serde(default, skip_serializing_if = "Option::is_none")] pub verb: Option<SelectVerb>, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum SelectVerb { Delete, } /// The words Delete asks with: what deleting one or several also means, the /// number column whose sum it frees, whether it can be undone, the verbs. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DeletionWords { #[serde(default, skip_serializing_if = "Option::is_none")] pub one: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub other: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub undo: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub confirm: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub cancel: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub asks: Option<bool>, /// The record waits in the bin: the question says where it goes in the /// words the Bin's place on Home calls for. #[serde(default, skip_serializing_if = "Option::is_none")] pub bin: Option<bool>, } /// Another table's records matching `where`, counted. With a `path`, a row /// of the list's menu opening that app route; without one, a link drawn on /// the list itself that opens the generic list of `table` read with `where` /// (titled "<label> · <this list>"), and is not drawn while it counts none. /// A `lead` link stands on its own line straight under the list's own /// records; an `above` link in one row over them, after the lists drawn above /// (the Code list's Machines and Runners); the others share one row after the /// list's `lists`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListLink { pub label: String, pub table: String, #[serde(rename = "where", default, skip_serializing_if = "Option::is_none")] pub where_: Option<OrderedMap<serde_json::Value>>, #[serde(default, skip_serializing_if = "Option::is_none")] pub words: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub lead: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub above: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub review: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub hides_empty: Option<bool>, /// The link's words once it counts something: "{n} recording did not /// work" / "{n} recordings did not work". Without them a count stands /// beside the label as a figure ("Senders · 12"). #[serde(default, skip_serializing_if = "Option::is_none")] pub units: Option<ColumnUnits>, /// The kind of database the link stands in; absent, every database /// ([`DatabaseWhen`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option<DatabaseWhen>, } /// Where a list's row of link tiles stands: after this many records. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LinkTiles { pub after: u32, } /// A line of a list's menu: its words, the app route it opens, and the object /// its card stands (by name, as a command's `object`). A line that names none /// stands the link, which is Connect's and Disconnect's, so a line that does /// something else names its own. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct MenuLine { pub label: String, pub path: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option<String>, } /// Another table's records the page reaches: those whose `column` names this /// record, matching `filter`; `new` offers a blank one, `archived` the /// archived, and `open` names the result's column whose record a tap opens. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RelatedRecords { pub label: String, pub table: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub column: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub filter: Option<OrderedMap<serde_json::Value>>, #[serde(default, skip_serializing_if = "Option::is_none")] pub new: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub archived: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub open: Option<String>, /// What the list is called when open ("Archived chats", not "Chats"). #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option<String>, /// What the list says when it holds nothing, in place of the table's words. #[serde(default, skip_serializing_if = "Option::is_none")] pub empty: Option<EmptyWords>, /// Offered only on a record whose named columns hold these values. #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option<OrderedMap<serde_json::Value>>, } /// A tool's picture: an asset key the app ships, or a photo the tool carries, /// or — for a table with no picture of its own — only how a link to one of /// its records is drawn on a card. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum ToolPicture { Asset(String), Photo(ToolPhoto), Link(LinkPicture), } impl ToolPicture { /// How a link to one of this table's records is drawn on a card; absent, /// the tool's own enamel (`picture`). pub fn link_object(&self) -> Option<LinkObject> { match self { ToolPicture::Asset(_) => None, ToolPicture::Photo(photo) => photo.link_object, ToolPicture::Link(link) => Some(link.link_object), } } } /// What a card draws for a link to a record of a table (architect, 13 Oct /// 2026): the record's cap (a project, a database), the face slip of a /// person, or the tool's own enamel — the default, so a table that says /// nothing needs nothing. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum LinkObject { #[default] Cap, People, Picture, } /// The `{"link_object": …}` form of a picture, for a table whose tool has no /// picture of its own. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct LinkPicture { #[serde(deserialize_with = "crate::definitions::tolerant::word")] pub link_object: LinkObject, } /// The six papers Home's tool cards are cut from (a stock, not a palette /// role: the colour is in the photographed blank). #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum CardStock { Cream, Sage, Rose, Slate, Tan, Grey, } /// The `{"photo": …}` form of a tool's picture. A built-in's picture also /// names the `object` the app ships with the same bytes, so a device draws it /// from its bundle (its prints, its small variant, offline) while the photo /// record is what the owner swaps: a picture the owner sets names no object /// and is drawn from the photo itself. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolPhoto { pub photo: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option<String>, /// How a link to one of this table's records is drawn on a card. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub link_object: Option<LinkObject>, } /// A column a tool adds to a table another tool brought (Birthdays' "Remind /// me" on People's person): on install an added column of that table, /// keyed in the tool's own part of the owner's namespace /// (`own_<tool>__<key>`), hidden in the table's own look and drawn in the /// tool's views; its values are the table's, kept when the tool goes. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolContribution { pub table: String, pub column: Column, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolAuthor { pub device: String, pub name: String, } /// Shipped generic capabilities a package may request. pub const ENGINE_CAPABILITIES: &[&str] = &["reserve@1", "rules@1", "sms@1"]; /// The acts a tool may offer (`ToolAct::id`): each is the phone's own, run by /// `tools.act` and never a verb of the core. `google_connect` opens Google's /// consent page for the person's object in the system browser; /// `google_disconnect` asks first, then has the object revoke and forget /// the grant. `spotify_connect` and `spotify_disconnect` are the same two /// for Spotify, the Music tool's. pub const TOOL_ACTS: &[&str] = &[ "google_connect", "google_disconnect", "spotify_connect", "spotify_disconnect", // This phone's own account, answered by the phone itself (Cotton Books' // On this phone, owner, 4 Nov 2026): Sign in while it backs up to no // object, Back up now and Sign out while it does. Sign out keeps // everything on the phone. "account_sign_in", "account_back_up", "account_sign_out", // Cotton Music's own, answered by the phone itself (Music definition, 4 // Nov 2026): Keep everything turns this phone's keeping of every song on // or off, a fact of this phone alone. Songs come in through the decks' // doors (`create.doors`), never an act. "music_keep_everything", // Cotton Cinemas' own (Cinemas definition, 4 Nov 2026): Keep everything // turns this phone's keeping of every film and episode on or off, a // fact of this phone alone. "cinemas_keep_everything", // Whether this phone's film downloads may use mobile data (Wi-Fi only by // default), and the most it keeps of films (32, 64, 128 or 256 GB). "cinemas_cellular", "cinemas_budget", // Podcasts' Export OPML (opml-ffi, 7 Nov 2026): the object writes the // subscribed shows as an OPML document (`export_opml`), asked through // `object.act`; it stands while the phone backs up, and before sign-in // it says Sign in first. "podcasts_export_opml", // Export library (Books, Music, Podcasts and Cinemas, 7 Nov 2026): the // tool's open bundle (`package.exportOpen`), laid by the core into a // folder the phone zips and hands to the share sheet. "export_library", // Cotton Keys' Turn on Cotton Keys (keys-android-autofill, 17 Nov 2026): // the system's settings where the person makes Cotton Keys the phone's // password, passkey and autofill provider. It stands in the Keys app on // Android alone, the build that ships those services. "keys_turn_on", ]; /// An act a tool offers on the long-press fan of every one of its cards, /// beside the card's own: the Calendar's Connect Google Calendar, Music's /// Connect Spotify. Its id names what it does ([`TOOL_ACTS`]); one this /// build does not name is left out of the read (`unavailable`). When it /// stands is the act's own rule (connect while no account of its service is /// connected, disconnect while one is), read where the fan is answered /// (`shell.opened`). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolAct { pub id: String, pub label: String, /// It asks before it runs (a disconnect): the fan turns into the act /// alone, and a second tap runs it. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub asks: bool, /// Its bare painted picture on the fan, one of [`commands::ACT_OBJECTS`] /// (Keep everything's parcel); none is a typed tile. #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option<String>, } /// How a tool's lists stand on their own decks (`lists`, owner, 7 Nov /// 2026): a list is one table shared by every app (`record_group`), so its /// look is chosen by the tool that lists it, never by the table — Music's /// lists of songs are cassettes while Books' and Cinemas' keep their plain /// deck. The list's card is the core's (`shell.deck`), drawn in `face` /// first on the list's deck, its members after it. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ToolLists { /// The face a list of the tool stands in. pub face: card::FaceId, } /// A tool's `lists` as a device reads it: one naming a face a newer build /// draws reads as none, the word it fell back on said ([`tolerant`]); an /// authored one is refused with the face named. fn lists_or_absent<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<ToolLists>, D::Error> { use serde::de::Error as _; let value = serde_json::Value::deserialize(deserializer)?; if value.is_null() { return Ok(None); } if let Some(face) = value.get("face").filter(|face| face.as_str().is_some_and(|id| card::FaceId::known(id).is_none())) { tolerant::fell_back(face); return Ok(None); } serde_json::from_value(value).map(Some).map_err(D::Error::custom) } /// What a tool's rows need the person's Cotton server for (`server`): a /// tool whose rows arrive only through the server — the Mac importer's /// WhatsApp, mail, calls and photos, Google Calendar — says so, and the line /// it says it in, so a phone that has not backed up draws that line on the /// tool's empty deck with a way to back up, and nothing about it is written /// in Swift (owner, 1 Nov 2026: tools are data). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ToolServer { /// The tool's rows come through the server. pub needs: bool, /// What the empty deck says before backup, in the tool's own words. pub line: String, } impl ToolServer { fn validate(&self, slot: &str) -> Result<(), DefinitionError> { if self.line.trim().is_empty() || self.line.chars().any(char::is_control) { return Err(DefinitionError::BadSlot { slot: slot.to_string(), why: refusal_words("says_what_the_server_brings") }); } Ok(()) } } /// A tool: a name and a picture over one or more tables. /// /// Automations contain only validated data actions; they never name code or engines. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(remote = "Self")] pub struct ToolDefinition { /// Views in definition order, read by every surface. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub views: Vec<tool_views::ToolView>, pub id: String, pub name: String, /// Plain words describing what the tool is for in the tool picker. #[serde(default, skip_serializing_if = "Option::is_none")] pub purpose: Option<String>, /// The card's picture. Optional as the Swift decoder reads it (a data /// tool's board may carry none): absent stays absent, and a null is read /// as absent and written back absent, as Swift writes it. #[serde(default, skip_serializing_if = "Option::is_none")] pub picture: Option<ToolPicture>, /// The paper the tool's card is printed on; absent, the plainest stock. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::definitions::tolerant::word_or_absent")] pub card_stock: Option<CardStock>, /// What every tile on the tool's fan tiers is drawn as ([`fan_tile::FanTile`]): /// its stock, its type and its pictograms. Absent, today's tiles. #[serde(default, skip_serializing_if = "Option::is_none")] pub fan_tile: Option<fan_tile::FanTile>, pub tables: Vec<String>, /// The order ink searches the tool's tables in (`shell.deck {ink}`), /// where its `tables` order reads wrong: Music's albums and artists /// before its many songs. Each is one of its `tables`; absent, `tables`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub search: Vec<String>, /// Columns the tool adds to tables the database already has, each kept /// as an added column of that table ([`owner::contributed_key`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub contributes: Vec<ToolContribution>, pub instructions: String, pub automations: Vec<serde_json::Value>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub engines: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reserve: Option<reserve::Reservation>, /// The acts the tool offers on its cards' fans ([`ToolAct`]). #[serde(default, skip_serializing_if = "Vec::is_empty")] pub acts: Vec<ToolAct>, /// What its rows need the person's Cotton server for ([`ToolServer`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub server: Option<ToolServer>, /// How the tool's lists (its tables' groups) stand on their own decks /// ([`ToolLists`]): Music's list of songs is a cassette, first on its /// deck before its songs. Absent, a list's deck is its members alone. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "lists_or_absent")] pub lists: Option<ToolLists>, pub author: ToolAuthor, pub signature: Option<String>, /// Keys this build cannot name, kept as they came so a row a newer /// device wrote is relayed and rewritten whole ([`tolerant`]). #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")] pub unknown: serde_json::Map<String, serde_json::Value>, /// The paths of the drawing words this read fell back on: a newer /// build's, read as each key's shipped default ([`tolerant`]). Filled /// by every read, never stored; empty when the row reads as it came. #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")] pub fallbacks: Vec<String>, /// The acts this read left out as unavailable — each holding a word /// that decides what it does (a kind, a class, a scheme) this build does /// not name, by its id ([`tolerant::available`]). Every other act draws. /// Filled by every read, never stored. #[serde(skip_deserializing, skip_serializing_if = "Vec::is_empty")] pub unavailable: Vec<String>, } crate::tolerant_read!(TableDefinition); crate::tolerant_read!(ToolDefinition); impl TableDefinition { /// A table's acts are left out as they are read ([`tolerant::available`]). fn unrunnable(&self) -> Vec<String> { Vec::new() } /// `id` is an act this read left out: a part naming it still reads, and /// draws without it. pub fn is_unavailable(&self, id: &str) -> bool { self.unavailable.iter().any(|act| act == id) } /// A figure the tool works out (`summary` or `formula`, never both): it /// names a read of its own, none of Home's; a summary reads a table of /// the tool's with a column its op needs; a formula names the tool's /// summaries. Its words say the total as `{n}`. The table's own columns /// are checked where its definition is in hand (Home's read refuses a /// figure whose where its table does not take). fn validate_worked_figure(&self, tool: &ToolHome, index: usize, figure: &ToolFigure) -> Result<(), DefinitionError> { let slot = |field: &str| format!("tool.figures.{index}{field}"); let bad = |field: &str, why: &str| DefinitionError::BadSlot { slot: slot(field), why: refusal_words(why) }; if !is_valid_id(&figure.read) || TOOL_FIGURE_READS.contains(&figure.read.as_str()) { return Err(bad(".read", "names_this_figure_with_a_word_of")); } if tool.figures.iter().filter(|other| other.read == figure.read).count() > 1 { return Err(bad(".read", "names_one_figure_of_the_tool")); } if !figure.many.contains("{n}") || figure.one.as_deref().is_some_and(|one| one.trim().is_empty()) { return Err(bad("", "says_its_total_as_and_a_count")); } let extreme = |summary: &FigureSummary| matches!(summary.op, SummaryOp::Min | SummaryOp::Max); if figure.many.contains("{date}") && !figure.summary.as_ref().is_some_and(extreme) { return Err(bad(".many", "says_only_for_a_lowest_or_highest")); } match (&figure.summary, &figure.formula) { (Some(_), Some(_)) => Err(bad("", "is_a_summary_or_a_formula_not")), (Some(summary), None) => { let tables: Vec<&str> = if tool.tables.is_empty() { vec![self.id.as_str()] } else { tool.tables.iter().map(String::as_str).collect() }; if !tables.contains(&summary.table.as_str()) { return Err(bad(".summary.table", "is_one_of_the_tool_s_tables")); } match (summary.op, &summary.column) { (SummaryOp::Count, None) | (SummaryOp::Sum | SummaryOp::Min | SummaryOp::Max, Some(_)) => {} (SummaryOp::Count, Some(_)) => return Err(bad(".summary.column", "is_not_asked_of_a_count")), (SummaryOp::Sum, None) => return Err(bad(".summary.column", "names_what_a_sum_adds")), (SummaryOp::Min | SummaryOp::Max, None) => { return Err(bad(".summary.column", "names_what_a_lowest_or_highest_reads")) } } if summary.column.as_deref().is_some_and(|column| !is_valid_id(column)) { return Err(bad(".summary.column", "is_a_column_key")); } if summary.where_.iter().flat_map(OrderedMap::keys).any(|key| !is_valid_id(key)) { return Err(bad(".summary.where", "names_column_keys")); } Ok(()) } (None, Some(formula)) => { if formula.plus.is_empty() && formula.minus.is_empty() { return Err(bad(".formula", "names_the_figures_it_adds_or_takes")); } for term in formula.plus.iter().chain(&formula.minus) { // A lowest or highest is no total to add: a formula adds counts and sums. let named = tool.figures.iter().find(|other| &other.read == term); if !named.and_then(|other| other.summary.as_ref()).is_some_and(|summary| !extreme(summary)) { return Err(bad(".formula", "names_counts_or_sums_of_this_tool")); } } Ok(()) } (None, None) => unreachable!("a worked figure has a summary or a formula"), } } /// This table as a database of `kind` reads it: every link and view whose /// `when` names the other kind left out ([`DatabaseWhen`]). Only that: a /// list's links said as none (`[]`, every act hidden) stay said, and an /// absent list stays absent. pub fn for_database(&mut self, kind: DatabaseKind) { let stands = |when: &Option<DatabaseWhen>| when.is_none_or(|when| when.database == kind); if let Some(links) = &mut self.links { links.retain(|link| stands(&link.when)); } if let Some(views) = &mut self.views { views.retain(|view| stands(&view.when)); } } } impl ToolDefinition { /// The automations naming an action this build cannot run, by id: each /// is left out of the tool's read, and a write it would run on is refused /// ([`automations::parse`]); and the acts this build does not name. fn unrunnable(&self) -> Vec<String> { let mut unrunnable = automations::unrunnable(self); unrunnable.extend(self.acts.iter().filter(|act| !TOOL_ACTS.contains(&act.id.as_str())).map(|act| act.id.clone())); unrunnable } /// The acts this build runs, in the definition's order. pub fn runnable_acts(&self) -> impl Iterator<Item = &ToolAct> { self.acts.iter().filter(|act| TOOL_ACTS.contains(&act.id.as_str())) } } /// A DEFINITION REFUSAL'S WORDS ARE LINES (contract 3, lane T1): a piece of /// a refusal the save check says — what a slot needs, what it cannot sit /// beside, what a column must be, why a slot is wrong — is named in code by /// its key under `refusal.definition` and said here in the kit's words. A /// piece still written as words (a file not yet moved) is said as written. pub fn refusal_words(piece: &str) -> String { static WORDS: std::sync::OnceLock<crate::rules::shell_lines::LineSet> = std::sync::OnceLock::new(); WORDS .get_or_init(|| crate::rules::shell_lines::LineSet::shipped("refusal").expect("the kit ships the refusal set")) .say(&format!("definition.{piece}"), &[]) .unwrap_or_else(|| piece.to_string()) } /// A whole definition refusal, `refusal.definition.<piece>` with each /// `{name}` filled — the save check's sentence about a value it names. pub fn refusal_said(piece: &str, fills: &[(&str, String)]) -> String { let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); static WORDS: std::sync::OnceLock<crate::rules::shell_lines::LineSet> = std::sync::OnceLock::new(); WORDS .get_or_init(|| crate::rules::shell_lines::LineSet::shipped("refusal").expect("the kit ships the refusal set")) .say(&format!("definition.{piece}"), &fills) .unwrap_or_else(|| piece.to_string()) } /// Why a definition is refused. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum DefinitionError { #[error("place column {0:?} needs distinct readonly text companion columns for id, country and zone")] PlaceColumns(String), #[error("package table shape: {0}")] PackageShape(String), #[error("id {0:?} must be lowercase letters, digits and underscores, starting with a letter")] BadId(String), #[error("column key {0:?} must be lowercase letters, digits and underscores, starting with a letter")] BadColumnKey(String), #[error("column {0:?} is declared twice")] DuplicateColumn(String), #[error("a table with groups cannot name a column \"group\": that key narrows its list to one group")] GroupColumnBesideGroups, #[error("a table whose records are worked out (derived) keeps no groups: its engine makes and remakes those records")] GroupsOnDerived, #[error("groups kept in another table name one of the pairs the core writes them through (album and album_item)")] GroupsKeptIn, #[error("a shipped view names a face once per table, and a name")] ShippedView, #[error("{slot} names {column:?}, which is not a declared column")] UnknownColumn { slot: String, column: String }, #[error("{slot} names {column:?}, which seal.clear keeps in the clear; a blind column is a sealed one")] SealBlindClear { slot: String, column: String }, #[error("{0}")] Send(String), #[error("a sealed table cannot declare {0:?}: the sealer writes it")] SealReserved(String), #[error("seal.blind_bytes names {0:?}: it caps a seal.blind column by a number of bytes above 0")] SealBlindBytes(String), #[error("{slot} names {column:?}, a {found:?} column; it must be {}", refusal_words(.wanted))] WrongColumnType { slot: String, column: String, found: ColumnType, wanted: &'static str, }, #[error("horizon {0} must be a whole number of months, at least 1")] Horizon(i64), #[error("link column {0:?} has no link_to")] LinkWithoutTarget(String), #[error("column {0:?} has a link_to but is not a link")] TargetWithoutLink(String), #[error("choice column {0:?} has no choices")] ChoiceWithoutChoices(String), #[error("column {0:?} has choices but is not a choice")] ChoicesWithoutChoice(String), #[error("Only built-in tables can declare an engine or a derived view ({0}).")] EngineOnUserTable(String), #[error("a built-in table names the engine that keeps it")] BuiltinWithoutEngine, #[error("a table needs at least one column")] NoColumns, #[error("{slot} is a {kind:?} part. {why}.")] RemovedPart { slot: String, kind: &'static str, why: &'static str }, #[error("{0} must not be empty")] Empty(&'static str), #[error("page names column {0:?} twice")] DuplicatePageColumn(String), #[error("a tool needs at least one table, or a view over a table the database has")] NoTables, #[error("{slot} names {value:?}, which is not one of {column:?}'s choices")] UnknownChoice { slot: String, column: String, value: String, }, #[error("{slot} needs {}", refusal_words(.needs))] Requires { slot: String, needs: &'static str }, #[error("{slot} cannot sit beside {}", refusal_words(.other))] Conflict { slot: String, other: &'static str }, #[error("{slot} must be at least {least}")] TooSmall { slot: String, least: u32 }, #[error("{0} must not be empty")] EmptyAt(String), #[error("file extension {0:?} must be lowercase letters and digits, without its dot")] BadExtension(String), #[error("{slot} names {id:?}, which is not one of the definition's commands")] UnknownCommand { slot: String, id: String }, #[error("command {0:?} is declared twice")] DuplicateCommand(String), #[error("invalid automation: {0}")] InvalidAutomation(String), #[error("definition JSON does not parse: {0}")] Parse(String), #[error("columns.{column}.default is not a value of its own type: {why}")] BadDefault { column: String, why: String }, #[error("tile.summary[{at}]: {why}")] BadSummary { at: usize, why: String }, #[error("group.summary[{at}]: {why}")] BadGroupSummary { at: usize, why: String }, #[error("tile.current: {0}")] BadCurrent(String), #[error("tile.sparkline: {0}")] BadSparkline(String), #[error("tile.chart: {0}")] BadChart(String), #[error("{slot}: {why}")] BadWhere { slot: &'static str, why: String }, #[error("{slot} names {table:?}, which is not a table here")] UnknownTable { slot: String, table: String }, #[error("{table}.columns.{column}.computed reads itself, directly or through other computed columns")] ComputedCycle { table: String, column: String }, #[error("{slot}: {why}")] BadSlot { slot: String, why: String }, #[error("keys this build does not name: {}", .0.join(", "))] UnknownKeys(Vec<String>), /// Each line names the key, the value it said and its range /// (`theme::ThemeOutOfRange`). #[error("values outside their range: {}", .0.join("; "))] OutOfRange(Vec<String>), #[error("{file} carries no format_version; this build reads format_version {build}")] NoFormatVersion { file: String, build: u32 }, #[error("{file} is format_version {found}; this build reads format_version {build} and older")] NewerFormat { file: String, found: String, build: u32 }, } /// Lowercase letters, digits and underscores, starting with a letter. pub fn is_valid_id(id: &str) -> bool { let mut chars = id.chars(); matches!(chars.next(), Some(c) if c.is_ascii_lowercase()) && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') } impl Column { /// The column as a person reads it: its own name, else its key in words /// ("role_title" → "Role title"). Every sentence that reaches a person /// names a column by this, never by its key. pub fn label(&self) -> String { match &self.name { Some(name) if !name.trim().is_empty() => name.clone(), _ => key_as_words(&self.key), } } /// A choice of this column as a person reads it: the definition's own /// words for it, else the key in words ("needs_action" → "Needs action"). pub fn choice_label(&self, value: &str) -> String { self.own_choice_label(value).unwrap_or_else(|| key_as_words(value)) } /// The definition's own words for a choice ("ta" → "Tamil"), if it gives any. pub fn own_choice_label(&self, value: &str) -> Option<String> { self.labels .as_ref() .or(self.choice_names.as_ref()) .and_then(|labels| labels.get(value)) .cloned() } /// Whether a page draws this column for the record `data`: not hidden /// by the owner, and no `shown_when`, or its column holds one of its /// values as words (a non-empty text, or a number). The app's /// `Column.isShown(on:)`. pub fn shown_on(&self, data: &serde_json::Map<String, serde_json::Value>) -> bool { if self.hidden == Some(true) { return false; } let Some(shown_when) = &self.shown_when else { return true }; let held = match data.get(&shown_when.column) { Some(serde_json::Value::String(text)) if !text.is_empty() => text.clone(), Some(serde_json::Value::Number(number)) => match number.as_f64() { Some(whole) if whole.fract() == 0.0 => format!("{}", whole as i64), _ => number.to_string(), }, _ => return false, }; shown_when.values.contains(&held) } } /// A key in words, as a sentence: "role_title" → "Role title", /// "inProgress" → "In progress", "HTTP_status" → "HTTP status", "DONE" → /// "Done". Words split at `_`, `-`, `.`, white space and a lower-to-upper /// turn; the first word takes a capital, the rest are lower case, except an /// initialism (two or more capitals) in a key that is not all capitals. /// Empty when the key holds no word. pub fn key_as_words(key: &str) -> String { let mut words: Vec<String> = Vec::new(); let mut current = String::new(); let mut previous: Option<char> = None; for letter in key.chars() { if matches!(letter, '_' | '-' | '.') || letter.is_whitespace() { if !current.is_empty() { words.push(std::mem::take(&mut current)); } } else { if previous.is_some_and(char::is_lowercase) && letter.is_uppercase() && !current.is_empty() { words.push(std::mem::take(&mut current)); } current.push(letter); } previous = Some(letter); } if !current.is_empty() { words.push(current); } let letters: String = key.chars().filter(|letter| letter.is_alphabetic()).collect(); let shouted = !letters.is_empty() && letters == letters.to_uppercase(); words .iter() .enumerate() .map(|(index, word)| { let initialism = !shouted && word.chars().count() > 1 && *word == word.to_uppercase() && word.chars().any(char::is_alphabetic); if initialism { return word.clone(); } let lower = word.to_lowercase(); if index > 0 { return lower; } let mut letters = lower.chars(); letters.next().map(|first| first.to_uppercase().chain(letters).collect()).unwrap_or_default() }) .collect::<Vec<_>>() .join(" ") } impl TableDefinition { /// Whether `key` is a state column: one the table's slip names as its /// status, its caption's status, or its answers column. The kind picks a /// receipt's form — a state is said as the verb under the record's name /// ("Restored Dentist", "Accepted Dentist"), any other choice is said of /// the record ("Marked Ada Tamil") — by the definition and never by the /// look of a label, so a tool whose status labels are not verbs still /// gets one sane line and a tool author knows which form their labels /// fill. pub fn is_state_column(&self, key: &str) -> bool { let slip = &self.slip; slip.status.as_deref() == Some(key) || slip.caption.as_ref().and_then(|caption| caption.status.as_deref()) == Some(key) || slip.answers.as_ref().map(|answers| answers.column.as_str()) == Some(key) } /// A native binding is code this build carries at this table id. Seeding /// provenance grants no access to an engine, storage, or executable SQL. pub fn has_engine(&self) -> bool { // The binding is code: the engine compiled for this built-in table. self.engine.is_some() && cotton_store::schema::package_tables::compiled_engine(&self.id) == self.engine.as_deref() } /// Whether the table is drawn at all: it states a slip. One that states /// none (a storage-only table the object serves — an email's /// participants, a reaction, an OAuth code) is kept as rows and drawn /// nowhere; its definition still reads, and its storage is its columns'. pub fn has_face(&self) -> bool { !self.slip.is_absent() } /// Physical storage is part of every package. Imported definitions without /// an authored tables section derive it from their declared columns. pub fn physical_tables(&self) -> Result<Vec<cotton_store::schema::package_tables::PackageTable>, DefinitionError> { if let Some(tables) = &self.tables { if self.has_engine() || !tables.is_empty() { return Ok(tables.clone()); } } if self.has_engine() { return Ok(Vec::new()); } let definition = serde_json::to_value(self).map_err(|error| DefinitionError::Parse(error.to_string()))?; cotton_store::schema::package_tables::from_definition(&definition) .map_err(|error| DefinitionError::PackageShape(error.to_string())) } pub fn from_json(json: &str) -> Result<TableDefinition, DefinitionError> { // Preserve a complete row exactly, including duplicate-key refusals. const FACE: [&str; 4] = ["title", "slip", "tile", "page"]; let shipped = |id: &str| BUILTIN_DEFINITION_FILES.iter().find(|(shipped, _)| *shipped == id); if let Ok(definition) = serde_json::from_str::<TableDefinition>(json) { // A built-in row that leaves part of its face out takes the // shipped part below, as it took any field the decoder required. let whole = || serde_json::from_str::<serde_json::Value>(json) .is_ok_and(|row| FACE.iter().all(|key| row.get(key).is_some())); if !definition.builtin || shipped(&definition.id).is_none() || whole() { return Ok(definition); } } let mut value = serde_json::from_str::<tolerant::Whole>(json) .map_err(|error| DefinitionError::Parse(error.to_string()))?.0; // Only a known builtin has a shipped counterpart. A made table must // never acquire a builtin's engine or storage by sharing its id. let defaults = if value["builtin"].as_bool() == Some(true) { value["id"].as_str().and_then(shipped) .map(|(_, raw)| serde_json::from_str::<serde_json::Value>(raw) .expect("a shipped definition is JSON")) } else { None }; // A reduced built-in row takes each part of its face it leaves out // from the shipped one. if let (Some(defaults), Some(row)) = (defaults.as_ref(), value.as_object_mut()) { for key in FACE { if let (false, Some(shipped)) = (row.contains_key(key), defaults.get(key)) { row.insert(key.to_string(), shipped.clone()); } } } loop { let mut track = serde_path_to_error::Track::new(); // Probe the derived decoder directly: the tolerant reader's whole- // tree pass otherwise hides the nested missing-field path. let (read, _, _) = tolerant::reading_acts(|| TableDefinition::deserialize( serde_path_to_error::Deserializer::new(&value, &mut track), )); match read { Ok(_) => return serde_json::from_value(value) .map_err(|error| DefinitionError::Parse(error.to_string())), Err(error) => { // A valid reduced row is already complete. Optional shipped // layouts may reference columns it does not declare; only // the precise field the decoder requires can be supplied. let message = error.to_string(); let missing = message.strip_prefix("missing field `") .and_then(|rest| rest.strip_suffix('`')); let mut path = Vec::new(); let error_path = track.path(); for segment in &error_path { match segment { serde_path_to_error::Segment::Map { key } => path.push(key.as_str()), // Arrays are authored collections, not corresponding // shipped objects: their indices confer no identity. _ => return Err(DefinitionError::Parse(error.to_string())), } } let Some((defaults, missing)) = defaults.as_ref().zip(missing) else { return Err(DefinitionError::Parse(error.to_string())); }; let root = path.first().copied().unwrap_or(missing); if !writable_definition_key(root) || root == "columns" { return Err(DefinitionError::Parse(error.to_string())); } let mut source = defaults; let mut target = &mut value; for key in path { let Some(next) = source.get(key) else { return Err(DefinitionError::Parse(error.to_string())); }; source = next; target = target.get_mut(key).expect("the error path exists in the row"); } let Some(default) = source.get(missing) else { return Err(DefinitionError::Parse(error.to_string())); }; if !target.is_object() || target.get(missing).is_some() { return Err(DefinitionError::Parse(error.to_string())); } let patch = serde_json::json!({missing: default}); fill_missing_keys(target, &patch); // A photo identity boundary can deliberately refuse a fill. if target.get(missing).is_none() { return Err(DefinitionError::Parse(error.to_string())); } } } } } /// An AUTHORED definition (a package's table, a built-in file): decoded, /// and refused for any key this build does not name ([`tolerant`]). pub fn authored(raw: &serde_json::Value) -> Result<TableDefinition, DefinitionError> { format::check_authored(&format!("{}.json", raw["id"].as_str().unwrap_or("definition")), raw)?; let definition: TableDefinition = serde_json::from_value(raw.clone()) .map_err(|error| DefinitionError::Parse(error.to_string()))?; tolerant::refuse_unknown(raw, &definition, &definition.unknown)?; Ok(definition) } /// The canonical stored form — the struct's own field order. pub fn to_json(&self) -> String { serde_json::to_string(self).expect("a TableDefinition always serialises") } pub fn column(&self, key: &str) -> Option<&Column> { self.columns.iter().find(|column| column.key == key) } /// The column that says when a record happened: `date`, or else the date /// column its `sort` orders by — a picture with no `date` was still taken /// at `taken_at`. pub fn when_column(&self) -> Option<&str> { self.date.as_deref().or_else(|| { let sort = self.sort.as_ref()?; let column = self.column(&sort.column)?; (column.column_type == ColumnType::Date).then_some(sort.column.as_str()) }) } /// Every key the definition names must be a declared column, and every /// column must carry what its type needs. pub fn validate(&self) -> Result<(), DefinitionError> { use visibility::Visibility; if let Some(card) = &self.card { card.validate(self, "card")?; } if let Some(key) = &self.row_key { if self.engine.is_some() || self.store_table().is_some() || !self.column(key).is_some_and(|column| column.column_type == ColumnType::Text && column.required == Some(true) && column.readonly != Some(true) && column.computed.is_none()) { return Err(DefinitionError::BadSlot { slot: "row_key".into(), why: refusal_words("row_key_writable_text") }); } } // A face choice names its table by its key and its face in `face`. if self.face_choices == Some(true) && (self.row_key.is_none() || !self.column("face").is_some_and(|column| column.column_type == ColumnType::Text)) { return Err(DefinitionError::BadSlot { slot: "face_choices".into(), why: refusal_words("face_choices_keyed") }); } let visibility = visibility::parse(self.visibility.as_deref()) .map_err(DefinitionError::PackageShape)?; if self.id == "person" && visibility == Visibility::Public { return Err(DefinitionError::PackageShape(refusal_words("people_cannot_be_a_public_customer_directory"))); } if let Visibility::Mine(column) = visibility { let person_id = self.id == "person" && column == "id"; if !person_id && !self.column(&column).is_some_and(|c| c.column_type == ColumnType::Link && c.link_to.is_some()) { return Err(DefinitionError::PackageShape(refusal_words("mine_visibility_must_name_a_link_column"))); } } if let Some(producer) = &self.producer { if producer.token_id.is_empty() || producer.token_id.trim() != producer.token_id || producer.token_id.chars().any(char::is_control) { return Err(DefinitionError::EmptyAt(refusal_words("producer_token_id_must_name_an_authenticated"))); } } if let Some(prices)=&self.prices { for (model,rates) in prices { if model.trim().is_empty() || model.chars().any(char::is_control) || [&rates.input,&rates.output,&rates.cache_read,&rates.cache_write].iter().any(|rate|rate.as_f64().is_none_or(|rate|!rate.is_finite()||rate<0.0)) { return Err(DefinitionError::EmptyAt(refusal_words("prices_must_name_a_model_with_finite"))); } } } // A built-in's storage is the store's code, never a definition's: a // table this build keeps under its engine is made by this build's // DDL, and whatever storage its definition carries makes no table and // runs nowhere here (`package_shape::declared` takes none), so it is // not read. The object and a phone are builds apart: schema 142 // changed four tables' storage, the object still served 141's, and a // phone a rise ahead refused Documents, Calendar, Notes and Money // whole over storage it would have thrown away (walk, 27 Oct 2026). // Every other table's storage is data and holds no SQL. if let Some(tables) = self.tables.as_ref().filter(|_| !self.has_engine()) { use cotton_store::schema::package_tables::{generate, validate_ownership}; generate(tables, false).map_err(|error| DefinitionError::PackageShape(error.to_string()))?; validate_ownership(tables, &std::collections::BTreeSet::new()) .map_err(|error| DefinitionError::PackageShape(error.to_string()))?; } if !is_valid_id(&self.id) { return Err(DefinitionError::BadId(self.id.clone())); } for retired in self.retired.iter().flatten() { if self.has_engine() || self.column(&retired.key).is_some() || !is_valid_id(&retired.key) { return Err(DefinitionError::PackageShape(refusal_said( "retired_column_must_be_a_made_table_s", &[("column", format!("{:?}", retired.key))], ))); } } // A view's own rules come first: what it reads, before whose engine. self.validate_source()?; if self.engine.is_some() && !self.has_engine() { return Err(DefinitionError::EngineOnUserTable(self.engine.clone().unwrap())); } if let Some(live) = &self.live_read { if !LIVE_READ_METHODS.contains(&live.method.as_str()) { return Err(DefinitionError::BadSlot { slot: "live_read.method".into(), why: refusal_words("is_one_native_read_this_build_permits"), }); } if live.bindings.is_empty() || live.fields.is_empty() { return Err(DefinitionError::Requires { slot: "live_read".into(), needs: "bindings_and_fields", }); } for (name, value) in live.bindings.iter() { // Native method arguments are camelCase (`deviceId`), unlike // definition keys, which are snake_case. let mut chars = name.chars(); let valid_argument = matches!(chars.next(), Some(ch) if ch.is_ascii_lowercase()) && chars.all(|ch| ch.is_ascii_alphanumeric()); if !valid_argument || (value != "$id" && self.column(value).is_none()) { return Err(DefinitionError::BadSlot { slot: format!("live_read.bindings.{name}"), why: refusal_words("binds_an_argument_to_id_or_a"), }); } } let mut named = std::collections::BTreeSet::new(); for field in &live.fields { let column = self.named("live_read.fields", field, None)?; if column.live != Some(true) || column.readonly != Some(true) || !named.insert(field) { return Err(DefinitionError::Requires { slot: format!("live_read.fields.{field}"), needs: "one_readonly_live_column_once", }); } } } else if let Some(column) = self.columns.iter().find(|column| column.live == Some(true)) { return Err(DefinitionError::Requires { slot: format!("columns.{}.live", column.key), needs: "live_read", }); } if self.derived == Some(true) && !self.has_engine() { return Err(DefinitionError::Requires { slot: "derived".into(), needs: "a_built_in_table", }); } for key in self.voice_words.iter().flatten() { let column = self.named( "voice_words", key, Some((&[ColumnType::Text, ColumnType::Place], "plain text")), )?; if column.secret == Some(true) || column.computed.is_some() { return Err(DefinitionError::Requires { slot: "voice_words".into(), needs: "nonsecret_stored_text", }); } } if self.name.trim().is_empty() { return Err(DefinitionError::Empty("name")); } if self.plural.trim().is_empty() { return Err(DefinitionError::Empty("plural")); } if self.columns.is_empty() { return Err(DefinitionError::NoColumns); } if let Some(groups) = &self.groups { // The core gathers no worked-out record into a group (groups.rs // `takes_groups`), so a stack there would be groups nobody can // make, and the fan's ring would fail reading them. if self.derived == Some(true) { return Err(DefinitionError::GroupsOnDerived); } if let Some(kept) = &groups.kept_in { // A pair the core has no writes for would be groups nobody // can make. if !GROUPS_KEPT_IN.iter().any(|(table, items)| *table == kept.table && *items == kept.items) { return Err(DefinitionError::GroupsKeptIn); } } } let mut faces = std::collections::BTreeSet::new(); for view in self.views.iter().flatten() { if view.name.trim().is_empty() || !faces.insert(view.face) { return Err(DefinitionError::ShippedView); } // A chart view is this database's own, one per table, and names // what it draws the way a chart tile does. match (&view.chart, view.face) { (None, ViewFace::Chart) => return Err(DefinitionError::BadChart(refusal_words("a_chart_view_needs_its_chart"))), (Some(_), face) if face != ViewFace::Chart => { return Err(DefinitionError::BadChart(refusal_said("a_view_s_chart_is_drawn_only", &[("face", format!("{:?}", face))]))) } (Some(chart), _) => self.validate_chart(chart).map_err(DefinitionError::BadChart)?, (None, _) => {} } } let mut seen = std::collections::BTreeSet::new(); for column in &self.columns { if !is_valid_id(&column.key) { return Err(DefinitionError::BadColumnKey(column.key.clone())); } if !seen.insert(column.key.as_str()) { return Err(DefinitionError::DuplicateColumn(column.key.clone())); } // `where: { group }` narrows a grouped table's list to one group, // so the key cannot also be one of its columns. if self.groups.is_some() && column.key == "group" { return Err(DefinitionError::GroupColumnBesideGroups); } match (column.column_type, &column.link_to) { (ColumnType::Link, None) if column.link_by.is_some() => {} (ColumnType::Link, None) => { return Err(DefinitionError::LinkWithoutTarget(column.key.clone())) } (ColumnType::Link, Some(target)) if !is_valid_id(target) => { return Err(DefinitionError::BadId(target.clone())) } (ColumnType::Link, Some(_)) | (_, None) => {} (_, Some(_)) => return Err(DefinitionError::TargetWithoutLink(column.key.clone())), } match (column.column_type, &column.choices) { // Its choices are the record's own, read from `choices_from`. (ColumnType::Choice, None) if column.choices_from.is_some() => {} (ColumnType::Choice, None) => { return Err(DefinitionError::ChoiceWithoutChoices(column.key.clone())) } (ColumnType::Choice, Some(choices)) if choices.is_empty() => { return Err(DefinitionError::ChoiceWithoutChoices(column.key.clone())) } (ColumnType::Choice, Some(_)) | (_, None) => {} (_, Some(_)) => { return Err(DefinitionError::ChoicesWithoutChoice(column.key.clone())) } } } if !self.has_face() { // Kept as rows and drawn nowhere: its columns, read above, are // all it says; how a record is named, dated, filed under a // project, ordered, drawn or edited asks nothing of it. return Ok(()); } self.named("title", &self.title, None)?; if let Some(date) = &self.date { self.named("date", date, Some((&[ColumnType::Date], "a date")))?; } if let Some(project) = &self.project { let column = self.named("project", project, Some((&[ColumnType::Link], "a link")))?; if column.link_to.as_deref() != Some("project") { return Err(DefinitionError::WrongColumnType { slot: "project".into(), column: project.clone(), found: column.column_type, wanted: "a_link_to_project", }); } } if let Some(order) = &self.order { self.named("order", order, Some((&[ColumnType::Number], "a number")))?; } self.named("slip.title", &self.slip.title, None)?; if matches!(&self.slip.subtitle, Some(SlipSubtitle::Several(keys)) if keys.is_empty()) { return Err(DefinitionError::Empty("slip.subtitle")); } for key in self.slip.subtitles() { self.named("slip.subtitle", key, None)?; } if let Some(key) = &self.slip.trailing { self.named("slip.trailing", key, None)?; } if let Some(photo) = &self.slip.photo { self.named("slip.photo", photo, Some((&[ColumnType::Photo], "a photo")))?; } if let Some(name) = &self.slip.photo_name { self.named("slip.photo_name", name, Some((&[ColumnType::Text], "text")))?; } if let Some(player) = &self.slip.player { self.named("slip.player", player, None)?; } if let Some(picture) = &self.slip.trailing_picture { self.picture("slip.trailing_picture", picture)?; } if let Some(toggle) = &self.slip.toggle { self.named( "slip.toggle", toggle, Some(( &[ColumnType::Bool, ColumnType::Choice], "a_bool_or_a_choice", )), )?; } let mut on_page = std::collections::BTreeSet::new(); let mut mains = 0; for (index, section) in self.page.iter().enumerate() { let slot = format!("page[{index}]"); if section.above.is_some() { return Err(DefinitionError::Requires { slot: format!("{slot}.above"), needs: "a_lists_entry_a_page_section_is", }); } self.validate_section(&slot, section)?; self.validate_role(&slot, section)?; if section.role == Some(SectionRole::Main) { mains += 1; if mains > 1 { return Err(DefinitionError::Conflict { slot: format!("{slot}.role"), other: "another_main_section", }); } } for key in section.columns() { if !on_page.insert(key.as_str()) { return Err(DefinitionError::DuplicatePageColumn(key.clone())); } } } for column in &self.columns { self.validate_column_keys(column)?; } self.validate_slip_keys()?; self.validate_slip_by()?; self.validate_list_keys()?; self.validate_round_two_keys()?; self.validate_round_three_keys()?; self.validate_tile_summary()?; self.validate_tile_current()?; self.validate_tile_sparkline()?; self.validate_tile_chart()?; Ok(()) } /// `tile.chart` is there exactly when the face is a chart, and reads this /// table: `x` a date column, `y` an amount or number column or `count`, /// 1 to 366 periods, a `where` over its declared columns. fn validate_tile_chart(&self) -> Result<(), DefinitionError> { let bad = |why: String| Err(DefinitionError::BadChart(why)); let chart = match (&self.tile.chart, self.tile.face) { (None, TileFace::Chart) => return bad(refusal_words("the_chart_face_needs_tile_chart")), (None, _) => return Ok(()), (Some(_), face) if face != TileFace::Chart => { return bad(refusal_said("tile_chart_is_drawn_only_by_the", &[("face", format!("{:?}", face))])) } (Some(chart), _) => chart, }; self.validate_chart(chart).map_err(DefinitionError::BadChart) } /// A chart's columns, window and `where` against this table. pub fn validate_chart(&self, chart: &ChartFace) -> Result<(), String> { if let Some(hour) = &chart.hour { if chart.by != ChartPeriod::Hour || self.column(hour).map(|c| c.column_type) != Some(ColumnType::Number) { return Err(refusal_words("hour_names_a_number_column_on_an")); } } if let Some(timezone) = &chart.timezone { if timezone.parse::<chrono_tz::Tz>().is_err() { return Err(refusal_said("timezone_is_not_a_timezone", &[("timezone", format!("{:?}", timezone))])); } } match self.column(&chart.x).map(|column| column.column_type) { Some(ColumnType::Date) => {} Some(_) => return Err(refusal_said("x_is_not_a_date_column", &[("column", format!("{:?}", chart.x))])), None => return Err(refusal_said("x_is_not_a_column_of_this", &[("column", format!("{:?}", chart.x))])), } if chart.counts() && chart.sign.is_some() { return Err(refusal_words("sign_keeps_the_values_of_a_sum")); } if !chart.counts() { match self.column(&chart.y).map(|column| column.column_type) { Some(ColumnType::Number | ColumnType::Amount) => {} Some(_) => return Err(refusal_said("y_is_not_an_amount_or_number", &[("column", format!("{:?}", chart.y))])), None => return Err(refusal_said("y_is_not_a_column_of_this", &[("column", format!("{:?}", chart.y))])), } } if !(1..=ChartFace::MAX_PERIODS).contains(&chart.periods()) { return Err(refusal_said("periods_is_1_to_not", &[("most", ChartFace::MAX_PERIODS.to_string()), ("periods", chart.periods().to_string())])); } if let Some(filter) = &chart.where_ { let filter = serde_json::to_value(filter).map_err(|why| why.to_string())?; crate::records::parse_where(self, Some(&filter)).map_err(|why| format!("where: {why}"))?; } Ok(()) } /// `tile.sparkline` is there exactly when the face is a sparkline, and /// links no record: a tile is the whole table. fn validate_tile_sparkline(&self) -> Result<(), DefinitionError> { let bad = |why: String| Err(DefinitionError::BadSparkline(why)); let line = match (&self.tile.sparkline, self.tile.face) { (None, TileFace::Sparkline) => return bad(refusal_words("the_sparkline_face_needs_tile_sparkline")), (None, _) => return Ok(()), (Some(_), face) if face != TileFace::Sparkline => { return bad(refusal_said("tile_sparkline_is_drawn_only_by_the", &[("face", format!("{:?}", face))])) } (Some(line), _) => line, }; if line.link.is_some() { return bad(refusal_words("a_tile_s_line_links_no_record")); } self.validate_sparkline(line).map_err(DefinitionError::BadSparkline) } /// A sparkline names a table and its columns by id and keeps a window of /// 1 to 366 days. Over this table its columns are checked here: `value` a /// number or amount, `at` a date, `link` a link. Another table's are /// checked where the line is read against that table's definition /// (`records::sparkline`), as a list section's linked table is. fn validate_sparkline(&self, line: &Sparkline) -> Result<(), String> { let bad = |why: String| Err(why); for (slot, id) in [("table", &line.table), ("value", &line.value), ("at", &line.at)] .into_iter() .chain(line.link.as_ref().map(|link| ("link", link))) { if !is_valid_id(id) { return bad(refusal_said("is_not_an_id", &[("slot", slot.to_string()), ("id", format!("{:?}", id))])); } } if !(1..=Sparkline::MAX_DAYS).contains(&line.days()) { return bad(refusal_said("days_is_1_to_not", &[("most", Sparkline::MAX_DAYS.to_string()), ("days", line.days().to_string())])); } if line.table == self.id { match self.column(&line.value).map(|column| column.column_type) { Some(ColumnType::Number | ColumnType::Amount) => {} Some(_) => return bad(refusal_said("is_not_a_number_or_amount_column", &[("column", format!("{:?}", line.value))])), None => return bad(refusal_said("is_not_a_column_of_this_table", &[("column", format!("{:?}", line.value))])), } match self.column(&line.at).map(|column| column.column_type) { Some(ColumnType::Date) => {} Some(_) => return bad(refusal_said("is_not_a_date_column", &[("column", format!("{:?}", line.at))])), None => return bad(refusal_said("is_not_a_column_of_this_table", &[("column", format!("{:?}", line.at))])), } if let Some(link) = &line.link { match self.column(link).map(|column| column.column_type) { Some(ColumnType::Link) => {} Some(_) => return bad(refusal_said("is_not_a_link_column", &[("link", format!("{:?}", link))])), None => return bad(refusal_said("is_not_a_column_of_this_table_2", &[("link", format!("{:?}", link))])), } } } Ok(()) } /// `tile.current` reads a date column of this table. fn validate_tile_current(&self) -> Result<(), DefinitionError> { let Some(current) = &self.tile.current else { return Ok(()) }; match self.column(¤t.column) { None => Err(DefinitionError::BadCurrent(refusal_said("is_not_a_column_of_this_table", &[("column", format!("{:?}", current.column))]))), Some(column) if column.column_type != ColumnType::Date => { Err(DefinitionError::BadCurrent(refusal_said("is_not_a_date_column", &[("column", format!("{:?}", current.column))]))) } Some(_) => Ok(()), } } /// `tile.summary`: a count names no column; a sum a number or amount /// column; min and max a date, number or amount column; a `where` reads /// against this table's columns the way `list_records` reads it. /// A view (`source`, ruling 03:55 17 Oct 2026) names another table — /// shipped or made — and keeps its rows by a where over its columns; it /// holds no store and orders its rows itself. Its computed columns are /// definitions the one evaluator works out, so it names no engine (ruling /// 10:52 IST): an engine is shipped code, which a view never is. fn validate_source(&self) -> Result<(), DefinitionError> { if let Some(source) = &self.source { let bad = |why: &str| DefinitionError::BadSlot { slot: "source".into(), why: refusal_words(why) }; if !is_valid_id(&source.table) || source.table == self.id { return Err(bad("names_another_table_by_its_id")); } if source.where_.iter().flat_map(OrderedMap::keys).any(|key| !is_valid_id(key)) { return Err(bad("keeps_rows_by_a_where_over_the")); } // A view holds no records of its own; it reads its source's, the // way the source's own reader answers them. // Package extraction says every shipped file's tables, a view's // as none. if self.tables.as_ref().is_some_and(|tables| !tables.is_empty()) { return Err(bad("holds_no_store_of_its_own")); } if self.engine.is_some() { return Err(bad("names_no_engine_its_columns_are_definitions")); } if self.sort.is_none() { return Err(bad("orders_its_rows_by_a_sort_of")); } } Ok(()) } fn validate_tile_summary(&self) -> Result<(), DefinitionError> { self.validate_summaries(&self.tile.summary, |at, why| DefinitionError::BadSummary { at, why })?; if let Some(group) = &self.group { self.validate_summaries(&group.summary, |at, why| DefinitionError::BadGroupSummary { at, why })?; // A head's line says what its figure is: "₹1,200 in". if let Some(at) = group.summary.iter().position(|summary| summary.label.as_deref().is_none_or(|label| label.trim().is_empty())) { return Err(DefinitionError::BadGroupSummary { at, why: refusal_words("says_what_its_figure_is_by_a") }); } } Ok(()) } fn validate_summaries( &self, summaries: &[TileSummary], refused: impl Fn(usize, String) -> DefinitionError, ) -> Result<(), DefinitionError> { use ColumnType::*; for (at, summary) in summaries.iter().enumerate() { let bad = |why: String| refused(at, why); match (summary.op, summary.column.as_deref()) { (SummaryOp::Count, Some(_)) => return Err(bad(refusal_words("a_count_names_no_column"))), (SummaryOp::Count, None) => {} (op, None) => return Err(bad(refusal_said("needs_a_column", &[("op", format!("{:?}", op))]).to_lowercase())), (op, Some(name)) => { let Some(column) = self.column(name) else { return Err(bad(refusal_said("is_not_a_column_of_this_table_3", &[("key", format!("{:?}", name))]))); }; let wanted: &[ColumnType] = match op { SummaryOp::Sum => &[Number, Amount], _ => &[Date, Number, Amount], }; if !wanted.contains(&column.column_type) { let takes = if op == SummaryOp::Sum { "a_number_or_amount_column" } else { "a_date_number_or_amount_column" }; return Err(bad(refusal_said( "is_a_column_takes", &[ ("key", format!("{name:?}")), ("kind", format!("{:?}", column.column_type)), ("op", format!("{op:?}").to_lowercase()), ("takes", refusal_words(takes)), ], ))); } } } if let Some(filter) = &summary.where_ { let filter = serde_json::to_value(filter).map_err(|why| bad(why.to_string()))?; crate::records::parse_where(self, Some(&filter)).map_err(|why| bad(why.to_string()))?; } } Ok(()) } /// The optional keys a column carries belong to the types they read. fn validate_column_keys(&self, column: &Column) -> Result<(), DefinitionError> { if column.column_type == ColumnType::Place { if let Some(place) = &column.place { let texts = [Some(&place.id), Some(&place.country), Some(&place.zone), place.version.as_ref()]; let numbers = [place.lat.as_ref(), place.lng.as_ref()]; let named: Vec<&String> = texts.iter().chain(numbers.iter()).flatten().copied().collect(); let distinct: std::collections::BTreeSet<_> = named.iter().collect(); if distinct.len() != named.len() || named.contains(&&column.key) { return Err(DefinitionError::PlaceColumns(column.key.clone())); } let siblings = texts.into_iter().flatten().map(|key| (key, ColumnType::Text, "text")) .chain(numbers.into_iter().flatten().map(|key| (key, ColumnType::Number, "number"))); for (key, kind, wanted) in siblings { let sibling = self.named("place", key, Some((&[kind], wanted)))?; if sibling.readonly != Some(true) { return Err(DefinitionError::PlaceColumns(column.key.clone())); } } } else { return Err(DefinitionError::PlaceColumns(column.key.clone())); } } let key = column.key.as_str(); let slot = |field: &str| format!("columns.{key}.{field}"); if column.place.is_some() && column.column_type != ColumnType::Place { return Err(DefinitionError::PlaceColumns(column.key.clone())); } let only_on = |field: &str, allowed: &[ColumnType], wanted: &'static str| { if allowed.contains(&column.column_type) { Ok(()) } else { Err(DefinitionError::WrongColumnType { slot: slot(field), column: key.into(), found: column.column_type, wanted, }) } }; let choice = (&[ColumnType::Choice][..], "a choice"); let said = |text: &str, field: &str| { if text.trim().is_empty() { Err(DefinitionError::EmptyAt(slot(field))) } else { Ok(()) } }; if let Some(placeholder) = &column.placeholder { said(placeholder, "placeholder")?; } if let Some(past_name) = &column.past_name { only_on("past_name", &[ColumnType::Date], "a date")?; said(past_name, "past_name")?; } if let Some(pair) = &column.pair { only_on("pair", &[ColumnType::Number], "a number")?; if pair == key { return Err(DefinitionError::Conflict { slot: slot("pair"), other: "its_own_column", }); } self.named( &slot("pair"), pair, Some((&[ColumnType::Number], "a number")), )?; } if let Some(units) = &column.units { // A date's units are the template its `ago` or `countdown` is said in. if matches!(column.format, Some(ColumnFormat::Ago | ColumnFormat::Countdown)) { only_on("units", &[ColumnType::Date], "a date")?; } else { only_on("units", &[ColumnType::Number, ColumnType::Bytes], "a_number_or_bytes")?; } said(&units.one, "units.one")?; said(&units.other, "units.other")?; for (field, template) in [("units.one", Some(&units.one)), ("units.other", Some(&units.other)), ("units.zero", units.zero.as_ref())] { let Some(template) = template else { continue; }; let fields = unit_fields(template).ok_or_else(|| DefinitionError::BadSlot { slot: slot(field), why: refusal_words("uses_n_or_a_declared_text_or") })?; for key in fields.into_iter().filter(|key| *key != "n") { // A number names its count plainly: "3 of {databases_to_move} databases". let source = self.named(&slot(field), key, Some((&[ColumnType::Text, ColumnType::Number], "a_text_or_number")))?; if source.secret == Some(true) { return Err(DefinitionError::BadSlot { slot: slot(field), why: refusal_words("never_reads_a_secret_column") }); } } } } if let Some(format) = column.format { let (allowed, wanted) = format.types(); only_on("format", allowed, wanted)?; } if let Some(stamps) = &column.stamps { only_on("stamps", choice.0, choice.1)?; among_choices(&slot("stamps"), column, stamps.keys())?; for (_, stamp) in stamps.iter() { said_at(stamp.words(), slot("stamps"))?; } } if let Some(moves) = &column.moves { only_on("moves", choice.0, choice.1)?; among_choices(&slot("moves"), column, moves.keys())?; for (_, to) in moves.iter() { among_choices(&slot("moves"), column, to.iter())?; } } if let Some(hints) = &column.hints { only_on("hints", choice.0, choice.1)?; among_choices(&slot("hints"), column, hints.keys())?; } if let Some(objects) = &column.objects { only_on("objects", choice.0, choice.1)?; among_choices(&slot("objects"), column, objects.keys())?; for (_, object) in objects.iter() { said_at(object, slot("objects"))?; } } if column.multiple.is_some() { only_on( "multiple", &[ColumnType::Choice, ColumnType::Text, ColumnType::Link], "a_choice_a_text_or_a_link", )?; } if column.month.is_some() { only_on("month", &[ColumnType::Date], "a date")?; } if column.week.is_some() { only_on("week", choice.0, choice.1)?; if column.week == Some(true) && column.multiple != Some(true) { return Err(DefinitionError::Requires { slot: slot("week"), needs: "multiple_true", }); } } if let Some(editable_when) = &column.editable_when { self.named(&slot("editable_when.column"), &editable_when.column, None)?; if editable_when.values.is_empty() { return Err(DefinitionError::EmptyAt(slot("editable_when.values"))); } if column.readonly != Some(true) { return Err(DefinitionError::Requires { slot: slot("editable_when"), needs: "readonly_true", }); } } if let Some(shown_when) = &column.shown_when { self.named(&slot("shown_when.column"), &shown_when.column, None)?; if shown_when.values.is_empty() { return Err(DefinitionError::EmptyAt(slot("shown_when.values"))); } } if column.secret.is_some() { only_on("secret", &[ColumnType::Text], "a text")?; } if let Some(tones) = &column.tones { only_on("tones", &[ColumnType::Choice], "a choice")?; among_choices(&slot("tones"), column, tones.keys())?; } if let Some(families) = &column.families { only_on("families", &[ColumnType::Choice], "a choice")?; among_choices(&slot("families"), column, families.keys())?; among_choices(&slot("families"), column, families.iter().map(|(_, family)| family))?; // One level: a family is no member, and no choice is its own family. if families.iter().any(|(member, family)| member == family || families.get(family).is_some()) { return Err(DefinitionError::Conflict { slot: slot("families"), other: "a_family_that_is_a_member", }); } } if let Some(examples) = &column.examples { only_on("examples", &[ColumnType::Choice], "a choice")?; among_choices(&slot("examples"), column, examples.keys())?; for (_, phrases) in examples.iter() { if phrases.is_empty() { return Err(DefinitionError::EmptyAt(slot("examples"))); } for phrase in phrases { said_at(phrase, slot("examples"))?; } } } if let Some(says) = &column.says { only_on("says", &[ColumnType::Choice], "a choice")?; if says.is_empty() { return Err(DefinitionError::EmptyAt(slot("says"))); } for (i, said) in says.iter().enumerate() { self.named(&slot(&format!("says[{i}]")), said, None)?; } } if column.markdown.is_some() { only_on("markdown", &[ColumnType::Longtext], "a long text")?; } if let Some(default) = &column.default { only_on( "default", &[ ColumnType::Text, ColumnType::Longtext, ColumnType::Date, ColumnType::Time, ColumnType::Number, ColumnType::Bytes, ColumnType::Amount, ColumnType::Choice, ColumnType::Bool, ColumnType::Url, ], "a_value_column_not_a_link_photo", )?; if default.is_null() { return Err(DefinitionError::EmptyAt(slot("default"))); } crate::records::check_value(column, default).map_err(|why| { DefinitionError::BadDefault { column: key.into(), why: why.to_string(), } })?; } if let Some(reveal) = &column.reveal { if column.secret != Some(true) { return Err(DefinitionError::Requires { slot: slot("reveal"), needs: "secret_true", }); } if !(1..=86400).contains(&reveal.expires) { return Err(DefinitionError::Requires { slot: slot("reveal.expires"), needs: "an integer from 1 through 86400", }); } self.named( &slot("reveal"), "reveal_count", Some((&[ColumnType::Number], "a number")), )?; self.named( &slot("reveal"), "last_revealed", Some((&[ColumnType::Date], "a date")), )?; } if let Some(red_when) = &column.red_when { if red_when.is_empty() { return Err(DefinitionError::EmptyAt(slot("red_when"))); } for value in red_when { said(value, "red_when")?; } } if column.currency.is_some() { only_on("currency", &[ColumnType::Amount], "an amount")?; } if column.signed.is_some() { only_on("signed", &[ColumnType::Amount], "an amount")?; } if let Some(currency) = &column.currency { let source = self.named( &slot("currency"), if currency == "account" { "account_id" } else { currency }, Some(( &[ColumnType::Text, ColumnType::Link], "a_text_or_a_money_account_link", )), )?; if source.column_type == ColumnType::Link && source.link_to.as_deref() != Some("money_account") { return Err(DefinitionError::Requires { slot: slot("currency"), needs: "a_link_to_money_account", }); } } if let Some(link_by) = &column.link_by { only_on("link_by", &[ColumnType::Link], "a link")?; if column.link_to.is_some() { return Err(DefinitionError::Conflict { slot: slot("link_by"), other: "link_to", }); } if column.readonly != Some(true) { return Err(DefinitionError::Requires { slot: slot("link_by"), needs: "readonly_true", }); } let source = self.named( &slot("link_by.column"), &link_by.column, Some((&[ColumnType::Choice], "a choice")), )?; if link_by.tables.0.is_empty() { return Err(DefinitionError::EmptyAt(slot("link_by.tables"))); } among_choices(&slot("link_by.tables"), source, link_by.tables.keys())?; for (_, table) in link_by.tables.iter() { if !is_valid_id(table) { return Err(DefinitionError::BadId(table.clone())); } } } self.validate_computed(column)?; self.validate_contributes(column)?; self.validate_round_two_column_keys(column) } /// The column keys the second round of Swift faces drew (1 Oct 2026). fn validate_round_two_column_keys(&self, column: &Column) -> Result<(), DefinitionError> { use ColumnType::*; let key = column.key.as_str(); let slot = |field: &str| format!("columns.{key}.{field}"); let only_on = |field: &str, allowed: &[ColumnType], wanted: &'static str| { if allowed.contains(&column.column_type) { Ok(()) } else { Err(DefinitionError::WrongColumnType { slot: slot(field), column: key.into(), found: column.column_type, wanted, }) } }; let picture = (&[Photo, File][..], "a_photo_or_a_file"); if let Some(presentation) = column.presentation { let (allowed, wanted) = presentation.types(); only_on("presentation", allowed, wanted)?; } // The generic record write (`records::check_value`) knows neither a // list value nor choices read off the record, so only an engine, // which writes such a column itself, may declare one. let engine_only = |field: &str| { if self.has_engine() { Ok(()) } else { Err(DefinitionError::Requires { slot: slot(field), needs: "a_compiled_engine_binding", }) } }; if let Some(from) = &column.choices_from { only_on("choices_from", &[Choice], "a choice")?; engine_only("choices_from")?; self.named(&slot("choices_from"), from, None)?; } if column.multiple == Some(true) { engine_only("multiple")?; } if let Some(on) = &column.toggle_on { only_on("toggle_on", &[Choice], "a choice")?; among_choices(&slot("toggle_on"), column, on.iter())?; } if let Some(decimals) = column.decimals { only_on("decimals", &[Number], "a_number")?; if decimals > cotton_rules::computed::MOST_DECIMALS { return Err(DefinitionError::BadSlot { slot: slot("decimals"), why: refusal_words("at_most_six_decimals") }); } } if let Some(reading) = &column.reading { let remaining = reading.replace("{value}", "").replace("{datetime}", "").replace("{date}", ""); if reading.trim().is_empty() || remaining.contains(['{', '}']) || (!reading.contains("{value}") && !reading.contains("{date}") && !reading.contains("{datetime}")) { return Err(DefinitionError::BadSlot { slot: slot("reading"), why: refusal_words("uses_value_date_or_datetime_in_a") }); } if reading.contains("{date}") { only_on("reading", &[Date], "a_date_for_date")?; } if reading.contains("{datetime}") { only_on("reading", &[Date], "a_date_for_datetime")?; } if matches!(column.column_type, Number | Amount) && remaining.trim().is_empty() && column.units.is_none() && !matches!(column.format, Some(ColumnFormat::Duration | ColumnFormat::DurationMs | ColumnFormat::Bytes)) { return Err(DefinitionError::BadSlot { slot: slot("reading"), why: refusal_words("names_the_figure_s_unit") }); } } if column.labels.is_some() && column.choice_names.is_some() { return Err(DefinitionError::Conflict { slot: slot("choice_names"), other: "labels", }); } for (field, words) in [ ("labels", &column.labels), ("choice_names", &column.choice_names), ] { if let Some(words) = words { if field == "labels" { only_on(field, &[Text, Choice], "a_text_or_a_choice")?; } else { only_on(field, &[Choice], "a choice")?; } if column.column_type == Choice { among_choices(&slot(field), column, words.keys())?; } for (_, text) in words.iter() { said_at(text, slot(field))?; } } } if let Some(until) = &column.until { only_on("until", &[Date], "a date")?; if until == key { return Err(DefinitionError::Conflict { slot: slot("until"), other: "its_own_column", }); } self.named(&slot("until"), until, Some((&[Date], "a date")))?; } if let Some(size) = &column.size { only_on("size", picture.0, picture.1)?; if size.len() != 2 { return Err(DefinitionError::Requires { slot: slot("size"), needs: "a_width_column_and_a_height_column", }); } for side in size { self.named(&slot("size"), side, Some((&[Number], "a number")))?; } } for (field, words) in [ ("caption", &column.caption), ("caption_fallback", &column.caption_fallback), ] { if let Some(words) = words { only_on(field, picture.0, picture.1)?; self.named(&slot(field), words, None)?; } } for (field, names) in [ ("plain_before", &column.plain_before), ("plain_after", &column.plain_after), ] { if let Some(names) = names { only_on(field, &[Link], "a link")?; self.named(&slot(field), names, Some((&[Text, Longtext], "text")))?; } } if let Some(opens) = &column.opens { // A picture opens what it shows (a duplicate's side); a text // opens what its words stand for (a todo's Repeats, its rule), // and only when read-only, since an editable one's tap edits it. only_on("opens", &[Photo, File, Text], "a_photo_a_file_or_a_text")?; if column.column_type == Text && column.readonly != Some(true) { return Err(DefinitionError::Requires { slot: slot("opens"), needs: "a_read_only_text_column", }); } self.validate_opens(&slot("opens"), opens)?; } if let Some(poster) = &column.poster { only_on("poster", &[File], "a file")?; self.named(&slot("poster"), poster, Some((&[Photo], "a photo")))?; } if column.zone.is_some() { only_on("zone", &[Text], "a text")?; } if column.yearly.is_some() { only_on("yearly", &[Date], "a date")?; } if column.untimed.is_some() { only_on("untimed", &[Date], "a date")?; } if let Some(reach) = &column.reach { only_on("reach", &[Text], "a text")?; if let Some(channel) = reach.channel() { self.named(&slot("reach.channel"), channel, None)?; } } if let Some(provenance) = &column.provenance { only_on("provenance", &[Longtext], "a long text")?; self.named(&slot("provenance.by"), &provenance.by, None)?; self.named( &slot("provenance.at"), &provenance.at, Some((&[Date], "a date")), )?; if let Some(since) = &provenance.since { self.named(&slot("provenance.since"), since, None)?; } } if let Some(signs) = &column.signs { only_on("signs", &[Amount], "an amount")?; said_at(&signs.positive, slot("signs.positive"))?; said_at(&signs.negative, slot("signs.negative"))?; } Ok(()) } /// A tap that opens another record: `column` holds its id; `table` is /// another table's (checked for form), `table_column` this one's. fn validate_opens(&self, slot: &str, opens: &RecordOpens) -> Result<(), DefinitionError> { self.named(&format!("{slot}.column"), &opens.column, None)?; if let Some(table) = opens.table.as_ref().filter(|table| !is_valid_id(table)) { return Err(DefinitionError::BadId(table.clone())); } if let Some(column) = &opens.table_column { self.named(&format!("{slot}.table_column"), column, None)?; } Ok(()) } /// Typed verbs writing one choice column: each value offered, still /// open, or agreeing must be one of its choices and say something. fn validate_answers(&self, slot: &str, answers: &RecordAnswers) -> Result<(), DefinitionError> { let column = self.named( &format!("{slot}.column"), &answers.column, Some((&[ColumnType::Choice], "a choice")), )?; if answers.values.is_empty() { return Err(DefinitionError::EmptyAt(format!("{slot}.values"))); } among_choices(&format!("{slot}.values"), column, answers.values.keys())?; for (_, words) in answers.values.iter() { said_at(words, format!("{slot}.values"))?; } among_choices( &format!("{slot}.when"), column, answers.when.iter().flatten(), )?; if let Some(primary) = &answers.primary { if answers.values.get(primary).is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.primary"), needs: "one_of_the_answers_values", }); } } Ok(()) } /// The list's and the page's keys the second round of Swift faces drew /// (1 Oct 2026). fn validate_round_two_keys(&self) -> Result<(), DefinitionError> { use ColumnType::*; if let Some(index) = &self.index { self.named("index", index, Some((&[Text, Place], "a text")))?; } if let Some(search) = &self.search { if search.is_empty() { return Err(DefinitionError::Empty("search")); } for key in search { self.named( "search", key, Some((&[Text, Longtext, Place], "a_text_or_a_long_text")), )?; } } if let Some(opens) = &self.opens { self.validate_opens("opens", opens)?; } if let Some(polaroid) = &self.polaroid { if self.tile.face != TileFace::PolaroidGrid { return Err(DefinitionError::Requires { slot: "polaroid".into(), needs: "the_polaroid_grid_tile", }); } for (slot, key) in [ ("polaroid.caption", &polaroid.caption), ("polaroid.title", &polaroid.title), ("polaroid.subtitle", &polaroid.subtitle), ] { if let Some(key) = key { self.named(slot, key, None)?; } } } if let Some(route) = &self.record_route { let parameters = route.split('/').filter(|part| part.starts_with('[') && part.ends_with(']')).count(); if !route.starts_with('/') || parameters != 1 { return Err(DefinitionError::Requires { slot: "record_route".into(), needs: "an_app_route_pattern_with_one_parameter", }); } } if let Some(route) = &self.list_route { if !route.starts_with('/') || route.contains('[') || route.contains(char::is_whitespace) { return Err(DefinitionError::Requires { slot: "list_route".into(), needs: "an_app_route_with_no_parameter", }); } } if let Some(linked) = &self.linked_when { for (slot, words) in [("linked_when.scheduled", &linked.scheduled), ("linked_when.made", &linked.made)] { if words.as_ref().is_some_and(|words| !words.contains("{when}")) { return Err(DefinitionError::Requires { slot: slot.into(), needs: "words_around_when" }); } } } if let Some(stories) = &self.stories { for (slot, key) in [ ("stories.picture.caption", &stories.picture.caption), ("stories.picture.title", &stories.picture.title), ("stories.picture.subtitle", &stories.picture.subtitle), ("stories.page.caption", &stories.page.caption), ("stories.page.title", &stories.page.title), ("stories.page.subtitle", &stories.page.subtitle), ] { if let Some(key) = key { self.named(slot, key, None)?; } } self.named("stories.video.column", &stories.video.column, None)?; } if let Some(filter) = &self.filter { let column = self.named("filter.column", &filter.column, None)?; if let Some(all) = &filter.all { not_blank(all, "filter.all")?; } let keyed = |values: Box<dyn Iterator<Item = &String> + '_>| { if column.column_type == Choice { among_choices("filter", column, values) } else { Ok(()) } }; keyed(Box::new(filter.words.iter().flat_map(OrderedMap::keys)))?; keyed(Box::new(filter.order.iter().flatten()))?; keyed(Box::new(filter.empty.iter().flat_map(OrderedMap::keys)))?; for (_, words) in filter.words.iter().flat_map(OrderedMap::iter) { not_blank(words, "filter.words")?; } for (_, empty) in filter.empty.iter().flat_map(OrderedMap::iter) { not_blank(&empty.title, "filter.empty.title")?; } } if let Some(count) = &self.count_words { let column = self.named("count_words.column", &count.column, None)?; if count.units.is_empty() { return Err(DefinitionError::Empty("count_words.units")); } if column.column_type == Choice { among_choices("count_words.units", column, count.units.keys())?; among_choices("count_words.order", column, count.order.iter().flatten())?; } for (_, units) in count.units.iter() { not_blank(&units.one, "count_words.units.one")?; not_blank(&units.other, "count_words.units.other")?; } } if let Some(months) = &self.months { if self.by_month.is_none() { return Err(DefinitionError::Requires { slot: "months".into(), needs: "by_month", }); } if let Some(undated) = &months.undated { not_blank(undated, "months.undated")?; } } if let Some(heads) = &self.heads { self.named("heads", heads, Some((&[ColumnType::Text], "a text")))?; } if let Some(tool) = &self.tool { tool_views::validate(&tool.views)?; // A table's own tool block declares no tool acts: its views name none. tool_views::validate_acts(&tool.views, &[])?; tool_views::validate_public_reads(&tool.views, std::slice::from_ref(self))?; not_blank(&tool.name, "tool.name")?; if let Some(server) = &tool.server { server.validate("tool.server")?; } if !tool.tables.is_empty() { if let Some(bad) = tool.tables.iter().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } if tool.tables.first() != Some(&self.id) { return Err(DefinitionError::Requires { slot: "tool.tables".into(), needs: "this_table_first_as_the_tool_s" }); } if tool.tables.len() < 2 { return Err(DefinitionError::Requires { slot: "tool.tables".into(), needs: "another_table_beside_the_home_a_tool" }); } let mut seen = std::collections::BTreeSet::new(); if !tool.tables.iter().all(|id| seen.insert(id.as_str())) { return Err(DefinitionError::Requires { slot: "tool.tables".into(), needs: "each_table_once" }); } } let bad = |slot: &str, why: &str| DefinitionError::BadSlot { slot: format!("tool.{slot}"), why: refusal_words(why) }; if tool.key.as_deref().is_some_and(|key| !is_valid_id(key)) { return Err(bad("key", "is_a_lowercase_word")); } let glyph = |icon: &str| !icon.is_empty() && icon.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-'); if tool.icon.as_deref().is_some_and(|icon| !glyph(icon)) { return Err(bad("icon", "is_a_kebab_case_icon_name")); } if tool.route.as_deref().is_some_and(|route| !route.starts_with('/') || route.chars().any(char::is_whitespace)) { return Err(bad("route", "is_an_app_path_starting_with")); } for (index, figure) in tool.figures.iter().enumerate() { if figure.summary.is_some() || figure.formula.is_some() { self.validate_worked_figure(tool, index, figure)?; continue; } if figure.term { return Err(bad(&format!("figures.{index}.term"), "is_a_figure_the_tool_works_out")); } if !TOOL_FIGURE_READS.contains(&figure.read.as_str()) { return Err(bad(&format!("figures.{index}.read"), "names_a_read_home_answers")); } let flag = TOOL_FIGURE_FLAGS.contains(&figure.read.as_str()); for words in std::iter::once(&figure.many).chain(&figure.one) { if words.trim().is_empty() || (flag && words.contains("{n}")) { return Err(bad(&format!("figures.{index}"), "says_its_words_for_a_count_plain")); } } if !flag && !figure.many.contains("{n}") { return Err(bad(&format!("figures.{index}.many"), "says_the_count_as")); } } } if let Some(when) = &self.delete_when { if self.delete == Some(false) { return Err(DefinitionError::Conflict { slot: "delete_when".into(), other: "delete false, which offers Delete on no record", }); } self.validate_when("delete_when", when)?; } if let Some(shows) = &self.shows { if shows.is_empty() { return Err(DefinitionError::Empty("shows")); } let bad = |why: String| DefinitionError::BadWhere { slot: "shows", why }; let shows = serde_json::to_value(shows).map_err(|why| bad(why.to_string()))?; crate::records::parse_where(self, Some(&shows)).map_err(|why| bad(why.to_string()))?; } if let Some(hidden) = &self.hidden { let column = self.named("hidden.column", &hidden.column, None)?; if hidden.values.is_empty() { return Err(DefinitionError::Empty("hidden.values")); } if column.column_type == Choice { among_choices("hidden.values", column, hidden.values.iter())?; } } if let Some(deletion) = &self.deletion { if let Some(size) = &deletion.size { self.named("deletion.size", size, Some((&[Number], "a number")))?; } for (slot, words) in [ ("deletion.one", &deletion.one), ("deletion.other", &deletion.other), ("deletion.confirm", &deletion.confirm), ("deletion.cancel", &deletion.cancel), ("deletion.label", &deletion.label), ] { if let Some(words) = words { not_blank(words, slot)?; } } } // Link tiles are the list's own links: one at least, drawn on the list. if self.link_tiles.is_some() && !self.links.iter().flatten().any(|link| link.path.is_none() && link.lead.is_none() && link.above.is_none()) { return Err(DefinitionError::Requires { slot: "link_tiles".into(), needs: "a_list_link_drawn_on_the_list" }); } for link in self.links.iter().flatten() { not_blank(&link.label, "links.label")?; if let Some(units) = &link.units { not_blank(&units.one, "links.units.one")?; not_blank(&units.other, "links.units.other")?; // A link's words name only its number: it has no row of its own. for template in [Some(&units.one), Some(&units.other), units.zero.as_ref()].into_iter().flatten() { if unit_fields(template).is_none_or(|fields| fields.iter().any(|key| *key != "n")) { return Err(DefinitionError::BadSlot { slot: "links.units".into(), why: refusal_words("uses_n_and_nothing_else_in_braces") }); } } } let ids = std::iter::once(&link.table).chain(link.where_.iter().flat_map(OrderedMap::keys)); if let Some(bad) = ids.into_iter().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } if let Some(path) = &link.path { app_route(path, "links.path")?; } else if link.review.is_some() { return Err(DefinitionError::Requires { slot: "links.review".into(), needs: "a path", }); } if link.lead.is_some() && link.path.is_some() { return Err(DefinitionError::Conflict { slot: "links.lead".into(), other: "a_path_a_menu_row_has_no", }); } if link.above.is_some() && link.path.is_some() { return Err(DefinitionError::Conflict { slot: "links.above".into(), other: "a_path_a_menu_row_has_no", }); } if link.above.is_some() && link.lead.is_some() { return Err(DefinitionError::Conflict { slot: "links.above".into(), other: "lead_a_link_stands_over_the_records", }); } } if let Some(path) = self.create.as_ref().and_then(|create| create.path.as_ref()) { app_route(path, "create.path")?; } if let Some(kept) = &self.kept_by { self.named("kept_by.when", &kept.when, None)?; not_blank(&kept.says, "kept_by.says")?; } if self.append == Some(true) && self.date.is_none() { return Err(DefinitionError::Empty("date")); } if let Some(capture) = &self.capture { if !is_valid_id(&capture.table) { return Err(DefinitionError::BadId(capture.table.clone())); } if let Some(placeholder) = &capture.placeholder { not_blank(placeholder, "capture.placeholder")?; } // The written table's column: checked for form only. if let Some(link) = capture.link.as_ref().filter(|link| !is_valid_id(link)) { return Err(DefinitionError::BadId(link.clone())); } if let Some(when) = &capture.when { if capture.link.is_none() { return Err(DefinitionError::Requires { slot: "capture.when".into(), needs: "capture_link_a_page_s_input_files" }); } self.validate_when("capture.when", when)?; } } if let Some(words) = self.words.as_ref().and_then(|words| words.could_not_read.as_ref()) { not_blank(&words.busy, "words.could_not_read.busy")?; not_blank(&words.too_long, "words.could_not_read.too_long")?; } if let Some(placeholder) = &self.search_placeholder { not_blank(placeholder, "search_placeholder")?; } for related in self.related.iter().flatten() { not_blank(&related.label, "related.label")?; // Another table's: checked for form only. let ids = std::iter::once(&related.table) .chain(&related.column) .chain(&related.open) .chain(related.filter.iter().flat_map(OrderedMap::keys)); if let Some(bad) = ids.into_iter().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } } self.validate_commands()?; self.validate_marks()?; self.validate_parts()?; if let Some(slips) = &self.slips { slips.validate()?; } if let Some(tie) = self.sort.as_ref().and_then(|sort| sort.tie.as_ref()) { self.named("sort.tie", tie, None)?; } // A grid is how many stand across the one layout: a list's would be // dead data, and a sheet with no count across has nothing to draw. match (self.layout.unwrap_or(ListLayout::List), &self.grid) { (ListLayout::List, Some(_)) => { return Err(DefinitionError::Requires { slot: "grid".into(), needs: "layout_cards_or_sheet_a_list_draws" }); } (ListLayout::Sheet, None) => { return Err(DefinitionError::Requires { slot: "layout".into(), needs: "grid_the_contact_sheet_s_count_across" }); } _ => {} } if let Some(search) = self.empty.as_ref().and_then(|empty| empty.search.as_ref()) { not_blank(&search.title, "empty.search.title")?; } if let Some(conversation) = &self.conversation { // The message table's columns: checked for form only. let ids = conversation .header .iter() .flatten() .chain(conversation.footer.iter().flat_map(MessageColumns::columns)) .chain(&conversation.media) .chain(&conversation.system) .chain(&conversation.color_by) .chain(&conversation.photo); if let Some(bad) = ids.into_iter().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } if let Some(anchor) = &conversation.anchor { self.named("conversation.anchor", anchor, None)?; } if let Some(CanSend::Column(column)) = &conversation.can_send { self.named("conversation.can_send", column, Some((&[ColumnType::Bool], "a bool")))?; } } Ok(()) } /// The slip's optional keys. /// `slip_by` names a choice column, keys its slips by that column's /// values, and each slip names declared columns. fn validate_slip_by(&self) -> Result<(), DefinitionError> { let Some(by) = &self.slip_by else { return Ok(()); }; let column = self.named("slip_by.column", &by.column, Some((&[ColumnType::Choice], "a choice")))?; if by.slips.is_empty() { return Err(DefinitionError::Empty("slip_by.slips")); } among_choices("slip_by.slips", column, by.slips.keys())?; for (_, variant) in by.slips.iter() { self.named("slip_by.title", &variant.title, None)?; if matches!(&variant.subtitle, Some(SlipSubtitle::Several(keys)) if keys.is_empty()) { return Err(DefinitionError::Empty("slip_by.subtitle")); } let subtitles: &[String] = match &variant.subtitle { None => &[], Some(SlipSubtitle::One(key)) => std::slice::from_ref(key), Some(SlipSubtitle::Several(keys)) => keys, }; for key in subtitles { self.named("slip_by.subtitle", key, None)?; } if let Some(key) = &variant.trailing { self.named("slip_by.trailing", key, None)?; } if let Some(caption) = &variant.caption { for key in caption.columns.iter().flatten().chain(caption.fields.iter().flatten()) { self.named("slip_by.caption", key, None)?; } if let Some(status) = &caption.status { self.named("slip_by.caption.status", status, None)?; } for key in caption.dates.iter().flatten() { self.named("slip_by.caption.dates", key, Some((&[ColumnType::Date], "a date")))?; } } } Ok(()) } fn validate_slip_keys(&self) -> Result<(), DefinitionError> { let slip = &self.slip; if let Some(stock_by) = &slip.stock_by { let column = self.named("slip.stock_by.column", &stock_by.column, Some((&[ColumnType::Text, ColumnType::Choice], "a_text_or_a_choice")))?; if column.secret == Some(true) { return Err(DefinitionError::Requires { slot: "slip.stock_by.column".into(), needs: "a_nonsecret_column" }); } if stock_by.values.is_empty() { return Err(DefinitionError::Empty("slip.stock_by.values")); } if column.column_type == ColumnType::Choice { among_choices("slip.stock_by.values", column, stock_by.values.keys())?; } } if let Some(tap) = &slip.tap { let command = self .commands .iter() .flatten() .find(|command| &command.id == tap) .ok_or(DefinitionError::Requires { slot: "slip.tap".into(), needs: "one_of_the_definition_s_commands" })?; if command.kind != CommandKind::Copy { return Err(DefinitionError::Requires { slot: "slip.tap".into(), needs: "a_copy_command" }); } if slip.opens.is_some() { return Err(DefinitionError::Requires { slot: "slip.tap".into(), needs: "a_slip_that_opens_nothing_else" }); } } if let Some(opens) = &slip.opens { match opens { SlipOpens::Column(column) => { self.named("slip.opens", column, Some((&[ColumnType::Link, ColumnType::Url], "a_link_or_a_url")))?; } SlipOpens::Record(record) => self.validate_opens("slip.opens", record)?, } } for (slot, key) in [ ("slip.title_fallback", &slip.title_fallback), ("slip.subtitle_fallback", &slip.subtitle_fallback), ("slip.figure", &slip.figure), ] { if let Some(key) = key { self.named(slot, key, None)?; } } if let Some(stub) = &slip.stub { self.named("slip.stub", stub, Some((&[ColumnType::Date], "a date")))?; } if let Some(toggle_on) = &slip.toggle_on { let Some(toggle) = &slip.toggle else { return Err(DefinitionError::Requires { slot: "slip.toggle_on".into(), needs: "slip.toggle", }); }; let column = self.named( "slip.toggle_on", toggle, Some((&[ColumnType::Choice], "a choice")), )?; among_choices("slip.toggle_on", column, toggle_on.iter())?; } if slip.toggle_style.is_some() && slip.toggle.is_none() { return Err(DefinitionError::Requires { slot: "slip.toggle_style".into(), needs: "slip.toggle", }); } for (name, form) in slip.forms.iter().flat_map(|forms| forms.iter()) { let column = self.named("slip.forms", name, None)?; form.fits(column).map_err(|needs| DefinitionError::Requires { slot: format!("slip.forms.{name}"), needs })?; } if let Some(caption) = &slip.caption { for key in caption.columns.iter().flatten() { self.named("slip.caption.columns", key, None)?; } // Any column's word: a choice past its first, or a text's own // (a device's state), as the Swift caption reads it. if let Some(status) = &caption.status { self.named("slip.caption.status", status, None)?; } for key in caption.dates.iter().flatten() { self.named( "slip.caption.dates", key, Some((&[ColumnType::Date], "a date")), )?; } // How the leading date is said: counted all the way, as its age, // or — a yearly date — as the age it turns next. match caption.date_form.as_deref() { None | Some("relative" | "age") => {} Some("turns") => { let yearly = caption.dates.iter().flatten().any(|key| self.column(key).is_some_and(|column| column.yearly == Some(true))); if !yearly { return Err(DefinitionError::Requires { slot: "slip.caption.date_form".into(), needs: "a_yearly_date_under_slip_caption_dates" }); } } Some(_) => return Err(DefinitionError::BadSlot { slot: "slip.caption.date_form".into(), why: refusal_words("is_relative_age_or_turns") }), } if let Some(form) = caption.form { if caption.date_form.is_some() { return Err(DefinitionError::Conflict { slot: "slip.caption.form".into(), other: "slip_caption_date_form_its_older_name" }); } let Some(leading) = caption.dates.iter().flatten().next().and_then(|key| self.column(key)) else { return Err(DefinitionError::Requires { slot: "slip.caption.form".into(), needs: "a_date_under_slip_caption_dates" }); }; form.fits(leading).map_err(|needs| DefinitionError::Requires { slot: "slip.caption.form".into(), needs })?; } for key in caption.fields.iter().flatten() { self.named("slip.caption.fields", key, None)?; } } if let Some(byline) = &slip.byline { let column = self.named("slip.byline.column", &byline.column, None)?; if byline.words.is_empty() { return Err(DefinitionError::Empty("slip.byline.words")); } if column.column_type == ColumnType::Choice { among_choices("slip.byline.words", column, byline.words.keys())?; } for (_, words) in byline.words.iter() { not_blank(words, "slip.byline.words")?; } } if let Some(badge) = &slip.badge { let column = self.named("slip.badge.column", &badge.column, None)?; not_blank(&badge.symbol, "slip.badge.symbol")?; not_blank(&badge.spoken, "slip.badge.spoken")?; if let Some(values) = &badge.values { if values.is_empty() { return Err(DefinitionError::Empty("slip.badge.values")); } if column.column_type == ColumnType::Choice { among_choices("slip.badge.values", column, values.iter())?; } } } if let Some(answers) = &slip.answers { self.validate_answers("slip.answers", answers)?; } if let Some(unread) = &slip.unread { // A date that holds nothing until the record is opened, or a // choice whose `unread` value is the unread state (a mail thread's // read_state). let column = self.named( "slip.unread", unread, Some((&[ColumnType::Date, ColumnType::Choice], "a_date_or_a_choice")), )?; if column.column_type == ColumnType::Choice { among_choices("slip.unread", column, ["unread".to_string()].iter())?; } } if let Some(status) = &slip.status { self.named("slip.status", status, None)?; } if let Some(reply) = &slip.reply { self.named( "slip.reply.column", &reply.column, Some(( &[ColumnType::Text, ColumnType::Longtext], "a_text_or_a_long_text", )), )?; if let Some(label) = &reply.label { not_blank(label, "slip.reply.label")?; } if let Some(placeholder) = &reply.placeholder { not_blank(placeholder, "slip.reply.placeholder")?; } } Ok(()) } /// The `seal` block: every name a declared column, the sealer's own /// columns undeclared, and a blind column a sealed one. fn validate_seal(&self, spec: &SealSpec) -> Result<(), DefinitionError> { for (slot, keys) in [("seal.clear", &spec.clear), ("seal.blind", &spec.blind), ("seal.blind_exact", &spec.blind_exact)] { for key in keys { self.named(slot, key, None)?; } } if let Some(column) = self.columns.iter().find(|c| seal::RESERVED_COLUMNS.contains(&c.key.as_str())) { return Err(DefinitionError::SealReserved(column.key.clone())); } for (slot, keys) in [("seal.blind", &spec.blind), ("seal.blind_exact", &spec.blind_exact)] { if let Some(column) = keys.iter().find(|k| !spec.seals(k)) { return Err(DefinitionError::SealBlindClear { slot: slot.into(), column: column.clone() }); } } if let Some((column, _)) = spec.blind_bytes.iter().find(|(k, n)| **n == 0 || !spec.blind.contains(k)) { return Err(DefinitionError::SealBlindBytes(column.clone())); } Ok(()) } /// The `send` block against this table's own columns (the rule's own /// check, [`cotton_rules::send::validate`]; what it names in other tables /// is checked across the kit). fn validate_send(&self) -> Result<(), DefinitionError> { let mut alone = self.send.clone().unwrap_or_default(); alone.with.clear(); let carried: Vec<String> = alone.carry.keys().cloned().collect(); alone.same.retain(|set| set.iter().all(|k| !carried.contains(k))); alone.carry.clear(); let shape = cotton_rules::send::TableShape { columns: self.columns.iter().map(send_column).collect(), send: Some(alone), sealed: self.send_refused(), }; let tables = cotton_rules::send::Tables::from([(self.id.clone(), shape)]); cotton_rules::send::validate(&self.id, &tables).map_err(|r| DefinitionError::Send(r.words)) } /// What the send rule knows of this table: its columns and its shape. pub fn send_shape(&self) -> cotton_rules::send::TableShape { cotton_rules::send::TableShape { columns: self.columns.iter().map(send_column).collect(), send: self.send.clone(), sealed: self.send_refused(), } } /// Whether the send rule reads this table as one whose records never /// travel: a table of secrets (`sealed: true`, passwords and passkeys). /// A table SEALED ON THE OBJECT (a `seal` block) is not one: the sender's /// device lays a send from its own plain copy and seals it to the /// receiver's sharing key (ruling R5), so the object's /// sealing never stops a send. pub fn send_refused(&self) -> bool { self.sealed == Some(true) } /// The list's and the page's optional keys. fn validate_list_keys(&self) -> Result<(), DefinitionError> { let date = Some((&[ColumnType::Date][..], "a date")); if let Some(archived) = &self.archived { self.named( "archived", archived, Some((&[ColumnType::Date, ColumnType::Bool], "a_date_or_a_bool")), )?; } for (slot, key) in [ ("readonly_when", &self.readonly_when), ("listed_when", &self.listed_when), ] { if let Some(key) = key { self.named(slot, key, None)?; } } if let Some(spec) = &self.seal { self.validate_seal(spec)?; } if self.send.is_some() { self.validate_send()?; } if let Some(sort) = &self.sort { let column = self.named("sort.column", &sort.column, None)?; if sort.next == Some(true) && (column.column_type != ColumnType::Date || column.yearly != Some(true)) { return Err(DefinitionError::Requires { slot: "sort.next".into(), needs: "a yearly date column" }); } } if let Some(months) = self.horizon.filter(|months| *months < 1) { return Err(DefinitionError::Horizon(months)); } if let Some(group) = &self.group { match &group.sections { // One section per run of the value: any column splits so. None => { self.named("group.column", &group.column, None)?; } Some(sections) => { let column = self.named( "group.column", &group.column, Some((&[ColumnType::Choice], "a choice")), )?; if sections.is_empty() { return Err(DefinitionError::Empty("group.sections")); } for section in sections { among_choices("group.sections", column, section.values.iter())?; if let Some(due) = §ion.due { self.named("group.sections.due.column", &due.column, Some((&[ColumnType::Date], "a date")))?; } } } } } for (slot, key) in [ ("by_day", &self.by_day), ("by_month", &self.by_month), ("day_grouping", &self.day_grouping), ("opened", &self.opened), ] { if let Some(key) = key { self.named(slot, key, date)?; } } if let Some(upcoming) = &self.upcoming { let dates = upcoming.dates.as_deref().unwrap_or_default(); if dates.is_empty() { return Err(DefinitionError::Empty("upcoming.dates")); } for key in dates { self.named("upcoming.dates", key, date)?; } if let Some(series) = &upcoming.series { self.named("upcoming.series", series, None)?; } } if let Some(recent) = &self.recent { self.named("recent.column", &recent.column, date)?; if recent.count == Some(0) { return Err(DefinitionError::TooSmall { slot: "recent.count".into(), least: 1, }); } } if let Some(dimmed) = &self.dimmed { let column = self.named("dimmed.column", &dimmed.column, None)?; if dimmed.values.is_empty() { return Err(DefinitionError::Empty("dimmed.values")); } if column.column_type == ColumnType::Choice { among_choices("dimmed.values", column, dimmed.values.iter())?; } } if let Some(grid) = &self.grid { if grid.columns == 0 { return Err(DefinitionError::TooSmall { slot: "grid.columns".into(), least: 1, }); } } if let Some(chips) = &self.chips { self.named( "chips.column", &chips.column, Some((&[ColumnType::Choice], "a choice")), )?; for key in chips.sends.iter().flat_map(OrderedMap::keys) { self.named("chips.sends", key, None)?; } } if let Some(paste) = &self.paste { let column = self.named("paste.column", &paste.column, Some((&[ColumnType::Text, ColumnType::Longtext], "a_text_or_a_long_text")))?; if column.secret == Some(true) || column.readonly == Some(true) { return Err(DefinitionError::Requires { slot: "paste.column".into(), needs: "a_column_a_person_writes_never_a" }); } } if let Some(cover) = &self.cover { for key in cover.footer.iter().flatten() { self.named("cover.footer", key, None)?; } } for (index, section) in self.lists.iter().flatten().enumerate() { let slot = format!("lists[{index}]"); if section.list.is_none() { return Err(DefinitionError::Requires { slot, needs: "a list", }); } if section.role.is_some() { return Err(DefinitionError::Conflict { slot: format!("{slot}.role"), other: "a_list_s_own_sections", }); } if section.list.as_ref().and_then(|list| list.empty.as_ref()).is_some_and(SectionEmpty::names_the_page) { return Err(DefinitionError::Conflict { slot: format!("{slot}.list.empty"), other: "title_which_only_a_page_s_section", }); } self.validate_section(&slot, section)?; } if let Some(empty) = &self.empty { not_blank(&empty.title, "empty.title")?; } if let Some(create) = &self.create { not_blank(&create.label, "create.label")?; if let Some(dated) = &create.dated { self.named("create.dated", dated, date)?; } validate_doors(create)?; } for export in self.exports.iter().flatten() { not_blank(&export.label, "exports.label")?; self.named("exports.column", &export.column, None)?; let plain = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit(); if export.extension.is_empty() || !export.extension.chars().all(plain) { return Err(DefinitionError::BadExtension(export.extension.clone())); } } if let Some(pager) = &self.pager { self.named("pager", pager, Some((&[ColumnType::Link], "a link")))?; } for action in self.actions.iter().flatten() { not_blank(&action.label, "actions.label")?; if action.object.as_deref().is_some_and(|object| !commands::ACT_OBJECTS.contains(&object)) { return Err(DefinitionError::Requires { slot: "actions.object".into(), needs: "a_known_act_object" }); } self.named("actions.column", &action.column, None)?; match (&action.scheme_column, &action.schemes) { (Some(column), Some(_)) => { self.named("actions.scheme_column", column, None)?; } (None, None) => {} (Some(_), None) => { return Err(DefinitionError::Requires { slot: "actions.scheme_column".into(), needs: "schemes", }) } (None, Some(_)) => { return Err(DefinitionError::Requires { slot: "actions.schemes".into(), needs: "scheme_column", }) } } } if let Some(parts) = &self.page_parts { if parts.is_empty() { return Err(DefinitionError::Empty("page_parts")); } if let Some((index, _)) = parts.iter().enumerate().find(|(index, part)| parts[..*index].contains(part)) { return Err(DefinitionError::Requires { slot: format!("page_parts[{index}]"), needs: "each_part_once", }); } } // A list says which comes first, the content or the grid: a page // whose content comes first (small cards in a strip, no hand) lists // its content before its grid, a hand page its grid first. let order = self.resolved_page_parts(); let at = |part: PagePart| order.iter().position(|held| *held == part); if let (Some(content), Some(grid), Some(_)) = (at(PagePart::Content), at(PagePart::Grid), &self.page_parts) { let content_first = self.content_first(); if content_first != (content < grid) { return Err(DefinitionError::Requires { slot: "page_parts".into(), needs: if content_first { "content_before_grid_on_a_page_whose" } else { "grid_before_content_on_a_page_with" }, }); } } let messages = order.contains(&PagePart::Messages); match (&self.conversation, messages) { (Some(conversation), messages) if messages || (self.parts.as_ref().is_some_and(|parts| parts.lists.iter().any(|list| list.table.as_deref() == Some(conversation.table.as_str()) && list.relation.as_ref().is_some_and(|relation| conversation.links.contains(relation))))) => { // The messages are another table's: its id and its column // keys are checked for form, never against this table. let ids = [ &conversation.table, &conversation.body, &conversation.at, &conversation.mine.column, ]; let more = conversation .links .iter() .chain(&conversation.blank_body) .chain(&conversation.status) .chain(conversation.header_columns.iter().flatten()) .chain(conversation.sends.iter().flat_map(OrderedMap::keys)); if let Some(bad) = ids.into_iter().chain(more).find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } if conversation.links.is_empty() { return Err(DefinitionError::Empty("conversation.links")); } if conversation.mine.values.is_empty() { return Err(DefinitionError::Empty("conversation.mine.values")); } if let Some(ended) = &conversation.ended { self.named("conversation.ended", ended, date)?; } } (None, true) => { return Err(DefinitionError::Requires { slot: "page_parts".into(), needs: "conversation", }) } (Some(_), _) => { return Err(DefinitionError::Requires { slot: "conversation".into(), needs: "page_parts_messages", }) } (None, _) => {} } Ok(()) } /// A column a picture is drawn from: a photo, a file, or a latitude with /// its `pair` (a map). fn picture(&self, slot: &str, name: &str) -> Result<&Column, DefinitionError> { let column = self.named(slot, name, None)?; let drawable = matches!(column.column_type, ColumnType::Photo | ColumnType::File) || column.pair.is_some(); if !drawable { return Err(DefinitionError::WrongColumnType { slot: slot.into(), column: name.into(), found: column.column_type, wanted: "a_photo_a_file_or_a_latitude", }); } Ok(column) } /// A page section's `role`: `facts` are columns said in a line, `main` /// is one long text or a list read as pages, `side` is a list or columns. fn validate_role(&self, slot: &str, section: &PageSection) -> Result<(), DefinitionError> { let slot = format!("{slot}.role"); let plain = section.list.is_none() && section.web.is_none() && section.links.is_none(); match section.role { None => {} Some(SectionRole::Facts) => { if !plain || section.columns().is_empty() { return Err(DefinitionError::Requires { slot, needs: "columns_and_nothing_else", }); } } // A list as the page's body: its records drawn as pages, or as // the slips of what the page is a list of (a statement's lines). Some(SectionRole::Main) => match (§ion.list, section.columns()) { (Some(_), []) => {} (None, [key]) if plain => { self.named(&slot, key, Some((&[ColumnType::Longtext], "a long text")))?; } _ => { return Err(DefinitionError::Requires { slot, needs: "one_long_text_column_or_a_list", }) } }, Some(SectionRole::Side) if section.web.is_some() || section.links.is_some() || (section.list.is_none() && section.columns().is_empty()) => { return Err(DefinitionError::Requires { slot, needs: "a_list_or_columns", }); } Some(SectionRole::Side) => {} } Ok(()) } /// One section of the page or of `lists`: its columns, its picture, its /// web page (which draws no columns) and its embedded list. fn validate_section(&self, slot: &str, section: &PageSection) -> Result<(), DefinitionError> { if let Some(line) = §ion.sparkline { let slot = format!("{slot}.sparkline"); for (other, held) in [("list", section.list.is_some()), ("links", section.links.is_some()), ("web", section.web.is_some())] { if held { return Err(DefinitionError::Conflict { slot, other }); } } self.validate_sparkline(line).map_err(|why| DefinitionError::BadSlot { slot, why })?; } if let Some(figure) = §ion.figure { self.named( &format!("{slot}.figure"), figure, Some((&[ColumnType::Amount], "an amount")), )?; if section.web.is_some() { return Err(DefinitionError::Conflict { slot: format!("{slot}.figure"), other: "web", }); } } for key in section.columns() { self.named(slot, key, None)?; } if let Some(picture) = §ion.picture { self.picture(&format!("{slot}.picture"), picture)?; } if let Some(web) = §ion.web { self.named( &format!("{slot}.web"), web, Some((&[ColumnType::Text], "a text")), )?; if !section.columns().is_empty() { return Err(DefinitionError::Conflict { slot: format!("{slot}.web"), other: "columns", }); } if section.list.is_some() { return Err(DefinitionError::Conflict { slot: format!("{slot}.web"), other: "a list", }); } } if let Some(list) = §ion.list { // Another table's: checked for form only. if let Some(bad) = std::iter::once(&list.table) .chain(&list.link) .find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } // Like list.link and conversation source columns, these belong to // another table. This definition can check their grammar only; // declared-column checks need that target table's definition. for key in list.where_.iter().flat_map(OrderedMap::keys) { if !is_valid_id(key) { return Err(DefinitionError::BadColumnKey(key.clone())); } } match &list.empty { Some(SectionEmpty::Sentence(empty)) => not_blank(empty, "list.empty")?, Some(SectionEmpty::Titled(empty)) => not_blank(&empty.title, "list.empty")?, None => {} } for (field, count) in [("limit", list.limit), ("columns", list.columns)] { if count == Some(0) { return Err(DefinitionError::TooSmall { slot: format!("{slot}.list.{field}"), least: 1, }); } } for with in list.with.iter().flatten() { if let Some(bad) = [&with.table, &with.link] .into_iter() .find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } } if let Some(add) = &list.add { said_at(add, format!("{slot}.list.add"))?; } if let Some(whole) = &list.whole { said_at(whole, format!("{slot}.list.whole"))?; if list.limit.is_none() { return Err(DefinitionError::Requires { slot: format!("{slot}.list.whole"), needs: "a limit", }); } } } if let Some(when) = §ion.when { self.validate_when(&format!("{slot}.when"), when)?; } if let Some(note) = §ion.note { said_at(note, format!("{slot}.note"))?; } // Ink colours a section's note, or a facts section's whole line. if section.ink.is_some() && section.note.is_none() && section.role != Some(SectionRole::Facts) { return Err(DefinitionError::Requires { slot: format!("{slot}.ink"), needs: "a_note_or_the_facts_role", }); } if let Some(hand) = §ion.hand { let lines: Vec<&str> = match hand { PageHand::Columns(entries) => entries.iter().map(String::as_str).collect(), PageHand::Sentence(sentence) => vec![sentence.as_str()], }; if lines .iter() .any(|line| line.matches('{').count() != line.matches('}').count()) { return Err(DefinitionError::Requires { slot: format!("{slot}.hand"), needs: "every { closed by a }", }); } let keys = hand.keys(); if keys.is_empty() { return Err(DefinitionError::Requires { slot: format!("{slot}.hand"), needs: "a_column_or_words_naming_one_as", }); } for key in keys { self.named(&format!("{slot}.hand"), key, None)?; } } if let Some(answers) = §ion.answers { self.validate_answers(&format!("{slot}.answers"), answers)?; } for id in section.commands.iter().flatten() { if !self.commands.iter().flatten().any(|command| &command.id == id) && !self.is_unavailable(id) { return Err(DefinitionError::UnknownCommand { slot: format!("{slot}.commands"), id: id.clone(), }); } } for action in section.actions.iter().flatten() { said_at(&action.label, format!("{slot}.actions.label"))?; if action.sets.is_none() && action.delete != Some(true) { return Err(DefinitionError::Requires { slot: format!("{slot}.actions"), needs: "sets_or_delete", }); } for (key, value) in action.sets.iter().flat_map(OrderedMap::iter) { let column = self.named(&format!("{slot}.actions.sets"), key, None)?; // A choice is set to one of its choices, or cleared. if column.column_type == ColumnType::Choice && !value.is_null() { let word = value .as_str() .map(str::to_owned) .unwrap_or_else(|| value.to_string()); among_choices( &format!("{slot}.actions.sets"), column, std::iter::once(&word), )?; } } } if let Some(links) = §ion.links { if let Some(bad) = links.except.iter().flatten().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } } Ok(()) } /// A condition on the record: a declared column, and which of its values /// (among a choice's choices) or that any value is enough. fn validate_when(&self, slot: &str, when: &SectionWhen) -> Result<(), DefinitionError> { let column = self.named(&format!("{slot}.column"), &when.column, None)?; match (&when.values, when.present) { (None, None) => Err(DefinitionError::Requires { slot: slot.into(), needs: "values_or_present", }), (Some(values), _) if values.is_empty() => { Err(DefinitionError::EmptyAt(format!("{slot}.values"))) } (Some(values), _) if column.column_type == ColumnType::Choice => { among_choices(&format!("{slot}.values"), column, values.iter()) } _ => Ok(()), } } /// The keys the third round of Swift faces drew (1 Oct 2026: Thoughts, /// Bin, Sessions, Email). fn validate_round_three_keys(&self) -> Result<(), DefinitionError> { use ColumnType::*; if let Some(links) = &self.slip.links { if let Some(bad) = links.except.iter().flatten().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } } // Whether `relation` links the other table here is checked where both // definitions are read; a line that cannot hold draws nothing. if let Some(lines) = &self.slip.lines { if let Some(bad) = [&lines.table, &lines.relation].into_iter().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } if lines.limit == Some(0) { return Err(DefinitionError::Empty("slip.lines.limit")); } } if let Some(when) = self.hand_over.as_ref().and_then(|hand| hand.when.as_ref()) { self.validate_when("hand_over.when", when)?; } if let Some(sources) = self .attachments .as_ref() .and_then(|strip| strip.sources.as_ref()) { if sources.is_empty() { return Err(DefinitionError::Empty("attachments.sources")); } } if let Some(clear) = &self.clear { not_blank(&clear.label, "clear.label")?; for (slot, words) in [ ("clear.note", &clear.note), ("clear.title", &clear.title), ("clear.message", &clear.message), ("clear.confirm", &clear.confirm), ("clear.cancel", &clear.cancel), ("clear.done", &clear.done), ] { if let Some(words) = words { not_blank(words, slot)?; } } } if let Some(live) = &self.live { // Read again more often than a second, or less often than a day, // is not what the Swift reader does with it (it holds the // cadence between the two), so a definition says neither. let every = live.every.as_f64().unwrap_or(f64::NAN); if every.is_nan() || every < f64::from(LiveReading::FLOOR) { return Err(DefinitionError::TooSmall { slot: "live.every".into(), least: LiveReading::FLOOR, }); } if every > f64::from(LiveReading::CEILING) { return Err(DefinitionError::Requires { slot: "live.every".into(), needs: "at_most_a_day_86400_seconds", }); } } if let Some(conversation) = &self.conversation { // The message table's and the merged tables' columns: checked // for form only. if let Some(bad) = conversation .header_columns .iter() .flatten() .find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } if let Some(started) = &conversation.started { // The thread's own columns. self.named( "conversation.started.at", &started.at, Some((&[Date], "a date")), )?; for key in started.words.iter().flatten() { self.named("conversation.started.words", key, None)?; } } if let Some(placeholder) = &conversation.placeholder { not_blank(placeholder, "conversation.placeholder")?; } for source in conversation.also.iter().flatten() { let ids = [&source.table, &source.at] .into_iter() .chain(&source.links) .chain(&source.body) .chain(source.mine.iter().map(|mine| &mine.column)); if let Some(bad) = ids.into_iter().find(|id| !is_valid_id(id)) { return Err(DefinitionError::BadId(bad.clone())); } if source.links.is_empty() { return Err(DefinitionError::Empty("conversation.also.links")); } if source .mine .as_ref() .is_some_and(|mine| mine.values.is_empty()) { return Err(DefinitionError::Empty("conversation.also.mine.values")); } // A note says its record's words; a slip says what its // table's own definition says. if source.face != Some(ConversationFace::Slip) && source.body.is_none() { return Err(DefinitionError::Requires { slot: "conversation.also.body".into(), needs: "a_body_unless_the_face_is_slip", }); } } } Ok(()) } fn named( &self, slot: &str, key: &str, types: Option<(&[ColumnType], &'static str)>, ) -> Result<&Column, DefinitionError> { let column = self .column(key) .ok_or_else(|| DefinitionError::UnknownColumn { slot: slot.into(), column: key.into(), })?; if let Some((allowed, wanted)) = types { if !allowed.contains(&column.column_type) { return Err(DefinitionError::WrongColumnType { slot: slot.into(), column: key.into(), found: column.column_type, wanted, }); } } Ok(column) } } /// A word a face reads must say something. fn not_blank(text: &str, slot: &'static str) -> Result<(), DefinitionError> { if text.trim().is_empty() { Err(DefinitionError::Empty(slot)) } else { Ok(()) } } /// A "+" with doors ([`ListCreate::doors`]) is its doors alone; each door /// has an id of its own, a word, a known picture, and does one thing: words /// sent to an act, or files chosen from the picker by their types. fn validate_doors(create: &ListCreate) -> Result<(), DefinitionError> { if let Some(act) = &create.act { validate_create_act(act, "create.act")?; } if let Some(method) = &create.method { if !commands::COMMAND_METHODS.contains(&method.as_str()) { return Err(DefinitionError::Requires { slot: "create.method".into(), needs: "an_app_method_on_the_allowlist" }); } if create.act.is_some() || create.path.is_some() { return Err(DefinitionError::Conflict { slot: "create.method".into(), other: "an_act_or_a_path" }); } } if create.doors.is_empty() { return Ok(()); } if create.act.is_some() || create.path.is_some() || create.method.is_some() || create.dated.is_some() { return Err(DefinitionError::Conflict { slot: "create.doors".into(), other: "an_act_a_path_or_a_day_of_its_own" }); } let mut seen = std::collections::BTreeSet::new(); for door in &create.doors { let slot = format!("create.doors.{}", door.id); let bad = |why: &str| DefinitionError::BadSlot { slot: slot.clone(), why: refusal_words(why) }; if !is_valid_id(&door.id) || !seen.insert(door.id.as_str()) { return Err(bad("a_door_has_an_id_of_its_own")); } said_at(&door.label, format!("{slot}.label"))?; if door.object.as_deref().is_some_and(|object| !commands::ACT_OBJECTS.contains(&object)) { return Err(DefinitionError::Requires { slot: format!("{slot}.object"), needs: "a_known_act_object" }); } if door.reads.is_some() && (door.act.is_some() || door.files.is_some() || door.pick.is_some() || door.draft.is_some()) { return Err(bad("a_door_types_words_or_chooses_files")); } match (&door.act, &door.files, &door.pick) { (None, None, None) if door.reads.is_some() => {} (None, None, None) if door.draft.is_some() => { let draft = door.draft.as_ref().expect("a draft door"); let twice = draft.asks.iter().enumerate().any(|(at, column)| draft.asks[..at].contains(column)); if twice || draft.asks.iter().chain(draft.dated.iter()).chain(draft.account.iter()).any(|column| !is_valid_id(column)) { return Err(bad("a_draft_door_asks_each_column_once")); } } _ if door.draft.is_some() => return Err(bad("a_door_types_words_or_chooses_files")), (Some(act), None, None) => validate_create_act(act, &format!("{slot}.act"))?, (None, Some(files), None) => { if files.types.is_empty() || !files.types.iter().all(|kind| file_type_mimes(kind).is_some()) { return Err(bad("a_door_s_files_name_their_types")); } } (None, None, Some(pick)) => { let twice = pick.kinds.iter().enumerate().any(|(at, kind)| pick.kinds[..at].contains(kind)); if pick.kinds.is_empty() || twice || (pick.source == PickSource::Camera && pick.many) { return Err(bad("a_picture_door_names_what_it_takes")); } } _ => return Err(bad("a_door_types_words_or_chooses_files")), } } Ok(()) } /// An act a "+" sends typed words to names itself and its argument, and the /// answer's key it lands by is a plain key. fn validate_create_act(act: &CreateAct, slot: &str) -> Result<(), DefinitionError> { if !is_valid_id(&act.name) || !is_valid_id(&act.argument) || act.lands.as_deref().is_some_and(|key| !is_valid_id(key)) { return Err(DefinitionError::BadSlot { slot: slot.to_string(), why: refusal_words("an_act_names_itself_and_its_argument") }); } if let Some(words) = act.signed_out.as_deref() { said_at(words, format!("{slot}.signed_out"))?; } Ok(()) } /// A word a face reads must say something — at a slot built at run time. fn said_at(text: &str, slot: String) -> Result<(), DefinitionError> { if text.trim().is_empty() { Err(DefinitionError::EmptyAt(slot)) } else { Ok(()) } } /// An app route: a path the app reads, never an address elsewhere. fn app_route(path: &str, slot: &'static str) -> Result<(), DefinitionError> { if path.starts_with('/') && !path.starts_with("//") && !path.contains(char::is_whitespace) { Ok(()) } else { Err(DefinitionError::Requires { slot: slot.into(), needs: "an_app_route_starting_with_one", }) } } /// Every value must be one of `column`'s choices. fn among_choices<'a>( slot: &str, column: &Column, mut values: impl Iterator<Item = &'a String>, ) -> Result<(), DefinitionError> { let choices = column.choices.as_deref().unwrap_or_default(); match values.find(|value| !choices.contains(value)) { Some(value) => Err(DefinitionError::UnknownChoice { slot: slot.into(), column: column.key.clone(), value: value.clone(), }), None => Ok(()), } } impl ToolDefinition { pub fn from_json(json: &str) -> Result<ToolDefinition, DefinitionError> { serde_json::from_str(json).map_err(|error| DefinitionError::Parse(error.to_string())) } pub fn validate(&self) -> Result<(), DefinitionError> { tool_views::validate(&self.views)?; if !is_valid_id(&self.id) { return Err(DefinitionError::BadId(self.id.clone())); } if self.name.trim().is_empty() || self.name.chars().any(char::is_control) { return Err(DefinitionError::Empty("name")); } // A tool owns its tables, or none: one that only reads tables the // database already has (Birthdays over People's person) carries no // table and is its views alone. if self.tables.is_empty() && self.views.is_empty() { return Err(DefinitionError::NoTables); } if let Some(table) = self.tables.iter().find(|table| !is_valid_id(table)) { return Err(DefinitionError::BadId(table.clone())); } if let Some((at, table)) = self.search.iter().enumerate().find(|(_, table)| !self.tables.contains(table)) { return Err(DefinitionError::BadSlot { slot: format!("tool.search.{at}"), why: refusal_said("searches_a_table_it_has_not", &[("table", format!("{table:?}"))]) }); } let mut contributed = std::collections::BTreeSet::new(); for (at, contribution) in self.contributes.iter().enumerate() { let bad = |why: String| DefinitionError::BadSlot { slot: format!("tool.contributes.{at}"), why }; if !is_valid_id(&contribution.table) { return Err(DefinitionError::BadId(contribution.table.clone())); } owner::contributed_column(&self.id, &contribution.column).map_err(bad)?; if !contributed.insert((&contribution.table, &contribution.column.key)) { return Err(bad(refusal_said("adds_to_twice", &[("column", format!("{:?}", contribution.column.key)), ("table", format!("{:?}", contribution.table))]))); } } if let Some(engine) = self.engines.iter().find(|e| !ENGINE_CAPABILITIES.contains(&e.as_str())) { return Err(DefinitionError::InvalidAutomation(refusal_said("unknown_capability", &[("engine", engine.to_string())]))); } reserve::validate(self).map_err(DefinitionError::InvalidAutomation)?; automations::validate(self).map_err(DefinitionError::InvalidAutomation)?; tool_views::validate_acts(&self.views, &self.acts)?; if let Some(tile) = &self.fan_tile { let views: Vec<&str> = self.views.iter().map(|view| view.id.as_str()).collect(); tile.validate(&views)?; } let mut acts = std::collections::BTreeSet::new(); for (at, act) in self.acts.iter().enumerate() { let slot = format!("tool.acts.{at}"); if !is_valid_id(&act.id) || !acts.insert(act.id.as_str()) { return Err(DefinitionError::BadSlot { slot, why: refusal_words("names_one_act_of_the_tool") }); } if act.label.trim().is_empty() || act.label.chars().any(char::is_control) { return Err(DefinitionError::BadSlot { slot, why: refusal_words("says_its_act_in_words") }); } if act.object.as_deref().is_some_and(|object| !commands::ACT_OBJECTS.contains(&object)) { return Err(DefinitionError::Requires { slot: format!("{slot}.object"), needs: "a_known_act_object" }); } } if let Some(server) = &self.server { server.validate("tool.server")?; } Ok(()) } } macro_rules! builtin_files { ($(($package:literal, $id:literal)),* $(,)?) => { /// Every built-in table definition the personal kit and the shell /// define, `(id, json)`, compiled in, each the one definition in its /// kit's `tables/`. The id IS the file name, so a file and /// its entry cannot disagree about which table they are. pub const BUILTIN_DEFINITION_FILES: &[(&str, &str)] = &[ $(($id, include_str!(concat!("../../kits/", $package, "/tables/", $id, ".json")))),* ]; }; } builtin_files!( ("personal", "todo"), ("personal", "todo_recurrence"), ("personal", "event"), ("personal", "note"), ("personal", "person"), ("personal", "person_handle"), ("personal", "email_thread"), ("personal", "email_sender"), ("personal", "email"), ("personal", "thread"), ("personal", "message"), ("personal", "photo"), ("personal", "video"), ("personal", "album"), ("personal", "secret"), ("personal", "story"), ("personal", "media"), ("personal", "album_item"), ("personal", "duplicate"), ("personal", "sighting"), ("personal", "face"), ("personal", "thread_member"), ("personal", "message_import"), ("personal", "document"), // Pages' reading pile: Cotton Pages adds its star and readable copy to it. // The shell's own tables: the Bin, Home's board and the themes, written at creation. ("shell", "bin"), ("shell", "board"), ("shell", "theme"), ("shell", "backup"), ("shell", "lines"), ("shell", "device"), // The Settings list (the settings board's rows): every database's, so the // dial's Settings card and the Tools screen always draw it (Rigby build 4). ("shell", "settings"), ("shell", "everything"), ("shell", "copy"), ("shell", "schema_move"), ); /// Settings tables whose record verbs are live through the shared core. /// /// This is deliberately a contract of what is live, not a catalogue of the /// app's remaining Settings sources. Add a table only with its generic /// records route and its engine's verbs; the Swift path remains authoritative /// for every table absent here while the migration proceeds one table at a /// time. pub const SETTINGS_RECORD_TABLES: &[&str] = &["agent_login", "device", "storage", "briefing", "project_feedback", "project_item", "record_version", "voice_word", "settings", "everything", "database", "code_default", "message_import", "copy", "backup"]; /// Native reads a definition may ask a record page to make after the synced /// record has loaded. This closed list prevents editable definition data from /// invoking a host write or an arbitrary native method. pub const LIVE_READ_METHODS: &[&str] = &["device.facts"]; /// The tables a device reads LIVE from the serving Mac rather than from its /// own copy: `cotton_ai_calls` is server-only metering (architect, 14 Oct /// 2026), so `ai_calls` and `ai_daily` (a summary over it) have no rows on a /// phone. Every device's `records.list` and `records.get` of these go to /// `POST /v1/metering/read`, which runs the same read tool on the Mac's file. pub const METERING_READS: &[&str] = &["ai_calls", "ai_daily"]; /// The serving Mac's route a metering read goes to. pub const METERING_READ_PATH: &str = "/v1/metering/read"; /// Built-in tables that are an engine's VIEW over rows it keeps or other /// kinds' rows, not a primitive kind's own table — so the guards that hold /// every other built-in to its kind's table and columns hold these to their /// engine instead. /// /// The photos engine's four (`engine: "media"`): `media` — every photo and /// every video as one library, `kind` saying which; `album_item` — one picture /// in one album (`cotton_media_album_items` with the picture's print beside /// it); `duplicate` — one OPEN pair the Mac thinks are copies /// (`cotton_media_duplicates` with both prints and their facts); `sighting` — /// one place a picture was seen (`cotton_media_sightings` with the chat's /// name). Every column of each is the engine's to say: declared read only, /// answered by the generic reads, written only through the tool of the record /// it stands for. The guard `the_media_views_are_read_only_and_the_engines_own` /// holds them. /// /// The bin (`bin.json`, engine `bin`) — every binned row of every /// `crate::constants::BinKind`, read off each kind's own table where /// `trashed_at` is set (`crate::rules::bin::bin_source`), and every deleted /// group and deleted record of a made table. Its `kind` column's choices are /// `BinKind::ALL`, then `group` and `record`, held by /// `the_bin_view_names_every_kind_the_engine_bins`. /// /// The three tables `/activity` is drawn from, all engine `assistant`: /// `activity` (one record, `this`: which file this device is reading and what /// it still owes the server), `assistant_run` (`cotton_assistant_runs`, a /// SUPPORTING table nobody files) and `assistant_call` (`cotton_mcp_audit`, /// server-only). Every column of each is the engine's to say, read only but /// for a run's `state`, which takes `cancelled` alone (`cancel_run`). Held by /// `the_activity_views_are_read_only_but_a_runs_cancel`. /// /// The ENGINE VIEWS the app's screens open through the generic verbs, each /// over rows its engine already keeps (a supporting table) and answered in /// the keys the app's faces read, which are not that table's column names /// (`cotton_tools::mcp::handlers::tables::engine_views`): `face` — a face the /// Mac thinks it recognises, still waiting for the owner's answer /// (`cotton_media_faces`); `person_suggestion` — "same as …?" /// (`cotton_person_suggestions`); `news_topic`, /// `news_settings` (one record) and `news_story`; `thread_member` — who is in /// a conversation. Each is written, where at all, only through its engine's /// own tool. Held by `the_engine_views_name_their_engine_and_belong_to_no_project`. /// /// `member` — who is in this database (Spec 9.3 Members): one record per /// person the membership facts make a member now (`cotton_store::membership` /// over `cotton_admissions`), keyed by the person key. A person still asking /// to join with an invite is the serving Mac's pending claim, not a row; its /// columns are the device's to answer. /// /// `import` — past runs in `cotton_imports`, newest first, with their counts /// and the author device's name. Read only; a new import starts in the app. /// /// `board` — one record per screen that draws a board (`home`, `tools`, /// `database`), keyed by the board id: the board this database draws there /// (`cotton_board_definitions`, else the shipped default) as JSON. Its /// `definition` is written through `cotton_tools::presentation::save_board`, /// held to exactly what this build draws; a delete puts the shipped board /// back (`reset_board`), and no board is created. /// /// `theme` — one record per theme the database can hold (`paper`, `plain`, and /// its own, `database`): its row in `cotton_theme_definitions` when it wrote /// one, else the default, and which is worn. Written through /// `presentation::save_theme` (strict), put back by `reset_theme`. pub const VIEW_TABLES: &[&str] = &[ "copy", "backup", "schema_move", "ai_budget", "ai_daily", "media", "album_item", "duplicate", "sighting", "bin", "activity", "assistant_call", "face", "thread_member", "member", "import", "board", "theme", "agent_login", "briefing", "code_default", "database", "everything", "message_import", "project_feedback", "project_item", "record_version", "storage", "voice_word", "settings", "camera", ]; thread_local! { /// How many times THIS THREAD parsed the whole built-in set — what the /// guard that validation parses no JSON counts (per thread, so tests /// running beside it cannot move it). static BUILTIN_PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } /// [`BUILTIN_PARSES`] on this thread. #[must_use] pub fn builtin_parses_on_this_thread() -> usize { BUILTIN_PARSES.with(std::cell::Cell::get) } /// What a read over a table no tool in this database draws answers: the /// refusal kind, one name on the server and the phone (architect, 21 Oct 2026). /// A table opens and syncs without a definition, but there is nothing to draw /// it with, and never a fallback to a shipped one. The table id travels as /// data, never in the line. pub const NO_TOOL_DRAWS_THIS_TABLE: &str = "no_tool_draws_this_table"; /// The line the refusal carries — `refusal.definition.<the kind>`, as every /// definition refusal is keyed — in these line rows' words, the kit's for /// none. The kind, never these words, says which refusal it is: a database /// may reword it. pub fn no_tool_draws_this_table(lines: &[crate::rules::shell_lines::LineRow]) -> String { crate::rules::shell_lines::resolve("refusal", &format!("definition.{NO_TOOL_DRAWS_THIS_TABLE}"), lines, &[]) .expect("the refusal line set ships definition.no_tool_draws_this_table") } /// Is `id` a built-in TABLE — one whose schema is code (the store's compiled /// storage, 72nd amendment, 21 Oct 2026)? Whether a tool draws it is a /// database's own rows, never this. pub fn is_builtin_table(id: &str) -> bool { cotton_store::schema::package_tables::compiled_shape(id).is_some() } /// Every built-in table definition, in declaration order — parsed once per /// process and shared, never re-parsed per call: a page open asks for them /// several times (records.get, records.page, each linked table) and a whole /// parse of the 1.1 MB set costs about 2 ms on a Mac (14 Oct 2026). /// /// A file that does not parse is a build defect the guard test names; here it /// is a panic with the file's id, never a silently shorter list. pub fn builtin_table_definitions() -> &'static [TableDefinition] { static PARSED: std::sync::OnceLock<Vec<TableDefinition>> = std::sync::OnceLock::new(); PARSED.get_or_init(|| { BUILTIN_PARSES.with(|parses| parses.set(parses.get() + 1)); BUILTIN_DEFINITION_FILES .iter() .map(|(id, json)| { let file = format!("{id}.json"); serde_json::from_str::<serde_json::Value>(json) .map_err(|error| DefinitionError::Parse(error.to_string())) .and_then(|raw| format::check_file(&file, &raw)) .and_then(|_| TableDefinition::from_json(json)) .unwrap_or_else(|error| panic!("built-in definition {file}: {error}")) }) .collect() }) } /// One shipped built-in by its id, from the process's one parsed set. pub fn builtin_table_definition(id: &str) -> Option<&'static TableDefinition> { builtin_table_definitions().iter().find(|definition| definition.id == id) } /// Built-in columns whose STORED value is not the value the definition's type /// promises, and which every reader answers through a resolver instead: /// `(table id, column key)`. /// /// One entry: a meeting's `segments` is the store's JSON manifest of the /// recording's pieces, and the definition declares it as the `file` a meeting /// plays. The generic read answers it as the ONE media key /// `crate::media::meeting_audio::meeting_audio_object` resolves — or null /// while the audio is split, or once `audio_deleted_at` says the bytes are /// gone. /// /// A news edition's `quiet` and `notes` are the JSON lists its row stores (a /// topic id with the moment it last had news; the run's one-liners), and the /// definition declares each as the long text a page draws: answered as the /// display lines `crate::rules::news_edition_facts` writes, one per line — /// "Nothing new on {topic}[ since {weekday date}]" with a deleted topic /// dropped, and the notes trimmed. The guard `no_builtin_column_is_a_json_column` /// exempts exactly these. /// /// An alarm's `repeat_days` is the JSON list of ISO weekdays it stores (1 is /// Monday), answered as the weekday choices the definition declares /// (`Mon` … `Sun`). A person's `emails` and `phones` are the JSON lists of /// strings the people engine stores, answered as the list itself. pub const RESOLVED_COLUMNS: &[(&str, &str)] = &[ // What was read off a paper, a labelled line each. ("document", "facts"), // What a meeting decided and who spoke, a line each in words. // A kit's tools, by the names Home gives them, a line each — never the // stored keys and carried packages. ("toolkit", "tools"), // A kit's picture: the photo it names, as the chooser draws it. ("toolkit", "picture"), // A message's media entries as a conversation draws them (none once it // is deleted), and its reactions as one line, read off the reactions // table; the row's own `reactions` column is not what anyone reacted. ("message", "media"), ("message", "reactions"), // What the owner attached to a session message: each entry's media key, // a line each. ("session_message", "media"), // The links a session says it shipped, a line each, read off the JSON // list its row stores (`cotton_tools::session_words::shipped_lines`). ("session", "shipped"), ]; /// Built-in columns the ENGINE computes from a record's state and the store /// keeps nowhere: `(table id, column key)`. Each is declared `readonly` in its /// definition (a face draws it, a filter or a hand line names it), answered by /// the generic reads (`cotton_tools::mcp::handlers::tables::builtin`), refused /// on every write, and left out of every undo. /// /// A thought's story, read off its routing state: what it `became` in words, /// whether it is still `standing` open, which of five `story` states it is in, /// how many records it became (`became_count`), and `why` the router stopped /// on one still waiting. The guard `every_computed_column_is_declared_read_only_and_stored_nowhere` /// holds the three promises. /// /// The albums a photo or a video is in (`albums`, a link holding several, read /// off `cotton_media_album_items`), and an album's print: its cover's picture /// (`cover_key`, a film's poster) and that picture's size, and how many /// pictures it holds (`member_count`). /// /// A news edition's `figure` (what it is or is doing, "6 stories · 4 min") /// and `state_message` (the run's progress or the failure's own sentence), /// read off its status by `crate::rules::news_edition_facts`. pub const COMPUTED_COLUMNS: &[(&str, &str)] = &[ // A list's refused-write head, worded here and filled by // `rules::refused_write::head_line` from the open Feedback rows. ("device", "devices_route"), // Whether this device is signed in to its personal object, on its own // row only and only in an app that backs up to one: what Sign in and // Sign out are offered on (`cotton_ffi` `records::mark_this_device`). ("device", "session"), // Whether Add and Remove sample records stand on this device's own row: // an app with no personal object (Rigby) and every development build // (`cotton_ffi` `records::mark_this_device`). ("device", "samples"), ("story", "retention_line"), ("story", "expiry_line"), ("story", "reactions"), // A person's phones, emails and Instagram handles, read off // `cotton_person_handles` (v90) as lists (`person_words::person_handles`). ("person", "phones"), ("person", "emails"), ("person", "instagrams"), ("email_thread", "sender"), ("email_thread", "preview"), ("email_thread", "read_state"), ("email_thread", "starred"), ("email_thread", "in_inbox"), ("email_thread", "binned"), ("email_thread", "marks"), ("email", "to_line"), ("email", "cc_line"), ("email", "media"), ("email", "direction"), ("email", "binned"), ("email_sender", "name"), ("email_sender", "last_at"), ("email_sender", "email_count"), ("email_sender", "unread_count"), ("email_sender", "blocked"), ("email_sender", "kind"), ("email_sender", "in_people"), ("email_sender", "reason"), // The statement read from a document, so its lines open from the paper. ("document", "statement_id"), // A paper's cover lines (its kind and day, its length), how it came in, // what is happening to it while it is not ready, the years it covers, the // people it is linked with, and — on its page only — its pages' words. ("document", "type_line"), ("document", "page_line"), ("document", "provenance"), ("document", "state_message"), ("document", "period_years"), ("document", "people"), ("document", "pages_text"), // A repeating todo's words ("Weekly") and the people it is linked with. ("todo", "repeats"), ("todo", "people"), // An event's guests and their replies in words, the people it is with, // its calendar by name, where it came from, and its day and start time // in the reader's zone (never words counted from today), and whether // someone else sent it (the reply is offered only then). ("event", "guest_responses"), ("event", "people"), ("event", "calendar_name"), ("event", "source"), ("event", "day"), ("event", "start_time"), ("event", "invited"), // The people a note is linked with: a person's page lists notes by it. ("note", "people"), // The people in a mail conversation (by any of their addresses) and the // people who spoke in a meeting (confirmed speakers): a person's page // lists both by it. ("email_thread", "people"), // The transaction and the event a Records thread was recorded as, and // the thread each of those came from (cotton_links, Records acts). ("email_thread", "transaction_id"), ("email_thread", "event_id"), ("event", "email_thread_id"), ("transaction", "email_thread_id"), // A meeting's summary's byline, why it failed in one sentence, the audio // that was lost, what was said and what was asked about it (the last two // on its page only), and the project it is filed under. // What a meeting whose audio has not arrived waits for, naming the device. // What arrived since a person's summary was written, and the channel // their conversation runs over. ("person", "summary_since"), ("person", "thread_channel"), // The caller's picture: the person's own, read through the call's link. ("call", "photo"), ("photo", "albums"), ("video", "albums"), // Who is in the picture: the people confirmed on its faces. ("photo", "people"), ("video", "people"), ("album", "cover_key"), ("album", "cover_width"), ("album", "cover_height"), ("album", "member_count"), // A chat's name (a dm stores no title: its contact names it), who is in // it, the channels its messages came by, and its marks in words. ("thread", "name"), ("thread", "members"), ("thread", "member_people"), ("thread", "member_self"), ("thread", "members_unmatched"), ("thread", "channels"), ("thread", "state_line"), ("thread", "unread"), ("thread", "pinned"), ("thread", "muted"), // Whether this chat can be filed in a shared database (it is a chat of // the personal Messages), and whether it is filed in `one` or `several` // (`crate::messages::filing`). ("thread", "fileable"), ("thread", "filed"), // The other side: this chat IS a filed copy, in a shared database, where // an act on it changes the copy for everybody there. ("thread", "filed_copy"), // Whether the owner's app can send into it, and why not in words // (`crate::messages::send`). ("thread", "sendable"), ("thread", "send_blocked_reason"), // A message as it reads: its words (a marker said in words, a deleted // one only that), its one-line form, who said it, the quoted line it // replies to and its marks (`cotton_core::messages::display`). ("message", "display_body"), ("message", "preview"), ("message", "sender_name"), ("message", "sender_label"), ("message", "paper_sender"), ("message", "provenance"), ("message", "reply_preview"), ("message", "is_system"), ("message", "sender_photo"), ("message", "edited_label"), ("message", "starred_label"), ("message", "kept"), // Resolution and attached originals together determine DM share availability. ("message", "shared_status"), // A failed text of the owner's, the one message Delete takes (to the bin). ("message", "can_delete"), // A line of a chat filed in a shared database: everybody's there, so one // reader's own marks (keep, delete from my copy) are not offered on it. ("message", "filed_copy"), // A sign-in code a text carries, as two facts (`crate::messages::sign_in`): // what it is for, which every read answers, and the code itself, which // only the sign-in engine reads — no read door fills it. ("message", "code_for"), ("message", "code"), ("call", "title"), ("call", "outcome_label"), // Where an owner's session message got to, as typed facts the // definition words (`rules::session_delivery`): its state, and the Mac a // delivered one reached. ("session_message", "delivery"), ("session_message", "delivered_on"), // A device's words (DeviceTableSource's, one copy in // `crate::device::words`): what it is, whether it runs the server, the // group it stands in, what it is doing, its place in the serving order, // its load, its last reading and typed access/serving facts. The stored `load1` // is answered as `load_1`. ("device", "kind"), ("device", "machine"), ("device", "status"), ("device", "state"), ("device", "serving_place"), ("device", "load"), // The provider pause is replicated typed JSON; the definition says it. ("device", "held_until"), ("device", "hold_reason"), // The keep-free rule beside its size (device_words), from keep_free_bytes and the disk. ("device", "keep_free_percent"), ("device", "keep_free_size"), ("device", "load_1"), // When this key replaced its predecessor, read off the replacement fact // (`device_words`), never a column of its own. ("device", "rekeyed_at"), ("device", "last_seen_at"), ("device", "has_access"), ("device", "can_serve"), // Target-Mac placement sentences joined by read.devices; never values. ("device", "placement_problems"), // The serving Mac's spend today in one line, said off `ai_spend` by // read.devices (`cotton_core::device::words::ai_spend_line`). ("device", "ai_spend_line"), // What a device said of itself with its last exchange, as plain lines // (`cotton_core::device::words::reported_state_lines`, read.devices). ("device", "reported_state_lines"), // How the app ran over the last day, off its MetricKit payload // (`cotton_core::device::words::usage_columns`, read.devices). ("device", "smooth_scrolling"), ("device", "hangs_today"), ("device", "cpu_time_today"), ("device", "peak_memory"), // The held act "Make this Mac a runner", its two steps // (`cotton_core::device::runner_steps`, read.devices). ("device", "runner_confirm"), ("device", "runner_drop"), // A connection's words (`cotton_tools::connections::words`): what it // brought, and for a code host its token line. // Draft editor choices are definition data, not the stored kind vocabulary. ("connection", "kind_choices"), ("connection", "brought"), // Browser identity is projected from the held config, never the profile. ("connection", "site"), ("connection", "account"), ("connection", "status"), // An assistant's key in words (`assistant_words`): what it may do, when // it was last used, the day a rotation signed it out, and its status word. ("assistant", "kept"), ("assistant", "account"), ("assistant", "status"), ("assistant", "last_synced_at"), ("assistant", "needs_sign_in_since"), // An MCP server's tools, from its stored tools/list (`words::tool_names`). ("connection", "tools"), // A note's length and how often a repeating todo was done before this // one, said on its page's facts line (`record_counts`). ("note", "words"), ("todo", "done_before"), // A coding session's words (the app's SessionTableSource said them in // Swift, `cotton_tools::session_words`): what it is called, the section // of the list it sits in, its project's slug, its line, its facts, its // state in words, the notice a terminal's session carries, whether it can // be carried on, its task list and count, and when it was last active. ("session", "heading"), ("session", "section"), ("session", "project_slug"), ("session", "line"), ("session", "facts"), ("session", "state_line"), ("session", "notice"), ("session", "can_resume"), ("session", "tasks"), ("session", "tasks_count"), ("session", "active_at"), ]; /// Built-in columns only the DEVICE that holds the fact can answer, and the /// store keeps nowhere: `(table id, column key)`. Each is declared `readonly` /// (a page draws it), is never stored, is refused on every write the way a /// [`COMPUTED_COLUMNS`] entry is, and is answered only on the device that /// holds the fact — absent from every other read, which cannot know it. /// /// A meeting's `waiting_to_upload`: whether this device's own media ledger /// (`_media`, device-local, never synced) still holds the recording's audio /// pending, while the meeting has not yet reached the server. The phone's /// records reads fill it (`cotton_ffi::phone::records`). /// /// A device's `digits` and `asked_at`: a device still asking to join is no /// row of the file — the serving Mac's registry holds the pairing, the six /// digits it shows and when it asked, and answers them with the waiting rows /// (`devices.pending`). /// /// A device's `host_answered_by`: whether `read.device` answered this Mac's /// own host switches (`cotton_ffi::methods::host_settings`) — never a row of /// the file. /// /// A device's `backup`: the serving Mac's backup in words, which the app /// writes off `read.device`'s `backup` on that Mac's own page — never a row /// of the file. /// /// A connection's `detail`: what a Google account's serving Mac last saw /// (`google.status`) or a code host's repositories in the app's own lines, /// never a row of the file. The app answers it. /// /// This device's own row (`status` "this device"): how it syncs, what failed /// to back up, the refusal a Mac holds against it, the system's answer on /// notifications and the owner's city — the app answers them on that row /// only, from this device's sync state and preferences. pub const DEVICE_ANSWERED_COLUMNS: &[(&str, &str)] = &[ // A person asking to join is the serving Mac's pending claim. ("member", "device_name"), ("member", "device_fingerprint"), ("member", "digits"), // What THIS device keeps of a film (`cotton_ffi::phone::films`): whether // its stream is kept here to play with no network — never a row of the // file, since a bundle is only ever on the phone that downloaded it. ("film", "on_phone"), // What THIS device keeps of a book's file (`cotton_ffi::phone::books`): // absent, or kept here to open with no network. ("book", "on_phone"), // What THIS device keeps of a song's file (`cotton_ffi::phone::songs`): // absent, keeping or kept; an album's is read from its songs (absent, // some, keeping, kept). ("song", "on_phone"), ("music_album", "on_phone"), // What THIS device keeps of a recording's audio (Cotton Meetings): the // file the recorder wrote, until it is backed up and let go, or not. ("meetings_meeting", "on_phone"), // What THIS device keeps of a picture in the library // (`cotton_ffi::phone::pictures_here`): its own bytes here, or not. ("media", "on_phone"), ("device", "removal_state"), ("device", "digits"), ("device", "asked_at"), // A re-key under way on THIS device (`phone::rekey`): its stage and the // six digits only this device holds. ("device", "rekey"), ("device", "rekey_digits"), ("device", "host_answered_by"), ("device", "backup"), ("device", "media_backup"), ("device", "backup_answered_by"), // When the serving Mac's own sender first rang the owner, or why it // cannot yet (first push): `device.push`, on that Mac's row only. ("device", "push"), // A phone whose notifications are off for Cotton, said beside the // switches off its reported `push_authorization` (schema 126). ("device", "notifications_off"), ("device", "refusal"), ("device", "refusal_clearable"), ("device", "last_synced"), // This device's ONE sync state for the shown database (walker pass 4, // row 9): the same columns and reader as its copy row (read.sync_state). ("device", "ambient"), ("device", "changes_waiting"), ("device", "waiting_since"), ("device", "mac_heard_at"), ("device", "bytes_wanted"), // Storage uses the same device-local sync reading as Device and Copy. ("storage", "ambient"), ("storage", "changes_waiting"), ("storage", "waiting_since"), ("storage", "mac_heard_at"), ("storage", "last_synced"), ("storage", "bytes_wanted"), // This device's sync, as its own page says it (sync programme, lane A): // what it has not sent, why the last try failed, the limit on a sync // that carries on while the app is closed, and what each tool still has // coming — all off `read.syncStatus`. ("device", "sync_trouble"), ("device", "sync_background"), ("device", "coming"), // Where this device's sync stands, for its page's sync groups (lane // syncface): the receipts and files both ways, the serving Mac and its // last answer, and the detail readings — all off `sync.status`. ("device", "receipts_behind"), ("device", "receipts_to_send"), ("device", "fetch_count"), ("device", "fetch_bytes"), ("device", "upload_count"), ("device", "upload_bytes"), ("device", "serving_mac"), ("device", "last_contact"), ("device", "received_since_open"), ("device", "sync_tables"), // How far mail's search index is filled (mailsearch): `read.syncStatus`. ("device", "search_index"), ("device", "has_server"), ("device", "backups"), ("device", "failed_files"), ("device", "notifications"), ("device", "notifications_permission"), // How the world reaches the household, on its serving Mac's page: the // gate that choice's own column is shown by. ("device", "reach_answered_by"), // What a phone keeps, on its own row (`keep.rules`): the gate the keep // section is shown by, and the groups and records it keeps always. ("device", "keeps_answered_by"), ("device", "keep_always"), // What a Mac keeps: the sentence a serving Mac's row carries beside it. ("device", "keep_bytes_note"), ("connection", "detail"), // The serving Mac's name as THIS device knows it, the field line under // "Sign in on the Mac": never a row of the file, so no engine of the file // writes it (295 E row 39). ("connection", "serving_mac"), // Actual cadence words from the serving Mac's local browser ledger. ("connection", "browser_facts"), // A device key's fingerprint, computed on THIS device from the row's // public half (`vault::wrap::fingerprint`), never a stored column: the // publisher could write a stored one (Keys › Devices, 8 Nov 2026). ("vault_key", "fingerprint"), ]; /// Is `(table, key)` one of [`DEVICE_ANSWERED_COLUMNS`]? pub fn is_device_answered_column(table: &str, key: &str) -> bool { DEVICE_ANSWERED_COLUMNS .iter() .any(|(device_table, device_key)| *device_table == table && *device_key == key) } /// Built-in columns a write may carry and NO read ever answers back, which /// the store keeps nowhere as a column: `(table id, column key)`. Each is /// declared writable; its table's adapter hands the value to the engine, /// which uses it and keeps nothing a read could return. /// /// A locked document's `unlock_password`: the page sends the file's password, /// the documents engine tries it and keeps it nowhere on the record. These /// are the only built-in columns a sensitive key /// (`crate::records::is_sensitive_column`) may name, because none is read. /// /// A mailbox's or a calendar's `password` on Connections: the phone seals the /// app password typed there into the vault and the connection row names only /// that secret's id (`secret_id`); no row and no read holds the value. A /// tailnet's `client_secret` the same way, sealed with its client id as one /// login. pub const WRITE_ONLY_COLUMNS: &[(&str, &str)] = &[("document", "unlock_password"), ("connection", "password"), ("connection", "client_secret")]; /// A Mac's four host switches on its own device page: stored in no table — /// that Mac's `host-settings.json` holds them, `read.device` answers them on /// its own page only and `device.setHost` writes them /// (`cotton_ffi::methods::host_settings`). Writable, unlike a device-answered /// column, and shown only where `host_answered_by` says this Mac answered. pub const HOST_SWITCH_COLUMNS: &[(&str, &str)] = &[ ("device", "start_at_login"), ("device", "stay_awake"), ("device", "error_reports"), ("device", "auto_updates"), ]; /// The two addresses a Mac can be pointed at, on the same page and kept in /// the same file as its switches: where its error reports go and where its /// updates come from (`cotton_ffi::methods::host_settings::ADDRESSES`). Text, /// empty for "what this build was stamped with"; otherwise exactly a host /// switch — stored in no table, answered and written by that Mac alone. pub const HOST_ADDRESS_COLUMNS: &[(&str, &str)] = &[("device", "error_reports_to"), ("device", "update_feed")]; /// The household's front door on its serving Mac's device page: which door /// the world reaches the household through. Stored in no column of the device /// — it is a fact of the household's own row /// (`cotton_workspaces.front_door`, `cotton_core::front_door`), which /// `read.devices` answers beside the one device that acts on it and /// `workspace.setReach` writes. Writable, unlike a device-answered /// column, and shown only where `reach_answered_by` says the household's /// choice is drawn on this row. The key says what a person reads — what the /// household is reached through — and never the row's own word for it, which /// the phone's language retired. WHERE it is reached is never a device's. pub const HOUSEHOLD_DOOR_COLUMNS: &[(&str, &str)] = &[("device", "reached_through")]; /// What a PHONE keeps of each table a rule may narrow, on that phone's own /// device page: stored in no column of the device — each is a row of /// `cotton_device_keep` (`cotton_store::keep`), which `keep.rules` answers and /// `keep.set` / `keep.clear` write. Writable, unlike a device-answered column, /// and shown only where `keeps_answered_by` says the row is a phone's: a Mac /// keeps everything. Empty reads as Cotton's default. pub const KEEP_RULE_COLUMNS: &[(&str, &str)] = &[("device", "keep_mail"), ("device", "keep_statuses")]; /// What a MAC keeps of its files, on that Mac's own device page: everything, /// or rows only (sync programme, lane D, 12 Oct 2026). Stored in no column of /// the device — it is the Mac's Storage rules for every byte tool /// (`cotton_store::storage_rules::MacKeeps`), which `keep.rules` answers and /// `keep.set {kind: bytes}` / `keep.clear` write. Shown only where /// `keeps_answered_by` says the row is a Mac's. Empty reads as "set tool by /// tool in Storage". pub const MAC_KEEP_COLUMNS: &[(&str, &str)] = &[("device", "keep_bytes")]; /// What a PHONE keeps of each byte tool's FILES, on that phone's own device /// page, beside its rows rules: everything, the last 3 months, or only what is /// opened (keepfetch, 12 Oct 2026) — Messages per source (WhatsApp media, /// Instagram media), Photos, Videos, Documents. Stored in no column of the /// device — each is that phone's Storage rule for the tool /// (`cotton_storage_rules`), answered resolved by `read.keepFetch {deviceId}`'s /// `byteRules` and written by `storage.keepRule`, so the device row and Storage /// can never disagree. The key is `keep_files_<tool>`. Shown only where /// `keeps_answered_by` says the row is a phone's. pub const PHONE_FILE_COLUMNS: &[(&str, &str)] = &[ ("device", "keep_files_whatsapp"), ("device", "keep_files_instagram"), ("device", "keep_files_photo"), ("device", "keep_files_video"), ("device", "keep_files_document"), ]; /// What a PHONE fetches by its keep rules, on its own device page /// (keepfetch, 12 Oct 2026): `kept_space_bytes`, the cap on bytes fetched by /// rule (1/2/5/10 GB, or "none" for no limit), written by `storage.keptSpace`; /// `keep_fetch_full`, the core's "kept things are full · 2 GB" while it is; /// and `keep_fetch_coming`, the core's progress lines under "What is coming". /// All three are answered by `read.keepFetch {deviceId}` — the cap's stored /// home is `cotton_devices.kept_space_bytes`, the lines are the core's — and /// shown only where `keeps_answered_by` says the row is a phone's. pub const KEEP_FETCH_COLUMNS: &[(&str, &str)] = &[("device", "kept_space_bytes"), ("device", "keep_fetch_full"), ("device", "keep_fetch_coming")]; /// Is `(table, key)` one of [`KEEP_FETCH_COLUMNS`]? pub fn is_keep_fetch_column(table: &str, key: &str) -> bool { KEEP_FETCH_COLUMNS.iter().any(|(keep_table, keep_key)| *keep_table == table && *keep_key == key) } /// Is `(table, key)` one of [`PHONE_FILE_COLUMNS`]? pub fn is_phone_file_column(table: &str, key: &str) -> bool { PHONE_FILE_COLUMNS.iter().any(|(keep_table, keep_key)| *keep_table == table && *keep_key == key) } /// Is `(table, key)` one of [`MAC_KEEP_COLUMNS`]? pub fn is_mac_keep_column(table: &str, key: &str) -> bool { MAC_KEEP_COLUMNS.iter().any(|(keep_table, keep_key)| *keep_table == table && *keep_key == key) } /// Is `(table, key)` one of [`KEEP_RULE_COLUMNS`]? pub fn is_keep_rule_column(table: &str, key: &str) -> bool { KEEP_RULE_COLUMNS.iter().any(|(keep_table, keep_key)| *keep_table == table && *keep_key == key) } /// Is `(table, key)` one of [`HOUSEHOLD_DOOR_COLUMNS`]? pub fn is_household_door_column(table: &str, key: &str) -> bool { HOUSEHOLD_DOOR_COLUMNS .iter() .any(|(door_table, door_key)| *door_table == table && *door_key == key) } /// This device's notification switches on its own device page: stored in no /// table — this device's own preferences hold them, and the app answers and /// writes them on that row only. Writable, unlike a device-answered column, /// and shown only on the row whose `status` is "this device". /// /// DELIVERY ONLY (owner, 11 Oct 2026): whether this device notifies, never /// when a tool asks — a tool's times are the tool's own, as News keeps its /// edition times. Nothing asks about mood on a schedule, so there is no mood /// switch; `the_device_row_holds_delivery_switches_and_no_tools_preference` /// holds it. pub const THIS_DEVICE_SWITCH_COLUMNS: &[(&str, &str)] = &[ ("device", "notify"), ("device", "notify_reminders"), ("device", "notify_events"), ("device", "notify_birthdays"), ("device", "notify_alarms"), ]; /// Is `(table, key)` one of [`THIS_DEVICE_SWITCH_COLUMNS`]? pub fn is_this_device_switch_column(table: &str, key: &str) -> bool { THIS_DEVICE_SWITCH_COLUMNS .iter() .any(|(device_table, device_key)| *device_table == table && *device_key == key) } /// Is `(table, key)` one of [`HOST_SWITCH_COLUMNS`] or /// [`HOST_ADDRESS_COLUMNS`] — a setting that Mac's own file holds? pub fn is_host_switch_column(table: &str, key: &str) -> bool { HOST_SWITCH_COLUMNS .iter() .chain(HOST_ADDRESS_COLUMNS) .any(|(switch_table, switch_key)| *switch_table == table && *switch_key == key) } /// Is `(table, key)` one of [`WRITE_ONLY_COLUMNS`]? pub fn is_write_only_column(table: &str, key: &str) -> bool { WRITE_ONLY_COLUMNS .iter() .any(|(written_table, written_key)| *written_table == table && *written_key == key) } /// Built-in columns the ENGINE reads off a record's state and the store keeps /// nowhere, which a write MAY name: `(table id, column key)`. Unlike a /// [`COMPUTED_COLUMNS`] entry each is writable, and the table's adapter turns /// the value written into the engine's own verb — never a column write. /// /// The guard `every_engine_written_column_is_writable_and_stored_nowhere` /// holds every entry to that. /// /// An alarm's `time`, `HH:mm`: the store keeps it as `hour` and `minute`, and /// a write of it is the alarms tool's `hour` and `minute`. /// /// A record's project where it is a link the projects engine keeps /// (`cotton_project_links`): the read answers the project it is filed under, /// and a write of it is `link_to_project` or `unlink_from_project`. /// /// A connection's `token`, `registrar_token`, `gmail_bin` and `statuses`: a code host's /// token is sealed into the vault (the read answers it masked), and so is a /// Cloudflare connection's registering token — a second secret only the /// owner's acts on a domain open, named by `config.registrar_secret`; /// a WhatsApp number's Statuses is `connections.setStatuses` over its config, /// and a Google account's "Deleting here also deletes in Gmail" (`gmail_bin`) /// is `connections.setGmailBin` over its config. /// /// A person's `birthday`, one day ("1992-08-17", "--08-17" without the year): /// the store keeps it as `birth_month`, `birth_day` and `birth_year`, and a /// write of it is `update_person`'s birthday. pub const ENGINE_WRITTEN_COLUMNS: &[(&str, &str)] = &[ ("person_handle", "kept"), ("person", "birthday"), ("todo", "project"), ("event", "project"), ("document", "projects"), ("connection", "token"), ("connection", "registrar_token"), ("connection", "server"), ("connection", "client_id"), ("connection", "gmail_bin"), ("connection", "statuses"), ]; /// Is `(table, key)` one of [`ENGINE_WRITTEN_COLUMNS`]? pub fn is_engine_written_column(table: &str, key: &str) -> bool { ENGINE_WRITTEN_COLUMNS .iter() .any(|(written_table, written_key)| *written_table == table && *written_key == key) } /// Built-in tables whose records are rows of a SUPPORTING table /// (`crate::primitives::SUPPORTING_TABLES`) rather than of a primitive kind: /// `(table id, store table)`. Every other built-in id IS a primitive kind and /// lives in that kind's table. // Sender groups are an archive projection; only their block state is stored. pub const SUPPORTING_BUILTINS: &[(&str, &str)] = &[ ("ai_calls", "cotton_ai_calls"), ("person_handle", "cotton_person_handles"), ("email_sender", "cotton_blocked_senders"), ("connection", "cotton_connections"), ("assistant", "cotton_mcp_tokens"), ("story", "cotton_stories"), // The kits a new database is made from, kept in the personal database. ("toolkit", "cotton_toolkits"), // What arrived in the personal database (rise 138); no longer written. ("arrival", "cotton_arrivals"), // The devices that asked to open the vault (Keys › Devices): the rows the // vault writes and the object's vault_key fills (storage.json), read where // they are rather than from a made table nothing writes (8 Nov 2026). ("vault_key", "cotton_vault_keys"), ]; /// The store table a built-in table's records live in: its primitive kind's, /// else its [`SUPPORTING_BUILTINS`] entry's. `None` for an id that is neither. pub fn builtin_store_table(id: &str) -> Option<&'static str> { if let Some(kind) = crate::constants::PrimitiveKind::parse(id) { return Some(crate::primitives::primitive(kind).table); } SUPPORTING_BUILTINS .iter() .find(|(table_id, _)| *table_id == id) .map(|(_, table)| *table) } impl TableDefinition { /// The table whose rows this definition reads: a view's source, else /// itself — what every per-table rule of a reader (a money projection, a /// table's own narrowings) is keyed by. pub fn rows_table(&self) -> &str { self.source.as_ref().map_or(self.id.as_str(), |source| source.table.as_str()) } /// The store table this definition's rows live in: a view's source's, /// else its own built-in store ([`builtin_store_table`]). pub fn store_table(&self) -> Option<&'static str> { builtin_store_table(self.rows_table()) } } /// Is `(table, key)` one of [`COMPUTED_COLUMNS`]? pub fn is_computed_column(table: &str, key: &str) -> bool { COMPUTED_COLUMNS .iter() .any(|(computed_table, computed_key)| *computed_table == table && *computed_key == key) } /// The content identity of the built-in definitions this build ships. /// /// Generated at build time from sorted definition paths and their bytes. pub const BUILTIN_DEFINITIONS_HASH: &str = env!("COTTON_DEFINITIONS_HASH"); /// The commit timestamp of the build, used only to prevent seed downgrades. pub const BUILTIN_DEFINITIONS_STAMP: i64 = parse_stamp(env!("COTTON_DEFINITIONS_STAMP")); const fn parse_stamp(value: &str) -> i64 { let bytes = value.as_bytes(); let mut out = 0; let mut i = 0; while i < bytes.len() { out = out * 10 + (bytes[i] - b'0') as i64; i += 1; } out } #[path = "revision.rs"] pub mod revision; #[cfg(test)] #[path = "definitions_tests.rs"] mod tests; #[cfg(test)] mod label_fill_tests; #[cfg(test)] mod engine_tests; #[cfg(test)] #[path = "forms_tests.rs"] mod forms_tests; pub mod visibility; /// One column as the send rule reads it. fn send_column(column: &Column) -> cotton_rules::send::ColumnShape { cotton_rules::send::ColumnShape { key: column.key.clone(), column_type: serde_json::to_value(&column.column_type).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default(), link_to: column.link_to.clone(), computed: column.computed.is_some(), } }