//! A CARD: one record drawn alone above the strip and the fan (programme//! cardtrial, 22 Oct 2026, a trial beside today's faces). A table or a view//! may carry a `card` block; while the phone's "Try cards" switch is on, a//! view of such a table is drawn as a deck of these, one in front.//!//! Everything a card shows is named here as data: which face draws it,//! which column fills each of the face's places, which facts may stand in its//! top corner ("why it is here now"), and whether it carries the pace art.//! The core resolves a record's card at read (`records::card`); the app draws//! what it is handed and composes no words of its own.//!//! ```json//! "card": {//! "face": "todo.card",//! "fields": [{"slot": "check", "column": "status"},//! {"slot": "title", "column": "title"},//! {"slot": "body", "column": "notes"},//! {"slot": "date", "column": "due_at", "form": "weekday_date"}],//! "corner": [{"column": "due_at", "form": "late", "within": 1}],//! "art": "pace",//! "pace": {"date": "due_at", "done": {"column": "status", "values": ["done", "dropped", "missed"]},//! "repeat": "recurrence_id"}//! }//! ```//!//! A MARK drawn over the card at rest acts on its record (owner, 3 Nov//! 2026: "marking a todo as done is just having a check mark"): the table//! binds each mark the ink reads ([`MARKS`]) to one of its commands, as data//! — `"marks": {"check": "done"}` — and the deck runs that command on the//! card's record as its acts would. Letters search, marks act.use serde::{Deserialize, Serialize};usesuper::{ColumnType, CommandKind, DefinitionError, Form, TableDefinition, ValueMatch};/// The marks the ink reads that a table may bind to a command/// (`TableDefinition::marks`).pubconst MARKS: &[&str] = &["check"];implTableDefinition {/// Each mark is one the ink reads, bound to one of the table's commands/// that runs on the record at once: an update that neither asks first/// nor picks, never a list's act.pub(super) fn validate_marks(&self) -> Result<(), DefinitionError> {for (mark, id) inself.marks.iter().flatten() {if !MARKS.contains(&mark.as_str()) {returnErr(DefinitionError::UnknownChoice { slot: "marks".into(), column: "marks".into(), value: mark.clone() }); }let slot = format!("marks.{mark}");ifself.is_unavailable(id) {continue; }letSome(command) = self.command(id) else {returnErr(DefinitionError::UnknownCommand { slot, id: id.clone() }); };let runs_at_once = command.kind == CommandKind::Update && !command.asks_first() && command.list.is_none() && command.pick.is_none() && command.picks.is_none() && command.pick_table.is_none() && command.sheet.is_none();if !runs_at_once {returnErr(DefinitionError::Requires { slot, needs: "an_update_command_that_does_not_ask" }); } }Ok(()) }}/// A table's or a view's card.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructCardFace {/// The face that draws it, by its open id.pub face: FaceId,/// Ordered faces the person may wear; absent, only `face`. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub offers: Vec<FaceId>,/// Faces tried in order; the first matching choice wears its face. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub faces: Vec<FaceByValue>,/// The face's places, each filled from one column, in the order drawn. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub fields: Vec<CardField>,/// The facts the top corner may say, tried in order; the first that/// holds is said, and none is said when none holds. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub corner: Vec<CornerFact>,/// The art the card carries; absent, none. #[serde(default, skip_serializing_if = "Option::is_none")]pub art: Option<CardArt>,/// What the pace is read from; present exactly when `art` is `pace`. #[serde(default, skip_serializing_if = "Option::is_none")]pub pace: Option<PaceInputs>,/// The text columns the card turns to after its face, in order, each/// cut into the pages it fills (a meeting's summary, its decisions, its/// transcript). Absent, the body place's column is the one page after. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub pages: Vec<String>,/// The parts a record opens into, when it is a whole made of them: an/// album its tracks, a series its seasons, a season its episodes, a/// story its scenes. The deck turns the fan into these. Absent, the/// record is no whole. #[serde(default, skip_serializing_if = "Option::is_none")]pub opens: Option<CardOpens>,}/// A face worn while a choice column holds one of the named values.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructFaceByValue {pub when: ValueMatch,pub face: FaceId,}/// The parts table a whole opens into: its records whose `by` link names the/// whole, in `order`; with `through`, each part stands for the record its/// link column names (a playlist's entries are its tracks).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructCardOpens {/// The parts' table.pub table: String,/// The parts' link column naming the whole.pub by: String,/// The parts' columns they are dealt in, first to last. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub order: Vec<String>,/// A link column of the parts' naming the record each part stands for. #[serde(default, skip_serializing_if = "Option::is_none")]pub through: Option<String>,/// The records that are wholes, when not every one is: those whose/// choice column holds one of these values (a film opens into its/// seasons only while its kind is series). Absent, every record opens. #[serde(default, skip_serializing_if = "Option::is_none")]pub when: Option<ValueMatch>,}/// Every whole among `tables` opens into parts that are there and read back/// to it: the parts table is one of `tables`, its `by` column links to the/// whole's table, each `order` column is the parts', and `through` is a link;/// `when` reads a choice column of the whole's own and names only its/// choices. A package's tables are checked together, as a whole and its/// parts arrive together.pubfn validate_openings(tables: &[TableDefinition]) -> Result<(), DefinitionError> {for whole in tables {letSome(opens) = whole.card.as_ref().and_then(|card| card.opens.as_ref()) else { continue };let bad = |why: String| DefinitionError::BadSlot { slot: "card.opens".into(), why };let parts = tables .iter() .find(|table| table.id == opens.table) .ok_or_else(|| bad(refusal("card.opens_parts", &[("whole", &whole.id), ("parts", &opens.table)])))?;let link = |key: &str| parts.column(key).filter(|column| column.column_type == ColumnType::Link);if link(&opens.by).and_then(|column| column.link_to.as_deref()) != Some(whole.id.as_str()) || opens.order.iter().any(|key| parts.column(key).is_none()) || opens.through.as_deref().is_some_and(|key| link(key).and_then(|column| column.link_to.as_deref()).is_none()) {returnErr(bad(refusal("card.opens_parts", &[("whole", &whole.id), ("parts", &opens.table)]))); }ifletSome(when) = &opens.when {let choices = whole .column(&when.column) .filter(|column| column.column_type == ColumnType::Choice) .and_then(|column| column.choices.as_deref());if when.values.is_empty() || !choices.is_some_and(|choices| when.values.iter().all(|value| choices.contains(value))) {returnErr(bad(refusal("card.opens_when", &[("whole", &whole.id)]))); } } }Ok(())}/// A face's open id: the name a kit gives the face that draws a card/// (`"face": "todo.card"`). The app holds its faces in Loom's registry/// (`apps/loom/faces.json`) and, until each moves there, in CottonUI/// (`apps/loom/faces-pending.json`); `pnpm gen:faces` writes the two together/// into `face_ids.json` beside this file, which the build compiles in. An id/// is lowercase words of letters, digits and `_`, each a letter first, joined/// by `.` (`todo`, `kitchen.dish`).////// Only a face the app draws is a `FaceId`: an authored definition naming any/// other is refused with the id named, and a device reads a card naming one/// a newer build drew as no card (`face_or_absent`).#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]pubstructFaceId(&'static str);mod known { include!(concat!(env!("OUT_DIR"), "/face_ids.rs"));}implFaceId {/// The group face (`records::card::deal_groups`): the core deals one card/// per record its people place names.pubconst GROUP: FaceId = FaceId("group");/// The face the app draws by `id`, or `None` when it draws none.pubfn known(id: &str) -> Option<FaceId> { known::KNOWN_FACES.binary_search(&id).ok().map(|at| FaceId(known::KNOWN_FACES[at])) }/// Every face the app draws, by id.pubfn all() -> implIterator<Item = FaceId> { known::KNOWN_FACES.iter().map(|id| FaceId(id)) }pubfn as_str(self) -> &'static str {self.0 }}impl std::fmt::DisplayforFaceId {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(self.0) }}implPartialEq<&str> forFaceId {fn eq(&self, other: &&str) -> bool {self.0 == *other }}implSerializeforFaceId {fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { serializer.serialize_str(self.0) }}impl<'de> Deserialize<'de> forFaceId {fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {let id = std::borrow::Cow::<'de, str>::deserialize(deserializer)?;FaceId::known(&id).ok_or_else(|| serde::de::Error::custom(unknown_face(&id))) }}/// Why a card naming `id` is refused: the app draws no face by that id.pubfn unknown_face(id: &str) -> String { refusal("card.unknown_face", &[("id", &format!("{id:?}"))])}/// One place on a face and the column that fills it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructCardField {pub slot: CardSlot,/// The column that fills the place. Absent exactly on the group place,/// which reads the record's own group. #[serde(default, skip_serializing_if = "Option::is_none")]pub column: Option<String>,/// On the state place: the values of its choice column whose label is/// said; any other value says nothing. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub only: Vec<String>,/// How the value in this place is said (contract 6, T1's [`Form`]),/// checked against the column's type. Absent on a date, the weekday date. #[serde(default, skip_serializing_if = "Option::is_none")]pub form: Option<Form>,/// More columns said in the same place after the first, each as its own/// words, joined by the `cards` set's `join` line ("Architect · Studio/// Iyer · Bengaluru"); an empty one is left out. #[serde(default, skip_serializing_if = "Vec::is_empty")]pub also: Vec<String>,/// A line of the `cards` set (under `field.`) the place is said inside:/// `{said}` is the first column's words and each `also` column fills the/// placeholder named by its key ("Last spoke {said} on {thread_channel}")./// The place is left empty when a placeholder has no value. #[serde(default, skip_serializing_if = "Option::is_none")]pub line: Option<String>,/// On the people place: how many it names at most; the rest are said as/// a count (the `cards` set's `people.more`, "+2"). #[serde(default, skip_serializing_if = "Option::is_none")]pub max: Option<u32>,/// A line of the `cards` set (under `label.`) said as this place's label/// on this card, over the face's own (Money's Future says its date/// "Due"); it reaches the face under `fields.labels`, keyed by place. #[serde(default, skip_serializing_if = "Option::is_none")]pub label: Option<String>,/// On the amount, expires and holder places: the key of the column's/// object the value is kept under (a document's facts: `total_minor`,/// its currency under `currency`; `expires_on`). #[serde(default, skip_serializing_if = "Option::is_none")]pub at: Option<String>,/// On the photo place: a choice column of the record a tap on the/// picture chooses, on the shell's fan of that column's choices, in the/// viewer's place (an event's picture chooses its kind). #[serde(default, skip_serializing_if = "Option::is_none")]pub chooses: Option<String>,/// On the body place: its words are Markdown, set as such wherever the/// record is read (a note's page, its search snippet). The card's word,/// not the column's: the card is the build's on every table, so it/// reaches a database whose column was defined before the flag. #[serde(default, skip_serializing_if = "std::ops::Not::not")]pub markdown: bool,}/// The places a face draws. A face draws the places it knows and passes over/// the rest, so a definition may name a place another face reads.#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pubenumCardSlot {/// The record's done state, drawn as a checkbox (a choice column).Check,Title,Subtitle,/// The longer words under the title.Body,/// The date at the foot.Date,Place,/// The city named by a person’s existing card definition.City,Photo,/// Who the record came from, said in its own words (a document's/// issuer: "From Studio Iyer"). A card never shows a record number/// (owner's ruling, 22 Oct 2026).Source,/// When the record was last in touch, said around its form (a person's/// "Last spoke 3 months ago on WhatsApp").Reached,/// A recording's or a film's length ("0:42").Length,/// The people a record is with (an event's guests): a link column, each/// linked record said as its name and the key of its picture, read once/// per answer by the caller (a read carries no link expansion).People,/// The name of the group the record stands in, when it stands in one;/// read from the record's own membership, never a column.Group,/// A choice column's label, said only for the values the field names in/// `only` (a todo's "Dropped"): the state a person should see beside the/// date, and nothing while the record is simply open. A yes/no column/// in `also` that is set stands there first, said by its own name (a/// film "Converting on your Mac").State,/// A sum of money, said in its currency ("₹1,250.00"; an amount column,/// the money form unless the field names another).Amount,/// The account money moved through: a link column, said as the linked/// record's name, read once per answer by the caller like the people.Account,/// A number kept masked as stored ("•• 4242"), said as it is.Mask,/// How many the record holds (an email thread's emails), said as a count.Count,/// Whether the record waits to be read, drawn as a dot: a yes/no column,/// or a choice column with its unread values named in `only`.Unread,/// The gauge's filled part (a number column): of `limit` when the card/// has one, else out of a hundred.Used,/// The gauge's empty part (a number column), of `limit`: a card names/// `used` or `free`, never both.Free,/// The gauge's whole (a number column).Limit,/// The period a figure is for or runs out with ("Monthly", "resets in/// 2d 23h"), said in words; a choice column says its label.Period,/// What a recurring payment costs each period (an amount column).Price,/// When a recurring payment is next taken (a date column), said as the/// date place is.NextCharge,/// The age a yearly date comes round to next ("turns 35"): a yearly date/// column kept with its year; a day kept without one says nothing.Turns,/// Whether wishes go out on the day: a yes/no column, drawn as a switch.Wishes,/// When the person was last wished (a date column), said against today/// unless the field names another form.LastWished,/// The days a record spans (an album's trip): its first day's date column/// and, in `also`, its last day's — "Sat 3 Oct – Fri 9 Oct", or the one/// day where they are the same or the last is not kept.Span,/// The file a card plays (a track's recording): a file column, said as/// the file's key, never words.Play,/// A few facts, each said under its column's label as the record page/// said it: the field's column, then each of `also`, in order; one with/// no value is left out. A link or a secret is never a fact.Facts,/// The record's number in its order (a scene's 12): a number column,/// said as the figure alone.Number,/// A line quoted from the work (a book's favourite quote), said as kept.Quote,/// A short note in the owner's own words, said as kept.Note,/// The choice a face draws in (a highlight's pencil colour): a choice/// column, said as its stored value and never its label, since the face/// picks its ink by the value and the label is copy.Ink,/// Who directed a film, said as kept.Director,/// Who recommended the record: a link to a person, said as their name,/// read once per answer by the caller like the people; or, where the/// link is empty, the name kept in `also`'s text column.RecommendedBy,/// Whom the owner watched or did it with, said as kept.WatchedWith,/// A machine's memory dial: the used part (a number column) of the whole/// in `also`, said as the two numbers `{used, total}` the face draws.MemoryDial,/// A machine's disk dial, as the memory dial: `{used, total}`.DiskDial,/// A machine's load dial: its load (a number column) of its cores in/// `also`, as `{used, total}`.LoadDial,/// The whole hours until a date column's instant, on the reader's clock/// ("38 hours left", "Under an hour left", "Has reset").HoursLeft,/// The weekday a date column's instant falls on, in the reader's zone/// ("resets Sunday"); nothing once it has passed.ResetsOn,/// The last few readings for a trend line: a text column holding a list/// of numbers, said as the numbers, oldest first.Trend,/// A share in words ("62 percent used"): a number column said through/// the field's line.Share,/// What the machine is ("Mac mini", "MacBook Pro"), said as kept: the/// face draws its picture by it.Model,/// When the record was begun (a book's first day of reading): a date/// column, said as the date place is.Started,/// When the record was last read (a book's page last turned): a date/// column, said as the date place is.LastRead,/// How many pages the record has (a book's): a number column, handed/// to the face as the number it reckons a place in pages with, never/// words.Pages,/// The year the record is of (an album's), said as kept; a date column/// says its year alone.Year,/// The whole the record sits in (a scene's story), said as its/// title, for the crumb over the card.Crumb,/// How the person was last wished (a choice column: a call, WhatsApp),/// said in its choice's label.WishedVia,/// A number to call the person on: a phone column, its first number/// said as kept.Phone,/// The album the record is in: a link column, said as the first linked/// album's name, read once per answer by the caller like the people.Album,/// The word the record is filed under (a transaction's category), said/// as kept; a choice says its label.Tag,/// When the record runs out (a document's expiry): a date column, or a/// day kept under `at` in a column's object, said as the date place is.Expires,/// Whose the record is (a document's holder): a text column, or a name/// kept under `at` in a column's object, said as kept.Holder,/// When the record ends (an event's end): a date column, with its start's/// in `also`; said as its clock alone on the day it starts ("8:00 pm"),/// else as its weekday date, with its clock when it keeps one.Ends,/// How the record repeats (an event's rule), said in words as its page/// says it ("Every week on Tuesday").Repeats,/// Who keeps the record in step: the column the table's `kept_by` reads,/// said in that block's own words ("Kept by your assistant") while it/// holds a value, never the value itself.KeptBy,/// The mood a page is sealed with (a diary's wax seal): a choice column,/// said as its stored value, since the face picks the wax by the value/// and the label is copy; no value leaves the seal unpressed.Seal,/// The day's weather drawn as a small glyph: a choice column, said as/// its stored value, the face drawing the glyph by it.Weather,/// Whether the record is starred (a diary's ribbon pulled out): a yes/no/// column, said as yes or no, never words.Star,}/// One fact the corner may say: a date column said in a [`Form`], while/// the fact calls for attention — the date at most `within` days ahead (a day/// behind always calls), or at least `behind` days back. `line` names a line/// of the `cards` set the form's words are said inside (`{said}`): "Not/// reached in {said}".#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructCornerFact {pub column: String,pub form: Form, #[serde(default, skip_serializing_if = "Option::is_none")]pub within: Option<u32>, #[serde(default, skip_serializing_if = "Option::is_none")]pub behind: Option<u32>, #[serde(default, skip_serializing_if = "Option::is_none")]pub line: Option<String>,/// Said only once the record is finished (a todo's "Done yesterday"):/// a finished record says its done facts and no other, an open record/// says no done fact. A done fact needs the card's pace, which says/// when the record is finished. #[serde(default, skip_serializing_if = "std::ops::Not::not")]pub done: bool,/// Said only while the date is today or ahead (an event's "in 6 days"):/// a date gone says nothing, where a window otherwise lets a day behind/// always call. #[serde(default, skip_serializing_if = "std::ops::Not::not")]pub ahead: bool,}/// The art a card may carry.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "lowercase")]pubenumCardArt {/// The pace animal on a band's paper (`transforms::pace`).Pace,}/// What a record's pace is read from: the date it is owed by, the values of/// a column that say it is finished, and the column that says it repeats.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructPaceInputs {pub date: String,pub done: ValueMatch, #[serde(default, skip_serializing_if = "Option::is_none")]pub repeat: Option<String>,}/// A card as a device on this build reads it (`tolerant`): a face this/// build cannot draw reads as no card, so the table falls back to its page,/// and a place it does not name is left off the face; the rest reads as it/// came.pubfn face_or_absent<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<CardFace>, D::Error> {use serde::de::Erroras _;use serde_json::Value;letmut value = Value::deserialize(deserializer)?;if value.is_null() {returnOk(None); }let faces = value.get("faces").and_then(Value::as_array).into_iter().flatten().filter_map(|rule| rule.get("face"));ifletSome(face) = value.get("face").into_iter().chain(faces).find(|face| face.as_str().is_some_and(|id| FaceId::known(id).is_none())) {super::tolerant::fell_back(face);returnOk(None); }ifletSome(Value::Array(fields)) = value.get_mut("fields") { fields.retain(|field| match field.get("slot") {Some(slot) ifsuper::tolerant::unnamed::<CardSlot>(slot) => {super::tolerant::fell_back(slot);false } _ => true, }); } serde_json::from_value(value).map(Some).map_err(D::Error::custom)}/// A card refusal said in the refusal set's `card` words, its pieces filled.fn refusal(line: &str, fills: &[(&str, &str)]) -> String {crate::rules::shell_lines::LineSet::shipped("refusal").and_then(|set| set.say(line, fills)).unwrap_or_else(|| line.to_string())}implCardFace {/// The card checked against the table it draws: every column it names/// exists, and each is of the type its place or fact reads.pubfn validate(&self, table: &TableDefinition, slot: &str) -> Result<(), DefinitionError> {let bad = |why: String| DefinitionError::BadSlot { slot: slot.into(), why };let column = |name: &str| table.column(name).ok_or_else(|| bad(format!("names {name:?}, which {} does not have", table.id)));let date = |name: &str, yearly: bool| -> Result<(), DefinitionError> {let held = column(name)?;if held.column_type != ColumnType::Date || held.yearly.unwrap_or(false) != yearly {let want = if yearly { "a yearly date" } else { "a date" };returnErr(bad(format!("reads {name:?} as {want}"))); }Ok(()) };if !self.offers.is_empty() {if !self.offers.contains(&self.face) {returnErr(bad(refusal("card.offers_include_face", &[]))); }let unique: std::collections::BTreeSet<_> = self.offers.iter().collect();if unique.len() != self.offers.len() {returnErr(bad(refusal("card.offers_unique", &[]))); } }for rule in &self.faces {let held = column(&rule.when.column)?;let choices = held.choices.as_deref().unwrap_or_default();if held.column_type != ColumnType::Choice || rule.when.values.is_empty() || rule.when.values.iter().any(|value| !choices.contains(value)) {returnErr(bad(refusal("card.faces_choice", &[]))); } }for name in &self.pages {if !matches!(column(name)?.column_type, ColumnType::Text | ColumnType::Longtext) {returnErr(bad(refusal("card.pages_text", &[("column", &format!("{name:?}"))]))); } }letmut seen = std::collections::BTreeSet::new();for field in &self.fields {if !seen.insert(field.slot) {returnErr(bad(format!("fills {:?} once", field.slot))); }letSome(name) = &field.column else {if field.slot == CardSlot::Group && field.form.is_none() && field.also.is_empty() && field.line.is_none() && field.only.is_empty() && field.max.is_none() {continue; }returnErr(bad(refusal("card.field_column", &[("slot", &format!("{:?}", field.slot))]))); };if field.slot == CardSlot::Group {returnErr(bad(refusal("card.group_column", &[]))); }let held = column(name)?;if field.slot == CardSlot::State {let choices = held.choices.as_deref().unwrap_or_default();if held.column_type != ColumnType::Choice || field.only.is_empty() || field.only.iter().any(|value| !choices.contains(value)) {returnErr(bad(refusal("card.state_only", &[]))); }if field.also.iter().any(|flag| column(flag).map_or(true, |flag| flag.column_type != ColumnType::Bool)) {returnErr(bad(refusal("card.state_flags", &[]))); } } elseif field.slot == CardSlot::Unread {let choices = held.choices.as_deref().unwrap_or_default();let reads = match held.column_type {ColumnType::Bool => field.only.is_empty(),ColumnType::Choice => !field.only.is_empty() && field.only.iter().all(|value| choices.contains(value)), _ => false, };if !reads || field.form.is_some() {returnErr(bad(refusal("card.unread_column", &[]))); } } elseif !field.only.is_empty() {returnErr(bad(refusal("card.only_on_state", &[]))); }let plain = field.form.is_none() && field.also.is_empty() && field.line.is_none();if field.markdown && (field.slot != CardSlot::Body || !plain || !matches!(held.column_type, ColumnType::Text | ColumnType::Longtext)) {returnErr(bad(refusal("card.markdown_body", &[]))); }if field.at.is_some() {let kept = matches!(field.slot, CardSlot::Amount | CardSlot::Expires | CardSlot::Holder);if !kept || !plain || !matches!(held.column_type, ColumnType::Text | ColumnType::Longtext) {returnErr(bad(refusal("card.at_object", &[]))); } }ifletSome(label) = &field.label {let said = crate::rules::shell_lines::LineSet::shipped("cards").and_then(|cards| cards.say(label, &[]));if !label.starts_with("label.") || said.is_none() {returnErr(bad(refusal("card.field_label", &[("line", &format!("{label:?}"))]))); } }match field.slot {CardSlot::Accountif held.column_type != ColumnType::Link || held.link_to.is_none() || !plain => {returnErr(bad(refusal("card.account_link", &[]))) }CardSlot::Albumif held.column_type != ColumnType::Link || held.link_to.is_none() || !plain => {returnErr(bad(refusal("card.album_link", &[]))) }CardSlot::WishedViaif held.column_type != ColumnType::Choice || !plain => {returnErr(bad(refusal("card.wished_via_choice", &[]))) }CardSlot::Inkif held.column_type != ColumnType::Choice || !plain => {returnErr(bad(refusal("card.ink_choice", &[]))) }CardSlot::Seal | CardSlot::Weatherif held.column_type != ColumnType::Choice || !plain => {returnErr(bad(refusal("card.drawn_choice", &[("slot", &format!("{:?}", field.slot))]))) }CardSlot::Starif held.column_type != ColumnType::Bool || !plain => {returnErr(bad(refusal("card.star_switch", &[]))) }CardSlot::Phoneif held.column_type != ColumnType::Text || !plain => {returnErr(bad(refusal("card.phone_text", &[]))) }CardSlot::Endsif held.column_type != ColumnType::Date || field.form.is_some() || field.line.is_some() || field.also.len() != 1 || field.also.iter().any(|start| column(start).map_or(true, |start| start.column_type != ColumnType::Date)) => {returnErr(bad(refusal("card.ends_dates", &[]))) }CardSlot::Repeatsif held.format != Some(super::ColumnFormat::RepeatRule) || !plain => {returnErr(bad(refusal("card.repeats_rule", &[]))) }CardSlot::KeptByif table.kept_by.as_ref().is_none_or(|kept| &kept.when != name) || !plain => {returnErr(bad(refusal("card.kept_by_column", &[]))) }CardSlot::Expiresif held.column_type != ColumnType::Date && field.at.is_none() => {returnErr(bad(refusal("card.date_place", &[("column", &format!("{name:?}"))]))) }CardSlot::Holderif held.column_type != ColumnType::Text && field.at.is_none() => {returnErr(bad(refusal("card.at_object", &[]))) }CardSlot::Used | CardSlot::Free | CardSlot::Limit | CardSlot::Pagesif held.column_type != ColumnType::Number || !plain => {returnErr(bad(refusal("card.gauge_number", &[("slot", &format!("{:?}", field.slot))]))) }CardSlot::Amount | CardSlot::Priceif held.column_type != ColumnType::Amount && field.at.is_none() => {returnErr(bad(refusal("card.amount_place", &[("slot", &format!("{:?}", field.slot))]))) }CardSlot::Countif held.column_type != ColumnType::Number => {returnErr(bad(refusal("card.count_number", &[]))) }CardSlot::NextCharge | CardSlot::LastWished | CardSlot::Started | CardSlot::LastReadif held.column_type != ColumnType::Date => {returnErr(bad(refusal("card.date_place", &[("column", &format!("{name:?}"))]))) }CardSlot::Turnsif held.column_type != ColumnType::Date || held.yearly != Some(true) || !plain => {returnErr(bad(refusal("card.turns_yearly", &[]))) }CardSlot::Wishesif held.column_type != ColumnType::Bool || !plain => {returnErr(bad(refusal("card.wishes_switch", &[]))) }CardSlot::Spanif held.column_type != ColumnType::Date || field.form.is_some() || field.line.is_some() || field.also.len() > 1 => {returnErr(bad(refusal("card.span_dates", &[]))) }CardSlot::Playif held.column_type != ColumnType::File || !plain => {returnErr(bad(refusal("card.play_file", &[]))) }CardSlot::MemoryDial | CardSlot::DiskDial | CardSlot::LoadDialif held.column_type != ColumnType::Number || field.form.is_some() || field.line.is_some() || field.also.len() != 1 || field.also.iter().any(|whole| column(whole).map_or(true, |whole| whole.column_type != ColumnType::Number)) => {returnErr(bad(refusal("card.dial_numbers", &[("slot", &format!("{:?}", field.slot))]))) }CardSlot::HoursLeft | CardSlot::ResetsOnif held.column_type != ColumnType::Date || !plain => {returnErr(bad(refusal("card.quota_places", &[("slot", &format!("{:?}", field.slot)), ("wanted", &"date")]))) }CardSlot::Trendif !matches!(held.column_type, ColumnType::Text | ColumnType::Longtext) || !plain => {returnErr(bad(refusal("card.quota_places", &[("slot", &format!("{:?}", field.slot)), ("wanted", &"text")]))) }CardSlot::RecommendedByif !(held.column_type == ColumnType::Text || held.column_type == ColumnType::Link && held.link_to.is_some()) || field.form.is_some() || field.line.is_some() || field.also.len() > 1 || field.also.iter().any(|key| column(key).map_or(true, |also| also.column_type != ColumnType::Text)) => {returnErr(bad(refusal("card.recommended_by", &[]))) }CardSlot::Factsif field.form.is_some() || field.line.is_some() => {returnErr(bad(refusal("card.facts_plain", &[]))) } _ => {} }if field.slot == CardSlot::People {let linked = held.column_type == ColumnType::Link && held.link_to.is_some();if !linked || field.form.is_some() || !field.also.is_empty() || field.line.is_some() || field.max == Some(0) {returnErr(bad(refusal("card.people_link", &[]))); } } elseif field.max.is_some() {returnErr(bad(refusal("card.max_on_people", &[]))); }ifletSome(chosen) = &field.chooses {let held = column(chosen)?;let written = held.column_type == ColumnType::Choice && held.multiple != Some(true) && held.readonly != Some(true) && held.computed.is_none() && held.choices.as_ref().is_some_and(|choices| !choices.is_empty());if field.slot != CardSlot::Photo || !written {returnErr(bad(refusal("card.chooses_choice", &[]))); } }match field.slot {CardSlot::Checkif held.column_type != ColumnType::Choice => {returnErr(bad("the check reads a choice column".into())) }CardSlot::Checkif field.form.is_some() => returnErr(bad("the check names no form".into())),CardSlot::Dateif held.column_type != ColumnType::Date => {returnErr(bad(refusal("card.date_place", &[("column", &format!("{name:?}"))]))) } _ => {} }ifletSome(form) = field.form { form.fits(held).map_err(|needs| { bad(refusal("card.form_needs", &[("form", &format!("{form:?}")), ("column", &format!("{name:?}")), ("needs", &super::refusal_words(needs))], )) })?; }for also in &field.also {let joined = column(also)?;if field.slot == CardSlot::Span && joined.column_type != ColumnType::Date {returnErr(bad(refusal("card.span_dates", &[]))); } }if field.slot == CardSlot::Facts {for fact in std::iter::once(name).chain(&field.also) {let fact = column(fact)?;if fact.column_type == ColumnType::Link || fact.secret == Some(true) {returnErr(bad(refusal("card.facts_plain", &[]))); } } }ifletSome(line) = &field.line {// A line with plural forms is picked by the column's count (`{n}`).let said = crate::rules::shell_lines::LineSet::shipped("cards").and_then(|cards| cards.say(line, &[("said", ""), ("n", "1")]));if !line.starts_with("field.") || said.is_none() {returnErr(bad(refusal("card.field_line", &[("line", &format!("{line:?}"))]))); } } }let fills = |slot: CardSlot| self.fields.iter().any(|field| field.slot == slot);if fills(CardSlot::Used) && fills(CardSlot::Free) {returnErr(bad(refusal("card.used_or_free", &[]))); }if fills(CardSlot::Free) && !fills(CardSlot::Limit) {returnErr(bad(refusal("card.free_of_limit", &[]))); }ifself.fields.iter().any(|field| field.slot == CardSlot::Check) && self.pace.is_none() {returnErr(bad("a check says the pace's done state, so the card names its pace".into())); }for fact in &self.corner {let held = column(&fact.column)?;if held.column_type != ColumnType::Date {returnErr(bad(format!("the corner reads {:?} as a date", fact.column))); } fact.form.fits(held).map_err(|needs| { bad(refusal("card.form_needs", &[("form", &format!("{:?}", fact.form)), ("column", &format!("{:?}", fact.column)), ("needs", &super::refusal_words(needs))], )) })?;if fact.done && self.pace.is_none() {returnErr(bad(refusal("card.done_fact_pace", &[]))); }if fact.within.is_some() == fact.behind.is_some() {returnErr(bad("a corner fact names one window: within or behind".into())); }ifletSome(line) = &fact.line {let said = crate::rules::shell_lines::LineSet::shipped("cards") .and_then(|cards| cards.say(line, &[("said", "")]));if !line.starts_with("corner.") || said.is_none() {returnErr(bad(format!("{line:?} is no corner line of the cards set"))); } } }// A group card is dealt per record its people place names.ifself.face == FaceId::GROUP && !self.fields.iter().any(|field| field.slot == CardSlot::People) {returnErr(bad(refusal("card.group_by", &[]))); }match (&self.art, &self.pace) { (Some(CardArt::Pace), None) => returnErr(bad("the pace art needs pace".into())), _ => {} }ifletSome(pace) = &self.pace { date(&pace.date, false)?;let done = column(&pace.done.column)?;let choices = done.choices.as_deref().unwrap_or_default();if done.column_type != ColumnType::Choice || pace.done.values.is_empty() || pace.done.values.iter().any(|value| !choices.contains(value)) {returnErr(bad("pace.done names values of a choice column".into())); }ifletSome(repeat) = &pace.repeat { column(repeat)?; } }Ok(()) }}#[cfg(test)]mod tests {usesuper::*;usecrate::definitions::builtin_table_definitions;use serde_json::json;fn todo() -> TableDefinition { builtin_table_definitions().iter().find(|table| table.id == "todo").unwrap().clone() }fn card(value: serde_json::Value) -> CardFace { serde_json::from_value(value).unwrap() }// RULE: a card names columns its table has, each of the type its place// reads — the app draws a card's places without checking them, so a// wrong column is refused at save, never drawn as nothing. #[test]fn a_card_reads_columns_of_the_right_type() {let table = todo();let pace = json!({"date": "due_at", "done": {"column": "status", "values": ["done"]}});for (bad, why) in [ (json!({"face": "todo.card", "fields": [{"slot": "title", "column": "nope"}]}), "missing column"), (json!({"face": "todo.card", "fields": [{"slot": "date", "column": "title"}]}), "date place on text"), (json!({"face": "todo.card", "fields": [{"slot": "check", "column": "title"}], "pace": pace}), "check on text"), (json!({"face": "todo.card", "fields": [{"slot": "title", "column": "title", "form": "relative"}]}), "date form on text"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "next_occurrence", "within": 7}]}), "yearly form on a plain date"), (json!({"face": "todo.card", "corner": [{"column": "title", "form": "late", "within": 1}]}), "corner on text"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "money", "within": 1}]}), "money on a date"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "late"}]}), "no window"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "late", "within": 1, "behind": 3}]}), "two windows"), (json!({"face": "todo.card", "corner": [{"column": "due_at", "form": "late", "within": 1, "line": "deck.search"}]}), "not a corner line"), (json!({"face": "todo.card", "art": "pace"}), "art without pace"), (json!({"face": "todo.card", "art": "pace", "pace": {"date": "due_at", "done": {"column": "status", "values": ["finished"]}}}), "done value not a choice"), ] { assert!(card(bad).validate(&table, "card").is_err(), "{why}"); } card(json!({"face": "todo.card", "art": "pace", "pace": pace,"fields": [{"slot": "check", "column": "status"}, {"slot": "date", "column": "due_at", "form": "relative"}],"corner": [{"column": "due_at", "form": "late", "within": 1}]})) .validate(&table, "card") .unwrap(); }// RULE (owner, 29 Oct 2026): only the photo place chooses, and it// chooses one choice column a person writes — the shell turns the fan// into that column's values on a tap of the picture, so a column it could// not write, or a place that is no picture, is refused at save; the// event's card chooses its kind. #[test]fn only_the_picture_chooses_and_it_chooses_a_choice_a_person_writes() {let find = |id: &str| builtin_table_definitions().iter().find(|table| table.id == id).unwrap().clone();let event = find("event");let photo = event.card.as_ref().unwrap().fields.iter().find(|field| field.slot == CardSlot::Photo).unwrap(); assert_eq!(photo.chooses.as_deref(), Some("kind"), "the event's picture chooses its kind");let table = event.clone();let refused = |value: serde_json::Value, why: &str| {let error = card(value).validate(&table, "card").unwrap_err().to_string(); assert!(error.contains("only the photo place chooses"), "{why}: {error}"); }; refused(json!({"face": "event.rolodex", "fields": [{"slot": "title", "column": "title", "chooses": "kind"}]}), "a title"); refused(json!({"face": "event.rolodex", "fields": [{"slot": "photo", "column": "picture", "chooses": "title"}]}), "a text"); refused(json!({"face": "event.rolodex", "fields": [{"slot": "photo", "column": "picture", "chooses": "invited"}]}), "a read-only choice"); card(json!({"face": "event.rolodex", "fields": [{"slot": "photo", "column": "picture", "chooses": "kind"}]})) .validate(&table, "card") .unwrap(); }// RULE: a card says its body is Markdown (a note's page), only on the// body place of a text column read plain; the note kit says so, rather// than the app guessing it from the face's name. #[test]fn only_the_body_place_is_markdown_and_the_note_says_so() {let find = |id: &str| builtin_table_definitions().iter().find(|table| table.id == id).unwrap().clone();let note = find("note");let body = note.card.as_ref().unwrap().fields.iter().find(|field| field.slot == CardSlot::Body).unwrap(); assert!(body.markdown, "the note's body is Markdown");let refused = |value: serde_json::Value, why: &str| {let error = card(value).validate(¬e, "card").unwrap_err().to_string(); assert!(error.contains("only the body place is Markdown"), "{why}: {error}"); }; refused(json!({"face": "note.page", "fields": [{"slot": "title", "column": "title", "markdown": true}]}), "a title"); refused(json!({"face": "note.page", "fields": [{"slot": "body", "column": "updated_at", "markdown": true}]}), "a date"); card(json!({"face": "note.page", "fields": [{"slot": "body", "column": "body", "markdown": true}]})) .validate(¬e, "card") .unwrap(); }// RULE: a card names its face by an open id, and only a face the app// draws reads: one it does not is refused with the id named, never drawn// as nothing (Loom step 5). #[test]fn a_card_names_a_face_the_app_draws() { assert_eq!(card(json!({"face": "todo.card"})).face, "todo.card");let refused = serde_json::from_value::<CardFace>(json!({"face": "hologram"})).unwrap_err().to_string(); assert!(refused.contains("\"hologram\" is no face the app draws"), "{refused}"); assert!(FaceId::known("Todo").is_none() && FaceId::known("").is_none()); assert_eq!(FaceId::known("group"), Some(FaceId::GROUP), "the core deals the group face"); assert_eq!(serde_json::to_value(FaceId::GROUP).unwrap(), json!("group")); }// RULE: the ids a card may name are face_ids.json's — Loom's registry// (apps/loom/faces.json) and the faces CottonUI still draws// (faces-pending.json), as `pnpm gen:faces` writes them, which the guard// faces-registry holds fresh — each a well-formed id, the group face// among them. #[test]fn the_known_faces_are_well_formed_ids() {let known: Vec<&str> = FaceId::all().map(FaceId::as_str).collect(); assert!(known.contains(&FaceId::GROUP.as_str()), "the core deals the group face");for id in known {let word = |word: &str| word.starts_with(|c: char| c.is_ascii_lowercase()) && word.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'); assert!(id.split('.').all(word), "{id:?} is lowercase words of letters, digits and _, joined by ."); } }// RULE: a device reads a card naming a face a newer build draws as no// card, and the row says the word it fell back on; an authored one is// refused. #[test]fn a_face_this_build_does_not_draw_reads_as_no_card() { #[derive(Deserialize)]structHeld { #[serde(deserialize_with = "face_or_absent")] card: Option<CardFace>, }let (held, words) = crate::definitions::tolerant::reading(|| serde_json::from_value::<Held>(json!({"card": {"face": "hologram"}}))); assert!(held.unwrap().card.is_none()); assert_eq!(words, ["hologram"]); } #[test]fn faces_by_value_read_only_choices_and_known_faces() {let table = todo();for (column, values) in [("status", json!([])), ("status", json!(["invented"])), ("title", json!(["done"])), ("missing", json!(["done"]))] {let card = card(json!({"face": "todo.card", "faces": [{"when": {"column": column, "values": values}, "face": "plain"}]})); assert!(card.validate(&table, "card").is_err(), "{column}: {values}"); }let held = card(json!({"face": "todo.card", "faces": [{"when": {"column": "status", "values": ["done"]}, "face": "plain"}]})); held.validate(&table, "card").unwrap(); assert_eq!(card(serde_json::to_value(&held).unwrap()), held);for face in [json!("hologram"), json!("Todo.card"), json!(7)] { assert!(serde_json::from_value::<CardFace>(json!({"face": "todo.card", "faces": [{"when": {"column": "status", "values": ["done"]}, "face": face}]})).is_err()); } assert!(serde_json::to_value(card(json!({"face": "todo.card"}))).unwrap().get("faces").is_none()); } #[test]fn offers_are_ordered_known_distinct_faces_including_the_base() {let table = todo();let offered = card(json!({"face":"todo.card", "offers":["todo.card", "plain"]})); offered.validate(&table, "card").unwrap(); assert_eq!(card(serde_json::to_value(&offered).unwrap()), offered);for offers in [json!(["plain"]), json!(["todo.card", "todo.card"])] { assert!(card(json!({"face":"todo.card", "offers":offers})).validate(&table, "card").is_err()); } assert!(serde_json::from_value::<CardFace>(json!({"face":"todo.card", "offers":["invented"]})).is_err()); assert!(serde_json::to_value(card(json!({"face":"todo.card"}))).unwrap().get("offers").is_none()); } #[test]fn a_row_key_names_a_required_writable_text_column() {letmut table: TableDefinition = serde_json::from_str(include_str!("../../kits/personal/tables/face_settings.json")).unwrap(); table.validate().unwrap();for key in ["missing", "chosen_at"] { table.row_key = Some(key.into()); assert!(table.validate().is_err()); } table.row_key = Some("table".into()); table.columns.iter_mut().find(|c| c.key == "table").unwrap().required = Some(false); assert!(table.validate().is_err()); }// RULE: every shipped card block passes its own table's check. #[test]fn every_shipped_card_is_valid() {letmut seen = 0;for table in builtin_table_definitions() {ifletSome(card) = &table.card { card.validate(table, "card").unwrap(); seen += 1; } } assert!(seen > 0, "the kit ships at least the todo card"); }// RULE: a whole opens only into parts that come with it and link back to// it — the deck turns the fan into a whole's parts by this block alone,// so a parts table that is not there, or a link that names another// table, is refused when the package is read, never dealt as nothing. #[test]fn a_whole_opens_into_parts_that_link_back_to_it() {let find = |id: &str| builtin_table_definitions().iter().find(|table| table.id == id).unwrap().clone();let (mut album, item) = (find("album"), find("album_item"));let opens = |by: &str, through: Option<&str>| -> CardOpens { serde_json::from_value(json!({"table": "album_item", "by": by, "order": ["taken_at"], "through": through})).unwrap() }; album.card.as_mut().unwrap().opens = Some(opens("album_id", None)); validate_openings(&[album.clone(), item.clone()]).unwrap();let read: CardFace = serde_json::from_value(serde_json::to_value(album.card.as_ref().unwrap()).unwrap()).unwrap(); assert_eq!(read.opens, Some(opens("album_id", None)), "the block reads back as written"); assert!(validate_openings(&[album.clone()]).is_err(), "the parts must come with the whole"); album.card.as_mut().unwrap().opens = Some(opens("record_id", None)); assert!(validate_openings(&[album.clone(), item.clone()]).is_err(), "the by column is a link to the whole"); album.card.as_mut().unwrap().opens = Some(opens("album_id", Some("caption"))); assert!(validate_openings(&[album.clone(), item.clone()]).is_err(), "through names a link");// Only some records may be wholes: those whose choice holds a value.let when = |column: &str, values: &[&str]| -> CardOpens {letmut opens = opens("album_id", None); opens.when = Some(ValueMatch { column: column.into(), values: values.iter().map(|value| value.to_string()).collect() }); opens }; album.card.as_mut().unwrap().opens = Some(when("kind", &["trip"])); validate_openings(&[album.clone(), item.clone()]).unwrap();for (bad, why) in [(when("kind", &["holiday"]), "a value that is no choice"), (when("kind", &[]), "no value"), (when("title", &["trip"]), "a column that is no choice"), (when("nope", &["trip"]), "a column the whole has not")] { album.card.as_mut().unwrap().opens = Some(bad);let refused = validate_openings(&[album.clone(), item.clone()]).unwrap_err().to_string(); assert!(refused.contains("opens only while"), "{why}: {refused}"); } }}