//! Actions: what a record's page offers to DO, as a closed list. //! //! A command is one of four kinds and nothing else — the file picks a kind, //! it never programs one. The kind says what happens to THIS record, so the //! page knows where the command sits and what its receipt can promise: //! //! | kind | what it does | it names | //! |----------|-----------------------------------------------|---------------------| //! | `create` | makes another record from this one | `verb`, `bindings` | //! | `update` | changes this record, which stays | `verb`, `bindings` | //! | `delete` | after it this record is gone; it asks first | `verb`, `confirm` | //! | `open` | goes to the record or address a column holds, or a tool view for this record | `opens` or `view` | //! //! A `create`, `update` or `delete` runs an engine verb (`verb`), or — for a //! table whose acts are a device's or the serving Mac's own calls, not a row //! write — one app method on [`COMMAND_METHODS`] (`method`), never both. //! //! One place runs them (`records.command`), and it answers a [`CommandOutcome`]: //! the `receipt` is what happened in the person's words ("Pinned") — the //! command's label when the definition gives none — and `undo` names the //! command that takes it back ("unpin"). //! //! `does` says what an act does to the record in one word of a closed list //! ([`CommandDoes`]), the same in every tool: it completes or affirms it, //! moves it in time, moves it in place or hands it over, destroys it, or //! puts it away. The act's card takes its colour from it (sage, tan, slate, //! rose, grey; absent, cream), so Mark done and Approve wear one colour. use serde::{Deserialize, Serialize}; use super::{is_valid_id, not_blank, refusal_said, refusal_words, ColumnType, DefinitionError, OrderedMap, TableDefinition}; /// The closed list of what a command can be. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum CommandKind { Create, Update, Delete, Open, /// Puts a value on the device's clipboard — a client act, never sent to /// the core: the column it names (`copies`), or a record's sealed primary /// value ([`COPY_SEALED`], a password's password), forgotten after 120 /// seconds when it is a secret. Copy, /// Opens the person's conversation with the business the record is from, /// about the record — a customer's "Ask Nancy" on a catering card. A /// client act: the app opens that thread (the customer's `message` verb /// writes into it) naming the record; nothing runs in the core. Ask, } /// What a `copy` command names to copy the record's sealed primary value — a /// value no column carries (the vault's payload), opened on the device. pub const COPY_SEALED: &str = "$sealed"; impl CommandKind { pub fn as_str(self) -> &'static str { match self { Self::Create => "create", Self::Update => "update", Self::Delete => "delete", Self::Open => "open", Self::Copy => "copy", Self::Ask => "ask", } } } /// Kit schema: the closed vocabulary for bare objects beneath an opened card, /// each the shipped picture `act-` in Loom's catalogue. Every act a /// kit ships names one (`tests/act_pictures.rs`): a tile is never words alone. pub const ACT_OBJECTS: &[&str] = &[ "stamp", "bin", "handset", "slip", "envelope", "clip", "loop", "folder", "star", "bell", "tag", // Books' Plus doors (Round 15, 4 Nov 2026): a catalogue card, a parcel, // a banded stack of record cards. "catalogue", "parcel", "stack", // Films' Plus doors (Round 14, 4 Nov 2026): a cream string-tie // envelope, a red cloth folder, a small brass-cornered lobby frame. "pouch", "portfolio", "frame", // Music's Plus doors (Round 15, 4 Nov 2026): an edge-on stack of // 7-inch singles in paper sleeves, an empty black record crate. "singles", "crate", // Photos' Plus doors (12 Nov 2026): a printed contact sheet, a compact // 35 mm camera, a 35 mm film canister. "sheet", "camera", "canister", // The hand-inked glyphs (scripts/draw-command-icons.py), each named by // what it shows: an act that names no painted object stands one of these. "archive", "tick", "copy", "plus", "cross", "device", "drop", "page", "lens", "bubble", "send", "arrow", "muted", "open", "person", "picture", "pin", "tray", "cycle", "undo", "retry", "clock", "pencil", ]; /// One thing a record's page offers to do. `create`, `update` and `delete` /// run an existing engine verb with `data` as its arguments and `bindings` /// from argument to this record's column — `$id` its id, `$id_list` a list of /// it. `destructive` asks first, and a `delete` always does. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RecordCommand { pub id: String, pub label: String, pub kind: CommandKind, /// `create`, `update` and `delete`: the engine verb. #[serde(default, skip_serializing_if = "Option::is_none")] pub verb: Option, /// `create`, `update` and `delete`, in place of a verb: the app method it /// runs, one of [`COMMAND_METHODS`]. #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub data: Option>, #[serde(default, skip_serializing_if = "Option::is_none")] pub destructive: Option, /// What a destructive command's confirmation says it will do. #[serde(default, skip_serializing_if = "Option::is_none")] pub confirm: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub bindings: Option>, /// Offered only while each named column holds this value (an absent /// value reads as `false`): Pin on a chat not pinned, Unpin on one that is. /// A list of values is "one of these": Pause on a connection reading, /// waiting for a sign-in or failed. #[serde(default, skip_serializing_if = "Option::is_none")] pub when: Option>, /// What happened, in the person's words, once it has run: "Pinned". /// Without one the receipt is the label. A one-word receipt is a verb /// followed by the record's name ("Pinned Example choir"); a sentence /// names it where it says `{name}` ("Moved {name} to the inbox"). #[serde(default, skip_serializing_if = "Option::is_none")] pub receipt: Option, /// The command of this table that takes this one back: Unpin for Pin. #[serde(default, skip_serializing_if = "Option::is_none")] pub undo: Option, /// `open`: the column holding where to go — a link opens its record, a /// url its address. Offered only while the column holds one. #[serde(default, skip_serializing_if = "Option::is_none")] pub opens: Option, /// `open`, in place of `opens`: the tool view it opens for this record, /// `/` — a partitioned view ([`super::ToolView::partition`]) /// narrowed to this record by its link column (a person's Between us). #[serde(default, skip_serializing_if = "Option::is_none")] pub view: Option, /// `copy`: the column whose value it puts on the clipboard, or /// [`COPY_SEALED`]. Offered only while the column holds one. #[serde(default, skip_serializing_if = "Option::is_none")] pub copies: Option, /// `create`, `update` and `delete`: the person picks a table before it /// runs, and the picked table's id is sent as this argument ("File /// into…" sends it as `as`). #[serde(default, skip_serializing_if = "Option::is_none")] pub pick_table: Option, /// `create`, `update` and `delete` running a verb: the person picks a /// value before it runs — words, a moment (Snooze until…) or a record of one /// table (Move to a project) — and it is sent as `argument`. An argument /// with a dot is one key inside another (`patch.project`). #[serde(default, skip_serializing_if = "Option::is_none")] pub pick: Option, /// Package acts ask these picks in order and run once with every answer. #[serde(default, skip_serializing_if = "Option::is_none")] pub picks: Option>, /// What the act does to the record, which colours its card; absent, it /// is none of [`CommandDoes`]'s (Pin, Build, Try again). #[serde(default, skip_serializing_if = "Option::is_none")] pub does: Option, /// The bare object it is drawn with, one of [`ACT_OBJECTS`]. The kit /// names the picture; the shell never guesses. #[serde(default, skip_serializing_if = "Option::is_none")] pub object: Option, /// This act is a slip inside the named field card's sheet, never a grid act. #[serde(default, skip_serializing_if = "Option::is_none")] pub sheet: Option, /// The form's act: offered only on the record page before its record /// exists, in Keep's place, and it runs its app method with the form's /// values as the record its bindings read. A `create` running a method, /// named as the page's main act; a table has at most one. #[serde(default, skip_serializing_if = "Option::is_none")] pub form: Option, /// A value the method answers that is shown once and never again: the /// answer's key, the heading over it and the line saying why it will not /// be shown again. #[serde(default, skip_serializing_if = "Option::is_none")] pub reveals: Option, /// The record of ANOTHER table the act made at the object, which comes /// to this phone by sync: an article's Fetch queues a download, and the /// person stands on that download once it arrives ([`CommandLands`]). #[serde(default, skip_serializing_if = "Option::is_none")] pub lands: Option, /// What the act says, in place of the general "sign in first", on a /// phone not signed in to the object it asks (an article's Fetch: "Sign /// in to fetch links on your Mac"), as a Plus door's act says its own. #[serde(default, skip_serializing_if = "Option::is_none")] pub signed_out: Option, /// A list's act, never a record's: offered at the head of the table's /// list while at least `at_least` of the listed rows are ones `when` /// offers it on, its label, question and receipt saying how many where /// they say [`COUNT_WORD`] and its method told the number by /// [`COUNT_BINDING`] — so a pile is removed only while it is the pile /// the person was asked about (Remove the 3 quiet runners). #[serde(default, skip_serializing_if = "Option::is_none")] pub list: Option, /// How the command is said to Home's record button ("order my usual /// from …"): its verbs, the word before the record's name and, for a /// record pick, the word before the picked one's (`CommandSpoken`). #[serde(default, skip_serializing_if = "Option::is_none")] pub spoken: Option, } /// Where a list act's words say how many rows it is for. pub const COUNT_WORD: &str = "{count}"; /// The binding that sends a list act's method the count the person saw. pub const COUNT_BINDING: &str = "$count"; /// A list's act: offered while at least this many listed rows meet its `when`. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CommandList { #[serde(default = "CommandList::one")] pub at_least: u32, } impl CommandList { fn one() -> u32 { 1 } } /// What a command shows once from its method's answer. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CommandReveal { /// The answer's key holding the value. pub answer: String, pub title: String, pub note: String, /// The answer's key holding the id of the record the act made, when it /// made one (a call link): a form's page becomes that record's page, /// its acts the record's own. #[serde(default, skip_serializing_if = "Option::is_none")] pub record: Option, } /// Where an act's made record lands (`RecordCommand::lands`): the table it /// is a record of, and the key of the method's answer holding its id /// (`fetch_add` answers `{ fetch }`). The opened page stands on it once sync /// brings it, as a Plus door's act does ([`super::CreateAct::lands`]). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct CommandLands { pub table: String, pub answer: String, } /// What an act does, the same word in every tool, and so the colour of its /// card: completes or affirms (sage: Mark done, Approve, Keep, Restore), /// moves in time (tan: Remind me, Reschedule), moves in place or hands over /// (slate: File to…, Move to inbox, Add to People, Record a transaction), /// destroys (rose, and always held: Delete, Remove, Disconnect, Erase, /// Clear, Junk), puts away (grey: Archive, Mute, Pause, Decline). Anything /// else says nothing and is cream. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "kebab-case")] pub enum CommandDoes { Completes, Times, Moves, Destroys, PutsAway, } impl CommandDoes { pub fn as_str(self) -> &'static str { match self { Self::Completes => "completes", Self::Times => "times", Self::Moves => "moves", Self::Destroys => "destroys", Self::PutsAway => "puts-away", } } } /// What a command asks the person to pick before it runs. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CommandPick { /// The verb argument the picked value is sent as. pub argument: String, pub kind: PickKind, /// The definition's words for this pick; absent, the act's label. #[serde(default, skip_serializing_if = "Option::is_none")] pub label: Option, /// `record`: the table whose record is picked; sent as its id. #[serde(default, skip_serializing_if = "Option::is_none")] pub table: Option, /// `record`: the held database containing the offered records, from a /// public column on this row or `$id` when the row is a database itself. #[serde(default, skip_serializing_if = "Option::is_none")] pub database_by: Option, /// `record`: equality/any-of filters passed to its list before paging, and /// checked again before the picked id reaches the engine. #[serde(default, rename = "where", skip_serializing_if = "Option::is_none")] pub filter: Option>, /// An engine-owned array of offered text values on this record. The /// generic picker draws these choices and core checks them before calling /// the method; a caller cannot supply another export's owner name. #[serde(default, skip_serializing_if = "Option::is_none")] pub choices_from: Option, /// `text`: the words may be left empty, and then nothing is sent — the /// owner's optional line on why he said "Not this". #[serde(default, skip_serializing_if = "Option::is_none")] pub optional: Option, /// `number`: inclusive bounds and the value offered before editing. #[serde(default, skip_serializing_if = "Option::is_none")] pub min: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub default: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub max: Option, /// `number`: the values offered, each a card of its own in this order, /// worded as given (a book's stars: `"4": "★★★★"`), in place of the /// stepper; a value not named here is refused. With `optional`, a Skip /// card beside them sends nothing. #[serde(default, skip_serializing_if = "Option::is_none")] pub labels: Option>, /// `file`: the extensions the phone's file picker offers, lowercase and /// without the dot (`["srt", "vtt"]`); a file with any other is refused. #[serde(default, skip_serializing_if = "Option::is_none")] pub accept: Option>, } impl CommandPick { /// A file pick names what it accepts, each a plain lowercase extension; /// only a file pick names one, and only an app method takes a file. pub fn validate_file(&self) -> Result<(), String> { match (&self.kind, &self.accept) { (PickKind::File, Some(accept)) if !accept.is_empty() && accept.iter().all(|ext| !ext.is_empty() && ext.len() <= 8 && ext.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())) => Ok(()), (PickKind::File, _) => Err(refusal_words("a_file_pick_names_what_it_accepts")), (_, Some(_)) => Err(refusal_words("accept_needs_a_file_pick")), (_, None) => Ok(()), } } /// The picked file's path, checked against `accept` by its extension. pub fn file_value(&self, picked: &serde_json::Value) -> Result { let path = picked.as_str().map(str::trim).filter(|path| !path.is_empty()).ok_or_else(|| refusal_words("a_file_pick_sends_the_file_s_path"))?; let ext = path.rsplit('/').next().and_then(|name| name.rsplit_once('.')).map(|(_, ext)| ext.to_ascii_lowercase()).unwrap_or_default(); if self.accept.iter().flatten().any(|accepted| *accepted == ext) { Ok(path.to_string()) } else { Err(refusal_said("a_file_pick_takes_only", &[("accept", self.accept.iter().flatten().map(|ext| format!(".{ext}")).collect::>().join(", "))])) } } pub fn validate_number(&self) -> Result<(), String> { if self.kind != PickKind::Number { return if self.min.is_some() || self.default.is_some() || self.max.is_some() || self.labels.is_some() { Err(refusal_words("pick_min_default_and_max_need_a").into()) } else { Ok(()) }; } if self .min .as_ref() .zip(self.max.as_ref()) .is_some_and(|(min, max)| min.as_f64() > max.as_f64()) { return Err(refusal_words("number_pick_min_must_not_exceed_max").into()); } if let Some(default) = &self.default { self.number_value(Some(&serde_json::Value::Number(default.clone())))?; } for (value, words) in self.labels.iter().flat_map(OrderedMap::iter) { let number = value.parse::().map_err(|_| refusal_words("a_number_pick_labels_numbers"))?; self.number_value(Some(&serde_json::Value::Number(number)))?; if words.trim().is_empty() { return Err(refusal_words("a_number_pick_labels_numbers").into()); } } Ok(()) } /// A labelled number pick's value, which must be one it names. pub fn labelled_value(&self, picked: &serde_json::Value) -> Result { let value = self.number_value(Some(picked))?; let Some(labels) = &self.labels else { return Ok(value) }; let named = labels.iter().any(|(key, _)| key.parse::().ok() == value.as_f64()); if named { Ok(value) } else { Err(refusal_words("number_is_outside_the_act_s_range")) } } /// The writer checks the same inclusive range as the picker. Explicit null is not a default. pub fn number_value( &self, picked: Option<&serde_json::Value>, ) -> Result { let number = match picked { Some(value) => value.as_number(), None => self.default.as_ref(), } .ok_or_else(|| refusal_words("act_needs_a_number"))?; let value = number .as_f64() .filter(|n| n.is_finite()) .ok_or_else(|| refusal_words("act_needs_a_finite_number"))?; if self .min .as_ref() .is_some_and(|min| Some(value) < min.as_f64()) || self .max .as_ref() .is_some_and(|max| Some(value) > max.as_f64()) { return Err(refusal_words("number_is_outside_the_act_s_range").into()); } Ok(serde_json::Value::Number(number.clone())) } /// The picked record still satisfies the same filters its list used. pub fn accepts(&self, data: &serde_json::Value) -> bool { self.accepts_on(data, None) } /// [`accepts`](Self::accepts) for an act on the record `on`: a filter /// value `"$id"` is that record's id (a dish's Order offers only the menu /// days of that dish). pub fn accepts_on(&self, data: &serde_json::Value, on: Option<&str>) -> bool { let at = |value: &serde_json::Value| match (value.as_str(), on) { (Some(RECORD_ID), Some(id)) => serde_json::Value::String(id.to_string()), _ => value.clone(), }; self.filter .iter() .flat_map(OrderedMap::iter) .all(|(column, wanted)| { let held = data.get(column).unwrap_or(&serde_json::Value::Null); match wanted { serde_json::Value::Array(any) => any.iter().any(|value| held == &at(value)), value => held == &at(value), } }) } } /// The filter value a record pick reads as the acted-on record's own id. pub const RECORD_ID: &str = "$id"; /// The closed list of what a person can pick for a command. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum PickKind { /// A moment, sent as an ISO 8601 timestamp. Datetime, /// A numeric value, checked against the pick's inclusive bounds. Number, /// Words supplied by the person, sent as nonblank trimmed text. Text, /// A record of the pick's table, sent as its id. Record, /// One of the person's OTHER databases, sent as its id: an act that /// reaches into a second database (a domain handed to it) is told which. Database, /// A file the person picks from the phone's files (Files on iPhone, the /// system picker on Android), one of the pick's `accept` extensions, /// sent as the path of the phone's own copy of it. Only an app method /// takes one: the method reads the file and keeps it. File, } /// Where a receipt that is a sentence says the record's name. pub const RECEIPT_NAME: &str = "{name}"; /// Where a receipt says what the person picked: the moment in the device's /// own zone ("Thu 8 Oct, 9:00 am"), or the picked record's name. pub const RECEIPT_PICKED: &str = "{picked}"; /// A command binding that is not a column: the record's id, or a list of it. pub const COMMAND_BINDINGS: [&str; 2] = ["$id", "$id_list"]; /// The app methods a command may run in place of an engine verb: each does /// the act through the same path its own screen calls (a device's write with /// its side effects, or a signed call to the serving Mac), never a row write /// standing in for one. Nothing outside this list runs. // RULE: A command's method is one of these and nothing else; a definition naming another does not load and records.command refuses it. pub const COMMAND_METHODS: &[&str] = &[ "databases.delete", "databases.restore", "definitions.undoTheme", "databases.remove", "databases.invite", "devices.revoke", "pairing.approve", "settings.forgetVoiceTerm", "settings.openFlow", "message.import.choose", "message.import.run", "message.import.retry", "message.import.owner", "device.serveFrom", "device.becomeRunner", "sync.now", // A device waiting to open the vault: its wrap written, or its request removed. "vault.approveDevice", "vault.refuseDevice", "device.notifications.request", "device.notifications.openSettings", "device.rekey", "storage.setMacFiles", "storage.measure", "diagnostics.report", "records.recordAsTransaction", "records.addToCalendar", // A compiled form submits its typed values through the generic writer. "records.create", "records.move", "domains.checkPrice", "domains.register", "domains.handOver", // Describe one photo or video now: the serving Mac asks the model. "media.describe", "media.share", // Pay by UPI: the deep link a money row's amount opens in the person's UPI app. "money.upiPay", // Cinemas' Give subtitles: a .srt or .vtt the person picks from the // phone's files, kept sealed in the film's folder for the Mac to lay // (`cotton_ffi::phone::film_subtitle_file`). "films.subtitleFile", // A domain the household holds made where it is reached (Domains' Reach // this household here): the same write the serving Mac's device page makes. "workspace.setReach", // This Device's sample records: invented todos and events, made and binned. "samples.add", "samples.remove", // An act at the person's own object (`cotton_ffi::phone::object_acts`): // Podcasts' Refresh reads a show's feed now. The method admits only its // own short list of acts. "object.act", // The book reader opens a book: the phone's own act (`cotton_ffi::phone::reader`). "reader.open", // The one player plays a song, an album, an artist or a list from here, // shuffled, next or at the queue's end, a podcast episode, a film or a // series' episode: the phone's own act (`cotton_ffi::phone::shell_player`), // which the instrument of its kind plays. "shell.player", // An album's Find details: the phone's own lookups (MusicBrainz, then the // object's fetch_cover, then iTunes), filling only what is empty. "music.findDetails", // A film's or an episode's Mark watched and Mark unwatched: the phone's // own write (`cotton_ffi::phone::films`), stamping the day and the time // in this phone's zone, which works before any object exists. "films.mark", // Cotton Story: a scene card's Write opens the writer on it; its held // acts move it, copy it and copy a story for translating; Scenes' // Plus makes one in the current story (`ListCreate::method`). "story.write", "story.scene.new", "story.scene.move", "story.scene.duplicate", "story.choose", "story.copy", // Cotton Meetings: Record (the list's Plus), Turn into text again, // Summarise, Export, a speaker's Name and an action's Add to todos // (`cotton_ffi::phone::meetings_app`). "meetings.record.start", "meetings.transcribe", "meetings.summarise", "meetings.export", "meetings.speaker.name", "meetings.action.todo", ]; /// The tables that are DATA and yet may declare commands: the tables of /// packages COTTON ITSELF CARRIES in this build — installed by Cotton's own /// code, never imported — whose page offers an act only an engine can do /// (Domains: ask a price, register, hand over). /// /// THIS LIST IS THE LINE BETWEEN A SHIPPED TOOL AND AN IMPORTED ONE. A tool /// that arrives as a file — from a person, an assistant or a kit somebody /// saved — is data and stays data: `decode_package` refuses any table that /// declares a command, whatever its id, so naming a table `domain` buys an /// imported package nothing. A table listed here is drawn by the shared list /// and page like any other data table; only its commands, which still run /// nothing outside [`COMMAND_METHODS`], come from the build. And the commands /// that run are read from the build's own copy of the definition /// (`records.command`), never from the row a database stores. // RULE: Only a table of a package Cotton itself carries may declare commands while being data; an imported package's table never may, whatever it is called. pub const CARRIED_COMMAND_TABLES: &[&str] = // `film`: the personal kit's Films, whose Keep on phone and Remove // download are flows the phone runs (`settings.openFlow`). `podcast` and // `episode`: the kit's Podcasts — a show's Refresh is an act at the object // (`object.act`), an episode's Keep on phone and Remove download are flows. // `book` and `highlight`: the books kit's — a book's Start reading and // Finished are acts at the object (`object.act`), which stamp the day and // count the reading; a highlight's Unmark deletes it. `song`, // `music_album` and `artist`: the music kit's — Play and the queue are the // phone's player (`shell.player`), Find lyrics an act at the object, Keep // on phone and Remove download flows. `film`, `film_season` and // `film_episode`: the cinemas kit's — Play is the phone's player // (`shell.player`), Mark watched the phone's own write (`films.mark`), // Find details an act at the object (`find_film`), Keep on phone, Keep // season, Keep series and Remove download flows. `fetch`: Downloads' — // Cancel and Try again are acts at the object (`object.act`), whose queue // the Mac fetches from; Remove deletes the row. `page`: Articles' — // Fetch and Fetch the sound queue the page's link at the object // (`object.act` `fetch_add`) and land on the download. `vault_key`: // Keys' Devices — Approve wraps the vault key for a waiting device and // Refuse removes its request (`vault.approveDevice`, `vault.refuseDevice`). // `journal_entry`: Journal's — Star and Unstar set the entry's star, the // phone's own write (`update_record`); Delete puts it in the Bin. // `meetings_meeting`, `meetings_speaker`, `meetings_action`: Meetings' — // Turn into text again, Summarise, Export, a speaker's Name and an // action's Add to todos are the phone core's own // (`cotton_ffi::phone::meetings_app`); Delete puts a row in the Bin. // `story_story`, `story_scene`, `story_character`, `story_place`, // `story_note`: Story's — Remove puts a row in the Bin; removing a // character or place never removes the text that names it. // `transaction`: Money's — Pay by UPI opens // the deep link paying an expected spend (`money.upiPay`). &["ahead", "artist", "book", "domain", "episode", "fetch", "film", "film_episode", "film_season", "highlight", "journal_entry", "meetings_action", "meetings_meeting", "meetings_speaker", "music_album", "order", "page", "podcast", "restaurant", "ride", "so_far", "song", "story_character", "story_note", "story_place", "story_scene", "story_story", "transaction", "vault_key"]; /// The one key of a `when` value that offers a command while its column /// holds NONE of the values it names: `{"not": value}` or `{"not": [values]}`. pub const WHEN_NOT: &str = "not"; /// What a `{"not": …}` `when` value names, or `None` for any other value. pub(crate) fn when_not(wanted: &serde_json::Value) -> Option<&serde_json::Value> { match wanted { serde_json::Value::Object(map) if map.len() == 1 => map.get(WHEN_NOT), _ => None, } } /// A `when` value's plain values: the list's, or the one. fn one_of(wanted: &serde_json::Value) -> Vec<&serde_json::Value> { match wanted { serde_json::Value::Array(any) => any.iter().collect(), one => vec![one], } } /// The generic verb that deletes any table's record (`records.delete`): a /// `delete` command running it on its own table is that table's Delete. pub const GENERIC_DELETE: &str = "delete_record"; /// What `records.command` answers once a command has run. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct CommandOutcome { pub command: String, pub kind: CommandKind, /// What happened: the definition's `receipt`, else the label; `null` /// for `open` and for the quiet stamp a page runs on opening. pub receipt: Option, /// The command that takes it back, when the definition names one. pub undo: Option, /// `create`, `update` and `delete`: the engine verb's own answer. pub answer: Option, /// `open`: `{table, id}` for a record, `{url}` for an address. pub open: Option, /// The way back when the app method answered its own — `{method, args}`, /// the same method with what it was before (how a household is reached, /// put back as it was) — where no command of the table could say it. /// Absent otherwise; `undo` names a command when the definition has one. #[serde(default, skip_serializing_if = "Option::is_none")] pub undo_call: Option, /// A value shown once (`RecordCommand::reveals`): `{title, value, note}`. #[serde(default, skip_serializing_if = "Option::is_none")] pub reveal: Option, } impl RecordCommand { /// Whole-record acts that put the object away are separated at the end. pub fn is_away_act(&self) -> bool { self.kind == CommandKind::Delete || self.destructive == Some(true) || matches!(self.does, Some(CommandDoes::Destroys | CommandDoes::PutsAway)) } /// A field chooser belongs on the field's tap map, never among record acts. pub fn edits_field(&self, table: &TableDefinition) -> bool { self.sheet.is_some() || (self.kind == CommandKind::Update && self.does.is_none() && self.pick.as_ref().is_some_and(|pick| pick.kind == PickKind::Text && pick.choices_from.is_none() && table.columns.iter().any(|column| column.key == pick.argument))) } pub fn ordered_picks(&self) -> &[CommandPick] { self.picks .as_deref() .unwrap_or_else(|| self.pick.as_slice()) } /// Whether the command is offered on a record holding `data`: every /// `when` column holds its value, one of a list of them, or — under /// [`WHEN_NOT`] — none of them (absent reads as `false`), and an `open` /// command's column holds somewhere to go. pub fn offered_on(&self, data: &serde_json::Value) -> bool { let held = |column: &str| data.get(column).cloned().unwrap_or(serde_json::Value::Null); let conditions = self .when .iter() .flat_map(OrderedMap::iter) .all(|(column, wanted)| { let held = held(column); let holds = |wanted: &serde_json::Value| { held == *wanted || (held.is_null() && *wanted == serde_json::Value::Bool(false)) }; match when_not(wanted) { Some(none) => !one_of(none).iter().any(|value| holds(value)), None => one_of(wanted).iter().any(|value| holds(value)), } }); let somewhere = self .opens .as_deref() .or(self .copies .as_deref() .filter(|column| *column != COPY_SEALED)) .is_none_or(|column| match held(column) { serde_json::Value::String(text) => !text.trim().is_empty(), _ => false, }); // The form's act is the form's alone: a kept record never offers it, // and a list's act is the list's. conditions && somewhere && !self.is_form() && self.list.is_none() } /// How many of a list's `rows` (each a record's data) this list act is /// for, when it is offered over them: those its `when` holds on, at /// least `at_least` of them. `None` for a record's act or too few rows. pub fn offered_over(&self, rows: &[serde_json::Value]) -> Option { let list = self.list.as_ref()?; let mut record = self.clone(); record.list = None; let count = rows.iter().filter(|row| record.offered_on(row)).count() as u32; (count >= list.at_least).then_some(count) } /// `words` saying `count` where they say [`COUNT_WORD`]. pub fn counted(words: &str, count: u32) -> String { words.replace(COUNT_WORD, &count.to_string()) } /// Whether it is table `table`'s own generic Delete: a `delete` running /// [`GENERIC_DELETE`] with `table` as its table and the record as its id. pub fn is_generic_delete(&self, table: &str) -> bool { let named = |key: &str| self.data.as_ref().and_then(|data| data.get(key)); let bound = |key: &str| { self.bindings .as_ref() .and_then(|bindings| bindings.get(key)) .map(String::as_str) }; self.kind == CommandKind::Delete && self.verb.as_deref() == Some(GENERIC_DELETE) && named("table") == Some(&serde_json::Value::from(table)) && bound("id") == Some("$id") } /// Whether the page asks before running it: a `delete` always, any other /// kind when it says `destructive`. pub fn asks_first(&self) -> bool { self.kind == CommandKind::Delete || self.destructive == Some(true) } /// Whether it is the form's act (`form`), run before the record exists. pub fn is_form(&self) -> bool { self.form == Some(true) } /// What it shows once, read off its method's `answer`: `{title, value, /// note}`, or `None` when it reveals nothing or the answer holds no text /// at its key. pub fn revealed(&self, answer: &serde_json::Value) -> Option { let reveal = self.reveals.as_ref()?; let value = answer .get(&reveal.answer)? .as_str() .filter(|value| !value.trim().is_empty())?; Some(serde_json::json!({ "title": reveal.title, "value": value, "note": reveal.note })) } /// The record the act made, read off its method's `answer` at the key /// `reveals.record` names: `{table, id}` for the page to open, as an /// `open` command answers. pub fn made(&self, table: &str, answer: &serde_json::Value) -> Option { let key = self.reveals.as_ref()?.record.as_ref()?; let id = answer .get(key)? .as_str() .filter(|id| !id.trim().is_empty())?; Some(serde_json::json!({ "table": table, "id": id })) } /// The record of another table the act made at the object, read off its /// method's `answer` at the key `lands.answer` names: `{table, id, /// by_sync: true}` — it comes to this phone by sync, and the page stands /// on it once it is here. `None` when it lands nowhere or the answer /// names no record. pub fn landed(&self, answer: &serde_json::Value) -> Option { let lands = self.lands.as_ref()?; let id = answer .get(&lands.answer)? .as_str() .map(str::trim) .filter(|id| !id.is_empty())?; Some(serde_json::json!({ "table": lands.table, "id": id, "by_sync": true })) } } impl TableDefinition { /// An act is a verb on the whole record and carries no placeholder: its /// label is said as written, `{count}` on a list act alone; which record /// or Mac it acts on is a fact, a field line on its card (architect, 17 /// Oct 2026 — the core's act-label fill is retired; this refusal and the /// page-cards guard are its tombstone). fn validate_label_fields(&self, command: &RecordCommand) -> Result<(), DefinitionError> { let slot = format!("commands.{}.label", command.id); let label = if command.list.is_some() { command.label.replace(COUNT_WORD, "") } else { command.label.clone() }; if label.contains('{') || label.contains('}') { return Err(requires( slot, "a_label_with_no_placeholder_a_fact", )); } Ok(()) } } fn requires(slot: String, needs: &'static str) -> DefinitionError { DefinitionError::Requires { slot, needs } } impl TableDefinition { /// The command with this id, if the definition declares it. pub fn command(&self, id: &str) -> Option<&RecordCommand> { self.all_commands().find(|command| command.id == id) } /// Native commands and package acts share rendering and lookup. pub fn all_commands(&self) -> impl Iterator + Clone { self.commands .iter() .flatten() .chain(self.acts.iter().flatten()) } /// Each command is one of the four kinds and carries what its kind needs /// and nothing another kind owns. pub(super) fn validate_commands(&self) -> Result<(), DefinitionError> { // A command runs an engine verb: a table a person defined has none. // The one exception is a table of a package Cotton itself carries // ([`CARRIED_COMMAND_TABLES`]). if !self.has_engine() && !CARRIED_COMMAND_TABLES.contains(&self.id.as_str()) { for (slot, set) in [ ("commands", self.commands.is_some()), ("on_open", self.on_open.is_some()), ] { if set { return Err(requires(slot.into(), "a_built_in_table")); } } } super::acts::validate(self).map_err(DefinitionError::InvalidAutomation)?; let mut commands = std::collections::BTreeSet::new(); for command in self.all_commands() { not_blank(&command.id, "commands.id")?; not_blank(&command.label, "commands.label")?; self.validate_label_fields(command)?; if !commands.insert(command.id.as_str()) { return Err(DefinitionError::DuplicateCommand(command.id.clone())); } } for command in self.all_commands() { self.validate_command(command, &commands)?; } // The form's act is a create running a method, the page's main act, // and one a table: Keep has one place on a form. let forms: Vec<&RecordCommand> = self .all_commands() .filter(|command| command.is_form()) .collect(); if forms.len() > 1 { return Err(requires("commands.form".into(), "one_form_act_a_table")); } if let Some(command) = forms.first() { let slot = format!("commands.{}.form", command.id); if command.kind != CommandKind::Create || command.method.is_none() { return Err(requires(slot, "a_create_command_running_an_app_method")); } if command.when.is_some() || command.pick.is_some() || command.pick_table.is_some() { return Err(requires( slot, "no_when_or_pick_a_form_has", )); } if self .parts .as_ref() .and_then(|parts| parts.acts.main.as_deref()) != Some(command.id.as_str()) { return Err(requires(slot, "the_page_s_main_act_parts_acts")); } } for command in self.all_commands() { self.validate_list_act(command)?; } for command in self.all_commands() { if let Some(reveal) = &command.reveals { let slot = format!("commands.{}.reveals", command.id); if command.method.is_none() { return Err(requires(slot, "a_command_running_an_app_method")); } for (key, said) in [ ("answer", &reveal.answer), ("title", &reveal.title), ("note", &reveal.note), ] .into_iter() .chain(reveal.record.as_ref().map(|record| ("record", record))) { if said.trim().is_empty() { return Err(DefinitionError::EmptyAt(format!("{slot}.{key}"))); } } } } for command in self.all_commands() { if let Some(lands) = &command.lands { let slot = format!("commands.{}.lands", command.id); if command.method.is_none() { return Err(requires(slot, "a_command_running_an_app_method")); } if command.reveals.as_ref().is_some_and(|reveal| reveal.record.is_some()) { return Err(requires(slot, "one_record_made_lands_or_reveals_record")); } for (key, said) in [("table", &lands.table), ("answer", &lands.answer)] { if !is_valid_id(said) { return Err(requires(format!("{slot}.{key}"), "an_id")); } } } } for command in self.all_commands() { if let Some(said) = &command.signed_out { let slot = format!("commands.{}.signed_out", command.id); if command.method.as_deref() != Some("object.act") { return Err(requires(slot, "a_command_running_object_act")); } if said.trim().is_empty() { return Err(DefinitionError::EmptyAt(slot)); } } } if let Some(on_open) = self.on_open.as_ref().filter(|id| !self.is_unavailable(id)) { let Some(command) = self.command(on_open) else { return Err(DefinitionError::UnknownCommand { slot: "on_open".into(), id: on_open.clone(), }); }; // Opening a page may quietly stamp it, through the engine that // runs the table's commands; it never asks (and so never // destroys: a destroying act always asks) or goes elsewhere. if command.kind != CommandKind::Update || command.asks_first() || self.engine.is_none() { return Err(requires( "on_open".into(), "an_update_command_that_does_not_ask", )); } } Ok(()) } /// A list's act runs an app method on no record: it picks nothing, /// opens nothing, is no form, and binds only the count; it is dealt on /// the list and never on a page. `$count` binds only a list's act. fn validate_list_act(&self, command: &RecordCommand) -> Result<(), DefinitionError> { let slot = |key: &str| format!("commands.{}.{key}", command.id); let counts = command .bindings .iter() .flat_map(OrderedMap::iter) .any(|(_, column)| column == COUNT_BINDING); if command.list.is_none() { if counts { return Err(requires( slot("bindings"), "a_list_act_list_to_send_the", )); } return Ok(()); } if command.method.is_none() || matches!(command.kind, CommandKind::Open | CommandKind::Copy) { return Err(requires( slot("list"), "a_create_update_or_delete_command_running", )); } if command.is_form() || command.pick.is_some() || command.pick_table.is_some() || command.sheet.is_some() || command.reveals.is_some() { return Err(requires( slot("list"), "no_form_pick_sheet_or_reveal_a", )); } if command .bindings .iter() .flat_map(OrderedMap::iter) .any(|(_, column)| column != COUNT_BINDING) { return Err(requires( slot("bindings"), "only_the_count_count_a_list_act", )); } let parts = self.resolved_parts(); if parts.acts.main.as_ref() == Some(&command.id) || parts.acts.away.as_ref() == Some(&command.id) || parts.acts.more.contains(&command.id) || parts .cards .iter() .flatten() .chain(parts.strip.iter().flatten()) .any(|card| card.act.as_ref() == Some(&command.id)) || self.page.iter().any(|section| { section .commands .iter() .flatten() .any(|id| id == &command.id) }) || self.on_open.as_ref() == Some(&command.id) { return Err(requires(slot("list"), "a_list_act_never_dealt_on_a")); } Ok(()) } fn validate_command( &self, command: &RecordCommand, declared: &std::collections::BTreeSet<&str>, ) -> Result<(), DefinitionError> { let slot = |key: &str| format!("commands.{}.{key}", command.id); let kind = command.kind; if command.object.as_deref().is_some_and(|object| !ACT_OBJECTS.contains(&object)) { return Err(requires(slot("object"), "a_known_act_object")); } if command.picks.is_some() && (!(self.acts.iter().flatten().any(|act| act.id == command.id) || command.method.is_some()) || command.pick.is_some() || command.picks.as_ref().is_some_and(Vec::is_empty)) { return Err(requires( slot("picks"), "an_app_method_or_package_act_with", )); } if let Some(sheet) = &command.sheet { self.named(&slot("sheet"), sheet, None)?; let parts = self.resolved_parts(); if !parts .cards .iter() .flatten() .chain(parts.strip.iter().flatten()) .any(|card| card.column.as_ref() == Some(sheet)) { return Err(requires(slot("sheet"), "a_declared_field_card")); } if parts.acts.main.as_ref() == Some(&command.id) || parts.acts.away.as_ref() == Some(&command.id) || parts.acts.more.contains(&command.id) || parts .cards .iter() .flatten() .chain(parts.strip.iter().flatten()) .any(|card| card.act.as_ref() == Some(&command.id)) || self.page.iter().any(|section| { section .commands .iter() .flatten() .any(|id| id == &command.id) }) { return Err(requires( slot("sheet"), "a_sheet_act_never_dealt_in_the", )); } } if kind == CommandKind::Copy || command.copies.is_some() { return self.validate_copy(command); } if kind == CommandKind::Ask { // An ask names its words and nothing it would run. let runs = command.verb.is_some() || command.method.is_some() || command.data.is_some() || command.bindings.is_some() || command.opens.is_some() || command.view.is_some() || command.pick.is_some() || command.picks.is_some() || command.pick_table.is_some(); if runs { return Err(requires(format!("commands.{}.kind", command.id), "an_ask_that_runs_nothing")); } return Ok(()); } let runs_a_verb = kind != CommandKind::Open; if let Some(spoken) = &command.spoken { if spoken.verbs.is_empty() || spoken .verbs .iter() .chain([&spoken.record]) .any(|words| words.trim().is_empty()) { return Err(DefinitionError::Empty("commands.spoken")); } if command.verb.is_none() { return Err(requires(slot("spoken"), "a_command_running_a_verb")); } if spoken.pick.is_some() && command .pick .as_ref() .is_none_or(|pick| pick.kind != PickKind::Record) { return Err(requires(slot("spoken.pick"), "a_record_pick")); } if spoken.pick_unsaid.is_some() && spoken.pick.is_none() { return Err(requires(slot("spoken.pick_unsaid"), "a_spoken_pick")); } if spoken .counted .as_ref() .is_some_and(|counted| !is_valid_id(&counted.argument)) { return Err(requires( slot("spoken.counted.argument"), "an_argument_name", )); } } if let Some(method) = &command.method { if command.verb.is_some() { return Err(DefinitionError::Conflict { slot: slot("method"), other: "a_verb", }); } if !runs_a_verb { return Err(requires( slot("method"), "a_create_update_or_delete_command", )); } if !COMMAND_METHODS.contains(&method.as_str()) { return Err(requires(slot("method"), "an_app_method_on_the_allowlist")); } } // A verb-less create or update is the shape made tools will use; it // is refused until they need it. match ( runs_a_verb, command.verb.is_some() || command.method.is_some(), command.opens.is_some() || command.view.is_some(), ) { (true, false, _) => return Err(requires(slot("kind"), "a_verb")), (true, _, true) => return Err(requires(slot("opens"), "an_open_command")), (false, true, _) => { return Err(requires(slot("verb"), "a_create_update_or_delete_command")) } (false, _, false) => return Err(requires(slot("kind"), "the_column_or_the_view_it_opens")), _ => {} } if !runs_a_verb && (command.data.is_some() || command.bindings.is_some() || command.pick_table.is_some() || command.pick.is_some()) { return Err(requires( slot("bindings"), "a_create_update_or_delete_command", )); } if let Some(verb) = &command.verb { if !is_valid_id(verb) { return Err(DefinitionError::BadId(verb.clone())); } } if let Some(argument) = &command.pick_table { not_blank(argument, "commands.pick_table")?; } for pick in command.ordered_picks() { if let Some(label) = &pick.label { not_blank(label, "commands.picks.label")?; } pick.validate_number() .map_err(DefinitionError::InvalidAutomation)?; pick.validate_file() .map_err(DefinitionError::InvalidAutomation)?; // A table pick cannot also ask for argument values. if command.pick_table.is_some() { return Err(DefinitionError::Conflict { slot: slot("pick"), other: "a_pick_table", }); } // A value is picked for a verb's argument; a database is picked // for an app method, which is what reaches another database. match (pick.kind, command.verb.is_some()) { (PickKind::Database | PickKind::File, true) => { return Err(requires(slot("pick"), "a_command_running_an_app_method")) } (PickKind::Database, false) => {} (_, false) if command.method.is_none() => { return Err(requires( slot("pick"), "a_command_running_an_engine_verb_or", )) } (_, false) => {} (_, true) => {} } if pick.argument.split('.').any(|key| key.trim().is_empty()) { return Err(DefinitionError::EmptyAt(slot("pick.argument"))); } let package_act = self.acts.iter().flatten().any(|act| act.id == command.id); let known = |table: &str| super::is_builtin_table(table) || (package_act && is_valid_id(table)); if let Some(database) = &pick.database_by { if pick.kind != PickKind::Record { return Err(requires(slot("pick.database_by"), "a_record_pick")); } if database != "$id" { let column = self.named( "commands.pick.database_by", database, Some((&[ColumnType::Text, ColumnType::Link], "text_or_a_link")), )?; if column.secret == Some(true) { return Err(requires(slot("pick.database_by"), "a_public_column")); } } } let labelled_number = pick.kind == PickKind::Number && pick.labels.is_some(); if pick.optional.is_some() && !labelled_number && (pick.kind != PickKind::Text || pick.choices_from.is_some()) { return Err(requires(slot("pick.optional"), "a_free_text_pick")); } if let Some(source) = &pick.choices_from { if pick.kind != PickKind::Text || self.column(source).is_none_or(|column| { column.readonly != Some(true) || column.secret == Some(true) }) { return Err(requires( slot("pick.choices_from"), "a_readonly_nonsecret_column_and_a_text", )); } } match (pick.kind, pick.table.as_deref()) { (PickKind::Record, Some(table)) if known(table) => {} (PickKind::Record, _) => { return Err(requires( slot("pick.table"), "a_built_in_table_its_record_is", )) } ( PickKind::Datetime | PickKind::Text | PickKind::Database | PickKind::Number | PickKind::File, Some(_), ) => return Err(requires(slot("pick.table"), "a_record_pick")), ( PickKind::Datetime | PickKind::Text | PickKind::Database | PickKind::Number | PickKind::File, None, ) => {} } if let Some(filter) = &pick.filter { if pick.kind != PickKind::Record { return Err(requires(slot("pick.where"), "a_record_pick")); } // THE TARGET IS THE PROCESS'S PARSED BUILT-IN, never a fresh // parse: validation runs on every page open, and a parse of a // whole definition inside it overflowed a debug build's worker // stack opening a todo (14 Oct 2026). Parsing the set does not // validate it, so this cannot re-enter its own loading. let target = pick .table .as_deref() .and_then(super::builtin_table_definition); let built_in = pick.table.as_deref().is_some_and(super::is_builtin_table); if !built_in && !package_act { return Err(requires(slot("pick.where"), "a_built_in_table")); } for (column, value) in filter.iter() { if let Some(target) = target { target.named("commands.pick.where", column, None)?; } let plain = |value: &serde_json::Value| !value.is_array() && !value.is_object(); let valid = match value { serde_json::Value::Array(any) => !any.is_empty() && any.iter().all(plain), value => plain(value), }; if !valid { return Err(requires( slot("pick.where"), "a_plain_value_or_a_nonempty_list", )); } } } } for (argument, column) in command.bindings.iter().flat_map(OrderedMap::iter) { not_blank(argument, "commands.bindings")?; if argument.split('.').any(|key| key.trim().is_empty()) { return Err(DefinitionError::EmptyAt(slot("bindings"))); } if !COMMAND_BINDINGS.contains(&column.as_str()) && column != COUNT_BINDING { self.named("commands.bindings", column, None)?; } } for (column, wanted) in command.when.iter().flat_map(OrderedMap::iter) { self.named("commands.when", column, None)?; // A list is "one of these" plain values, never a list to match; // `{"not": …}` is none of them, and no other object is a value. let plain = |value: &serde_json::Value| { !matches!( value, serde_json::Value::Array(_) | serde_json::Value::Object(_) ) }; let named = when_not(wanted).unwrap_or(wanted); let well_formed = match named { serde_json::Value::Array(any) => !any.is_empty() && any.iter().all(plain), one => plain(one), }; if !well_formed || (matches!(wanted, serde_json::Value::Object(_)) && when_not(wanted).is_none()) { return Err(requires( slot("when"), "one_value_a_list_of_plain_values", )); } } if command.opens.is_some() && command.view.is_some() { return Err(requires(slot("view"), "an_open_command_naming_no_column")); } if let Some(view) = &command.view { let named = view.split_once('/').is_some_and(|(tool, view)| is_valid_id(tool) && is_valid_id(view)); if !named { return Err(requires(slot("view"), "a_tool_view_named_tool_view")); } } if let Some(column) = &command.opens { // A plain text column is never opened as an address. self.named( "commands.opens", column, Some((&[ColumnType::Link, ColumnType::Url], "a_link_or_a_url")), )?; } if kind == CommandKind::Delete { // It takes the generic Delete's place, so the two are never both // offered, and it always says what goes before it runs — unless // it IS the generic Delete (the generic verb on this very // table), named so the page's away act runs it. if command.is_generic_delete(&self.id) { if self.delete == Some(false) { return Err(requires( slot("kind"), "a_table_whose_generic_delete_is_taken", )); } } else if self.delete != Some(false) { return Err(requires( slot("kind"), "the_definition_to_say_delete_false", )); } if command.destructive == Some(false) { return Err(requires( slot("destructive"), "a_command_that_leaves_the_record", )); } if command.confirm.is_none() { return Err(requires(slot("kind"), "a_confirm_saying_what_goes")); } let deletes = self .commands .iter() .flatten() // A list act takes rows of the list away, never this record. .filter(|other| other.kind == CommandKind::Delete && other.list.is_none()); if command.list.is_none() && deletes.count() > 1 { return Err(requires( slot("kind"), "to_be_the_definition_s_only_delete", )); } } // Going somewhere changes nothing, so it says nothing. let changes = runs_a_verb; if let Some(receipt) = &command.receipt { if !changes { return Err(requires( slot("receipt"), "a_command_that_changes_something", )); } if receipt.trim().is_empty() { return Err(DefinitionError::EmptyAt(slot("receipt"))); } // The only words in braces a receipt fills are the record's // name and, on a command that asks for one, what was picked; a // list act has no record and says how many rows instead. let unfilled = if command.list.is_some() { receipt.replace(COUNT_WORD, "") } else { receipt.replace(RECEIPT_NAME, "") }; let unfilled = if command.pick.is_some() { unfilled.replace(RECEIPT_PICKED, "") } else { unfilled }; if unfilled.contains(['{', '}']) { return Err(requires( slot("receipt"), "no_braces_but_name_count_on_a", )); } } if let Some(confirm) = &command.confirm { if confirm.trim().is_empty() { return Err(DefinitionError::EmptyAt(slot("confirm"))); } } if let Some(undo) = command.undo.as_ref().filter(|id| !self.is_unavailable(id)) { let back = declared .contains(undo.as_str()) .then(|| self.command(undo)) .flatten() .ok_or_else(|| DefinitionError::UnknownCommand { slot: slot("undo"), id: undo.clone(), })?; if !changes || command.asks_first() { return Err(requires( slot("undo"), "a_command_that_changes_something_without_asking", )); } if back.id == command.id || back.kind != CommandKind::Update || back.asks_first() { return Err(requires( slot("undo"), "another_update_command_that_does_not_ask", )); } } if command.confirm.is_some() && !command.asks_first() { return Err(requires(slot("confirm"), "a_command_that_asks_first")); } // A destroying act is rose and always held; going somewhere does nothing. match command.does { Some(CommandDoes::Destroys) if !command.asks_first() => { return Err(requires( slot("does"), "a_command_that_asks_first_destructive_or", )); } Some(_) if !changes => { return Err(requires(slot("does"), "a_command_that_changes_something")) } _ => {} } Ok(()) } /// A `copy` names what it copies and nothing else: it runs no verb, picks /// nothing, asks nothing and says nothing — the card stamps "Copied". fn validate_copy(&self, command: &RecordCommand) -> Result<(), DefinitionError> { let slot = |key: &str| format!("commands.{}.{key}", command.id); let Some(copies) = &command.copies else { return Err(requires(slot("kind"), "the_column_it_copies")); }; if command.kind != CommandKind::Copy { return Err(requires(slot("copies"), "a_copy_command")); } if copies != COPY_SEALED { self.named("commands.copies", copies, None)?; } let more = command.verb.is_some() || command.method.is_some() || command.data.is_some() || command.bindings.is_some() || command.pick_table.is_some() || command.pick.is_some() || command.opens.is_some() || command.view.is_some() || command.destructive.is_some() || command.confirm.is_some() || command.receipt.is_some() || command.undo.is_some() || command.does.is_some(); if more { return Err(requires( slot("copies"), "nothing_but_what_it_copies_and_when", )); } for (column, _) in command.when.iter().flat_map(OrderedMap::iter) { self.named("commands.when", column, None)?; } Ok(()) } } #[cfg(test)] #[path = "commands_tests.rs"] mod tests;