Cotton code
6185 lines · 245.5 KB · RustRaw
use super::*;use crate::constants::PrimitiveKind;use cotton_store::schema::decl::Codec;use cotton_store::schema::table_specs::TABLE_SPECS;use serde_json::{json, Value};use std::collections::BTreeSet;/// RULE: Handles reuse canonical identities and normalized readonly facts, so a generic record write cannot create a second identity or corrupt normalization.#[test]fn person_handles_definition_uses_the_canonical_kinds_and_person_relation() {    use crate::rules::people::handles::HandleKind;    let handle = builtin_table_definition("person_handle").expect("the Handles definition");    assert_eq!(        builtin_store_table(&handle.id),        Some("cotton_person_handles")    );    let json = serde_json::to_value(&handle).unwrap();    let choices = json["columns"]        .as_array()        .unwrap()        .iter()        .find(|c| c["key"] == "kind")        .unwrap()["choices"]        .clone();    assert_eq!(choices, json!(HandleKind::ALL.map(|kind| kind.as_str())));    for key in ["normalised", "source", "verified_at", "position"] {        assert_eq!(handle.column(key).unwrap().readonly, Some(true), "{key}");    }    let keep = handle        .commands        .as_ref()        .unwrap()        .iter()        .find(|c| c.id == "keep")        .unwrap();    assert_eq!(keep.kind, CommandKind::Update);    assert_eq!(keep.verb.as_deref(), Some("update_record"));    let remove = handle        .commands        .as_ref()        .unwrap()        .iter()        .find(|c| c.id == "remove")        .unwrap();    assert_eq!(remove.kind, CommandKind::Delete);    assert_eq!(remove.verb.as_deref(), Some("delete_record"));}/// The shared format's own example, every column type and every optional/// field spelled the way the app reads them.fn example() -> Value {    json!({        "id": "todo",        "name": "Todo",        "plural": "Todos",        "picture": "tool-todos",        "builtin": true,        "engine": "todos",        "columns": [            { "key": "title", "name": "Title", "type": "text", "required": true },            { "key": "notes", "type": "longtext" },            { "key": "due_date", "type": "date" },            { "key": "due_time", "type": "time" },            { "key": "done", "type": "bool" },            { "key": "project", "type": "link", "link_to": "project" },            { "key": "person", "type": "link", "link_to": "person", "indexed": true },            { "key": "status", "type": "choice", "choices": ["open", "done"] },            { "key": "amount", "type": "amount" },            { "key": "count", "type": "number" },            { "key": "position", "type": "number" },            { "key": "photo", "type": "photo" },            { "key": "file", "type": "file" }        ],        "title": "title",        "date": "due_date",        "project": "project",        "order": "position",        "slip": { "title": "title", "subtitle": "notes", "trailing": "due_date", "photo": null, "toggle": "done" },        "tile": { "face": "slip-list" },        "page": [            { "heading": null, "columns": ["title", "notes"] },            { "heading": "When", "columns": ["due_date", "due_time"] }        ],        "instructions": "A todo is one thing to do."    })}fn parse(value: &Value) -> TableDefinition {    serde_json::from_value(value.clone()).expect("parses")}fn refused(mutate: impl FnOnce(&mut Value)) -> DefinitionError {    let mut value = example();    mutate(&mut value);    parse(&value).validate().expect_err("refused")}/// RULE: Reading a reduced builtin must preserve its declared shape, even when a required nested word needs a shipped default; optional layouts can name columns this row does not have.#[test]fn required_defaults_do_not_add_optional_column_references() {    let value = example();    let read = TableDefinition::from_json(&value.to_string()).unwrap();    assert_eq!(read, parse(&value));    read.validate().unwrap();    let (_, media) = BUILTIN_DEFINITION_FILES.iter().find(|(id, _)| *id == "media").unwrap();    let mut value: Value = serde_json::from_str(media).unwrap();    value["viewer"]["words"].as_object_mut().unwrap().remove("fetching");    value["viewer"]["words"]["fetch"] = json!("Owner's fetch words");    // Missing optional data must stay missing while the required word is filled.    let expected: Value = serde_json::from_str(media).unwrap();    value["slip"] = json!({"title": "title"});    let read = TableDefinition::from_json(&value.to_string()).unwrap();    assert_eq!(read.slip, serde_json::from_value(value["slip"].clone()).unwrap());    let read = serde_json::to_value(read).unwrap();    assert_eq!(read["viewer"]["words"]["fetch"], value["viewer"]["words"]["fetch"]);    assert_eq!(read["viewer"]["words"]["fetching"], expected["viewer"]["words"]["fetching"]);}#[test]fn the_shared_format_round_trips_field_for_field() {    let definition = parse(&example());    definition.validate().expect("valid");    assert_eq!(serde_json::to_value(&definition).unwrap(), example());    assert_eq!(        TableDefinition::from_json(&definition.to_json()).unwrap(),        definition    );}/// RULE: A slip's player and trailing picture, the cover-grid and receipt faces and the page's part list round-trip in the shared format's exact spelling, and a definition without them round-trips without them.#[test]fn the_player_the_trailing_picture_the_cover_and_the_page_parts_round_trip() {    let mut value = example();    value["slip"]["player"] = json!("file");    value["slip"]["trailing_picture"] = json!("photo");    value["tile"]["face"] = json!("cover-grid");    value["page_parts"] = json!(["title", "facts", "script", "grid"]);    let definition = parse(&value);    definition.validate().expect("valid");    assert_eq!(definition.slip.player.as_deref(), Some("file"));    assert_eq!(definition.slip.trailing_picture.as_deref(), Some("photo"));    assert_eq!(definition.tile.face, TileFace::CoverGrid);    assert_eq!(definition.page_parts, Some(vec![PagePart::Title, PagePart::Facts, PagePart::Script, PagePart::Grid]));    assert_eq!(serde_json::to_value(&definition).unwrap(), value);    assert!(value["page"].is_array(), "page stays the array of sections");    let mut receipt = example();    receipt["tile"]["face"] = json!("receipt");    let parsed = parse(&receipt);    assert_eq!(parsed.tile.face, TileFace::Receipt);    assert_eq!(serde_json::to_value(&parsed).unwrap(), receipt);    for (part, spelled) in [        (PagePart::Title, "title"),        (PagePart::Facts, "facts"),        (PagePart::Grid, "grid"),        (PagePart::Content, "content"),        (PagePart::Messages, "messages"),        (PagePart::Script, "script"),        (PagePart::Sections, "sections"),        (PagePart::Strip, "strip"),    ] {        assert_eq!(serde_json::to_value(part).unwrap(), json!(spelled));    }    // Absent is absent: an older definition gains no keys on the way back.    let plain = parse(&example());    assert_eq!(plain.slip.player, None);    assert_eq!(plain.page_parts, None);    assert_eq!(plain.resolved_page_parts(), PLAIN_PAGE.to_vec(), "absent is the plain page, derived");    let written = serde_json::to_value(&plain).unwrap();    assert!(written["slip"].get("player").is_none());    assert!(written["slip"].get("trailing_picture").is_none());    assert!(written.get("page_parts").is_none());}/// RULE: A slip's player and trailing picture must name declared columns, and a page part is one of the fixed vocabulary, named once, in a list that is not empty.#[test]fn the_player_and_the_trailing_picture_name_declared_columns() {    for slot in ["player", "trailing_picture"] {        let error = refused(|v| v["slip"][slot] = json!("nowhere"));        assert_eq!(            error,            DefinitionError::UnknownColumn {                slot: format!("slip.{slot}"),                column: "nowhere".into()            }        );    }    let error = refused(|v| v["page_parts"] = json!(["title", "facts", "title"]));    assert_eq!(error, DefinitionError::Requires { slot: "page_parts[2]".into(), needs: "each_part_once" });    assert_eq!(refused(|v| v["page_parts"] = json!([])), DefinitionError::Empty("page_parts"));    let mut value = example();    value["page"] = json!({ "style": "plain" });    assert!(        TableDefinition::from_json(&value.to_string()).is_err(),        "page is the array of sections, never an object"    );}#[test]fn column_types_round_trip_their_shared_spellings() {    for column_type in ColumnType::ALL {        let encoded = serde_json::to_value(column_type).unwrap();        assert_eq!(serde_json::from_value::<ColumnType>(encoded).unwrap(), column_type);    }    let mut value = example();    value["columns"][1]["type"] = json!("richtext");    assert!(serde_json::from_value::<TableDefinition>(value).is_err());}/// RULE: A definition is read tolerantly — a key this build cannot name is kept (top level) or read around (deeper) so a newer device's row is relayed and drawn — and refused only where it is authored here.#[test]fn an_unknown_key_is_kept_on_read_and_refused_when_authored() {    let mut value = example();    value["colour"] = json!("blue");    let read = parse(&value);    assert_eq!(read.unknown.get("colour"), Some(&json!("blue")));    assert_eq!(serde_json::to_value(&read).unwrap()["colour"], json!("blue"), "kept on the next write");    assert_eq!(        tolerant::refuse_unknown(&value, &read, &read.unknown),        Err(DefinitionError::UnknownKeys(vec!["colour".into()]))    );    let mut value = example();    value["columns"][0]["width"] = json!(3);    let read = parse(&value);    assert_eq!(tolerant::unknown_keys(&value, &read, &read.unknown), vec!["columns.0.width".to_string()]);    assert!(tolerant::unknown_keys(&example(), &parse(&example()), &Default::default()).is_empty());}#[test]fn every_named_key_must_be_a_declared_column() {    for (slot, mutate) in [        (            "title",            Box::new(|v: &mut Value| v["title"] = json!("nope")) as Box<dyn Fn(&mut Value)>,        ),        ("date", Box::new(|v: &mut Value| v["date"] = json!("nope"))),        (            "project",            Box::new(|v: &mut Value| v["project"] = json!("nope")),        ),        (            "order",            Box::new(|v: &mut Value| v["order"] = json!("nope")),        ),        (            "slip.title",            Box::new(|v: &mut Value| v["slip"]["title"] = json!("nope")),        ),        (            "slip.trailing",            Box::new(|v: &mut Value| v["slip"]["trailing"] = json!("nope")),        ),        (            "page[1]",            Box::new(|v: &mut Value| v["page"][1]["columns"][0] = json!("nope")),        ),    ] {        assert_eq!(            refused(|v| mutate(v)),            DefinitionError::UnknownColumn {                slot: slot.into(),                column: "nope".into()            },            "{slot}"        );    }}#[test]fn a_key_must_name_a_column_of_the_type_its_slot_needs() {    assert!(matches!(        refused(|v| v["date"] = json!("title")),        DefinitionError::WrongColumnType { .. }    ));    assert!(matches!(        refused(|v| v["project"] = json!("person")),        DefinitionError::WrongColumnType {            wanted: "a_link_to_project",            ..        }    ));    assert!(matches!(        refused(|v| v["slip"]["photo"] = json!("file")),        DefinitionError::WrongColumnType { .. }    ));}#[test]fn a_link_needs_its_target_and_a_choice_its_choices() {    assert_eq!(        refused(|v| {            v["columns"][6].as_object_mut().unwrap().remove("link_to");        }),        DefinitionError::LinkWithoutTarget("person".into())    );    assert_eq!(        refused(|v| v["columns"][7]["choices"] = json!([])),        DefinitionError::ChoiceWithoutChoices("status".into())    );    assert_eq!(        refused(|v| v["columns"][0]["link_to"] = json!("person")),        DefinitionError::TargetWithoutLink("title".into())    );    assert_eq!(        refused(|v| v["columns"][0]["choices"] = json!(["a"])),        DefinitionError::ChoicesWithoutChoice("title".into())    );}#[test]fn ids_and_keys_are_lowercase() {    assert_eq!(        refused(|v| v["id"] = json!("Todo")),        DefinitionError::BadId("Todo".into())    );    assert_eq!(        refused(|v| v["id"] = json!("")),        DefinitionError::BadId("".into())    );    assert_eq!(        refused(|v| v["columns"][2]["key"] = json!("dueDate")),        DefinitionError::BadColumnKey("dueDate".into())    );    assert!(is_valid_id("story_scene"));    assert!(!is_valid_id("9lives"));}#[test]fn a_tool_round_trips_and_refuses_malformed_automations() {    let value = json!({        "id": "attendance",        "name": "Attendance",        "picture": { "photo": "photo:abc" },        "tables": ["student", "attendance"],        "instructions": "Mark who came to class.",        "automations": [],        "author": { "device": "dev-1", "name": "Asha" },        "signature": null    });    let tool = ToolDefinition::from_json(&value.to_string()).expect("parses");    tool.validate().expect("valid");    assert_eq!(        tool.picture,        Some(ToolPicture::Photo(ToolPhoto {            photo: "photo:abc".into(),            object: None,            link_object: None,        }))    );    assert_eq!(serde_json::to_value(&tool).unwrap(), value);    let mut asset = value.clone();    asset["picture"] = json!("tool-attendance");    let tool = ToolDefinition::from_json(&asset.to_string()).unwrap();    assert_eq!(        tool.picture,        Some(ToolPicture::Asset("tool-attendance".into()))    );    assert_eq!(serde_json::to_value(&tool).unwrap(), asset);    let mut busy = value.clone();    busy["automations"] = json!([{ "when": "daily" }]);    let tool = ToolDefinition::from_json(&busy.to_string()).unwrap();    assert!(matches!(tool.validate(), Err(DefinitionError::InvalidAutomation(_))));    let mut empty = value.clone();    empty["tables"] = json!([]);    let tool = ToolDefinition::from_json(&empty.to_string()).unwrap();    assert_eq!(tool.validate(), Err(DefinitionError::NoTables));    let mut nameless = value.clone();    nameless["name"] = json!("  ");    let tool = ToolDefinition::from_json(&nameless.to_string()).unwrap();    assert_eq!(tool.validate(), Err(DefinitionError::Empty("name")));}/// RULE: A tool's picture is optional, as the Swift decoder reads it: absent stays absent, a null reads as absent and is written back absent (as Swift writes it), and its photo form carries nothing else.#[test]fn a_tools_picture_is_optional_and_its_photo_form_carries_nothing_else() {    let tool = json!({        "id": "attendance",        "name": "Attendance",        "tables": ["student"],        "instructions": "",        "automations": [],        "author": { "device": "dev-1", "name": "Asha" },        "signature": null    });    let parsed = ToolDefinition::from_json(&tool.to_string()).expect("no picture");    parsed.validate().expect("valid");    assert_eq!(parsed.picture, None);    assert_eq!(        serde_json::to_value(&parsed).unwrap(),        tool,        "absent stays absent"    );    let mut null = tool.clone();    null["picture"] = json!(null);    let parsed = ToolDefinition::from_json(&null.to_string()).expect("a null picture");    assert_eq!(parsed.picture, None);    assert_eq!(        serde_json::to_value(&parsed).unwrap(),        tool,        "a null is written back absent"    );    let mut extra = tool;    extra["picture"] = json!({ "photo": "photo:abc", "caption": "x" });    let read = ToolDefinition::from_json(&extra.to_string()).expect("read tolerantly");    assert_eq!(        tolerant::unknown_keys(&extra, &read, &read.unknown),        vec!["picture.caption".to_string()],        "an unknown key beside photo is refused when authored"    );}#[test]fn a_table_needs_a_name_and_a_plural_and_its_page_names_a_column_once() {    assert_eq!(        refused(|v| v["name"] = json!("")),        DefinitionError::Empty("name")    );    assert_eq!(        refused(|v| v["plural"] = json!(" ")),        DefinitionError::Empty("plural")    );    assert_eq!(        refused(|v| v["page"][1]["columns"][0] = json!("title")),        DefinitionError::DuplicatePageColumn("title".into())    );}// ---- the built-in definitions -------------------------------------------/// The table a built-in's columns live on: the kind's own table.fn table_columns(table: &str) -> BTreeSet<&'static str> {    TABLE_SPECS        .iter()        .find(|spec| spec.name == table)        .unwrap_or_else(|| panic!("{table} is not in TABLE_SPECS"))        .columns        .iter()        .map(|(name, _)| *name)        .collect()}/// RULE: Every built-in table definition parses, validates, and round-trips its file exactly.#[test]fn every_builtin_definition_parses_validates_and_round_trips() {    for (id, json) in BUILTIN_DEFINITION_FILES {        let definition =            TableDefinition::from_json(json).unwrap_or_else(|e| panic!("{id}.json: {e}"));        definition            .validate()            .unwrap_or_else(|e| panic!("{id}.json: {e}"));        assert_eq!(&definition.id, id, "{id}.json declares another id");        assert!(            definition.builtin,            "{id}.json is shipped, so it is built in"        );        // A built-in file is AUTHORED: no key this build does not name.        assert!(            definition.unknown.is_empty(),            "{id}.json carries keys this build does not name: {:?}",            definition.unknown.keys().collect::<Vec<_>>()        );        let file: Value = serde_json::from_str(json).unwrap();        assert_eq!(            serde_json::to_value(&definition).unwrap(),            file,            "{id}.json carries something the shared format would not write back"        );    }}/// RULE: Every built-in column is stored, declared by its engine, or computed by a validated definition; definition rollups live in the local computed index, never as physical columns.#[test]fn every_builtin_column_is_a_real_column_of_its_table() {    let mut missing = Vec::new();    for definition in kind_tables() {        let table = builtin_store_table(&definition.id)            .unwrap_or_else(|| panic!("{} is not a kind or a supporting built-in", definition.id));        let mut real = table_columns(table);        // The object's rows of the table are kept in the store table the        // storage map names (`kits/personal/storage.json`: an email sender's        // in `cotton_email_senders`), a column the object names otherwise        // under the store's name (a note's project in `project_id`).        let storage: Value = serde_json::from_str(crate::toolkits::PERSONAL_STORAGE).expect("the storage map");        let entry = storage.as_array().into_iter().flatten().find(|entry| entry["table"] == definition.id.as_str()).cloned().unwrap_or(Value::Null);        if let Some(from) = entry["from"].as_str() {            real.extend(table_columns(from));        }        let renamed = entry["columns"].clone();        for column in &definition.columns {            let stored = renamed[&column.key].as_str().unwrap_or(&column.key);            if real.contains(stored) && stored != column.key {                continue;            }            // A column a kit tool contributes (Birthdays' wish on a person)            // is kept with the owner's own columns, never in the table.            if crate::definitions::owner::is_own_column(&column.key) {                continue;            }            // A secret's value as the object keeps it, sealed under its vault            // key: no phone keeps a secret's row (the phone's store keeps its            // own sealing in `value_enc`).            if (definition.id.as_str(), column.key.as_str()) == ("secret", "sealed") {                continue;            }            if column.live == Some(true)                || column.computed.is_some()                || is_computed_column(&definition.id, &column.key)                || is_engine_written_column(&definition.id, &column.key)                || is_device_answered_column(&definition.id, &column.key)                || is_write_only_column(&definition.id, &column.key)                || super::is_host_switch_column(&definition.id, &column.key)                || super::is_this_device_switch_column(&definition.id, &column.key)                || super::is_household_door_column(&definition.id, &column.key)                || super::is_keep_rule_column(&definition.id, &column.key)                || super::is_mac_keep_column(&definition.id, &column.key)                || super::is_phone_file_column(&definition.id, &column.key)                || super::is_keep_fetch_column(&definition.id, &column.key)            {                continue;            }            // A table the object serves into a typed table here keeps every            // column its definition names: the copy adds the ones the build's            // table lacks (`cotton_client::transport::object`'s served            // columns; owner, 27 Oct 2026 — the money engine's running            // balance on every transaction).            if !(real.contains(column.key.as_str()) || !entry.is_null()) {                missing.push(format!("{}: {} is not a column of {table}", definition.id, column.key));            }            assert!(                !column.key.starts_with('_') && column.key != "workspace_id",                "{}: {} is sync machinery, not a column a person reads",                definition.id,                column.key            );        }    }    assert!(missing.is_empty(), "{}", missing.join("\n"));}/// RULE: A built-in that is not a primitive kind lives in a table the registry declares as supporting, never in a kind's table and never in a table the registry does not know.#[test]fn every_supporting_builtin_lives_in_a_supporting_table() {    for (id, table) in SUPPORTING_BUILTINS {        assert!(            PrimitiveKind::parse(id).is_none(),            "{id} is a kind, so it lives in the kind's table"        );        assert!(            crate::primitives::SUPPORTING_TABLES                .iter()                .any(|(name, _)| name == table),            "{id} lives in {table}, which the registry does not declare as supporting"        );        assert_eq!(builtin_store_table(id), Some(*table));    }    assert_eq!(builtin_store_table("todo"), Some("cotton_todos"));    assert_eq!(builtin_store_table("nowhere"), None);}/// Every native engine kind table; definition-owned tables derive storage separately.fn kind_tables() -> Vec<TableDefinition> {    builtin_table_definitions()        .iter().cloned()        .filter(|definition| definition.has_engine() && !VIEW_TABLES.contains(&definition.id.as_str()))        .collect()}/// RULE: The photos engine's views — the library, an album's pictures, the duplicates, where a picture was seen — are read only column for column, in no project and no order, so only the engine's reads and the tools of the records they stand for reach them.#[test]fn the_media_views_are_read_only_and_the_engines_own() {    for id in ["media", "album_item", "duplicate", "sighting"] {        assert!(VIEW_TABLES.contains(&id), "{id} is a view");        let view = builtin_table_definitions()            .iter().cloned()            .find(|definition| definition.id == id)            .unwrap_or_else(|| panic!("{id}.json is shipped"));        assert_eq!(view.engine.as_deref(), Some("media"), "{id}");        for column in &view.columns {            assert_eq!(                column.readonly,                Some(true),                "{id}.{} is the engine's to say",                column.key            );        }        assert_eq!(view.project, None, "{id}");        assert_eq!(view.order, None, "{id}");    }    // The library's kind and an album picture's kind are exactly the two    // tables a picture lives in.    for id in ["media", "album_item"] {        let view = builtin_table_definitions()            .iter().cloned()            .find(|definition| definition.id == id)            .unwrap();        let kind = view.column("kind").expect("a kind column");        assert_eq!(            kind.choices.as_deref(),            Some(&["photo".to_string(), "video".to_string()][..]),            "{id}"        );    }}/// RULE (76ef0e120, 12 Nov 2026): A photo's and a video's favourite is the person's to set: a print takes and drops its star, update_photo and update_video take it, so neither definition declares it read only.#[test]fn a_pictures_favourite_is_the_persons() {    for id in ["photo", "video"] {        let definition = builtin_table_definition(id).unwrap_or_else(|| panic!("{id}.json"));        let favourite = definition.column("favourite").expect("a favourite column");        assert_ne!(favourite.readonly, Some(true), "{id}.favourite");    }}/// RULE: A built-in definition never declares a column the store codes as JSON, because none of the eleven column types can hold one — but as read-only long text, the text the Mac's JSON came as, which the object serves and no face edits.#[test]fn no_builtin_column_is_a_json_column() {    for definition in kind_tables() {        let table = builtin_store_table(&definition.id)            .unwrap_or_else(|| panic!("{} is not a kind or a supporting built-in", definition.id));        let spec = TABLE_SPECS            .iter()            .find(|spec| spec.name == table)            .unwrap_or_else(|| panic!("{table} is not in TABLE_SPECS"));        for column in &definition.columns {            let codec = spec                .columns                .iter()                .find(|(name, _)| *name == column.key)                .map(|(_, codec)| *codec);            if RESOLVED_COLUMNS.contains(&(definition.id.as_str(), column.key.as_str())) {                assert_eq!(                    codec,                    Some(Codec::Json),                    "{}.{} is declared resolved, so it must still be the JSON column the \                     resolver reads",                    definition.id,                    column.key                );                continue;            }            // The one definition the object serves keeps a Mac column the            // store codes as JSON as read-only long text: its text, drawn as            // it came, never edited (`pnpm personal-tables`).            if column.column_type == ColumnType::Longtext && column.readonly == Some(true) {                continue;            }            assert_ne!(                codec,                Some(Codec::Json),                "{}.{} is a JSON column on {table}",                definition.id,                column.key            );        }    }}/// RULE: Every link column of a built-in definition points at another built-in table, or at a table the personal kit defines (the object serves it, and the phone keeps its rows in the table its definition makes), by its id.#[test]fn every_builtin_link_names_a_builtin_table() {    let kit = cotton_store::manifest_dir().join("kits/personal/tables");    for definition in builtin_table_definitions() {        for column in &definition.columns {            if let Some(target) = &column.link_to {                assert!(                    crate::definitions::is_builtin_table(target) || kit.join(format!("{target}.json")).is_file(),                    "{}.{} links to {target}, which is neither a built-in table nor the kit's",                    definition.id,                    column.key                );            }        }    }}/// RULE: No face of a secret draws a column holding its sealed value — its slip, tile, page, card and record page name none — so a face cannot expose it. The one definition the object serves declares the column it keeps the value sealed in under its vault key (`sealed`); the phone keeps no secret's row, and no read answers it (`sensitive_columns_are_never_declared_or_read`).#[test]fn no_face_shows_a_secret() {    let mut secret = builtin_table_definitions()        .iter().cloned()        .find(|d| d.id == "secret")        .unwrap();    let faces = serde_json::to_string(&serde_json::json!([secret.slip, secret.tile, secret.page, secret.card, secret.parts])).unwrap();    secret.columns.retain(|column| faces.contains(&format!("\"{}\"", column.key)));    let sealed = [        "payload",        "sealed",        "ciphertext",        "nonce",        "password",        "value",    ];    for column in &secret.columns {        assert!(            !sealed.iter().any(|word| column.key.contains(word)),            "secret: {} holds the secret itself and has no place in a definition",            column.key        );    }}/// RULE: No page line reads a key column — a device's or a person's key, drawn as a fingerprint, is machinery and never reaches a person's screen: no page section, head, card, strip, slip or caption names one (architect, 16 Oct 2026: a member's page drew "key ZrUN_xny" and the asking page "their phone's key").#[test]fn no_page_line_reads_a_key_column() {    fn named(value: &Value, keys: &[&str], found: &mut Vec<String>) {        match value {            Value::String(text) if keys.contains(&text.as_str()) => found.push(text.clone()),            Value::Array(items) => items.iter().for_each(|item| named(item, keys, found)),            Value::Object(map) => map.values().for_each(|item| named(item, keys, found)),            _ => {}        }    }    for definition in builtin_table_definitions() {        let keys: Vec<&str> = definition            .columns            .iter()            .map(|column| column.key.as_str())            .filter(|key| key.contains("fingerprint"))            .collect();        if keys.is_empty() {            continue;        }        let mut drawn = serde_json::to_value(definition).unwrap();        let object = drawn.as_object_mut().unwrap();        // The columns declare them and the instructions may speak of them; every        // other key of a definition says how something is drawn or sorted.        for declared in ["columns", "instructions", "commands"] {            object.remove(declared);        }        let mut found = Vec::new();        named(&drawn, &keys, &mut found);        assert!(found.is_empty(), "{} draws {found:?}", definition.id);    }}// ---- the optional keys the Swift side drew first ------------------------/// Sets a top-level key the way the stored form orders it: every optional/// key sits before `instructions`, which stays last.fn set_top(value: &mut Value, key: &str, new: Value) {    let object = value.as_object_mut().unwrap();    let instructions = object.remove("instructions").unwrap();    object.insert(key.into(), new);    object.insert("instructions".into(), instructions);}/// Sets a key inside the object `pointer` names, appended after what is there.fn set_at(value: &mut Value, pointer: &str, key: &str, new: Value) {    value        .pointer_mut(pointer)        .and_then(Value::as_object_mut)        .unwrap_or_else(|| panic!("{pointer} is not an object"))        .insert(key.into(), new);}/// One optional key: where it lives, its name, how to set it, and whether its/// value is a struct (so an unknown key INSIDE it must be refused too) rather/// than an open map.struct KeyCase {    pointer: &'static str,    key: &'static str,    set: fn(&mut Value),    is_struct: bool,}fn key_cases() -> Vec<KeyCase> {    fn case(        pointer: &'static str,        key: &'static str,        set: fn(&mut Value),        is_struct: bool,    ) -> KeyCase {        KeyCase {            pointer,            key,            set,            is_struct,        }    }    // Columns: 0 title, 1 notes, 2 due_date, 7 status [open, done], 9 count,    // 10 position (numbers), 11 photo, 5 project and 6 person (links).    vec![        case("/columns/0", "readonly", |v| set_at(v, "/columns/0", "readonly", json!(true)), false),        case(            "/columns/1",            "editable_when",            |v| {                set_at(v, "/columns/1", "readonly", json!(true));                set_at(v, "/columns/1", "editable_when", json!({ "column": "status", "values": ["open"] }));            },            true,        ),        case("/columns/0", "placeholder", |v| set_at(v, "/columns/0", "placeholder", json!("Untitled")), false),        case("/columns/2", "past_name", |v| set_at(v, "/columns/2", "past_name", json!("Was")), false),        case("/columns/2", "month", |v| set_at(v, "/columns/2", "month", json!(true)), false),        case("/columns/9", "pair", |v| set_at(v, "/columns/9", "pair", json!("position")), false),        case(            "/columns/9",            "units",            |v| set_at(v, "/columns/9", "units", json!({ "one": "item", "other": "items", "zero": "" })),            true,        ),        case("/columns/9", "format", |v| set_at(v, "/columns/9", "format", json!("duration")), false),        case("/columns/7", "stamps", |v| set_at(v, "/columns/7", "stamps", json!({ "done": "done" })), false),        case(            "/columns/7",            "moves",            |v| set_at(v, "/columns/7", "moves", json!({ "open": ["done"], "done": [] })),            false,        ),        case(            "/columns/7",            "hints",            |v| set_at(v, "/columns/7", "hints", json!({ "done": "Also files it" })),            false,        ),        case("/columns/7", "multiple", |v| set_at(v, "/columns/7", "multiple", json!(true)), false),        case(            "/columns/7",            "week",            |v| {                set_at(v, "/columns/7", "multiple", json!(true));                set_at(v, "/columns/7", "week", json!(true));            },            false,        ),        case(            "/columns/1",            "shown_when",            |v| set_at(v, "/columns/1", "shown_when", json!({ "column": "status", "values": ["done"] })),            true,        ),        case("/columns/0", "secret", |v| set_at(v, "/columns/0", "secret", json!(true)), false),        case("/columns/7", "red_when", |v| set_at(v, "/columns/7", "red_when", json!(["open"])), false),        case("/slip", "photo_name", |v| set_at(v, "/slip", "photo_name", json!("title")), false),        case("/slip", "title_fallback", |v| set_at(v, "/slip", "title_fallback", json!("notes")), false),        case("/slip", "subtitle_fallback", |v| set_at(v, "/slip", "subtitle_fallback", json!("title")), false),        case(            "/slip",            "toggle_on",            |v| {                set_at(v, "/slip", "toggle", json!("status"));                set_at(v, "/slip", "toggle_on", json!(["done"]));            },            false,        ),        case("/slip", "toggle_style", |v| set_at(v, "/slip", "toggle_style", json!("switch")), false),        case(            "/slip",            "caption",            |v| {                set_at(                    v,                    "/slip",                    "caption",                    json!({ "columns": ["count"], "status": "status", "dates": ["due_date"], "fields": ["amount"] }),                )            },            true,        ),        case("/slip", "figure", |v| set_at(v, "/slip", "figure", json!("amount")), false),        case("/slip", "stub", |v| set_at(v, "/slip", "stub", json!("due_date")), false),        case(            "/slip",            "byline",            |v| set_at(v, "/slip", "byline", json!({ "column": "status", "words": { "done": "closed by hand" } })),            true,        ),        case(            "/slip",            "badge",            |v| set_at(v, "/slip", "badge", json!({ "column": "person", "symbol": "repeat", "spoken": "Repeats" })),            true,        ),        case("/slip", "ordinal", |v| set_at(v, "/slip", "ordinal", json!(true)), false),        case("/slip", "title_lines", |v| set_at(v, "/slip", "title_lines", json!(0)), false),        case("/page/0", "picture", |v| set_at(v, "/page/0", "picture", json!("photo")), false),        case(            "/page/2",            "web",            |v| v["page"].as_array_mut().unwrap().push(json!({ "heading": null, "web": "title" })),            false,        ),        case(            "/page/2",            "list",            |v| {                v["page"].as_array_mut().unwrap().push(json!({                    "heading": "Linked",                    "list": { "table": "person", "link": "todo_id", "empty": "None yet.", "face": "page", "archived": true }                }))            },            true,        ),        case("", "archived", |v| set_top(v, "archived", json!("due_date")), false),        case("", "readonly_when", |v| set_top(v, "readonly_when", json!("done")), false),        case("", "listed_when", |v| set_top(v, "listed_when", json!("title")), false),        case("", "sort", |v| set_top(v, "sort", json!({ "column": "due_date", "descending": true })), true),        case(            "",            "group",            |v| {                set_top(                    v,                    "group",                    json!({ "column": "status", "sections": [                        { "heading": null, "values": ["open"] },                        { "heading": "Done", "values": ["done"], "note": "Finished." }                    ] }),                )            },            true,        ),        case("", "by_day", |v| set_top(v, "by_day", json!("due_date")), false),        case("", "by_month", |v| set_top(v, "by_month", json!("due_date")), false),        case("", "day_grouping", |v| set_top(v, "day_grouping", json!("due_date")), false),        case(            "",            "upcoming",            |v| set_top(v, "upcoming", json!({ "dates": ["due_date"], "undated": "No date", "late": "Late", "series": "project" })),            true,        ),        case(            "",            "recent",            |v| set_top(v, "recent", json!({ "column": "due_date", "count": 2, "over": 3 })),            true,        ),        case("", "dimmed", |v| set_top(v, "dimmed", json!({ "column": "status", "values": ["done"] })), true),        case("", "layout", |v| set_top(v, "layout", json!("cards")), false),        case("", "grid", |v| { set_top(v, "layout", json!("cards")); set_top(v, "grid", json!({ "columns": 2 })) }, true),        case(            "",            "chips",            |v| set_top(v, "chips", json!({ "column": "status", "sends": { "done": true, "count": 1 } })),            true,        ),        case("", "cover", |v| set_top(v, "cover", json!({ "footer": ["notes"], "bound": true })), true),        case(            "",            "lists",            |v| set_top(v, "lists", json!([{ "heading": "Others", "list": { "table": "todo" } }])),            true,        ),        case(            "/lists/0",            "above",            |v| set_top(v, "lists", json!([{ "heading": "Others", "above": true, "list": { "table": "todo" } }])),            false,        ),        case("", "opened", |v| set_top(v, "opened", json!("due_date")), false),        case(            "",            "empty",            |v| set_top(v, "empty", json!({ "title": "Nothing yet.", "message": "Tap + for one." })),            true,        ),        case(            "",            "create",            |v| set_top(v, "create", json!({ "label": "New todo", "dated": "due_date" })),            true,        ),        case(            "",            "exports",            |v| set_top(v, "exports", json!([{ "label": "Export", "column": "notes", "extension": "txt" }])),            true,        ),        case("", "pager", |v| set_top(v, "pager", json!("person")), false),        case(            "",            "actions",            |v| {                set_top(                    v,                    "actions",                    json!([                        { "label": "Call", "column": "title", "scheme": "tel", "scheme_column": "notes",                          "schemes": { "video": "facetime", "audio": "facetime-audio" } },                        { "label": "Text", "column": "title", "scheme": "sms" }                    ]),                )            },            true,        ),        case(            "",            "conversation",            |v| {                set_top(v, "page_parts", json!(["title", "facts", "messages"]));                set_top(                    v,                    "conversation",                    json!({                        "table": "session_message",                        "links": ["to_session_id", "from_session_id"],                        "body": "body",                        "at": "created_at",                        "mine": { "column": "from_kind", "values": ["owner"] },                        "status": "status",                        "ended": "due_date",                        "sends": { "kind": "instruction", "to_kind": "session" }                    }),                )            },            true,        ),    ]    .into_iter()    .chain(round_two_key_cases())    .chain(round_three_key_cases())    .chain(round_four_key_cases())    .chain(round_five_format_key_cases())    .chain(round_five_derived_key_cases())    .chain(round_five_reveal_key_cases())    .chain(round_five_section_where_key_cases())    .chain(round_five_column_words_key_cases())    .chain(slip_by_key_cases())    .chain(computed_key_cases())    .chain(contributes_key_cases())    .chain(parts_key_cases())    .collect()}/// A second date column, `ends`, for the keys that pair two dates.fn with_ends(value: &mut Value) {    value["columns"]        .as_array_mut()        .unwrap()        .push(json!({ "key": "ends", "type": "date" }));}/// A list section at /page/2 holding `list`.fn list_section(value: &mut Value, list: Value) {    value["page"]        .as_array_mut()        .unwrap()        .push(json!({ "heading": "Linked", "list": list }));}/// The conversation page with every key the Messages conversion reads.fn full_conversation(value: &mut Value) {    set_top(value, "page_parts", json!(["title", "facts", "messages"]));    set_top(        value,        "conversation",        json!({            "table": "message",            "links": ["thread_id"],            "body": "display_body",            "at": "sent_at",            "mine": { "column": "direction", "values": ["out"] },            "header": ["sender_label", "reply_preview"],            "footer": ["reactions"],            "media": "media",            "system": "is_system",            "color_by": "paper_sender",            "photo": "sender_photo",            "anchor": "title",            "can_send": false,            "folds": true        }),    );}/// The keys the second round of Swift faces decodes (1 Oct 2026: People,/// Photos, Videos, Passwords, Devices, News, Documents, Messages).fn round_two_key_cases() -> Vec<KeyCase> {    fn case(        pointer: &'static str,        key: &'static str,        set: fn(&mut Value),        is_struct: bool,    ) -> KeyCase {        KeyCase {            pointer,            key,            set,            is_struct,        }    }    vec![        case(            "/columns/12",            "presentation",            |v| set_at(v, "/columns/12", "presentation", json!("file")),            false,        ),        case(            "/columns/7",            "choices_from",            |v| set_at(v, "/columns/7", "choices_from", json!("notes")),            false,        ),        case(            "/columns/7",            "labels",            |v| set_at(v, "/columns/7", "labels", json!({ "open": "To do" })),            false,        ),        case(            "/columns/7",            "choice_names",            |v| {                set_at(                    v,                    "/columns/7",                    "choice_names",                    json!({ "done": "Finished" }),                )            },            false,        ),        case(            "/columns/2",            "until",            |v| {                with_ends(v);                set_at(v, "/columns/2", "until", json!("ends"));            },            false,        ),        case(            "/columns/11",            "size",            |v| set_at(v, "/columns/11", "size", json!(["count", "position"])),            false,        ),        case(            "/columns/11",            "caption",            |v| set_at(v, "/columns/11", "caption", json!("title")),            false,        ),        case(            "/columns/12",            "caption_fallback",            |v| set_at(v, "/columns/12", "caption_fallback", json!("count")),            false,        ),        case(            "/columns/11",            "opens",            |v| {                set_at(                    v,                    "/columns/11",                    "opens",                    json!({ "column": "person", "table": "person", "table_column": "status" }),                )            },            true,        ),        case(            "/columns/12",            "poster",            |v| set_at(v, "/columns/12", "poster", json!("photo")),            false,        ),        case(            "/columns/0",            "zone",            |v| set_at(v, "/columns/0", "zone", json!(true)),            false,        ),        case(            "/columns/2",            "yearly",            |v| set_at(v, "/columns/2", "yearly", json!(true)),            false,        ),        case(            "/columns/0",            "reach",            |v| {                set_at(                    v,                    "/columns/0",                    "reach",                    json!({ "kind": "phone", "channel": "notes" }),                )            },            true,        ),        case(            "/columns/1",            "provenance",            |v| {                set_at(                    v,                    "/columns/1",                    "provenance",                    json!({ "by": "title", "at": "due_date", "since": "notes" }),                )            },            true,        ),        case(            "/columns/8",            "signs",            |v| {                set_at(                    v,                    "/columns/8",                    "signs",                    json!({ "positive": "{first} owes you", "negative": "You owe {first}", "zero": "Square." }),                )            },            true,        ),        case(            "/slip",            "answers",            |v| {                set_at(                    v,                    "/slip",                    "answers",                    json!({ "column": "status", "values": { "done": "Keep" }, "when": ["open"],                            "leaves": false, "primary": "done" }),                )            },            true,        ),        case(            "/slip",            "unread",            |v| set_at(v, "/slip", "unread", json!("due_date")),            false,        ),        case(            "/slip",            "edge",            |v| set_at(v, "/slip", "edge", json!("receipt")),            false,        ),        case(            "/slip",            "status",            |v| set_at(v, "/slip", "status", json!("notes")),            false,        ),        case(            "/slip/byline",            "ink",            |v| {                set_at(                    v,                    "/slip",                    "byline",                    json!({ "column": "status", "words": { "done": "marked" }, "ink": "red" }),                )            },            false,        ),        case(            "/slip/badge",            "values",            |v| {                set_at(                    v,                    "/slip",                    "badge",                    json!({ "column": "status", "symbol": "play", "spoken": "Film", "values": ["done"] }),                )            },            false,        ),        case(            "/page/0",            "when",            |v| {                set_at(                    v,                    "/page/0",                    "when",                    json!({ "column": "status", "values": ["open"], "present": true }),                )            },            true,        ),        case(            "/page/0",            "note",            |v| set_at(v, "/page/0", "note", json!("Suggested for review.")),            false,        ),        case(            "/page/0",            "ink",            |v| {                set_at(v, "/page/0", "note", json!("Suggested for review."));                set_at(v, "/page/0", "ink", json!("red"));            },            false,        ),        case(            "/page/0",            "hand",            |v| {                set_at(                    v,                    "/page/0",                    "hand",                    json!(["due_date", "Away from {notes}"]),                )            },            false,        ),        case(            "/page/0",            "answers",            |v| {                set_at(                    v,                    "/page/0",                    "answers",                    json!({ "column": "status", "values": { "open": "Bring it back" }, "when": ["done"] }),                )            },            true,        ),        case(            "/page/0",            "actions",            |v| {                set_at(                    v,                    "/page/0",                    "actions",                    json!([{ "label": "Keep", "sets": { "notes": null } }, { "label": "Delete", "delete": true }]),                )            },            true,        ),        case(            "/page/0",            "links",            |v| set_at(v, "/page/0", "links", json!({ "except": ["note"] })),            true,        ),        case(            "/page/2/list",            "limit",            |v| {                list_section(                    v,                    json!({ "table": "person", "link": "todo_id", "limit": 3 }),                )            },            false,        ),        case(            "/page/2/list",            "columns",            |v| {                list_section(                    v,                    json!({ "table": "person", "link": "todo_id", "columns": 3 }),                )            },            false,        ),        case(            "/page/2/list",            "with",            |v| {                list_section(                    v,                    json!({ "table": "person", "link": "todo_id", "with": [{ "table": "note", "link": "people" }] }),                )            },            true,        ),        case(            "/page/2/list",            "add",            |v| {                list_section(                    v,                    json!({ "table": "photo", "link": "todo_id", "add": "Add photos" }),                )            },            false,        ),        case(            "/group/sections/0",            "closed",            |v| {                set_top(                    v,                    "group",                    json!({ "column": "status", "sections": [{ "heading": "Removed", "values": ["done"], "closed": true }] }),                )            },            false,        ),        case(            "/sort",            "tie",            |v| {                set_top(                    v,                    "sort",                    json!({ "column": "due_date", "descending": true, "tie": "title" }),                )            },            false,        ),        case(            "/empty",            "search",            |v| {                set_top(                    v,                    "empty",                    json!({ "title": "Nothing yet.", "search": { "title": "Nothing matches.", "message": "It reads captions." } }),                )            },            true,        ),        case(            "/create",            "path",            |v| {                set_top(                    v,                    "create",                    json!({ "label": "Import contacts", "path": "/people/import" }),                )            },            false,        ),        case("/conversation", "header", full_conversation, false),        case("/conversation", "footer", full_conversation, false),        case("/conversation", "media", full_conversation, false),        case("/conversation", "system", full_conversation, false),        case("/conversation", "color_by", full_conversation, false),        case("/conversation", "photo", full_conversation, false),        case("/conversation", "anchor", full_conversation, false),        case("/conversation", "can_send", full_conversation, false),        case("/conversation", "folds", full_conversation, false),        case("", "index", |v| set_top(v, "index", json!("title")), false),        case(            "",            "search",            |v| set_top(v, "search", json!(["title", "notes"])),            false,        ),        case("", "delete", |v| set_top(v, "delete", json!(false)), false),        case(            "",            "opens",            |v| {                set_top(                    v,                    "opens",                    json!({ "column": "person", "table_column": "status" }),                )            },            true,        ),        case(            "",            "polaroid",            |v| {                v["tile"]["face"] = json!("polaroid-grid");                set_top(                    v,                    "polaroid",                    json!({ "caption": "count", "title": "title", "subtitle": "due_date" }),                );            },            true,        ),        case(            "",            "filter",            |v| {                set_top(                    v,                    "filter",                    json!({ "column": "status", "all": "all", "words": { "open": "open ones" },                            "order": ["open", "done"], "empty": { "open": { "title": "None open." } } }),                )            },            true,        ),        case(            "",            "count_words",            |v| {                set_top(                    v,                    "count_words",                    json!({ "column": "status", "units": { "open": { "one": "open todo", "other": "open todos" } },                            "order": ["open"] }),                )            },            true,        ),        case(            "",            "months",            |v| {                set_top(v, "by_month", json!("due_date"));                set_top(v, "months", json!({ "over": 0, "undated": "No date" }));            },            true,        ),        case(            "/columns/10",            "format",            |v| set_at(v, "/columns/10", "format", json!("duration_ms")),            false,        ),        case(            "",            "hidden",            |v| {                set_top(                    v,                    "hidden",                    json!({ "column": "status", "values": ["done"] }),                )            },            true,        ),        case(            "",            "select",            |v| set_top(v, "select", json!({ "verb": "delete" })),            true,        ),        case(            "",            "deletion",            |v| {                set_top(                    v,                    "deletion",                    json!({ "one": "This also removes it.", "other": "This also removes them.", "size": "count",                            "undo": false, "confirm": "Delete", "cancel": "Keep", "label": "Remove", "asks": false }),                )            },            true,        ),        case(            "",            "links",            |v| {                set_top(                    v,                    "links",                    json!([{ "label": "Albums", "table": "album", "where": { "state": "open" }, "words": "suggested",                             "path": "/photos/albums", "review": true, "hides_empty": true }]),                )            },            true,        ),        case(            "",            "search_placeholder",            |v| set_top(v, "search_placeholder", json!("Search todos")),            false,        ),        case(            "",            "related",            |v| {                set_top(                    v,                    "related",                    json!([{ "label": "Kept", "table": "message", "column": "thread_id", "filter": { "kept": true },                             "new": true, "archived": true, "open": "thread_id" }]),                )            },            true,        ),        case(            "",            "commands",            |v| {                set_top(                    v,                    "commands",                    json!([{ "id": "read", "label": "Mark read", "kind": "update", "verb": "mark_thread_read", "data": { "less": null },                             "destructive": false, "bindings": { "threadId": "$id", "title": "title" }, "receipt": "It was done" }]),                )            },            true,        ),        case(            "",            "on_open",            |v| {                set_top(                    v,                    "commands",                    json!([{ "id": "read", "label": "Mark read", "kind": "update", "verb": "mark_thread_read",                             "bindings": { "ids": "$id_list" }, "receipt": "It was done" }]),                );                set_top(v, "on_open", json!("read"));            },            false,        ),    ]}/// The keys the third round of Swift faces decodes (1 Oct 2026: Thoughts,/// Bin, Sessions and its live conversation, Email).fn round_three_key_cases() -> Vec<KeyCase> {    fn case(        pointer: &'static str,        key: &'static str,        set: fn(&mut Value),        is_struct: bool,    ) -> KeyCase {        KeyCase {            pointer,            key,            set,            is_struct,        }    }    vec![        case(            "/slip",            "links",            |v| set_at(v, "/slip", "links", json!({ "except": ["person"] })),            true,        ),        case(            "",            "hand_over",            |v| {                set_top(                    v,                    "hand_over",                    json!({ "when": { "column": "status", "values": ["done"] } }),                )            },            true,        ),        case(            "",            "attachments",            |v| {                set_top(                    v,                    "attachments",                    json!({ "editable": true, "sources": ["library", "camera"] }),                )            },            true,        ),        case(            "",            "clear",            |v| {                set_top(                    v,                    "clear",                    json!({ "label": "Empty the bin", "note": "Your mail provider keeps its own bin.",                            "title": "Empty the bin?", "message": "This erases all {count}.", "confirm": "Empty",                            "cancel": "Keep", "done": "Bin emptied" }),                )            },            true,        ),        case(            "",            "live",            |v| set_top(v, "live", json!({ "every": 5 })),            true,        ),        case(            "/conversation",            "header_columns",            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "header_columns",                    json!(["from", "to", "cc"]),                );            },            false,        ),        case(            "/conversation",            "started",            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "started",                    json!({ "at": "due_date", "words": ["title", "notes"] }),                );            },            true,        ),        case(            "/conversation",            "placeholder",            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "placeholder",                    json!("Send an instruction"),                );            },            false,        ),        case(            "/conversation",            "also",            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "also",                    json!([                        { "table": "prompt", "links": ["session_id"], "body": "text", "at": "ts",                          "mine": { "column": "role", "values": ["user"] } },                        { "table": "run", "links": ["session_id"], "at": "started_at", "face": "slip" }                    ]),                );            },            true,        ),    ]}fn round_four_key_cases() -> Vec<KeyCase> {    vec![KeyCase {        pointer: "/slip",        key: "reply",        set: |v| {            set_at(                v,                "/slip",                "reply",                json!({ "column": "notes", "label": "Answer", "placeholder": "Your answer, in your own words" }),            )        },        is_struct: true,    }]}/// RULE: A lists entry's `above` is read (the list is drawn before the table's own slips) and a page section carrying `above` is refused, since a page section is never above anything.#[test]fn above_is_read_on_a_lists_entry_and_refused_on_a_page_section() {    let mut value = example();    set_top(&mut value, "lists", json!([{ "heading": "Others", "above": true, "list": { "table": "todo" } }]));    let definition = TableDefinition::from_json(&value.to_string()).unwrap();    definition.validate().unwrap();    assert_eq!(definition.lists.as_ref().unwrap()[0].above, Some(true));    let mut page = example();    page["page"][0]["above"] = json!(true);    let definition = TableDefinition::from_json(&page.to_string()).unwrap();    let refused = definition.validate().unwrap_err().to_string();    assert!(refused.contains("page[0].above"), "a page section's above was accepted: {refused}");}/// RULE: A page section's `commands` name commands its own table declares, and one naming any other is refused, because a section may only draw a verb the engine really has.#[test]fn a_page_sections_commands_name_the_tables_declared_commands() {    let declared = json!([{ "id": "read", "label": "Read", "kind": "update", "receipt": "It was done", "verb": "mark_read" }]);    let mut value = example();    set_top(&mut value, "commands", declared.clone());    value["page"][0]["commands"] = json!(["read"]);    let definition = TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate().map(|()| d));    assert_eq!(        definition.expect("a declared command is drawn").page[0].commands,        Some(vec!["read".to_string()])    );    let mut value = example();    set_top(&mut value, "commands", declared);    value["page"][0]["commands"] = json!(["clear"]);    let refused = TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate());    assert_eq!(        refused.expect_err("an undeclared command is refused"),        DefinitionError::UnknownCommand {            slot: "page[0].commands".into(),            id: "clear".into(),        }    );}/// RULE: Every optional key the Swift decoder reads round-trips byte for byte through the Rust types in the stored order, and validates.#[test]fn every_optional_key_round_trips_byte_for_byte() {    for case in key_cases() {        let mut value = example();        (case.set)(&mut value);        let json = serde_json::to_string(&value).unwrap();        let definition =            TableDefinition::from_json(&json).unwrap_or_else(|e| panic!("{}: {e}", case.key));        definition            .validate()            .unwrap_or_else(|e| panic!("{}: {e}", case.key));        assert_eq!(            definition.to_json(),            json,            "{} does not round-trip",            case.key        );    }}/// RULE: An authored definition refuses a misspelled optional key, and an unknown key inside one whose value is a struct.#[test]fn a_misspelled_optional_key_or_an_unknown_one_inside_it_is_refused() {    for case in key_cases() {        let mut value = example();        (case.set)(&mut value);        let mut misspelled = value.clone();        let object = misspelled            .pointer_mut(case.pointer)            .and_then(Value::as_object_mut)            .unwrap();        let held = object.remove(case.key).unwrap();        object.insert(format!("{}s", case.key), held);        assert!(            TableDefinition::authored(&misspelled).is_err(),            "{}s was accepted",            case.key        );        if case.is_struct {            let mut inner = value.clone();            let slot = &mut inner.pointer_mut(case.pointer).unwrap()[case.key];            let target = match slot {                Value::Array(items) => items.first_mut().unwrap(),                other => other,            };            target                .as_object_mut()                .unwrap()                .insert("unknown".into(), json!(true));            assert!(                TableDefinition::authored(&inner).is_err(),                "an unknown key inside {} was accepted",                case.key            );        }    }}/// RULE: The new enumerations are spelled the shared way and nothing else parses — formats, toggle styles, grid defaults, section faces, action schemes and the conversation page style.#[test]fn the_new_enumerations_are_spelled_the_shared_way() {    for (format, spelled) in [        (ColumnFormat::Duration, "duration"),        (ColumnFormat::Words, "words"),        (ColumnFormat::RepeatRule, "repeat-rule"),        (ColumnFormat::AppName, "app-name"),    ] {        assert_eq!(serde_json::to_value(format).unwrap(), json!(spelled));    }    for (scheme, spelled) in [        (ActionScheme::Tel, "tel"),        (ActionScheme::Sms, "sms"),        (ActionScheme::Facetime, "facetime"),        (ActionScheme::FacetimeAudio, "facetime-audio"),    ] {        assert_eq!(serde_json::to_value(scheme).unwrap(), json!(spelled));    }    assert_eq!(        serde_json::to_value(PagePart::Messages).unwrap(),        json!("messages")    );    let parses = |mutate: fn(&mut Value)| {        let mut value = example();        mutate(&mut value);        TableDefinition::from_json(&value.to_string()).is_ok()    };    // Another Mac's filed contract widens stamp values from done/dropped to words.    assert!(parses(|v| set_at(v, "/columns/7", "stamps", json!({ "done": "approved" }))));    assert!(!parses(|v| set_at(v, "/columns/7", "stamps", json!({ "done": 7 }))));    assert!(!parses(|v| set_top(v, "grid", json!({ "columns": -1 }))));    // A JSON object can name a key twice; a definition's map cannot mean it.    let mut twice = example().to_string();    twice = twice.replacen(        "\"choices\":[\"open\",\"done\"]",        "\"choices\":[\"open\",\"done\"],\"hints\":{\"done\":\"a\",\"done\":\"b\"}",        1,    );    assert!(twice.contains("hints"));    assert!(TableDefinition::from_json(&twice).is_err());}/// A mutation of the example, and the refusal it must earn.type RefusalCase = (fn(&mut Value), DefinitionError);fn wrong_type(    slot: &str,    column: &str,    found: ColumnType,    wanted: &'static str,) -> DefinitionError {    DefinitionError::WrongColumnType {        slot: slot.into(),        column: column.into(),        found,        wanted,    }}fn unknown(slot: &str, column: &str) -> DefinitionError {    DefinitionError::UnknownColumn {        slot: slot.into(),        column: column.into(),    }}fn not_a_choice(slot: &str, value: &str) -> DefinitionError {    DefinitionError::UnknownChoice {        slot: slot.into(),        column: "status".into(),        value: value.into(),    }}fn requires(slot: &str, needs: &'static str) -> DefinitionError {    DefinitionError::Requires {        slot: slot.into(),        needs,    }}/// RULE: A column's optional keys belong to the types they read, and every value they name is one of the column's choices.////// Stamps, moves, hints and week to a choice; multiple to a choice, a text or a/// link; past_name to a date; units and pair to a number; secret to a text; each/// format to its own types.#[test]fn a_columns_optional_keys_belong_to_its_type() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_at(v, "/columns/0", "stamps", json!({ "done": "done" })),            wrong_type("columns.title.stamps", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/columns/7", "stamps", json!({ "closed": "done" })),            not_a_choice("columns.status.stamps", "closed"),        ),        (            |v| set_at(v, "/columns/7", "moves", json!({ "open": ["closed"] })),            not_a_choice("columns.status.moves", "closed"),        ),        (            |v| set_at(v, "/columns/7", "moves", json!({ "shut": [] })),            not_a_choice("columns.status.moves", "shut"),        ),        (            |v| set_at(v, "/columns/0", "hints", json!({ "a": "b" })),            wrong_type("columns.title.hints", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/columns/7", "hints", json!({ "shut": "b" })),            not_a_choice("columns.status.hints", "shut"),        ),        (            |v| set_at(v, "/columns/9", "multiple", json!(true)),            wrong_type(                "columns.count.multiple",                "count",                Number,                "a_choice_a_text_or_a_link",            ),        ),        (            |v| set_at(v, "/columns/0", "week", json!(true)),            wrong_type("columns.title.week", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/columns/7", "week", json!(true)),            requires("columns.status.week", "multiple_true"),        ),        (            |v| set_at(v, "/columns/0", "past_name", json!("Was")),            wrong_type("columns.title.past_name", "title", Text, "a date"),        ),        (            |v| set_at(v, "/columns/0", "month", json!(true)),            wrong_type("columns.title.month", "title", Text, "a date"),        ),        (            |v| set_at(v, "/columns/2", "past_name", json!(" ")),            DefinitionError::EmptyAt("columns.due_date.past_name".into()),        ),        (            |v| {                set_at(                    v,                    "/columns/8",                    "units",                    json!({ "one": "a", "other": "b" }),                )            },            wrong_type("columns.amount.units", "amount", Amount, "a_number_or_bytes"),        ),        (            |v| set_at(v, "/columns/9", "units", json!({ "one": "", "other": "b" })),            DefinitionError::EmptyAt("columns.count.units.one".into()),        ),        (            |v| set_at(v, "/columns/9", "pair", json!("nowhere")),            unknown("columns.count.pair", "nowhere"),        ),        (            |v| set_at(v, "/columns/9", "pair", json!("title")),            wrong_type("columns.count.pair", "title", Text, "a number"),        ),        (            |v| set_at(v, "/columns/9", "pair", json!("count")),            DefinitionError::Conflict {                slot: "columns.count.pair".into(),                other: "its_own_column",            },        ),        (            |v| set_at(v, "/columns/0", "pair", json!("count")),            wrong_type("columns.title.pair", "title", Text, "a number"),        ),        (            |v| {                set_at(                    v,                    "/columns/1",                    "shown_when",                    json!({ "column": "nowhere", "values": ["a"] }),                )            },            unknown("columns.notes.shown_when.column", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/columns/1",                    "shown_when",                    json!({ "column": "status", "values": [] }),                )            },            DefinitionError::EmptyAt("columns.notes.shown_when.values".into()),        ),        (            |v| set_at(v, "/columns/1", "editable_when", json!({ "column": "status", "values": ["open"] })),            DefinitionError::Requires { slot: "columns.notes.editable_when".into(), needs: "readonly_true" },        ),        (            |v| {                set_at(v, "/columns/1", "readonly", json!(true));                set_at(v, "/columns/1", "editable_when", json!({ "column": "status", "values": [] }));            },            DefinitionError::EmptyAt("columns.notes.editable_when.values".into()),        ),        (            |v| set_at(v, "/columns/0", "format", json!("duration")),            wrong_type("columns.title.format", "title", Text, "a number"),        ),        (            |v| set_at(v, "/columns/9", "format", json!("words")),            wrong_type(                "columns.count.format",                "count",                Number,                "a_text_or_a_choice",            ),        ),        (            |v| set_at(v, "/columns/7", "format", json!("repeat-rule")),            wrong_type("columns.status.format", "status", Choice, "a text"),        ),        (            |v| set_at(v, "/columns/9", "secret", json!(true)),            wrong_type("columns.count.secret", "count", Number, "a text"),        ),        (            |v| set_at(v, "/columns/7", "red_when", json!([])),            DefinitionError::EmptyAt("columns.status.red_when".into()),        ),        (            |v| set_at(v, "/columns/7", "red_when", json!([""])),            DefinitionError::EmptyAt("columns.status.red_when".into()),        ),        (            |v| set_at(v, "/columns/0", "placeholder", json!("")),            DefinitionError::EmptyAt("columns.title.placeholder".into()),        ),        (            |v| set_at(v, "/columns/0", "families", json!({ "a": "b" })),            wrong_type("columns.title.families", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/columns/7", "families", json!({ "shut": "open" })),            not_a_choice("columns.status.families", "shut"),        ),        (            |v| set_at(v, "/columns/7", "families", json!({ "done": "shut" })),            not_a_choice("columns.status.families", "shut"),        ),        (            |v| set_at(v, "/columns/7", "families", json!({ "done": "done" })),            DefinitionError::Conflict { slot: "columns.status.families".into(), other: "a_family_that_is_a_member" },        ),        (            |v| set_at(v, "/columns/7", "families", json!({ "done": "open", "open": "done" })),            DefinitionError::Conflict { slot: "columns.status.families".into(), other: "a_family_that_is_a_member" },        ),        (            |v| set_at(v, "/columns/0", "examples", json!({ "a": ["b"] })),            wrong_type("columns.title.examples", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/columns/7", "examples", json!({ "shut": ["Closed for good"] })),            not_a_choice("columns.status.examples", "shut"),        ),        (            |v| set_at(v, "/columns/7", "examples", json!({ "done": [] })),            DefinitionError::EmptyAt("columns.status.examples".into()),        ),        (            |v| set_at(v, "/columns/7", "examples", json!({ "done": [" "] })),            DefinitionError::EmptyAt("columns.status.examples".into()),        ),        (            |v| set_at(v, "/columns/0", "says", json!(["title"])),            wrong_type("columns.title.says", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/columns/7", "says", json!([])),            DefinitionError::EmptyAt("columns.status.says".into()),        ),        (            |v| set_at(v, "/columns/7", "says", json!(["title", "nowhere"])),            DefinitionError::UnknownColumn { slot: "columns.status.says[1]".into(), column: "nowhere".into() },        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }}/// RULE: A choice column's families and exemplars are kept as the source said them, in order, and an event's kinds are a vocabulary of families and their members, each kind with phrases an engine compares an event's words with.#[test]fn a_choice_columns_families_and_examples_round_trip() {    let event = builtin_table_definition("event").expect("the kit's event");    let kind = event.column("kind").expect("an event has a kind");    assert_eq!(kind.column_type, ColumnType::Choice);    let families = kind.families.as_ref().expect("its families");    assert_eq!(families.get("dinner").map(String::as_str), Some("meal"));    assert_eq!(families.get("gym").map(String::as_str), Some("workout"));    assert_eq!(families.get("flight").map(String::as_str), Some("travel"));    assert!(families.get("meal").is_none(), "a family is no member");    let examples = kind.examples.as_ref().expect("its exemplars");    let choices = kind.choices.as_deref().unwrap_or_default();    assert!(choices.iter().all(|choice| examples.get(choice).is_some_and(|phrases| !phrases.is_empty())), "every kind is said with phrases");    assert_eq!(kind.says.as_deref(), Some(&["title".to_string(), "notes".into(), "location".into()][..]), "an event is said by its title, notes and place");    let written = serde_json::to_value(kind).unwrap();    let read: Column = serde_json::from_value(written.clone()).unwrap();    assert_eq!(serde_json::to_value(&read).unwrap(), written);    assert_eq!(written["families"].as_object().unwrap().keys().next().map(String::as_str), Some("breakfast"), "in the source's order");}/// RULE: A slip's optional keys name declared columns of the right type — stub a date, caption status a choice and dates dates — toggle_on and toggle_style need a toggle, toggle_on a choice toggle and its choices, and a byline or badge says something.#[test]fn a_slips_optional_keys_name_declared_columns() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_at(v, "/slip", "title_fallback", json!("nowhere")),            unknown("slip.title_fallback", "nowhere"),        ),        (            |v| set_at(v, "/slip", "subtitle_fallback", json!("nowhere")),            unknown("slip.subtitle_fallback", "nowhere"),        ),        (            |v| set_at(v, "/slip", "figure", json!("nowhere")),            unknown("slip.figure", "nowhere"),        ),        (            |v| set_at(v, "/slip", "stub", json!("title")),            wrong_type("slip.stub", "title", Text, "a date"),        ),        (            |v| {                set_at(v, "/slip", "toggle", json!(null));                set_at(v, "/slip", "toggle_on", json!(["done"]));            },            requires("slip.toggle_on", "slip.toggle"),        ),        (            |v| set_at(v, "/slip", "toggle_on", json!(["done"])),            wrong_type("slip.toggle_on", "done", Bool, "a choice"),        ),        (            |v| {                set_at(v, "/slip", "toggle", json!("status"));                set_at(v, "/slip", "toggle_on", json!(["closed"]));            },            not_a_choice("slip.toggle_on", "closed"),        ),        (            |v| {                set_at(v, "/slip", "toggle", json!(null));                set_at(v, "/slip", "toggle_style", json!("switch"));            },            requires("slip.toggle_style", "slip.toggle"),        ),        (            |v| set_at(v, "/slip", "caption", json!({ "status": "nowhere" })),            unknown("slip.caption.status", "nowhere"),        ),        (            |v| set_at(v, "/slip", "caption", json!({ "dates": ["title"] })),            wrong_type("slip.caption.dates", "title", Text, "a date"),        ),        (            |v| set_at(v, "/slip", "caption", json!({ "columns": ["nowhere"] })),            unknown("slip.caption.columns", "nowhere"),        ),        (            |v| set_at(v, "/slip", "caption", json!({ "fields": ["nowhere"] })),            unknown("slip.caption.fields", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "byline",                    json!({ "column": "nowhere", "words": { "a": "b" } }),                )            },            unknown("slip.byline.column", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "byline",                    json!({ "column": "status", "words": {} }),                )            },            DefinitionError::Empty("slip.byline.words"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "byline",                    json!({ "column": "status", "words": { "shut": "b" } }),                )            },            not_a_choice("slip.byline.words", "shut"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "badge",                    json!({ "column": "nowhere", "symbol": "repeat", "spoken": "Repeats" }),                )            },            unknown("slip.badge.column", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "badge",                    json!({ "column": "person", "symbol": "", "spoken": "Repeats" }),                )            },            DefinitionError::Empty("slip.badge.symbol"),        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }}/// RULE: A slip's paper follows a declared public text or choice state; a/// choice map cannot invent a state, and a secret can never colour a slip.#[test]fn a_slips_stock_by_uses_a_public_declared_state() {    let mut valid = example();    valid["slip"]["stock_by"] = json!({ "column": "status", "values": { "open": "plain", "done": "sage" } });    let definition = parse(&valid);    definition.validate().expect("a choice state may select stock");    assert_eq!(serde_json::to_value(&definition).unwrap()["slip"]["stock_by"], valid["slip"]["stock_by"]);    let mut unknown_choice = valid.clone();    unknown_choice["slip"]["stock_by"]["values"] = json!({ "late": "rose" });    assert!(parse(&unknown_choice).validate().is_err());    let mut secret = example();    secret["columns"][0]["secret"] = json!(true);    secret["slip"]["stock_by"] = json!({ "column": "title", "values": { "Private": "rose" } });    assert!(parse(&secret).validate().is_err());}/// RULE: Page and list keys name columns of the right type; a conversation replaces a page only when its style says so, otherwise it belongs to a matching list on the shared page.#[test]fn the_lists_and_the_pages_optional_keys_name_declared_columns() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_top(v, "archived", json!("title")),            wrong_type("archived", "title", Text, "a_date_or_a_bool"),        ),        (            |v| set_top(v, "readonly_when", json!("nowhere")),            unknown("readonly_when", "nowhere"),        ),        (            |v| set_top(v, "listed_when", json!("nowhere")),            unknown("listed_when", "nowhere"),        ),        (            |v| set_top(v, "seal", json!({ "clear": ["nowhere"] })),            unknown("seal.clear", "nowhere"),        ),        (            |v| set_top(v, "seal", json!({ "clear": ["title"], "blind": ["nowhere"] })),            unknown("seal.blind", "nowhere"),        ),        (            |v| set_top(v, "seal", json!({ "clear": ["title"], "blind": ["title"] })),            DefinitionError::SealBlindClear { slot: "seal.blind".into(), column: "title".into() },        ),        (            |v| set_top(v, "seal", json!({ "clear": ["title"], "blind_exact": ["title"] })),            DefinitionError::SealBlindClear { slot: "seal.blind_exact".into(), column: "title".into() },        ),        (            |v| set_top(v, "seal", json!({ "blind": ["title"], "blind_bytes": { "nowhere": 10 } })),            DefinitionError::SealBlindBytes("nowhere".into()),        ),        (            |v| set_top(v, "seal", json!({ "blind": ["title"], "blind_bytes": { "title": 0 } })),            DefinitionError::SealBlindBytes("title".into()),        ),        (            |v| set_top(v, "kept_by", json!({ "when": "nowhere", "says": "Kept in step with Gmail" })),            unknown("kept_by.when", "nowhere"),        ),        (            |v| set_top(v, "sort", json!({ "column": "nowhere" })),            unknown("sort.column", "nowhere"),        ),        (            |v| set_top(v, "group", json!({ "column": "title", "sections": [] })),            wrong_type("group.column", "title", Text, "a choice"),        ),        (            |v| set_top(v, "group", json!({ "column": "status", "sections": [] })),            DefinitionError::Empty("group.sections"),        ),        (            |v| {                set_top(                    v,                    "group",                    json!({ "column": "status", "sections": [{ "heading": null, "values": ["shut"] }] }),                )            },            not_a_choice("group.sections", "shut"),        ),        (            |v| set_top(v, "by_day", json!("title")),            wrong_type("by_day", "title", Text, "a date"),        ),        (            |v| set_top(v, "by_month", json!("title")),            wrong_type("by_month", "title", Text, "a date"),        ),        (            |v| set_top(v, "day_grouping", json!("title")),            wrong_type("day_grouping", "title", Text, "a date"),        ),        (            |v| set_top(v, "opened", json!("title")),            wrong_type("opened", "title", Text, "a date"),        ),        (            |v| set_top(v, "upcoming", json!({ "undated": "No date" })),            DefinitionError::Empty("upcoming.dates"),        ),        (            |v| set_top(v, "upcoming", json!({ "dates": ["title"] })),            wrong_type("upcoming.dates", "title", Text, "a date"),        ),        (            |v| set_top(v, "upcoming", json!({ "dates": ["due_date"], "series": "nowhere" })),            DefinitionError::UnknownColumn { slot: "upcoming.series".into(), column: "nowhere".into() },        ),        (            |v| set_top(v, "recent", json!({ "column": "title" })),            wrong_type("recent.column", "title", Text, "a date"),        ),        (            |v| set_top(v, "recent", json!({ "column": "due_date", "count": 0 })),            DefinitionError::TooSmall {                slot: "recent.count".into(),                least: 1,            },        ),        (            |v| set_top(v, "dimmed", json!({ "column": "nowhere", "values": ["a"] })),            unknown("dimmed.column", "nowhere"),        ),        (            |v| set_top(v, "dimmed", json!({ "column": "status", "values": [] })),            DefinitionError::Empty("dimmed.values"),        ),        (            |v| {                set_top(                    v,                    "dimmed",                    json!({ "column": "status", "values": ["shut"] }),                )            },            not_a_choice("dimmed.values", "shut"),        ),        (            |v| set_top(v, "grid", json!({ "columns": 0 })),            DefinitionError::TooSmall {                slot: "grid.columns".into(),                least: 1,            },        ),        (            |v| set_top(v, "chips", json!({ "column": "title" })),            wrong_type("chips.column", "title", Text, "a choice"),        ),        (            |v| {                set_top(                    v,                    "chips",                    json!({ "column": "status", "sends": { "nowhere": 1 } }),                )            },            unknown("chips.sends", "nowhere"),        ),        (            |v| set_top(v, "cover", json!({ "footer": ["nowhere"] })),            unknown("cover.footer", "nowhere"),        ),        (            |v| {                set_top(                    v,                    "lists",                    json!([{ "heading": "Others", "columns": ["title"] }]),                )            },            requires("lists[0]", "a list"),        ),        (            |v| {                set_top(                    v,                    "lists",                    json!([{ "heading": "Others", "list": { "table": "Not An Id" } }]),                )            },            DefinitionError::BadId("Not An Id".into()),        ),        (            |v| set_top(v, "empty", json!({ "title": " " })),            DefinitionError::Empty("empty.title"),        ),        (            |v| set_top(v, "create", json!({ "label": "" })),            DefinitionError::Empty("create.label"),        ),        (            |v| set_top(v, "create", json!({ "label": "New", "dated": "title" })),            wrong_type("create.dated", "title", Text, "a date"),        ),        (            |v| {                set_top(                    v,                    "exports",                    json!([{ "label": "", "column": "notes", "extension": "txt" }]),                )            },            DefinitionError::Empty("exports.label"),        ),        (            |v| {                set_top(                    v,                    "exports",                    json!([{ "label": "Export", "column": "nowhere", "extension": "txt" }]),                )            },            unknown("exports.column", "nowhere"),        ),        (            |v| {                set_top(                    v,                    "exports",                    json!([{ "label": "Export", "column": "notes", "extension": ".txt" }]),                )            },            DefinitionError::BadExtension(".txt".into()),        ),        (            |v| {                set_top(                    v,                    "exports",                    json!([{ "label": "Export", "column": "notes", "extension": "TXT" }]),                )            },            DefinitionError::BadExtension("TXT".into()),        ),        (            |v| {                set_top(                    v,                    "exports",                    json!([{ "label": "Export", "column": "notes", "extension": "" }]),                )            },            DefinitionError::BadExtension("".into()),        ),        (            |v| set_top(v, "pager", json!("title")),            wrong_type("pager", "title", Text, "a link"),        ),        (            |v| {                set_top(                    v,                    "actions",                    json!([{ "label": "Call", "column": "nowhere", "scheme": "tel" }]),                )            },            unknown("actions.column", "nowhere"),        ),        (            |v| {                set_top(                    v,                    "actions",                    json!([{ "label": " ", "column": "title", "scheme": "tel" }]),                )            },            DefinitionError::Empty("actions.label"),        ),        (            |v| {                set_top(                    v,                    "actions",                    json!([{ "label": "Call", "column": "title", "scheme": "tel", "scheme_column": "notes" }]),                )            },            requires("actions.scheme_column", "schemes"),        ),        (            |v| {                set_top(                    v,                    "actions",                    json!([{ "label": "Call", "column": "title", "scheme": "tel", "schemes": { "a": "sms" } }]),                )            },            requires("actions.schemes", "scheme_column"),        ),        (            |v| {                set_top(                    v,                    "actions",                    json!([{ "label": "Call", "column": "title", "scheme": "tel",                                               "scheme_column": "nowhere", "schemes": { "a": "sms" } }]),                )            },            unknown("actions.scheme_column", "nowhere"),        ),        (            |v| {                set_top(                    v,                    "conversation",                    json!({ "table": "session_message", "links": ["to_session_id"], "body": "body",                                                    "at": "created_at", "mine": { "column": "from_kind", "values": ["owner"] } }),                )            },            requires("conversation", "page_parts_messages"),        ),        (            |v| set_top(v, "page_parts", json!(["title", "facts", "messages"])),            requires("page_parts", "conversation"),        ),        (            |v| {                set_top(v, "page_parts", json!(["title", "facts", "messages"]));                set_top(                    v,                    "conversation",                    json!({ "table": "Messages", "links": ["to_session_id"], "body": "body",                                                    "at": "created_at", "mine": { "column": "from_kind", "values": ["owner"] } }),                );            },            DefinitionError::BadId("Messages".into()),        ),        (            |v| {                set_top(v, "page_parts", json!(["title", "facts", "messages"]));                set_top(                    v,                    "conversation",                    json!({ "table": "session_message", "links": [], "body": "body",                                                    "at": "created_at", "mine": { "column": "from_kind", "values": ["owner"] } }),                );            },            DefinitionError::Empty("conversation.links"),        ),        (            |v| {                set_top(v, "page_parts", json!(["title", "facts", "messages"]));                set_top(                    v,                    "conversation",                    json!({ "table": "session_message", "links": ["to_session_id"], "body": "body",                                                    "at": "created_at", "mine": { "column": "from_kind", "values": [] } }),                );            },            DefinitionError::Empty("conversation.mine.values"),        ),        (            |v| {                set_top(v, "page_parts", json!(["title", "facts", "messages"]));                set_top(                    v,                    "conversation",                    json!({ "table": "session_message", "links": ["to_session_id"], "body": "body",                                                    "at": "created_at", "mine": { "column": "from_kind", "values": ["owner"] },                                                    "ended": "title" }),                );            },            wrong_type("conversation.ended", "title", Text, "a date"),        ),        (            |v| set_at(v, "/page/0", "picture", json!("title")),            wrong_type(                "page[0].picture",                "title",                Text,                "a_photo_a_file_or_a_latitude",            ),        ),        (            |v| set_at(v, "/page/0", "picture", json!("nowhere")),            unknown("page[0].picture", "nowhere"),        ),        (            |v| set_at(v, "/slip", "trailing_picture", json!("count")),            wrong_type(                "slip.trailing_picture",                "count",                Number,                "a_photo_a_file_or_a_latitude",            ),        ),        (            |v| set_at(v, "/page/1", "web", json!("due_date")),            wrong_type("page[1].web", "due_date", Date, "a text"),        ),        (            |v| set_at(v, "/page/1", "web", json!("title")),            DefinitionError::Conflict {                slot: "page[1].web".into(),                other: "columns",            },        ),        (            |v| {                v["page"].as_array_mut().unwrap().push(                    json!({ "heading": null, "list": { "table": "person", "link": "Todo Id" } }),                )            },            DefinitionError::BadId("Todo Id".into()),        ),        (            |v| {                v["page"]                    .as_array_mut()                    .unwrap()                    .push(json!({ "heading": null, "web": "title", "list": { "table": "person" } }))            },            DefinitionError::Conflict {                slot: "page[2].web".into(),                other: "a list",            },        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }    // A latitude with its pair draws a map, so it may head a section.    let mut value = example();    set_at(&mut value, "/columns/9", "pair", json!("position"));    set_at(&mut value, "/page/0", "picture", json!("count"));    parse(&value)        .validate()        .expect("a latitude with its pair is a picture");}/// RULE: A "+" with doors is a choice tier and nothing else (coordinator, 4 Nov 2026: Books' Plus is Find a book · Add a file · Bring Goodreads in). Each door has an id of its own, a word and a known picture, and does one thing: words typed and sent to an object act (saying its own words for Sign in instead on a phone not signed in), or files of named types chosen from the picker; a create with doors carries no act, path or day of its own.#[test]fn a_plus_with_doors_is_its_doors_alone() {    let doors = json!([        { "id": "find", "label": "Find a book", "object": "slip", "act": { "name": "find_book", "argument": "query", "lands": "book", "signed_out": "Sign in to find books by name" } },        { "id": "file", "label": "Add a file", "object": "folder", "files": { "types": ["org.idpf.epub-container", "com.adobe.pdf"], "many": true } },        { "id": "goodreads", "label": "Bring Goodreads in", "object": "envelope", "files": { "types": ["public.comma-separated-values-text"] } },    ]);    let mut value = example();    set_top(&mut value, "create", json!({ "label": "Add a book", "doors": doors }));    let definition = parse(&value);    definition.validate().expect("three doors stand");    let create = definition.create.as_ref().expect("a create");    assert_eq!(create.doors.iter().map(|door| door.id.as_str()).collect::<Vec<_>>(), ["find", "file", "goodreads"]);    assert_eq!(create.doors[0].act.as_ref().and_then(|act| act.lands.as_deref()), Some("book"));    assert_eq!(create.doors[0].act.as_ref().and_then(|act| act.signed_out.as_deref()), Some("Sign in to find books by name"));    assert!(create.doors[1].files.as_ref().is_some_and(|files| files.many));    assert!(!create.doors[2].files.as_ref().is_some_and(|files| files.many));    // Written back as it was read: no empty doors on a plain create, no `many: false`.    let written = serde_json::to_value(create).unwrap();    assert_eq!(written, json!({ "label": "Add a book", "doors": doors }));    let plain = serde_json::to_value(ListCreate { label: "New".into(), dated: None, path: None, method: None, act: None, doors: vec![] }).unwrap();    assert_eq!(plain, json!({ "label": "New" }));    let bad = |why: &str, slot: &str| DefinitionError::BadSlot { slot: slot.into(), why: refusal_words(why) };    let cases: Vec<(Value, DefinitionError)> = vec![        (            json!({ "label": "Add", "act": { "name": "find_book", "argument": "query" }, "doors": [doors[0].clone()] }),            DefinitionError::Conflict { slot: "create.doors".into(), other: "an_act_a_path_or_a_day_of_its_own" },        ),        (            json!({ "label": "Add", "path": "/books", "doors": [doors[0].clone()] }),            DefinitionError::Conflict { slot: "create.doors".into(), other: "an_act_a_path_or_a_day_of_its_own" },        ),        (            json!({ "label": "Add", "doors": [doors[0].clone(), doors[0].clone()] }),            bad("a_door_has_an_id_of_its_own", "create.doors.find"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "Find", "label": "Find", "act": { "name": "find_book", "argument": "query" } }] }),            bad("a_door_has_an_id_of_its_own", "create.doors.Find"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "find", "label": " ", "act": { "name": "find_book", "argument": "query" } }] }),            DefinitionError::EmptyAt("create.doors.find.label".into()),        ),        (            json!({ "label": "Add", "doors": [{ "id": "find", "label": "Find", "object": "magnifier", "act": { "name": "find_book", "argument": "query" } }] }),            requires("create.doors.find.object", "a_known_act_object"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "find", "label": "Find" }] }),            bad("a_door_types_words_or_chooses_files", "create.doors.find"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "find", "label": "Find", "act": { "name": "find_book", "argument": "query" }, "files": { "types": ["com.adobe.pdf"] } }] }),            bad("a_door_types_words_or_chooses_files", "create.doors.find"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "file", "label": "Add a file", "files": { "types": [] } }] }),            bad("a_door_s_files_name_their_types", "create.doors.file"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "file", "label": "Add a file", "files": { "types": ["com adobe pdf"] } }] }),            bad("a_door_s_files_name_their_types", "create.doors.file"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "file", "label": "Add a file", "files": { "types": ["com.example.unheard-of"] } }] }),            bad("a_door_s_files_name_their_types", "create.doors.file"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "find", "label": "Find", "act": { "name": "find_book", "argument": "query", "lands": "the book" } }] }),            bad("an_act_names_itself_and_its_argument", "create.doors.find.act"),        ),        (            json!({ "label": "Add", "act": { "name": "", "argument": "query" } }),            bad("an_act_names_itself_and_its_argument", "create.act"),        ),        (            json!({ "label": "Add", "doors": [{ "id": "find", "label": "Find", "act": { "name": "find_book", "argument": "query", "signed_out": " " } }] }),            DefinitionError::EmptyAt("create.doors.find.act.signed_out".into()),        ),    ];    for (index, (create, wanted)) in cases.into_iter().enumerate() {        let mut value = example();        set_top(&mut value, "create", create);        assert_eq!(parse(&value).validate(), Err(wanted), "case {index}");    }}/// RULE: The phone's shipped decoder names every column type the core can write: `DefinitionColumnType` in the generated Swift carries exactly `ColumnType::ALL`'s spellings, and `ALL` names every variant (the match below stops compiling when one is added). 294, walker293: the Mac wrote `account_number` and a phone refused Personal's money_account; a type the core writes that the phone's decoder lacks would refuse the row on every phone of that build.#[test]fn the_phones_decoder_names_every_column_type_the_core_writes() {    for kind in ColumnType::ALL {        match kind {            ColumnType::Text | ColumnType::AccountNumber | ColumnType::Longtext | ColumnType::Date            | ColumnType::Time | ColumnType::Number | ColumnType::Bytes | ColumnType::Amount            | ColumnType::Choice | ColumnType::Link | ColumnType::Photo | ColumnType::File            | ColumnType::Bool | ColumnType::Url | ColumnType::Place => {}        }    }    let written: BTreeSet<String> = ColumnType::ALL        .iter()        .map(|kind| serde_json::to_value(kind).unwrap().as_str().unwrap().to_string())        .collect();    assert_eq!(written.len(), ColumnType::ALL.len(), "ALL names a type twice");    for kind in &written {        let read: ColumnType = serde_json::from_value(serde_json::Value::from(kind.as_str())).unwrap();        assert_eq!(serde_json::to_value(read).unwrap(), kind.as_str(), "{kind} round-trips");    }    let swift = std::fs::read_to_string(        // Run time, not `env!` — a cached test binary carries a checkout that is gone (#403).        std::path::PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR"))            .join("../../apps/cotton/Sources/CottonUI/Definitions/GeneratedDefinitionTypes.swift"),    )    .expect("the generated Swift decoder");    let body = swift        .split("public enum DefinitionColumnType: String")        .nth(1)        .and_then(|rest| rest.split("\n}").next())        .expect("DefinitionColumnType in the generated Swift");    let decoded: BTreeSet<String> = body        .lines()        .filter_map(|line| line.trim().strip_prefix("case "))        .filter_map(|case| case.split('"').nth(1))        .map(str::to_string)        .collect();    assert_eq!(decoded, written, "the phone's decoder and the core's column types differ: run pnpm gen:swift-definitions");}/// RULE: Every amount column of a built-in definition names the column its currency is read from, because an amount without one is drawn as bare minor units, a hundred times too large.#[test]fn every_builtin_amount_names_its_currency() {    let mut bare: Vec<(String, String)> = Vec::new();    for definition in builtin_table_definitions().iter().cloned() {        for column in &definition.columns {            if column.column_type == ColumnType::Amount                && column.currency.is_none()            {                bare.push((definition.id.clone(), column.key.clone()));            }        }    }    bare.sort();    bare.dedup();    assert!(bare.is_empty(), "these amounts name no currency column; add \"currency\" to each: {bare:?}");}/// RULE: A command's `when` names columns of its own table; one naming anything else is refused, so a condition can never silently hide a command.#[test]fn a_commands_when_names_its_tables_columns() {    let thread = builtin_table_definition("thread").expect("the chat definition");    thread.validate().expect("the shipped conditions are its columns");    let mut bad = thread.clone();    let pin = bad.commands.as_mut().unwrap().iter_mut().find(|command| command.id == "pin").unwrap();    pin.when = Some(serde_json::from_value(json!({ "nowhere": true })).unwrap());    assert!(bad.validate().is_err());}// ---- the second round (1 Oct 2026) ------------------------------------------/// RULE: A column's second-round keys belong to the types they read, and every column they name is declared, of the type its meaning needs.////// Labels, choice_names and choices_from to a choice; until and yearly to a date;/// size, caption, caption_fallback and opens to a picture; poster to a file over a/// photo; zone and reach to a text; provenance to a long text; signs to an amount;/// each presentation to its own types.#[test]fn a_columns_second_round_keys_belong_to_its_type() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_at(v, "/columns/0", "presentation", json!("file")),            wrong_type("columns.title.presentation", "title", Text, "a file"),        ),        (            |v| set_at(v, "/columns/12", "presentation", json!("password")),            wrong_type("columns.file.presentation", "file", File, "a text"),        ),        (            |v| set_at(v, "/columns/2", "presentation", json!("sources")),            wrong_type(                "columns.due_date.presentation",                "due_date",                Date,                "a_text_or_a_long_text",            ),        ),        (            |v| set_at(v, "/columns/0", "choices_from", json!("notes")),            wrong_type("columns.title.choices_from", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/columns/7", "choices_from", json!("nowhere")),            unknown("columns.status.choices_from", "nowhere"),        ),        (            |v| set_at(v, "/columns/2", "labels", json!({ "a": "b" })),            wrong_type("columns.due_date.labels", "due_date", Date, "a_text_or_a_choice"),        ),        (            |v| set_at(v, "/columns/7", "labels", json!({ "shut": "Shut" })),            not_a_choice("columns.status.labels", "shut"),        ),        (            |v| set_at(v, "/columns/7", "labels", json!({ "open": " " })),            DefinitionError::EmptyAt("columns.status.labels".into()),        ),        (            |v| set_at(v, "/columns/7", "choice_names", json!({ "shut": "Shut" })),            not_a_choice("columns.status.choice_names", "shut"),        ),        (            |v| {                set_at(v, "/columns/7", "labels", json!({ "open": "To do" }));                set_at(v, "/columns/7", "choice_names", json!({ "open": "Open" }));            },            DefinitionError::Conflict {                slot: "columns.status.choice_names".into(),                other: "labels",            },        ),        (            |v| set_at(v, "/columns/0", "until", json!("due_date")),            wrong_type("columns.title.until", "title", Text, "a date"),        ),        (            |v| set_at(v, "/columns/2", "until", json!("due_date")),            DefinitionError::Conflict {                slot: "columns.due_date.until".into(),                other: "its_own_column",            },        ),        (            |v| set_at(v, "/columns/2", "until", json!("title")),            wrong_type("columns.due_date.until", "title", Text, "a date"),        ),        (            |v| set_at(v, "/columns/0", "size", json!(["count", "position"])),            wrong_type("columns.title.size", "title", Text, "a_photo_or_a_file"),        ),        (            |v| set_at(v, "/columns/11", "size", json!(["count"])),            requires("columns.photo.size", "a_width_column_and_a_height_column"),        ),        (            |v| set_at(v, "/columns/11", "size", json!(["count", "title"])),            wrong_type("columns.photo.size", "title", Text, "a number"),        ),        (            |v| set_at(v, "/columns/0", "caption", json!("notes")),            wrong_type("columns.title.caption", "title", Text, "a_photo_or_a_file"),        ),        (            |v| set_at(v, "/columns/11", "caption", json!("nowhere")),            unknown("columns.photo.caption", "nowhere"),        ),        (            |v| set_at(v, "/columns/12", "caption_fallback", json!("nowhere")),            unknown("columns.file.caption_fallback", "nowhere"),        ),        (            |v| set_at(v, "/columns/2", "opens", json!({ "column": "person" })),            wrong_type(                "columns.due_date.opens",                "due_date",                Date,                "a_photo_a_file_or_a_text",            ),        ),        (            |v| set_at(v, "/columns/11", "opens", json!({ "column": "nowhere" })),            unknown("columns.photo.opens.column", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/columns/11",                    "opens",                    json!({ "column": "person", "table": "Person" }),                )            },            DefinitionError::BadId("Person".into()),        ),        (            |v| {                set_at(                    v,                    "/columns/11",                    "opens",                    json!({ "column": "person", "table_column": "nowhere" }),                )            },            unknown("columns.photo.opens.table_column", "nowhere"),        ),        (            |v| set_at(v, "/columns/11", "poster", json!("photo")),            wrong_type("columns.photo.poster", "photo", Photo, "a file"),        ),        (            |v| set_at(v, "/columns/12", "poster", json!("title")),            wrong_type("columns.file.poster", "title", Text, "a photo"),        ),        (            |v| set_at(v, "/columns/2", "zone", json!(true)),            wrong_type("columns.due_date.zone", "due_date", Date, "a text"),        ),        (            |v| set_at(v, "/columns/0", "yearly", json!(true)),            wrong_type("columns.title.yearly", "title", Text, "a date"),        ),        (            |v| set_at(v, "/columns/9", "reach", json!("phone")),            wrong_type("columns.count.reach", "count", Number, "a text"),        ),        (            |v| {                set_at(                    v,                    "/columns/0",                    "reach",                    json!({ "kind": "phone", "channel": "nowhere" }),                )            },            unknown("columns.title.reach.channel", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/columns/0",                    "provenance",                    json!({ "by": "title", "at": "due_date" }),                )            },            wrong_type("columns.title.provenance", "title", Text, "a long text"),        ),        (            |v| {                set_at(                    v,                    "/columns/1",                    "provenance",                    json!({ "by": "nowhere", "at": "due_date" }),                )            },            unknown("columns.notes.provenance.by", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/columns/1",                    "provenance",                    json!({ "by": "title", "at": "title" }),                )            },            wrong_type("columns.notes.provenance.at", "title", Text, "a date"),        ),        (            |v| {                set_at(                    v,                    "/columns/1",                    "provenance",                    json!({ "by": "title", "at": "due_date", "since": "nowhere" }),                )            },            unknown("columns.notes.provenance.since", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/columns/9",                    "signs",                    json!({ "positive": "a", "negative": "b" }),                )            },            wrong_type("columns.count.signs", "count", Number, "an amount"),        ),        (            |v| {                set_at(                    v,                    "/columns/8",                    "signs",                    json!({ "positive": "", "negative": "b" }),                )            },            DefinitionError::EmptyAt("columns.amount.signs.positive".into()),        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }}/// RULE: A slip's second-round keys name declared columns of the right type — answers a choice and its values, unread a date or a choice holding `unread` — a badge's values are the column's choices, and a list subtitle names at least one column.#[test]fn a_slips_second_round_keys_name_declared_columns() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_at(v, "/slip", "subtitle", json!([])),            DefinitionError::Empty("slip.subtitle"),        ),        (            |v| set_at(v, "/slip", "subtitle", json!(["notes", "nowhere"])),            unknown("slip.subtitle", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "answers",                    json!({ "column": "title", "values": { "a": "b" } }),                )            },            wrong_type("slip.answers.column", "title", Text, "a choice"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "answers",                    json!({ "column": "status", "values": {} }),                )            },            DefinitionError::EmptyAt("slip.answers.values".into()),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "answers",                    json!({ "column": "status", "values": { "shut": "Shut" } }),                )            },            not_a_choice("slip.answers.values", "shut"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "answers",                    json!({ "column": "status", "values": { "done": "" } }),                )            },            DefinitionError::EmptyAt("slip.answers.values".into()),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "answers",                    json!({ "column": "status", "values": { "done": "Done" }, "when": ["shut"] }),                )            },            not_a_choice("slip.answers.when", "shut"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "answers",                    json!({ "column": "status", "values": { "done": "Done" }, "primary": "open" }),                )            },            requires("slip.answers.primary", "one_of_the_answers_values"),        ),        (            |v| set_at(v, "/slip", "unread", json!("title")),            wrong_type("slip.unread", "title", Text, "a_date_or_a_choice"),        ),        (            |v| set_at(v, "/slip", "status", json!("nowhere")),            unknown("slip.status", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "badge",                    json!({ "column": "status", "symbol": "play", "spoken": "Film", "values": [] }),                )            },            DefinitionError::Empty("slip.badge.values"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "badge",                    json!({ "column": "status", "symbol": "play", "spoken": "Film", "values": ["shut"] }),                )            },            not_a_choice("slip.badge.values", "shut"),        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }}/// RULE: A page section's second-round keys name declared columns — when, hand, answers and actions — a when says which values or that any is enough, ink goes with a note or a facts line, and an action sets something or deletes./// A list section draws at least one record across at least one column.#[test]fn a_page_sections_second_round_keys_name_declared_columns() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| {                set_at(                    v,                    "/page/0",                    "when",                    json!({ "column": "nowhere", "present": true }),                )            },            unknown("page[0].when.column", "nowhere"),        ),        (            |v| set_at(v, "/page/0", "when", json!({ "column": "status" })),            requires("page[0].when", "values_or_present"),        ),        (            |v| {                set_at(                    v,                    "/page/0",                    "when",                    json!({ "column": "status", "values": [] }),                )            },            DefinitionError::EmptyAt("page[0].when.values".into()),        ),        (            |v| {                set_at(                    v,                    "/page/0",                    "when",                    json!({ "column": "status", "values": ["shut"] }),                )            },            not_a_choice("page[0].when.values", "shut"),        ),        (            |v| set_at(v, "/page/0", "note", json!(" ")),            DefinitionError::EmptyAt("page[0].note".into()),        ),        (            |v| set_at(v, "/page/0", "ink", json!("red")),            requires("page[0].ink", "a_note_or_the_facts_role"),        ),        (            |v| set_at(v, "/page/0", "hand", json!(["nowhere"])),            unknown("page[0].hand", "nowhere"),        ),        (            |v| set_at(v, "/page/0", "hand", json!("Suggested by {nowhere}")),            unknown("page[0].hand", "nowhere"),        ),        (            |v| set_at(v, "/page/0", "hand", json!("No column at all")),            requires("page[0].hand", "a_column_or_words_naming_one_as"),        ),        (            |v| {                set_at(                    v,                    "/page/0",                    "answers",                    json!({ "column": "title", "values": { "a": "b" } }),                )            },            wrong_type("page[0].answers.column", "title", Text, "a choice"),        ),        (            |v| set_at(v, "/page/0", "actions", json!([{ "label": "Keep" }])),            requires("page[0].actions", "sets_or_delete"),        ),        (            |v| {                set_at(                    v,                    "/page/0",                    "actions",                    json!([{ "label": "", "delete": true }]),                )            },            DefinitionError::EmptyAt("page[0].actions.label".into()),        ),        (            |v| {                set_at(                    v,                    "/page/0",                    "actions",                    json!([{ "label": "Keep", "sets": { "nowhere": null } }]),                )            },            unknown("page[0].actions.sets", "nowhere"),        ),        (            |v| {                set_at(                    v,                    "/page/0",                    "actions",                    json!([{ "label": "Shut", "sets": { "status": "shut" } }]),                )            },            not_a_choice("page[0].actions.sets", "shut"),        ),        (            |v| {                set_at(                    v,                    "/page/0",                    "actions",                    json!([{ "label": "Shut", "sets": { "status": 1 } }]),                )            },            not_a_choice("page[0].actions.sets", "1"),        ),        (            |v| set_at(v, "/page/0", "hand", json!("Suggested by {title")),            requires("page[0].hand", "every { closed by a }"),        ),        (            |v| set_at(v, "/page/0", "links", json!({ "except": ["Notes"] })),            DefinitionError::BadId("Notes".into()),        ),        (            |v| list_section(v, json!({ "table": "person", "limit": 0 })),            DefinitionError::TooSmall {                slot: "page[2].list.limit".into(),                least: 1,            },        ),        (            |v| list_section(v, json!({ "table": "person", "columns": 0 })),            DefinitionError::TooSmall {                slot: "page[2].list.columns".into(),                least: 1,            },        ),        (            |v| {                list_section(                    v,                    json!({ "table": "person", "with": [{ "table": "note", "link": "People" }] }),                )            },            DefinitionError::BadId("People".into()),        ),        (            |v| list_section(v, json!({ "table": "person", "add": " " })),            DefinitionError::EmptyAt("page[2].list.add".into()),        ),        (            |v| list_section(v, json!({ "table": "person", "empty": { "title": "" } })),            DefinitionError::Empty("list.empty"),        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }}/// RULE: The list's second-round keys name declared columns of the type their meaning needs, and its routes, commands and cross-table ids are well formed.////// Index a text, search texts, deletion's size a number, the filter's, count's and/// hidden's values among a choice's choices. A route starts with one slash, a/// command is declared once with a well-formed verb and binds declared columns,/// on_open names a declared command, and a cross-table id is at least a/// well-formed id.#[test]fn the_lists_second_round_keys_name_declared_columns() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_top(v, "index", json!("count")),            wrong_type("index", "count", Number, "a text"),        ),        (            |v| set_top(v, "search", json!([])),            DefinitionError::Empty("search"),        ),        (            |v| set_top(v, "search", json!(["due_date"])),            wrong_type("search", "due_date", Date, "a_text_or_a_long_text"),        ),        (            |v| set_top(v, "opens", json!({ "column": "nowhere" })),            unknown("opens.column", "nowhere"),        ),        (            |v| {                v["tile"]["face"] = json!("polaroid-grid");                set_top(v, "polaroid", json!({ "title": "nowhere" }));            },            unknown("polaroid.title", "nowhere"),        ),        (            |v| set_top(v, "polaroid", json!({ "title": "title" })),            requires("polaroid", "the_polaroid_grid_tile"),        ),        (            |v| set_top(v, "filter", json!({ "column": "nowhere" })),            unknown("filter.column", "nowhere"),        ),        (            |v| {                set_top(                    v,                    "filter",                    json!({ "column": "status", "words": { "shut": "shut ones" } }),                )            },            not_a_choice("filter", "shut"),        ),        (            |v| {                set_top(                    v,                    "filter",                    json!({ "column": "status", "order": ["shut"] }),                )            },            not_a_choice("filter", "shut"),        ),        (            |v| set_top(v, "filter", json!({ "column": "status", "all": "" })),            DefinitionError::Empty("filter.all"),        ),        (            |v| set_top(v, "count_words", json!({ "column": "status", "units": {} })),            DefinitionError::Empty("count_words.units"),        ),        (            |v| {                set_top(                    v,                    "count_words",                    json!({ "column": "status", "units": { "shut": { "one": "a", "other": "b" } } }),                )            },            not_a_choice("count_words.units", "shut"),        ),        (            |v| {                set_top(v, "by_month", json!("due_date"));                set_top(v, "months", json!({ "undated": " " }));            },            DefinitionError::Empty("months.undated"),        ),        (            |v| set_top(v, "months", json!({ "over": 0 })),            requires("months", "by_month"),        ),        (            |v| set_top(v, "hidden", json!({ "column": "status", "values": [] })),            DefinitionError::Empty("hidden.values"),        ),        (            |v| {                set_top(                    v,                    "hidden",                    json!({ "column": "status", "values": ["shut"] }),                )            },            not_a_choice("hidden.values", "shut"),        ),        (            |v| set_top(v, "deletion", json!({ "size": "title" })),            wrong_type("deletion.size", "title", Text, "a number"),        ),        (            |v| set_top(v, "deletion", json!({ "confirm": "" })),            DefinitionError::Empty("deletion.confirm"),        ),        (            |v| {                set_top(                    v,                    "links",                    json!([{ "label": "Albums", "table": "album", "path": "photos/albums" }]),                )            },            requires("links.path", "an_app_route_starting_with_one"),        ),        (            |v| {                set_top(                    v,                    "links",                    json!([{ "label": "Albums", "table": "album", "path": "//example.org" }]),                )            },            requires("links.path", "an_app_route_starting_with_one"),        ),        (            |v| {                set_top(                    v,                    "links",                    json!([{ "label": "Albums", "table": "Album", "path": "/photos" }]),                )            },            DefinitionError::BadId("Album".into()),        ),        (            |v| {                set_top(                    v,                    "create",                    json!({ "label": "Import", "path": "https://example.org" }),                )            },            requires("create.path", "an_app_route_starting_with_one"),        ),        (            |v| set_top(v, "search_placeholder", json!("")),            DefinitionError::Empty("search_placeholder"),        ),        (            |v| set_top(v, "grid", json!({ "columns": 2 })),            requires("grid", "layout_cards_or_sheet_a_list_draws"),        ),        (            |v| set_top(v, "layout", json!("sheet")),            requires("layout", "grid_the_contact_sheet_s_count_across"),        ),        (            |v| {                set_top(                    v,                    "related",                    json!([{ "label": "Kept", "table": "message", "open": "Thread" }]),                )            },            DefinitionError::BadId("Thread".into()),        ),        (            |v| set_top(v, "related", json!([{ "label": " ", "table": "message" }])),            DefinitionError::Empty("related.label"),        ),        (            |v| {                set_top(                    v,                    "commands",                    json!([{ "id": "read", "label": "Read", "kind": "update", "receipt": "It was done", "verb": "mark_read" },                                               { "id": "read", "label": "Again", "kind": "update", "receipt": "It was done", "verb": "mark_read" }]),                )            },            DefinitionError::DuplicateCommand("read".into()),        ),        (            |v| {                set_top(                    v,                    "commands",                    json!([{ "id": "read", "label": "Read", "kind": "update", "receipt": "It was done", "verb": "markRead" }]),                )            },            DefinitionError::BadId("markRead".into()),        ),        (            |v| {                set_top(                    v,                    "commands",                    json!([{ "id": "read", "label": "Read", "kind": "update", "receipt": "It was done", "verb": "mark_read", "bindings": { "id": "nowhere" } }]),                )            },            unknown("commands.bindings", "nowhere"),        ),        (            |v| {                set_top(                    v,                    "commands",                    json!([{ "id": "read", "label": "Read", "kind": "update", "receipt": "It was done", "verb": "mark_read" }]),                );                set_top(v, "on_open", json!("clear"));            },            DefinitionError::UnknownCommand {                slot: "on_open".into(),                id: "clear".into(),            },        ),        (            |v| set_top(v, "on_open", json!("read")),            DefinitionError::UnknownCommand {                slot: "on_open".into(),                id: "read".into(),            },        ),        (            |v| set_top(v, "sort", json!({ "column": "due_date", "tie": "nowhere" })),            unknown("sort.tie", "nowhere"),        ),        (            |v| {                set_top(                    v,                    "empty",                    json!({ "title": "None.", "search": { "title": "" } }),                )            },            DefinitionError::Empty("empty.search.title"),        ),        (            |v| set_top(v, "group", json!({ "column": "nowhere" })),            unknown("group.column", "nowhere"),        ),        (            |v| {                full_conversation(v);                v["conversation"]["anchor"] = json!("nowhere");            },            unknown("conversation.anchor", "nowhere"),        ),        (            |v| {                full_conversation(v);                v["conversation"]["header"] = json!(["Sender"]);            },            DefinitionError::BadId("Sender".into()),        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }}/// RULE: A key the builders spell in two forms reads both and writes back the one it was given, and a group with no sections splits by any column's runs.////// A slip subtitle as one column or a list, a list section's empty words as a/// sentence or a title and message, a reach as a word or an object, a hand line as/// columns or one sentence.#[test]fn a_key_spelled_two_ways_round_trips_whichever_was_given() {    let round_trips = |mutate: fn(&mut Value)| {        let mut value = example();        mutate(&mut value);        let json = serde_json::to_string(&value).unwrap();        let definition =            TableDefinition::from_json(&json).unwrap_or_else(|e| panic!("{json}: {e}"));        definition            .validate()            .unwrap_or_else(|e| panic!("{json}: {e}"));        assert_eq!(definition.to_json(), json);        definition    };    let several = round_trips(|v| set_at(v, "/slip", "subtitle", json!(["notes", "title"])));    assert_eq!(        several.slip.subtitles(),        ["notes".to_string(), "title".to_string()]    );    assert_eq!(parse(&example()).slip.subtitles(), ["notes".to_string()]);    let titled = round_trips(|v| {        list_section(            v,            json!({ "table": "photo", "empty": { "title": "No photos.", "message": "Add some." } }),        )    });    assert!(matches!(        titled.page[2]            .list            .as_ref()            .and_then(|list| list.empty.as_ref()),        Some(SectionEmpty::Titled(_))    ));    round_trips(|v| list_section(v, json!({ "table": "photo", "empty": "No photos." })));    let word = round_trips(|v| set_at(v, "/columns/0", "reach", json!("email")));    assert_eq!(        word.column("title")            .and_then(|c| c.reach.as_ref())            .map(ColumnReach::kind),        Some(ReachKind::Email)    );    round_trips(|v| set_at(v, "/columns/0", "reach", json!({ "kind": "phone" })));    let sentence = round_trips(|v| {        set_at(            v,            "/page/0",            "hand",            json!("Suggested by {title} on {due_date}"),        )    });    assert_eq!(        sentence.page[0].hand.as_ref().map(PageHand::keys),        Some(vec!["title", "due_date"])    );    round_trips(|v| set_top(v, "group", json!({ "column": "person" })));    // A link and a text hold several values too (People's phones, a photo's tags).    round_trips(|v| set_at(v, "/columns/0", "multiple", json!(true)));    round_trips(|v| set_at(v, "/columns/6", "multiple", json!(true)));}/// RULE: Where every Swift decoder reads more than the first round allowed, Rust reads it too — a definition with no instructions (which stays without), a choice column whose choices come from the record (`choices_from`), and a caption status read from a text column.#[test]fn what_every_swift_decoder_reads_rust_reads_too() {    let mut value = example();    value.as_object_mut().unwrap().remove("instructions");    let json = serde_json::to_string(&value).unwrap();    let definition = TableDefinition::from_json(&json).expect("parses");    definition.validate().expect("valid");    assert_eq!(definition.instructions, None);    assert_eq!(definition.to_json(), json, "absent stays absent");    let mut value = example();    value["columns"]        .as_array_mut()        .unwrap()        .push(json!({ "key": "owner", "type": "choice", "choices_from": "notes" }));    parse(&value)        .validate()        .expect("its choices are the record's own");    let mut value = example();    value["columns"]        .as_array_mut()        .unwrap()        .push(json!({ "key": "owner", "type": "choice" }));    assert_eq!(        parse(&value).validate(),        Err(DefinitionError::ChoiceWithoutChoices("owner".into()))    );    let mut value = example();    set_at(        &mut value,        "/slip",        "caption",        json!({ "status": "title", "dates": ["due_date"] }),    );    parse(&value)        .validate()        .expect("a text's own word leads the caption");}/// RULE: The second round's enumerations are spelled the shared way and nothing else parses — the bytes and dimensions formats, the presentations, the receipt edge, the inks, the select verb and the reach kinds.#[test]fn the_second_rounds_enumerations_are_spelled_the_shared_way() {    for (format, spelled) in [        (ColumnFormat::Bytes, "bytes"),        (ColumnFormat::Dimensions, "dimensions"),    ] {        assert_eq!(serde_json::to_value(format).unwrap(), json!(spelled));    }    for (presentation, spelled) in [        (ColumnPresentation::Sources, "sources"),        (ColumnPresentation::File, "file"),        (ColumnPresentation::Password, "password"),        (ColumnPresentation::Attachments, "attachments"),        (ColumnPresentation::Turns, "turns"),        (ColumnPresentation::Heading, "heading"),        (ColumnPresentation::Changes, "changes"),    ] {        assert_eq!(serde_json::to_value(presentation).unwrap(), json!(spelled));    }    assert_eq!(        serde_json::to_value(SlipEdge::Receipt).unwrap(),        json!("receipt")    );    assert_eq!(serde_json::to_value(Ink::Red).unwrap(), json!("red"));    assert_eq!(serde_json::to_value(Ink::Pencil).unwrap(), json!("pencil"));    assert_eq!(        serde_json::to_value(SelectVerb::Delete).unwrap(),        json!("delete")    );    assert_eq!(        serde_json::to_value(ReachKind::Phone).unwrap(),        json!("phone")    );    assert_eq!(        serde_json::to_value(ReachKind::Email).unwrap(),        json!("email")    );    let parses = |mutate: fn(&mut Value)| {        let mut value = example();        mutate(&mut value);        TableDefinition::authored(&value).is_ok()    };    assert!(parses(|v| set_at(        v,        "/columns/9",        "format",        json!("bytes")    )));    assert!(!parses(|v| set_at(        v,        "/columns/9",        "format",        json!("megabytes")    )));    assert!(!parses(|v| set_at(        v,        "/columns/12",        "presentation",        json!("video")    )));    assert!(!parses(|v| set_at(v, "/slip", "edge", json!("torn"))));    assert!(!parses(|v| set_at(v, "/page/0", "ink", json!("blue"))));    assert!(!parses(|v| set_at(        v,        "/slip",        "byline",        json!({ "column": "status", "words": { "done": "x" }, "ink": "green" })    )));    assert!(!parses(|v| set_top(        v,        "select",        json!({ "verb": "archive" })    )));    assert!(!parses(|v| set_at(v, "/columns/0", "reach", json!("fax"))));    assert!(!parses(|v| set_at(        v,        "/columns/0",        "reach",        json!({ "kind": "fax" })    )));    assert!(!parses(|v| set_at(        v,        "/columns/0",        "reach",        json!({ "kind": "phone", "line": "notes" })    )));    assert!(!parses(|v| set_at(v, "/slip", "subtitle", json!(7))));    assert!(!parses(|v| list_section(        v,        json!({ "table": "photo", "empty": { "title": "None.", "extra": true } })    )));    assert!(!parses(|v| set_at(        v,        "/page/0",        "hand",        json!({ "columns": ["title"] })    )));    // A list section has no search of its own, so its empty words carry none.    assert!(!parses(|v| {        list_section(            v,            json!({ "table": "photo", "empty": { "title": "None.", "search": { "title": "No match." } } }),        )    }));    assert_eq!(        serde_json::to_value(ColumnFormat::DurationMs).unwrap(),        json!("duration_ms")    );    assert_eq!(        serde_json::to_value(ColumnFormat::Duration).unwrap(),        json!("duration")    );    assert!(!parses(|v| set_at(        v,        "/columns/9",        "format",        json!("duration-ms")    )));}/// A table a person defined: no engine to run a verb, and the generic record write behind it.fn user_table(value: &mut Value) {    value["builtin"] = json!(false);    value["engine"] = json!(null);}/// RULE: Commands and engine-written columns require a compiled engine binding; a data-only table has no engine to execute them, and provenance never supplies one.////// Such a column holds several values (`multiple`) or reads its choices off the/// record (`choices_from`), and `records::check_value` takes one value from a/// column's own choices.#[test]fn commands_and_engine_written_columns_belong_to_built_ins() {    let cases: Vec<(fn(&mut Value), &str)> = vec![        (            |v| {                user_table(v);                set_top(                    v,                    "commands",                    json!([{ "id": "read", "label": "Read", "kind": "update", "receipt": "It was done", "verb": "mark_read" }]),                );            },            "commands",        ),        (            |v| {                user_table(v);                set_top(v, "on_open", json!("read"));            },            "on_open",        ),        (            |v| {                user_table(v);                set_at(v, "/columns/7", "multiple", json!(true));            },            "columns.status.multiple",        ),        (            |v| {                user_table(v);                set_at(v, "/columns/0", "multiple", json!(true));            },            "columns.title.multiple",        ),        (            |v| {                user_table(v);                set_at(v, "/columns/7", "choices_from", json!("notes"));            },            "columns.status.choices_from",        ),    ];    for (mutate, wanted_slot) in cases {        for provenance in [false, true] {            let mut value = example();            mutate(&mut value);            value["builtin"] = json!(provenance);            match parse(&value).validate().expect_err("a data-only table cannot run an engine") {                DefinitionError::Requires { slot, .. } => assert_eq!(slot, wanted_slot),                error => panic!("wrong refusal for {wanted_slot}: {error:?}"),            }        }    }    // `multiple: false` says nothing the write cannot take.    let mut value = example();    user_table(&mut value);    set_at(&mut value, "/columns/7", "multiple", json!(false));    parse(&value)        .validate()        .expect("a single value is the generic write's");}fn format_face_example() -> Value {    let mut value = example();    value["columns"].as_array_mut().unwrap().extend([        json!({"key":"currency", "type":"text"}),        json!({"key":"kind", "type":"choice", "choices":["document","external"]}),        json!({"key":"ref_id", "type":"link", "readonly":true,            "link_by":{"column":"kind","tables":{"document":"document"}}}),    ]);    value["columns"][8]["currency"] = json!("currency");    value["columns"][8]["signed"] = json!(true);    value["page"][0]["figure"] = json!("amount");    value["slip"]["opens"] = json!("ref_id");    value}/// RULE: Figures retain their currency, sign, page prominence and evidence destination through the shared definition format.#[test]fn format_face_keys_round_trip() {    let value = format_face_example();    let definition = parse(&value);    definition.validate().unwrap();    assert_eq!(serde_json::to_value(definition).unwrap(), value);}/// RULE: Face references name columns of the right type, and a dynamic evidence link never opens an editor that cannot validate its target.#[test]fn format_face_keys_refuse_invalid_references() {    for (pointer, replacement) in [        ("/columns/8/currency", json!("missing")),        ("/columns/8/currency", json!("count")),        ("/columns/0/currency", json!("currency")),        ("/columns/0/signed", json!(true)),        ("/page/0/figure", json!("title")),        ("/slip/opens", json!("title")),        ("/columns/15/link_by/column", json!("title")),        ("/columns/15/link_by/tables", json!({})),        (            "/columns/15/link_by/tables",            json!({"document":"bad table"}),        ),        ("/columns/15/link_by/tables", json!({"missing":"document"})),        ("/columns/15/readonly", json!(false)),    ] {        let mut value = format_face_example();        let (parent, key) = pointer.rsplit_once('/').unwrap();        value            .pointer_mut(parent)            .unwrap()            .as_object_mut()            .unwrap()            .insert(key.into(), replacement);        assert!(parse(&value).validate().is_err(), "{pointer}");    }}/// RULE: The existing RecordOpens object is also accepted for a slip, while a column-key spelling stays a column key on round-trip.#[test]fn format_slip_opens_reuses_record_opens() {    let mut value = format_face_example();    value["slip"]["opens"] = json!({"column":"ref_id", "table":"document"});    let definition = parse(&value);    definition.validate().unwrap();    assert_eq!(serde_json::to_value(definition).unwrap(), value);}/// RULE: An amount may take its currency from an account link, but never an unrelated link.#[test]fn format_currency_accepts_account_sources() {    for source in ["account_id", "account"] {        let mut value = format_face_example();        value["columns"]            .as_array_mut()            .unwrap()            .push(json!({"key":"account_id","type":"link","link_to":"money_account"}));        value["columns"][8]["currency"] = json!(source);        value["columns"][8]["signed"] = json!(false);        let definition = parse(&value);        definition.validate().unwrap();        assert_eq!(serde_json::to_value(definition).unwrap(), value);        value["columns"][16]["link_to"] = json!("person");        assert!(parse(&value).validate().is_err());    }}/// RULE: Format keys refuse wrong wire types and unknown nested fields instead of dropping them on a write.#[test]fn format_keys_refuse_malformed_wire_shapes() {    for (pointer, replacement) in [        ("/columns/8/signed", json!("true")),        ("/columns/8/currency", json!(true)),        ("/page/0/figure", json!(12)),        ("/slip/opens", json!({"column":"ref_id", "typo":true})),        (            "/columns/15/link_by",            json!({"column":"kind", "tables":{"document":"document"},"typo":true}),        ),    ] {        let mut value = format_face_example();        *value.pointer_mut(pointer).unwrap() = replacement;        assert!(TableDefinition::authored(&value).is_err(), "{pointer}");    }    let mut value = format_face_example();    value["columns"][15]["link_to"] = json!("document");    assert!(parse(&value).validate().is_err());    let mut value = format_face_example();    value["page"][0]["web"] = json!("title");    assert!(parse(&value).validate().is_err());}// ---- the third round (1 Oct 2026) -------------------------------------------/// RULE: The third round's keys name declared columns of the type their meaning needs, cross-table ids are well formed, and every word a face reads says something.////// A hand-over's condition names a declared column and its choices; the words/// sent to a session are a text; the conversation's opening line is a date and/// declared columns. A slip's links, the merged tables and the email envelope are/// at least well-formed ids. The hand-over never writes the record's id over its/// own arguments, and a table is read again no more often than every second nor/// less often than once a day.#[test]fn the_third_rounds_keys_name_declared_columns() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_at(v, "/slip", "links", json!({ "except": ["Todo"] })),            DefinitionError::BadId("Todo".into()),        ),        (            |v| {                set_top(                    v,                    "hand_over",                    json!({ "when": { "column": "nowhere", "present": true } }),                )            },            unknown("hand_over.when.column", "nowhere"),        ),        (            |v| set_top(v, "hand_over", json!({ "when": { "column": "status" } })),            requires("hand_over.when", "values_or_present"),        ),        (            |v| {                set_top(                    v,                    "hand_over",                    json!({ "when": { "column": "status", "values": [] } }),                )            },            DefinitionError::EmptyAt("hand_over.when.values".into()),        ),        (            |v| {                set_top(                    v,                    "hand_over",                    json!({ "when": { "column": "status", "values": ["shut"] } }),                )            },            not_a_choice("hand_over.when.values", "shut"),        ),        (            |v| set_top(v, "attachments", json!({ "sources": [] })),            DefinitionError::Empty("attachments.sources"),        ),        (            |v| set_top(v, "clear", json!({ "label": "" })),            DefinitionError::Empty("clear.label"),        ),        (            |v| set_top(v, "clear", json!({ "label": "Empty", "message": " " })),            DefinitionError::Empty("clear.message"),        ),        (            |v| set_top(v, "clear", json!({ "label": "Empty", "done": "" })),            DefinitionError::Empty("clear.done"),        ),        (            |v| set_top(v, "live", json!({ "every": 0.5 })),            DefinitionError::TooSmall {                slot: "live.every".into(),                least: 1,            },        ),        (            |v| set_top(v, "live", json!({ "every": -3 })),            DefinitionError::TooSmall {                slot: "live.every".into(),                least: 1,            },        ),        (            |v| set_top(v, "live", json!({ "every": 86401 })),            requires("live.every", "at_most_a_day_86400_seconds"),        ),        (            |v| {                full_conversation(v);                set_at(v, "/conversation", "header_columns", json!(["From"]));            },            DefinitionError::BadId("From".into()),        ),        (            |v| {                full_conversation(v);                set_at(v, "/conversation", "started", json!({ "at": "nowhere" }));            },            unknown("conversation.started.at", "nowhere"),        ),        (            |v| {                full_conversation(v);                set_at(v, "/conversation", "started", json!({ "at": "title" }));            },            wrong_type("conversation.started.at", "title", Text, "a date"),        ),        (            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "started",                    json!({ "at": "due_date", "words": ["nowhere"] }),                );            },            unknown("conversation.started.words", "nowhere"),        ),        (            |v| {                full_conversation(v);                set_at(v, "/conversation", "placeholder", json!(""));            },            DefinitionError::Empty("conversation.placeholder"),        ),        (            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "also",                    json!([{ "table": "Prompts", "links": ["session_id"], "body": "text", "at": "ts" }]),                );            },            DefinitionError::BadId("Prompts".into()),        ),        (            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "also",                    json!([{ "table": "prompt", "links": [], "body": "text", "at": "ts" }]),                );            },            DefinitionError::Empty("conversation.also.links"),        ),        (            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "also",                    json!([{ "table": "prompt", "links": ["session_id"], "body": "text", "at": "ts",                             "mine": { "column": "role", "values": [] } }]),                );            },            DefinitionError::Empty("conversation.also.mine.values"),        ),        (            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "also",                    json!([{ "table": "prompt", "links": ["session_id"], "at": "ts" }]),                );            },            requires("conversation.also.body", "a_body_unless_the_face_is_slip"),        ),        (            |v| {                full_conversation(v);                set_at(                    v,                    "/conversation",                    "also",                    json!([{ "table": "prompt", "links": ["session_id"], "at": "ts", "face": "note" }]),                );            },            requires("conversation.also.body", "a_body_unless_the_face_is_slip"),        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }    // The cadence's bounds are themselves allowed, a fraction between them too.    for every in [json!(1), json!(86400), json!(2.5)] {        let mut value = example();        set_top(&mut value, "live", json!({ "every": every }));        let json = serde_json::to_string(&value).unwrap();        let definition = TableDefinition::from_json(&json).expect("parses");        definition            .validate()            .unwrap_or_else(|e| panic!("{every}: {e}"));        assert_eq!(definition.to_json(), json, "{every} is kept as written");    }    // A hand-over with no condition hands over whenever there is one link,    // and a strip says nothing but that it is one.    let mut value = example();    set_top(&mut value, "hand_over", json!({}));    set_top(&mut value, "attachments", json!({}));    let json = serde_json::to_string(&value).unwrap();    let definition = TableDefinition::from_json(&json).expect("parses");    definition.validate().expect("an empty hand-over and strip");    assert_eq!(definition.to_json(), json);}/// RULE: A conversation's footer reads as one message column (the Sessions spelling, a line under the note) or several (the Messages spelling) and writes back the form it was given, and a merged table drawn as its own slips needs neither words nor a side.#[test]fn a_conversation_footer_is_one_column_or_several_and_a_slip_source_needs_no_words() {    for footer in [json!("footer"), json!(["reactions", "edited"])] {        let mut value = example();        full_conversation(&mut value);        set_at(&mut value, "/conversation", "footer", footer.clone());        let json = serde_json::to_string(&value).unwrap();        let definition =            TableDefinition::from_json(&json).unwrap_or_else(|e| panic!("{footer}: {e}"));        definition            .validate()            .unwrap_or_else(|e| panic!("{footer}: {e}"));        assert_eq!(            definition.to_json(),            json,            "{footer} is written back as given"        );    }    let mut value = example();    full_conversation(&mut value);    set_at(&mut value, "/conversation", "footer", json!("Footer Line"));    assert_eq!(        parse(&value).validate(),        Err(DefinitionError::BadId("Footer Line".into()))    );    let mut value = example();    full_conversation(&mut value);    set_at(        &mut value,        "/conversation",        "also",        json!([{ "table": "run", "links": ["session_id"], "at": "started_at", "face": "slip" }]),    );    parse(&value)        .validate()        .expect("a slip says what its own table's definition says");}/// RULE: The session inbox is gone (Nov 2026): a definition written before it went, carrying a conversation's `send` act or a page's `send_to_session` hand-over, still reads, and neither is drawn — Cotton sends nothing to a session.#[test]fn a_definition_from_before_the_session_inbox_went_still_reads() {    let mut value = example();    full_conversation(&mut value);    set_at(&mut value, "/conversation", "send", json!("send_to_session"));    set_top(&mut value, "send_to_session", json!({ "label": "Send to a session\u{2026}", "body": "notes", "record_as": "thoughtId" }));    let definition = TableDefinition::from_json(&value.to_string()).expect("an old definition reads");    let written: Value = serde_json::from_str(&definition.to_json()).unwrap();    assert_eq!(written.pointer("/conversation/send"), None, "the act is not carried");    assert!(definition.conversation.is_some(), "the conversation still draws");}/// RULE: The third round's enumerations are spelled the shared way and nothing else parses — a strip's sources and a merged table's faces — and a cadence is a number.#[test]fn the_third_rounds_enumerations_are_spelled_the_shared_way() {    assert_eq!(        serde_json::to_value(AttachmentSource::Library).unwrap(),        json!("library")    );    assert_eq!(        serde_json::to_value(AttachmentSource::Camera).unwrap(),        json!("camera")    );    assert_eq!(        serde_json::to_value(ConversationFace::Note).unwrap(),        json!("note")    );    assert_eq!(        serde_json::to_value(ConversationFace::Slip).unwrap(),        json!("slip")    );    let parses = |mutate: fn(&mut Value)| {        let mut value = example();        mutate(&mut value);        TableDefinition::from_json(&value.to_string()).is_ok()    };    assert!(!parses(|v| set_top(v, "live", json!({ "every": "5" }))));    assert!(!parses(|v| set_top(v, "live", json!({}))));    assert!(        !parses(|v| set_top(v, "clear", json!({ "note": "Gone for good." }))),        "the verb's label is the act"    );    assert!(!parses(|v| {        full_conversation(v);        set_at(v, "/conversation", "footer", json!(7));    }));}// ---- the fourth round (1 Oct 2026) ------------------------------------------/// RULE: A slip's reply writes the owner's words into a declared text or long text column, and its verb's and field's words, when given, say something.#[test]fn a_slips_reply_names_a_declared_text_column_and_its_words_say_something() {    use ColumnType::*;    let cases: Vec<RefusalCase> = vec![        (            |v| set_at(v, "/slip", "reply", json!({ "column": "nowhere" })),            unknown("slip.reply.column", "nowhere"),        ),        (            |v| set_at(v, "/slip", "reply", json!({ "column": "due_date" })),            wrong_type(                "slip.reply.column",                "due_date",                Date,                "a_text_or_a_long_text",            ),        ),        (            |v| set_at(v, "/slip", "reply", json!({ "column": "status" })),            wrong_type(                "slip.reply.column",                "status",                Choice,                "a_text_or_a_long_text",            ),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "reply",                    json!({ "column": "notes", "label": " " }),                )            },            DefinitionError::Empty("slip.reply.label"),        ),        (            |v| {                set_at(                    v,                    "/slip",                    "reply",                    json!({ "column": "notes", "placeholder": "" }),                )            },            DefinitionError::Empty("slip.reply.placeholder"),        ),    ];    for (index, (mutate, wanted)) in cases.into_iter().enumerate() {        assert_eq!(refused(mutate), wanted, "case {index}");    }    // The column alone is a reply ("Answer", an empty field), on a text or a    // long text, beside the typed answers it settles the same question as.    for reply in [json!({ "column": "title" }), json!({ "column": "notes" })] {        let mut value = example();        set_at(            &mut value,            "/slip",            "answers",            json!({ "column": "status", "values": { "done": "Close without an answer" }, "when": ["open"] }),        );        set_at(&mut value, "/slip", "reply", reply.clone());        let json = serde_json::to_string(&value).unwrap();        let definition =            TableDefinition::from_json(&json).unwrap_or_else(|e| panic!("{reply}: {e}"));        definition            .validate()            .unwrap_or_else(|e| panic!("{reply}: {e}"));        assert_eq!(            definition.to_json(),            json,            "{reply} is written back as given"        );    }    let parses = |mutate: fn(&mut Value)| {        let mut value = example();        mutate(&mut value);        TableDefinition::from_json(&value.to_string()).is_ok()    };    assert!(        !parses(|v| set_at(v, "/slip", "reply", json!({ "label": "Answer" }))),        "the column is the reply"    );    assert!(        !parses(|v| set_at(v, "/slip", "reply", json!("notes"))),        "a reply is an object"    );}/// RULE: A reveal policy belongs only to a secret text column, expires in positive bounded seconds, and names the row's typed reveal metadata.#[test]fn secret_reveal_policy_round_trips_and_validates() {    let mut value = serde_json::to_value(        builtin_table_definitions()            .iter().cloned()            .find(|d| d.id == "note")            .unwrap(),    )    .unwrap();    value["columns"].as_array_mut().unwrap().extend([        json!({"key":"token", "type":"text", "secret":true, "reveal":{"once":true,"expires":60}}),        json!({"key":"reveal_count", "type":"number"}),        json!({"key":"last_revealed", "type":"date"}),    ]);    let definition = TableDefinition::from_json(&value.to_string()).unwrap();    definition.validate().unwrap();    assert_eq!(        serde_json::to_value(&definition).unwrap()["columns"],        value["columns"]    );    let token = value["columns"].as_array().unwrap().len() - 3;    for bad in [json!(0), json!(-1), json!(86401), json!(1.5), json!("60")] {        let mut changed = value.clone();        changed["columns"][token]["reveal"]["expires"] = bad;        assert!(TableDefinition::from_json(&changed.to_string())            .and_then(|d| d.validate())            .is_err());    }    for (key, bad) in [("secret", json!(false)), ("type", json!("number"))] {        let mut changed = value.clone();        changed["columns"][token][key] = bad;        assert!(TableDefinition::from_json(&changed.to_string())            .unwrap()            .validate()            .is_err());    }    // Swift refuses Copy without both typed metadata columns; Rust must    // refuse those definitions too, before any record can reach that page.    for index in [token + 1, token + 2] {        let mut changed = value.clone();        changed["columns"].as_array_mut().unwrap().remove(index);        assert!(parse(&changed).validate().is_err());        let mut changed = value.clone();        changed["columns"][index]["type"] = json!("text");        assert!(parse(&changed).validate().is_err());    }    let mut changed = value.clone();    changed["columns"][token]["reveal"]["expiry"] = json!(60);    assert!(TableDefinition::authored(&changed).is_err());}// RULE: Email's conversion takes a catalogue revision newer than the main catalogue it merged and retains the single shared conversation archive fields.#[test]fn email_conversion_advances_revision_and_uses_one_conversation_layout() {    // The conversation conversion shipped by revision 19. Later tool updates    // must remain free to advance the catalogue so stored definitions refresh.    let definition = builtin_table_definition("email_thread").unwrap();    let conversation = definition.conversation.as_ref().unwrap();    assert_eq!(conversation.can_send, Some(CanSend::Always(false)));    // An email's envelope: the page draws the FIRST column with the time as its one line, and the rest    // (address, To, Cc, a subject the thread's head does not say) behind a tap (architect, 5 Oct).    let envelope: Vec<String> = ["from_name", "from_email", "to_line", "cc_line", "subject"].map(String::from).to_vec();    assert_eq!(conversation.header_columns.as_deref(), Some(&envelope[..]));}// RULE: A chat's page offers the input only where its own sendable column says so; an email conversation never offers it.#[test]fn a_chat_sends_where_its_sendable_column_says_and_email_never() {    let thread = builtin_table_definition("thread").unwrap();    let can_send = thread.conversation.as_ref().unwrap().can_send.clone().unwrap();    assert_eq!(can_send, CanSend::Column("sendable".into()));    let mut record = serde_json::Map::new();    assert!(!can_send.for_record(&record), "a chat whose sendable is unread does not send");    record.insert("sendable".into(), json!(true));    assert!(can_send.for_record(&record));    record.insert("sendable".into(), json!(false));    assert!(!can_send.for_record(&record));    assert!(!CanSend::Always(false).for_record(&record));    // The column it names must be one of the table's bools.    let mut value: Value = serde_json::from_str(include_str!("../../kits/personal/tables/thread.json")).unwrap();    value["conversation"]["can_send"] = json!("send_blocked_reason");    assert!(parse(&value).validate().is_err(), "a text column cannot say whether a chat sends");    value["conversation"]["can_send"] = json!("no_such_column");    assert!(parse(&value).validate().is_err());}/// RULE: An email's starred, inbox and read state are acts and marks, never On/Off rows (R6): no page section draws them, the star is the slip's badge, and each act is a command offered only in the state it changes.#[test]fn email_state_is_an_act_and_a_mark_never_a_row() {    let states = ["starred", "in_inbox", "read_state", "unread", "binned"];    for id in ["email", "email_thread"] {        let definition = builtin_table_definition(id).unwrap();        for section in &definition.page {            for key in section.columns() {                assert!(!states.contains(&key.as_str()), "{id} draws {key} as a row");            }        }        assert_eq!(definition.slip.toggle, None, "{id}");    }    let thread = builtin_table_definition("email_thread").unwrap();    assert_eq!(thread.slip.badge.as_ref().map(|badge| badge.column.as_str()), Some("starred"));    for (id, twin, column) in [        ("star", "unstar", "starred"),        ("archive", "inbox", "in_inbox"),    ] {        for (one, other) in [(id, twin), (twin, id)] {            let command = thread.command(one).unwrap_or_else(|| panic!("email_thread offers {one}"));            assert_eq!(command.verb.as_deref(), Some("update_email"), "{one}");            assert_eq!(command.undo.as_deref(), Some(other), "{one}");            assert!(command.when.as_ref().is_some_and(|when| when.get(column).is_some()), "{one} is offered by {column}");            assert!(command.receipt.is_some(), "{one}");        }    }}// RULE: Sender groups are supporting archive views, never independent primitive records with invented address ids.#[test]fn email_senders_remain_a_supporting_builtin() {    assert!(PrimitiveKind::parse("email_sender").is_none());    assert_eq!(builtin_store_table("email_sender"), Some("cotton_blocked_senders"));    assert!(crate::primitives::SUPPORTING_TABLES.iter().any(|(table, _)| *table == "cotton_blocked_senders"));}fn round_five_format_key_cases() -> Vec<KeyCase> {    vec![        KeyCase {            pointer: "/columns/8",            key: "currency",            set: |v| set_at(v, "/columns/8", "currency", json!("title")),            is_struct: false,        },        KeyCase {            pointer: "/columns/8",            key: "signed",            set: |v| set_at(v, "/columns/8", "signed", json!(false)),            is_struct: false,        },        KeyCase {            pointer: "/columns/5",            key: "link_by",            set: |v| {                v["project"] = Value::Null;                v["columns"][5].as_object_mut().unwrap().remove("link_to");                v["columns"][5]["readonly"] = json!(true);                set_at(                    v,                    "/columns/5",                    "link_by",                    json!({"column":"status", "tables":{"open":"project", "done":"person"}}),                );            },            is_struct: true,        },        KeyCase {            pointer: "/page/0",            key: "figure",            set: |v| set_at(v, "/page/0", "figure", json!("amount")),            is_struct: false,        },        KeyCase {            pointer: "/page/0",            key: "role",            set: |v| set_at(v, "/page/0", "role", json!("side")),            is_struct: false,        },        KeyCase {            pointer: "/slip",            key: "opens",            set: |v| set_at(v, "/slip", "opens", json!("person")),            is_struct: false,        },        KeyCase {            pointer: "/slip",            key: "opens",            set: |v| {                set_at(                    v,                    "/slip",                    "opens",                    json!({"column":"person", "table":"person", "table_column":"title"}),                )            },            is_struct: true,        },    ]}/// RULE: Format keys name declared columns of the needed types; dynamic links are readonly and have one target rule, so a write cannot invent a destination.#[test]fn round_five_format_keys_validate_their_references_and_types() {    for mutate in [        (|v: &mut Value| v["columns"][8]["currency"] = json!("nowhere")) as fn(&mut Value),        |v| v["columns"][8]["currency"] = json!("count"),        |v| v["columns"][0]["currency"] = json!("title"),        |v| v["columns"][0]["signed"] = json!(false),        |v| v["page"][0]["figure"] = json!("nowhere"),        |v| v["page"][0]["figure"] = json!("count"),        |v| {            v["page"][0]["figure"] = json!("amount");            v["page"][0]["web"] = json!("title");        },        |v| v["lists"] = json!([{ "heading": "Total", "figure": "nowhere" }]),        |v| v["lists"] = json!([{ "heading": "Total", "figure": "amount", "web": "title" }]),        |v| v["slip"]["opens"] = json!("nowhere"),        |v| v["slip"]["opens"] = json!("title"),        |v| v["slip"]["opens"] = json!({"column":"nowhere"}),        |v| v["slip"]["opens"] = json!({"column":"person", "table_column":"nowhere"}),        |v| v["slip"]["opens"] = json!({"column":"person", "table":"Bad"}),    ] {        refused(mutate);    }    for mutate in [        (|v: &mut Value| v["columns"][5]["link_to"] = json!("project")) as fn(&mut Value),        |v| v["columns"][5]["readonly"] = json!(false),        |v| {            v["columns"][5]                .as_object_mut()                .unwrap()                .remove("readonly")                .map(|_| ())                .unwrap()        },        |v| v["columns"][5]["type"] = json!("text"),        |v| v["columns"][5]["link_by"]["column"] = json!("nowhere"),        |v| v["columns"][5]["link_by"]["column"] = json!("title"),        |v| v["columns"][5]["link_by"]["tables"] = json!({"missing":"project"}),        |v| v["columns"][5]["link_by"]["tables"] = json!({"open":"Bad"}),    ] {        let mut value = example();        (round_five_format_key_cases()[2].set)(&mut value);        mutate(&mut value);        parse(&value)            .validate()            .expect_err("invalid dynamic link refused");    }    // An account link provides the currency; other links do not.    let mut value = example();    value["project"] = Value::Null;    value["columns"][5]["link_to"] = json!("money_account");    value["columns"][8]["currency"] = json!("project");    parse(&value).validate().unwrap();    value["columns"][5]["link_to"] = json!("person");    parse(&value)        .validate()        .expect_err("currency link must target money_account");    // Unmapped choice values have no destination and are valid.    let mut value = example();    (round_five_format_key_cases()[2].set)(&mut value);    value["columns"][5]["link_by"]["tables"] = json!({"open":"project"});    parse(&value).validate().unwrap();}fn round_five_derived_key_cases() -> Vec<KeyCase> {    vec![        KeyCase {            pointer: "",            key: "derived",            set: |v| set_top(v, "derived", json!(true)),            is_struct: false,        },        KeyCase {            pointer: "",            key: "derived",            set: |v| set_top(v, "derived", json!(false)),            is_struct: false,        },    ]}/// RULE: Only built-in tables can derive records from an engine; absent and false retain the stored-table form.#[test]fn round_five_derived_is_builtin_only() {    let mut value = example();    value["builtin"] = json!(false);    value["engine"] = Value::Null;    set_top(&mut value, "derived", json!(true));    assert_eq!(        parse(&value).validate(),        Err(requires("derived", "a_built_in_table"))    );    value["derived"] = json!(false);    parse(&value).validate().unwrap();    assert_eq!(parse(&value).to_json(), value.to_string());    value.as_object_mut().unwrap().remove("derived");    assert_eq!(parse(&value).to_json(), value.to_string());}fn round_five_reveal_key_cases() -> Vec<KeyCase> {    vec![        KeyCase {            pointer: "/columns/0",            key: "reveal",            set: |v| {                v["columns"][0]["secret"] = json!(true);                v["columns"].as_array_mut().unwrap().extend([                    json!({"key":"reveal_count","type":"number"}),                    json!({"key":"last_revealed","type":"date"}),                ]);                set_at(v, "/columns/0", "reveal", json!({"once":true,"expires":60}));            },            is_struct: true,        },        KeyCase {            pointer: "/columns/0",            key: "reveal",            set: |v| {                v["columns"][0]["secret"] = json!(true);                v["columns"].as_array_mut().unwrap().extend([                    json!({"key":"reveal_count","type":"number"}),                    json!({"key":"last_revealed","type":"date"}),                ]);                set_at(                    v,                    "/columns/0",                    "reveal",                    json!({"once":false,"expires":86400}),                );            },            is_struct: true,        },    ]}/// RULE: Reveal policy belongs only to secret text columns, and its expiry is an integer from one second through one day; malformed policy must never be silently dropped.#[test]fn round_five_reveal_requires_a_secret_and_bounded_integer_expiry() {    for secret in [None, Some(false)] {        let mut value = example();        value["columns"][0]["reveal"] = json!({"once":true,"expires":60});        if let Some(secret) = secret {            value["columns"][0]["secret"] = json!(secret);        }        assert_eq!(            parse(&value).validate(),            Err(requires("columns.title.reveal", "secret_true"))        );    }    for expires in [1, 86400] {        let mut value = example();        (round_five_reveal_key_cases()[0].set)(&mut value);        value["columns"][0]["reveal"]["expires"] = json!(expires);        parse(&value).validate().unwrap();        assert_eq!(parse(&value).to_json(), value.to_string());    }    for expires in [0, 86401] {        let mut value = example();        (round_five_reveal_key_cases()[0].set)(&mut value);        value["columns"][0]["reveal"]["expires"] = json!(expires);        parse(&value)            .validate()            .expect_err("invalid expiry refused");    }    for expires in [json!(-1), json!(1.5), json!(4294967296_u64), json!("60")] {        let mut value = example();        (round_five_reveal_key_cases()[0].set)(&mut value);        value["columns"][0]["reveal"]["expires"] = expires;        assert!(TableDefinition::from_json(&value.to_string()).is_err());    }    refused(|v| {        v["columns"][2]["secret"] = json!(true);        v["columns"][2]["reveal"] = json!({"once":true,"expires":60});    });}fn round_five_section_where_key_cases() -> Vec<KeyCase> {    vec![KeyCase {        pointer: "/page/2/list",        key: "where",        set: |v| {            list_section(                v,                json!({"table":"person", "link":"todo_id", "where":{"state":"open","archived":false,"tag":null,"rank":2}}),            );        },        is_struct: false,    }]}/// RULE: A section filter names columns of its target table in the shared key grammar, never this page's columns, and retains the filter values and order exactly.#[test]fn round_five_section_where_names_foreign_columns_in_the_key_grammar() {    let mut value = example();    (round_five_section_where_key_cases()[0].set)(&mut value);    parse(&value).validate().unwrap();    value["page"][2]["list"]["where"] = json!({"Bad key":"open"});    assert_eq!(        parse(&value).validate(),        Err(DefinitionError::BadColumnKey("Bad key".into()))    );    // The same section layout is available in the table's header lists.    value["page"][2]["list"]["where"] = json!({"state":"open"});    value["lists"] = json!([value["page"][2].clone()]);    parse(&value).validate().unwrap();    value["lists"][0]["list"]["where"] = json!({"Bad key":true});    parse(&value)        .validate()        .expect_err("header list filter is validated too");    let raw = value        .to_string()        .replace("\"Bad key\":true", "\"state\":true,\"state\":false");    assert!(        TableDefinition::from_json(&raw).is_err(),        "duplicate filter columns are refused"    );}fn slip_by_key_cases() -> Vec<KeyCase> {    vec![KeyCase {        pointer: "",        key: "slip_by",        set: |v| {            set_top(                v,                "slip_by",                json!({"column":"status","slips":{"done":{"title":"title","subtitle":"notes","trailing":"due_date","caption":{"dates":["due_date"]}}}}),            )        },        is_struct: true,    }]}// RULE: A slip drawn by a choice column's value is the definition's (Records// slips typed by kind, 11 Oct 2026): `slip_by` names a choice column, keys its// slips by that column's values, and each slip names declared columns — or the// definition is refused.#[test]fn a_slip_by_names_a_choice_column_its_values_and_declared_columns() {    let refused = |slip_by: Value| {        let mut value = example();        set_top(&mut value, "slip_by", slip_by);        TableDefinition::from_json(&value.to_string()).and_then(|definition| definition.validate()).is_err()    };    assert!(!refused(json!({"column":"status","slips":{"done":{"title":"title"}}})));    assert!(refused(json!({"column":"notes","slips":{"done":{"title":"title"}}})), "not a choice column");    assert!(refused(json!({"column":"status","slips":{"closed":{"title":"title"}}})), "not one of its values");    assert!(refused(json!({"column":"status","slips":{}})), "no slips");    assert!(refused(json!({"column":"status","slips":{"done":{"title":"nowhere"}}})), "an undeclared title");    assert!(refused(json!({"column":"status","slips":{"done":{"title":"title","subtitle":"nowhere"}}})), "an undeclared subtitle");    assert!(refused(json!({"column":"status","slips":{"done":{"title":"title","caption":{"dates":["notes"]}}}})), "a caption date that is no date");}/// RULE: A slip variant replaces its word slots, keeps the base behavior, and falls back to the base title; this is independent of any shipped tool's layout.#[test]fn slip_variants_replace_words_and_keep_base_behavior() {    let base = builtin_table_definition("email_thread").unwrap().slip.clone();    let variant: SlipVariant = serde_json::from_value(json!({"title":"invented_title", "subtitle":"invented_detail", "trailing":"invented_time"})).unwrap();    let reading = base.with_variant(&variant);    assert_eq!(reading.title, variant.title);    assert_eq!(reading.subtitle, variant.subtitle);    assert_eq!(reading.trailing, variant.trailing);    assert_eq!(reading.caption, variant.caption);    assert_eq!(reading.title_fallback.as_ref(), Some(&base.title));    assert_eq!(reading.badge, base.badge);    assert_eq!(reading.unread, base.unread);}/// RULE: Any table may type its slips by a choice column — a kit table a/// person installs as well as a built-in one.#[test]fn a_kit_table_may_type_its_slips_by_a_choice_column() {    let kits = crate::toolkits::shipped_kit_tools();    let (table, column) = kits        .iter()        .flat_map(|package| package.tables.iter())        .find_map(|table| {            table                .columns                .iter()                .find(|column| column.column_type == ColumnType::Choice && column.choices.as_ref().is_some_and(|c| !c.is_empty()))                .map(|column| (table.clone(), column.clone()))        })        .expect("a kit table with a choice column");    let mut value: Value = serde_json::from_str(&table.to_json()).unwrap();    let first = column.choices.as_ref().unwrap()[0].clone();    value["slip_by"] = json!({"column": column.key, "slips": {first.clone(): {"title": table.slip.title}}});    let typed = TableDefinition::from_json(&value.to_string()).expect("a kit table's slip_by parses");    typed.validate().expect("a kit table's slip_by validates");    let variant = typed.slip_by.as_ref().unwrap().slips.get(&first).unwrap();    assert_eq!(typed.slip.with_variant(variant).title, table.slip.title);}fn round_five_column_words_key_cases() -> Vec<KeyCase> {    vec![        KeyCase {            pointer: "/columns/7",            key: "stamps",            set: |v| {                set_at(                    v,                    "/columns/7",                    "stamps",                    json!({"open":"Waiting for you","done":"approved"}),                )            },            is_struct: false,        },        KeyCase {            pointer: "/columns/7",            key: "tones",            set: |v| {                set_at(                    v,                    "/columns/7",                    "tones",                    json!({"open":"amber","done":"green"}),                )            },            is_struct: false,        },        KeyCase {            pointer: "/columns/7",            key: "tones",            set: |v| set_at(v, "/columns/7", "tones", json!({"open":"red"})),            is_struct: false,        },        KeyCase {            pointer: "/columns/1",            key: "markdown",            set: |v| set_at(v, "/columns/1", "markdown", json!(true)),            is_struct: false,        },        KeyCase {            pointer: "/columns/1",            key: "markdown",            set: |v| set_at(v, "/columns/1", "markdown", json!(false)),            is_struct: false,        },    ]}/// RULE: Stamp words are nonblank, tones are red/amber/green over declared choices, and Markdown belongs to longtext; a future key or unknown tone must never disappear on a write.#[test]fn round_five_column_words_and_tones_validate_their_column_types() {    for mutate in [        (|v: &mut Value| v["columns"][0]["tones"] = json!({"open":"red"})) as fn(&mut Value),        |v| v["columns"][7]["tones"] = json!({"unknown":"red"}),        |v| v["columns"][7]["stamps"] = json!({"done":"  "}),        |v| v["columns"][0]["markdown"] = json!(true),        |v| v["columns"][0]["markdown"] = json!(false),    ] {        refused(mutate);    }    for bad in [json!(true), json!(1)] {        let mut value = example();        value["columns"][7]["tones"] = json!({"open":bad});        assert!(TableDefinition::from_json(&value.to_string()).is_err());    }}// ── round six: the gaps the Subscriptions tool found ────────────────────────/// A round-six fixture decodes, validates and writes itself back byte for byte.fn filed_fixture_round_trips(json: &str) {    let definition = TableDefinition::from_json(json).expect("filed definition decodes");    definition.validate().expect("filed definition validates");    assert_eq!(definition.to_json(), json.trim_end());}/// RULE: Round-six filed keys decode and validate from crate-local fixtures and round-trip byte for byte, so the Swift copy and the Rust reference cannot drift on them.#[test]fn round_six_filed_definition_fixtures_decode_validate_and_round_trip() {    filed_fixture_round_trips(include_str!(        "../../tests/fixtures/definitions-parity-6/column_default_parity.json"    ));    filed_fixture_round_trips(include_str!(        "../../tests/fixtures/definitions-parity-6/url_parity.json"    ));}/// RULE: A column default is a value of the column's own type and, for a choice, one of its choices; a link, photo or file column takes none, because a default there would name something that need not exist.#[test]fn a_column_default_is_of_its_own_type_and_never_a_reference() {    let set = |value: &mut Value, index: usize, default: Value| {        value["columns"][index]["default"] = default;    };    let mut ok = example();    set(&mut ok, 7, json!("open"));    parse(&ok).validate().expect("a choice among its choices");    assert!(matches!(        refused(|v| set(v, 7, json!("gone"))),        DefinitionError::BadDefault { ref column, .. } if column == "status"    ));    assert!(matches!(        refused(|v| set(v, 0, json!(3))),        DefinitionError::BadDefault { ref column, .. } if column == "title"    ));    // "default": null is no default at all — it decodes as absent.    let mut none = example();    set(&mut none, 0, Value::Null);    assert_eq!(parse(&none).column("title").unwrap().default, None);    assert!(matches!(        refused(|v| set(v, 5, json!("p1"))),        DefinitionError::WrongColumnType { ref slot, .. } if slot == "columns.project.default"    ));}/// RULE: A tool's worked figure may be a lowest or highest of a column, and only that says {date}, the day of its row; a formula adds counts and sums, never a lowest — so Ahead's card says its lowest point and when, and no line says a day it cannot have.#[test]fn a_tools_lowest_figure_names_its_column_and_alone_says_a_day() {    let figures = |value: &mut Value, figures: Value| {        value["tool"] = json!({ "name": "Todos", "figures": figures });    };    let sum = json!({ "read": "spent", "many": "{n}", "summary": { "table": "todo", "op": "sum", "column": "count" } });    let mut ok = example();    figures(&mut ok, json!([        sum,        { "read": "lowest", "many": "Lowest {n} on {date}", "summary": { "table": "todo", "op": "min", "column": "count" } },        { "read": "highest", "many": "Highest {n}", "summary": { "table": "todo", "op": "max", "column": "count" } },        { "read": "net", "many": "Net {n}", "formula": { "plus": ["spent"] } }    ]));    parse(&ok).validate().expect("a lowest, a highest and a formula over a sum");    let slot = |error: DefinitionError| match error {        DefinitionError::BadSlot { slot, .. } => slot,        other => panic!("refused for another reason: {other:?}"),    };    assert_eq!(slot(refused(|v| figures(v, json!([        { "read": "lowest", "many": "Lowest {n}", "summary": { "table": "todo", "op": "min" } }    ])))), "tool.figures.0.summary.column");    assert_eq!(slot(refused(|v| figures(v, json!([        { "read": "spent", "many": "{n} on {date}", "summary": { "table": "todo", "op": "sum", "column": "count" } }    ])))), "tool.figures.0.many");    assert_eq!(slot(refused(|v| figures(v, json!([        { "read": "lowest", "many": "{n}", "summary": { "table": "todo", "op": "min", "column": "count" } },        { "read": "net", "many": "Net {n}", "formula": { "plus": ["lowest"] } }    ])))), "tool.figures.1.formula");}/// RULE: A tile summary names what a tile can add up — a count takes no column, a sum a number or amount column, min and max a date, number or amount column, and its where reads the table's own columns — so a figure never divides by a wrong column at draw time.#[test]fn a_tile_summary_names_a_column_of_the_right_type_and_a_where_the_table_can_read() {    let set = |value: &mut Value, summary: Value| {        value["tile"]["summary"] = summary;    };    let mut ok = example();    set(        &mut ok,        json!([            { "op": "count", "where": { "status": "open" }, "label": "open" },            { "op": "sum", "column": "amount", "where": { "status": "open" }, "label": "a month" },            { "op": "min", "column": "due_date", "label": "next" },            { "op": "max", "column": "count" }        ]),    );    let parsed = parse(&ok);    parsed.validate().expect("figures over declared columns");    assert_eq!(serde_json::to_value(&parsed).unwrap()["tile"], ok["tile"], "round-trips in the order written");    assert!(matches!(        refused(|v| set(v, json!([{ "op": "count", "column": "amount" }]))),        DefinitionError::BadSummary { at: 0, .. }    ));    assert!(matches!(        refused(|v| set(v, json!([{ "op": "sum" }]))),        DefinitionError::BadSummary { at: 0, .. }    ));    assert!(matches!(        refused(|v| set(v, json!([{ "op": "count" }, { "op": "sum", "column": "title" }]))),        DefinitionError::BadSummary { at: 1, ref why } if why.contains("number or amount")    ));    assert!(matches!(        refused(|v| set(v, json!([{ "op": "min", "column": "status" }]))),        DefinitionError::BadSummary { at: 0, .. }    ));    assert!(matches!(        refused(|v| set(v, json!([{ "op": "max", "column": "gone" }]))),        DefinitionError::BadSummary { at: 0, ref why } if why.contains("gone")    ));    assert!(matches!(        refused(|v| set(v, json!([{ "op": "count", "where": { "status": "lost" } }]))),        DefinitionError::BadSummary { at: 0, .. }    ));    let mut unknown = example();    set(&mut unknown, json!([{ "op": "count", "total": true }]));    assert!(TableDefinition::authored(&unknown).is_err(), "a summary key the format does not name is refused");}/// RULE: The sparkline face and its line come together — a face with no line, or a line under another face, is refused — and a line over the table's own records names a number column and a date column, in a window of 1 to 366 days.#[test]fn a_sparkline_face_names_its_line_and_its_line_its_columns() {    let set = |value: &mut Value, tile: Value| {        value["tile"] = tile;    };    let id = example()["id"].as_str().unwrap().to_string();    let mut other = example();    set(&mut other, json!({ "face": "sparkline", "sparkline": { "table": "reading", "value": "pct", "at": "sampled_at", "days": 14 } }));    let parsed = parse(&other);    parsed.validate().expect("another table's columns are checked where it is read");    assert_eq!(parsed.tile.sparkline.as_ref().map(|line| line.days()), Some(14));    assert_eq!(serde_json::to_value(&parsed).unwrap()["tile"], other["tile"], "round-trips as written");    let bad = |tile: Value| refused(|v| set(v, tile));    assert!(matches!(bad(json!({ "face": "sparkline" })), DefinitionError::BadSparkline(_)));    assert!(matches!(        bad(json!({ "face": "slip-list", "sparkline": { "table": "reading", "value": "pct", "at": "at" } })),        DefinitionError::BadSparkline(_)    ));    assert!(matches!(        bad(json!({ "face": "sparkline", "sparkline": { "table": "reading", "value": "pct", "at": "at", "days": 0 } })),        DefinitionError::BadSparkline(_)    ));    assert!(matches!(        bad(json!({ "face": "sparkline", "sparkline": { "table": id, "value": "title", "at": "due_date" } })),        DefinitionError::BadSparkline(ref why) if why.contains("not a number")    ));}/// RULE: A tile's current rule names a date column of its own table, so the database page never decides what is recent by a column that is missing or holds no date.#[test]fn a_tile_current_names_a_date_column_of_the_table() {    let set = |value: &mut Value, current: Value| {        value["tile"]["current"] = current;    };    let mut ok = example();    set(&mut ok, json!({ "column": "due_date", "days": 2 }));    let parsed = parse(&ok);    parsed.validate().expect("a date column of the table");    assert_eq!(parsed.tile.current, Some(TileCurrent { column: "due_date".into(), days: 2 }));    assert_eq!(serde_json::to_value(&parsed).unwrap()["tile"], ok["tile"], "round-trips as written");    assert!(matches!(        refused(|v| set(v, json!({ "column": "gone", "days": 2 }))),        DefinitionError::BadCurrent(ref why) if why.contains("gone")    ));    assert!(matches!(        refused(|v| set(v, json!({ "column": "title", "days": 2 }))),        DefinitionError::BadCurrent(ref why) if why.contains("not a date column")    ));}/// The `computed` column key (computed.rs): one case per closed shape.fn computed_key_cases() -> Vec<KeyCase> {    vec![        KeyCase {            pointer: "/columns/1",            key: "computed",            set: |v| {                set_at(                    v,                    "/columns/1",                    "computed",                    json!({"lookup":{"through":"project","column":"notes"}}),                )            },            is_struct: true,        },        KeyCase {            pointer: "/columns/9",            key: "computed",            set: |v| {                set_at(                    v,                    "/columns/9",                    "computed",                    json!({"rollup":{"table":"todo","link":"project","op":"max","column":"position","where":{"column":"status","values":["open"]}}}),                )            },            is_struct: true,        },        KeyCase {            pointer: "/columns/9",            key: "computed",            set: |v| {                set_at(                    v,                    "/columns/9",                    "computed",                    json!({"formula":{"op":"signed","of":["position"],"flip_when":{"column":"status","values":["done"]}}}),                )            },            is_struct: true,        },    ]}/// `contributes` on a link column and `contributions` on a table/// (contributors.rs).fn contributes_key_cases() -> Vec<KeyCase> {    vec![        KeyCase {            pointer: "/columns/5",            key: "contributes",            set: |v| set_at(v, "/columns/5", "contributes", json!(false)),            is_struct: false,        },        KeyCase {            pointer: "/columns/6",            key: "contributes",            set: |v| set_at(v, "/columns/6", "contributes", json!({"label":"Asked of them"})),            is_struct: true,        },        KeyCase {            pointer: "",            key: "contributions",            set: |v| set_at(v, "", "contributions", json!(false)),            is_struct: false,        },        // `groups` (Spec 6): a table whose records are gathered into hand-picked groups.        KeyCase {            pointer: "",            key: "groups",            set: |v| set_at(v, "", "groups", json!({"stack":"polaroids"})),            is_struct: true,        },        // `views`: the views a table ships for Home.        KeyCase {            pointer: "",            key: "views",            set: |v| set_at(v, "", "views", json!([{"face":"today","name":"Today"}])),            is_struct: true,        },        // `groups.kept_in` (Spec 10 G item 3): the groups are another table's records — albums.        KeyCase {            pointer: "/groups",            key: "kept_in",            set: |v| set_at(v, "", "groups", json!({"stack":"polaroids","kept_in":{"table":"album","items":"album_item"}})),            is_struct: true,        },    ]}/// RULE: A page has at most one main section, and a role fits what the section holds — facts are columns alone, main is one long text or a list (as pages or as slips), side is a list or columns — so the app never guesses what a page is for.#[test]fn a_page_sections_role_fits_what_the_section_holds() {    let split = |v: &mut Value| v["page"] = json!([{ "heading": null, "columns": ["title"] }, { "heading": null, "columns": ["notes"] }]);    for role in ["main", "facts", "side"] {        let mut value = example();        split(&mut value);        value["page"][1]["role"] = json!(role);        TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate()).unwrap_or_else(|e| panic!("{role}: {e}"));    }    let mut value = example();    split(&mut value);    value["page"].as_array_mut().unwrap().push(json!({ "heading": "Slips", "role": "main", "list": { "table": "todo" } }));    TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate()).expect("a list of slips is a page's body");    for mutate in [        (|v: &mut Value| v["page"][0]["role"] = json!("main")) as fn(&mut Value),        |v| {            v["page"][1]["role"] = json!("main");            v["page"].as_array_mut().unwrap().push(json!({ "heading": "Again", "role": "main", "list": { "table": "todo", "face": "page" } }));        },        |v| v["page"].as_array_mut().unwrap().push(json!({ "heading": "Slips", "role": "main", "list": { "table": "todo" }, "columns": ["title"] })),        |v| v["page"].as_array_mut().unwrap().push(json!({ "heading": "Listed", "role": "facts", "list": { "table": "todo" } })),        |v| v["page"].as_array_mut().unwrap().push(json!({ "heading": "Nothing", "role": "side" })),        |v| v["lists"] = json!([{ "heading": "Others", "role": "side", "list": { "table": "todo" } }]),    ] {        let mut value = example();        split(&mut value);        mutate(&mut value);        assert!(TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate()).is_err(), "{}", value["page"]);    }}/// RULE: A table with groups names no column "group", because where group narrows its list to one group's records and the key must mean one thing.#[test]fn a_table_with_groups_names_no_column_called_group() {    let mut value = example();    value["groups"] = json!({ "stack": "slips" });    TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate()).expect("groups alone is fine");    value["columns"].as_array_mut().unwrap().push(json!({ "key": "group", "type": "text" }));    assert!(TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate()).is_err());}/// RULE: Groups kept in another table name a pair the core writes groups through — album and album_item, the only one; only the photo list and the film list keep their groups so, as their albums (architect, Spec 10 G item 3 B: "groups backed by the album table, no column"; walker 604bcce6: the Videos tool is its own list, its own albums counted in films).#[test]fn groups_kept_elsewhere_are_albums_and_only_the_photo_and_film_lists() {    let with = |groups: Value| {        let mut value = example();        value["groups"] = groups;        TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate())    };    with(json!({ "stack": "polaroids", "kept_in": { "table": "album", "items": "album_item" } })).expect("albums are a pair the core writes");    for refused in [        json!({ "stack": "polaroids", "kept_in": { "table": "album", "items": "photo" } }),        json!({ "stack": "slips", "kept_in": { "table": "project", "items": "todo" } }),    ] {        assert!(with(refused.clone()).is_err(), "{refused} was accepted");    }    let kept: std::collections::BTreeSet<(String, String, String)> = builtin_table_definitions()        .iter().cloned()        .filter_map(|definition| {            let kept = definition.groups.as_ref()?.kept_in.clone()?;            Some((definition.id, kept.table, kept.items))        })        .collect();    let albums = |table: &str| (table.to_string(), "album".to_string(), "album_item".to_string());    assert_eq!(kept, [albums("media"), albums("video")].into_iter().collect());}/// Every `where` a built-in sends to another table's read — a list's own/// sections, a page's lists, a list's links — and its `shows`, with the table/// each is read on.fn builtin_wheres() -> Vec<(String, String, Value)> {    let mut out = Vec::new();    for definition in builtin_table_definitions() {        let sections = definition.lists.iter().flatten().chain(&definition.page);        for section in sections {            if let Some(list) = &section.list {                if let Some(filter) = &list.where_ {                    out.push((format!("{} list of {}", definition.id, list.table), list.table.clone(), serde_json::to_value(filter).unwrap()));                }            }        }        // A link with no route opens the generic list with its where.        for link in definition.links.iter().flatten().filter(|link| link.path.is_none()) {            if let Some(filter) = &link.where_ {                out.push((format!("{} link {}", definition.id, link.label), link.table.clone(), serde_json::to_value(filter).unwrap()));            }        }        if let Some(shows) = &definition.shows {            out.push((format!("{} shows", definition.id), definition.id.clone(), serde_json::to_value(shows).unwrap()));        }    }    out}/// RULE: A list's input that files what it hears under the page it is said on names a link column of the table it writes, linking back to this table.#[test]fn a_captures_link_is_a_link_back_to_its_page() {    let definitions = builtin_table_definitions();    for definition in definitions {        let Some(capture) = &definition.capture else { continue };        // (ListCapture page_only) a capture that is the page's alone files under that page, so it names its link.        assert!(capture.page_only != Some(true) || capture.link.is_some(), "{}: a page_only capture names its link", definition.id);        let Some(link) = &capture.link else { continue };        let written = definitions.iter().find(|d| d.id == capture.table).expect("the captured table");        let column = written.column(link).unwrap_or_else(|| panic!("{}: {link} is no column of {}", definition.id, capture.table));        assert_eq!(column.column_type, ColumnType::Link, "{}.{link}", capture.table);        assert_eq!(column.link_to.as_deref(), Some(definition.id.as_str()), "{}.{link}", capture.table);    }}/// RULE: A link with no route opens the generic list and may stand on its own line; a menu row with a route never does, a review is a route's, and words after a limited list need the limit.#[test]fn list_links_and_whole_rows_validate() {    let fixture = || {        let mut value = serde_json::to_value(builtin_table_definition("note").unwrap()).unwrap();        value["links"] = json!([            {"label":"Entries", "table":"note", "lead":true},            {"label":"Other entries", "table":"note"}        ]);        value["lists"] = json!([{"columns":[], "list":{"table":"note", "limit":3, "whole":"All entries"}}]);        value    };    let parse = |value: &Value| TableDefinition::from_json(&value.to_string()).unwrap().validate();    assert!(parse(&fixture()).is_ok(), "the neutral list fixture is valid");    let mut value = fixture();    value["links"][0]["path"] = json!("/money");    assert!(parse(&value).is_err(), "a lead link is drawn on the list, never a menu row");    let mut value = fixture();    value["links"][1]["review"] = json!(true);    assert!(parse(&value).is_err(), "a review opens a route");    let mut value = fixture();    value["lists"][0]["list"]["limit"] = Value::Null;    value["lists"][0]["list"].as_object_mut().unwrap().remove("limit");    assert!(parse(&value).is_err(), "the whole list's row follows a limit");    let mut value = fixture();    value["shows"] = json!({"section": "nowhere"});    assert!(parse(&value).is_err(), "shows takes a where of this table");    let mut value = fixture();    value["shows"] = json!({"colour": "red"});    assert!(parse(&value).is_err());}/// RULE: A built-in tool's home table names built-ins, each in one tool only, so a home list headed by the tool's name speaks for every table under it.#[test]fn a_tools_home_names_its_tables_truly() {    let definitions = builtin_table_definitions();    let mut owner: std::collections::BTreeMap<&str, &str> = std::collections::BTreeMap::new();    for definition in definitions {        let Some(tool) = &definition.tool else { continue };        for table in &tool.tables {            assert!(definitions.iter().any(|d| &d.id == table), "{}: {table} is not a built-in", tool.name);            // Settings is a board of other tools' engine tables while their            // existing tool routes remain live during the staged migration.            if tool.key.as_deref() == Some("settings") { continue; }            if let Some(other) = owner.insert(table, &tool.name) {                panic!("{table} is in {other} and {}", tool.name);            }        }    }}#[test]fn voice_words_only_accept_plain_nonsecret_text_columns() {    // Names feed an on-device recogniser; a definition must never select a password or prose.    let original = serde_json::to_value(super::builtin_table_definition("person").unwrap()).unwrap();    for keys in [json!(["full_name", "org"]), json!([])] {        let mut value = original.clone();        value["voice_words"] = keys;        assert!(parse(&value).validate().is_ok());    }    for key in ["missing", "birthday", "avatar_key"] {        let mut value = original.clone();        value["voice_words"] = json!([key]);        assert!(parse(&value).validate().is_err(), "{key}");    }    let mut value = original;    value["voice_words"] = json!(["full_name"]);    value["columns"][0]["secret"] = json!(true);    assert!(parse(&value).validate().is_err());}// ---- the record page's parts (Spec 11) --------------------------------------/// Every key of `parts` written out: a sheet whose head says the due date,/// whose state is the status, whose links are the project and person.fn full_parts() -> Value {    json!({        "shape": "sheet",        "head": { "facts": ["due_date", "count"], "state": "status" },        "links": ["project", "person"],        "body": "notes",        "lists": [{ "table": "pull", "relation": "open_in", "heading": "Pull requests", "main_act": "approve" }],        "acts": { "more": [] },        "cards": [{ "column": "due_date" }, { "column": "notes", "width": "full", "acts": ["copy"] }]    })}/// `parts`, the record page's five parts (Spec 11).fn parts_key_cases() -> Vec<KeyCase> {    vec![        KeyCase { pointer: "", key: "parts", set: |v| set_at(v, "", "parts", full_parts()), is_struct: true },        KeyCase {            pointer: "",            key: "slips",            set: |v| set_at(v, "", "slips", json!({                "widths": { "date": "half", "longtext": "full" },                "acts": { "date": ["open_day", "copy", "edit", "clear"], "other": ["edit"] },                "words": { "open_day": "Open day", "edit": "Edit", "copy": "Copy", "clear": "Clear", "more": "and {n} more" },                "objects": { "open_day": "clock", "edit": "edit", "copy": "copy", "clear": "bin" }            })),            is_struct: true,        },        KeyCase {            pointer: "/parts",            key: "head",            set: |v| set_at(v, "", "parts", full_parts()),            is_struct: true,        },        KeyCase {            pointer: "/parts",            key: "lists",            set: |v| set_at(v, "", "parts", full_parts()),            is_struct: true,        },        KeyCase {            pointer: "/parts",            key: "acts",            set: |v| set_at(v, "", "parts", full_parts()),            is_struct: true,        },    ]}/// RULE: A definition's parts name only its own columns, each of the type its part draws, and only its own commands, each act once; a state is never also a fact.#[test]fn parts_name_only_the_tables_own_columns_and_commands() {    let with = |change: fn(&mut Value)| {        let mut value = example();        let mut parts = full_parts();        change(&mut parts);        set_at(&mut value, "", "parts", parts);        TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate())    };    with(|_| {}).expect("every key of parts, each naming what it should");    for change in [        (|p: &mut Value| p["head"]["facts"] = json!(["nowhere"])) as fn(&mut Value),        |p| p["head"]["facts"] = json!(["notes"]),        |p| p["head"]["facts"] = json!(["project"]),        |p| p["head"]["state"] = json!("due_date"),        |p| p["head"]["facts"] = json!(["status"]),        |p| p["links"] = json!(["title"]),        |p| p["body"] = json!("title"),        |p| p["lists"][0]["relation"] = json!("Open In"),        |p| p["lists"][0]["heading"] = json!(" "),        |p| p["acts"]["main"] = json!("approve"),    ] {        assert!(with(change).is_err(), "accepted: {change:?}");    }    // Commands are a built-in's; the example is one, with no commands.    let mut value = example();    value["commands"] = json!([{ "id": "done", "label": "Mark done", "kind": "update", "verb": "update_todo", "bindings": { "id": "$id" } }]);    let mut parts = full_parts();    parts["acts"] = json!({ "main": "done", "more": [], "away": null });    set_at(&mut value, "", "parts", parts.clone());    TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate()).expect("the main act is its command");    parts["acts"] = json!({ "main": "done", "more": ["done"], "away": null });    value["parts"] = parts;    assert!(TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate()).is_err(), "an act is offered once");}/// The definitions a list's table is read from: the built-ins.fn every_definition() -> Vec<TableDefinition> {    builtin_table_definitions().to_vec()}/// The kinds Spec 11 (b) maps by hand against the board.const BOARD_KINDS: [&str; 8] = ["note", "repository", "connection", "todo", "person", "member", "device", "assistant"];// RULE: A slip can name its person's print independently of its words; without photo bytes the existing full-name card stands in, never guessed initials or another person's picture.#[test]fn a_slips_photo_name_is_a_named_text_column_and_round_trips() {    let mut value = example();    value["slip"]["photo_name"] = json!("title");    let definition = TableDefinition::from_json(&value.to_string()).expect("the print's name");    assert_eq!(serde_json::to_value(definition).unwrap(), value);    value["slip"]["photo_name"] = json!("missing");    assert!(TableDefinition::from_json(&value.to_string()).unwrap().validate().is_err());    value["slip"]["photo_name"] = json!("count");    assert!(TableDefinition::from_json(&value.to_string()).unwrap().validate().is_err());}/// Built-in tables no tool's card, tool tables or links reach, and the one/// way each is reached instead.const REACHED_ELSEWHERE: &[(&str, &str)] = &[    ("board", "an assistant's update_record; Home, the Tools screen and the database page draw it"),    ("theme", "an assistant's update_record; every screen wears it, and the database page's recolour writes its cap"),    ("code_credential", "the Code tool's settings"),    ("code_runner", "the Code tool's settings"),    ("comment", "every record page's comments"),    ("copy", "the database page's Open sync and a cap's long press on the Databases screen"),    ("schema_move", "Home's sync line while a schema move runs (HomeSync.movesTable)"),    ("record_version", "every record page's History action"),    ("toolkit", "the new-database chooser (\"What is it for?\") and an assistant's list_toolkits"),];/// RULE: A shipped view names a face, once per table, and a name — so Home's catalogue is built from definitions and never offers a face twice or a view with no name.#[test]fn a_shipped_view_names_its_face_once_and_a_name() {    let with = |views: Value| {        let mut value = example();        value["views"] = views;        TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate())    };    with(json!([{ "face": "today", "name": "Today" }])).expect("one view is fine");    with(json!([{ "face": "today", "name": "Today" }, { "face": "upcoming", "name": "Upcoming" }])).expect("two faces are fine");    for refused in [        json!([{ "face": "today", "name": " " }]),        json!([{ "face": "today", "name": "A" }, { "face": "today", "name": "B" }]),    ] {        assert!(with(refused.clone()).is_err(), "{refused} was accepted");    }}/// RULE: A chart view names what it draws — a date `x`, an amount or number `y` or `count` of its own table — and only the chart face draws one. Refused where the definition is checked, so a kit's mistake never reaches a tile.#[test]fn a_chart_view_names_its_chart_and_is_the_tables_own() {    let with = |views: Value| {        let mut value = example();        value["columns"].as_array_mut().unwrap().push(json!({ "key": "held_on", "type": "date" }));        value["views"] = views;        TableDefinition::from_json(&value.to_string()).and_then(|d| d.validate())    };    let chart = json!({ "kind": "bar", "x": "held_on", "y": "count", "by": "week" });    with(json!([{ "face": "chart", "name": "By week", "chart": chart }])).expect("a chart view validates");    for (refused, why) in [        (json!([{ "face": "chart", "name": "By week" }]), "a_chart_view_needs_its_chart"),        (json!([{ "face": "today", "name": "Today", "chart": chart }]), "only the chart face draws one"),        (json!([{ "face": "chart", "name": "By week", "chart": { "kind": "bar", "x": "nowhere", "y": "count", "by": "week" } }]), "x is checked"),    ] {        assert!(matches!(with(refused.clone()), Err(DefinitionError::BadChart(_))), "{why}: {refused}");    }}/// RULE: A repeating todo's Repeats opens its repeat rule — the built-in todo's `repeats` words carry `opens` naming the `recurrence_id` link to `todo_recurrence` — because a plain read-only text there left the rule, its History and any repeat editor unreachable from the app (owner's todo 78181841, 7 Oct 2026). A text that opens a record is read-only, since an editable text's tap edits it.#[test]fn a_todos_repeats_opens_its_repeat_rule() {    let todo = builtin_table_definitions()        .iter().cloned()        .find(|definition| definition.id == "todo")        .expect("todo");    let repeats = todo.column("repeats").expect("repeats");    let opens = repeats.opens.as_ref().expect("Repeats opens the rule, never plain words");    let link = todo.column(&opens.column).expect("the column Repeats opens through");    assert_eq!(link.column_type, ColumnType::Link);    assert_eq!(link.link_to.as_deref(), Some("todo_recurrence"));    let error = refused(|v| {        v["columns"]            .as_array_mut()            .unwrap()            .push(json!({ "key": "said", "type": "text", "opens": { "column": "project" } }))    });    assert_eq!(        error,        DefinitionError::Requires {            slot: "columns.said.opens".into(),            needs: "a_read_only_text_column"        }    );    let mut value = example();    value["columns"].as_array_mut().unwrap().push(        json!({ "key": "said", "type": "text", "readonly": true, "opens": { "column": "project" } }),    );    parse(&value).validate().expect("a read-only text may open a record");}/// RULE: Every non-builtin definition derives real typed storage from its declared columns, and an explicit empty tables section cannot select a generic store.#[test]fn imported_definitions_derive_physical_storage_and_round_trip_it() {    let mut value = example();    value["id"] = json!("lesson");    value["builtin"] = json!(false);    value["engine"] = Value::Null;    let mut definition = parse(&value);    definition.validate().unwrap();    let generated = definition.physical_tables().unwrap();    assert_eq!(generated[0].name, "cotton_lesson");    assert!(generated[0].columns.iter().any(|column| column.name == "amount" && column.sql_type == "INTEGER"));    definition.tables = Some(Vec::new());    assert_eq!(definition.physical_tables().unwrap(), generated);    definition.tables = Some(generated);    definition.validate().unwrap();    assert_eq!(TableDefinition::from_json(&definition.to_json()).unwrap(), definition);    definition.tables.as_mut().unwrap()[0].name = "cotton_workspaces".into();    assert!(definition.validate().is_err());}/// RULE (walk, 27 Oct 2026; schema 142): a built-in's storage is the store's/// code, never a definition's — a table this build keeps under its engine/// reads whatever storage the object serves with it (the object a rise/// behind: 141's `status_changed_at TEXT NOT NULL`; or a rise ahead: a rule/// this build has not met), since none of it makes a table here; every other/// table's storage is data, and an SQL fragment in it is still refused.#[test]fn a_built_ins_served_storage_from_another_rise_is_not_read_and_an_imported_ones_sql_is_refused() {    let document = builtin_table_definition("document").expect("the Documents definition");    assert!(document.has_engine(), "Documents is kept under its engine");    let compiled = cotton_store::schema::package_tables::compiled_shape("document").expect("its compiled storage").to_vec();    for rise in ["behind", "ahead"] {        let mut served = serde_json::to_value(&document).unwrap();        served["tables"] = serde_json::to_value(&compiled).unwrap();        let storage = served["tables"].as_array_mut().unwrap().iter_mut().find(|table| table["name"] == "cotton_documents").expect("the documents table");        let columns = storage["columns"].as_array_mut().unwrap();        let changed = columns.iter_mut().find(|column| column["name"] == "status_changed_at").expect("the state time");        changed["declaration"] = json!(match rise {            "behind" => "\n    status_changed_at TEXT NOT NULL",            _ => "\n    status_changed_at TEXT CHECK (status_changed_at IS NULL OR length(status_changed_at) > 0)",        });        assert_ne!(served["tables"], serde_json::to_value(&compiled).unwrap(), "the object's storage is another rise's");        let parsed = TableDefinition::from_json(&served.to_string()).expect("the served definition parses");        parsed.validate().unwrap_or_else(|error| panic!("a rise {rise}: {error}"));    }    let mut value = example();    value["id"] = json!("lesson");    value["builtin"] = json!(false);    value["engine"] = Value::Null;    let mut imported = parse(&value);    imported.tables = Some(compiled);    let refused = imported.validate().expect_err("an imported table's storage holds no SQL");    assert!(refused.to_string().contains("SQL fragments"), "{refused}");}/// RULE: Choice objects are definition data; only declared choices may name nonempty drawn objects, so a generic page never branches on a table or accepts mismatched metadata.#[test]fn choice_objects_round_trip_and_refuse_wrong_types_or_values() {    let mut value = example();    value["columns"][7]["objects"] = json!({"open":"ring","done":"check"});    let definition = parse(&value);    definition.validate().unwrap();    assert_eq!(serde_json::to_value(&definition).unwrap()["columns"][7]["objects"], value["columns"][7]["objects"]);    let mut bad = value.clone();    bad["columns"][7]["objects"] = json!({"absent":"mac"});    assert!(parse(&bad).validate().is_err());    bad = value.clone();    bad["columns"][7]["objects"] = json!({"open":" "});    assert!(parse(&bad).validate().is_err());    bad = value;    bad["columns"][7]["type"] = json!("text");    bad["columns"][7].as_object_mut().unwrap().remove("choices");    assert!(parse(&bad).validate().is_err());}/// RULE: A counted pair is one text reading with a primary figure and small denominator; applying it to numeric storage must refuse rather than invent a second measurement.#[test]fn counted_pair_format_is_text_only_and_round_trips() {    let mut value = example();    value["columns"][1]["type"] = json!("text");    value["columns"][1]["format"] = json!("counted-pair");    let definition = parse(&value);    definition.validate().unwrap();    assert_eq!(serde_json::to_value(&definition).unwrap()["columns"][1]["format"], "counted-pair");    value["columns"][1]["type"] = json!("number");    assert!(parse(&value).validate().is_err());}/// RULE: A native reorder declaration survives export even when its order field is derived and readonly; sorting alone does not imply a reorder verb.#[test]fn manual_reorder_is_an_explicit_optional_definition_capability() {    let mut value = example();    value["order"] = json!("position");    let position = value["columns"].as_array_mut().unwrap().iter_mut()        .find(|column| column["key"] == "position").expect("position column");    position["readonly"] = json!(true);    let sorting = parse(&value);    sorting.validate().expect("derived sorting column");    assert_eq!(sorting.reorder, None);    assert!(serde_json::to_value(&sorting).unwrap().get("reorder").is_none());    value["reorder"] = json!(true);    let manual = parse(&value);    manual.validate().expect("native reorder with readonly position");    assert_eq!(manual.reorder, Some(true));    assert_eq!(serde_json::to_value(&manual).unwrap()["reorder"], json!(true));    value["reorder"] = json!(false);    assert_eq!(parse(&value).reorder, Some(false));}/// RULE: Engines fill typed columns and never compose slip or card sentences; definitions pick the columns, so changing the wording is data and a new composed text column is refused./// No exceptions remain: the former composed columns were replaced by typed engine facts.#[test]fn engines_never_declare_composed_display_columns() {    for definition in builtin_table_definitions() {        for column in &definition.columns {            assert!(                !(column.column_type == ColumnType::Text && matches!(column.key.as_str(), "sentence" | "readings" | "summary")),                "{}.{} must be typed data, never composed display words", definition.id, column.key            );        }    }}/// RULE: A list filter may hide its tabs while preserving the column and value narrowing; an absent tabs flag defaults to the existing visible controls, and false survives definition export.#[test]fn filter_tabs_do_not_remove_the_filter() {    let legacy: ListFilter = serde_json::from_value(json!({"column":"kind", "words":{"photo":"Photos","video":"Videos"}})).unwrap();    assert!(legacy.tabs.unwrap_or(true));    let hidden: ListFilter = serde_json::from_value(json!({"column":"kind", "tabs":false, "words":{"photo":"Photos","video":"Videos"}})).unwrap();    assert_eq!(hidden.tabs, Some(false));    assert_eq!(hidden.column, legacy.column);    assert_eq!(hidden.words, legacy.words);    assert_eq!(serde_json::to_value(hidden).unwrap()["tabs"], json!(false));}/// RULE: A place stores its kept words as text, so search, voice vocabulary and slip subtitles can read it just as they read the previous city text column.#[test]fn place_words_are_readable_in_text_slots() {    let mut raw = serde_json::to_value(builtin_table_definition("person").unwrap()).unwrap();    let columns = raw["columns"].as_array_mut().unwrap();    let city = columns.iter_mut().find(|c| c["key"] == "city").unwrap();    city["type"] = json!("place");    city["place"] = json!({"id":"city_place","country":"country","zone":"timezone"});    for key in ["city_place","country","timezone"] {        if let Some(column) = columns.iter_mut().find(|c| c["key"] == key) {            column["readonly"] = json!(true);        } else {            columns.push(json!({"key":key,"type":"text","readonly":true}));        }    }    raw["search"] = json!(["full_name","city"]);    raw["voice_words"] = json!(["full_name","city"]);    raw["index"] = json!("city");    raw["slip"]["subtitle"] = json!(["city"]);    let definition = TableDefinition::from_json(&raw.to_string()).unwrap();    definition.validate().unwrap();    assert_eq!(TableDefinition::from_json(&definition.to_json()).unwrap(),definition);}/// RULE: A slip's tap runs only one of the definition's own copy commands, and only on a slip that opens nothing else — a tap that wrote or destroyed would be an act with no look first (Clips, 14 Oct 2026).#[test]fn a_slips_tap_names_a_copy_command_of_its_own() {    let with = |commands: Value, tap: &str, opens: Option<&str>| {        let mut value = example();        value["commands"] = commands;        value["slip"]["tap"] = json!(tap);        if let Some(opens) = opens {            value["slip"]["opens"] = json!(opens);        }        parse(&value).validate()    };    let copy = json!([{ "id": "copy", "label": "Copy", "kind": "copy", "copies": "title" }]);    with(copy.clone(), "copy", None).expect("a copy command is a slip's tap");    let tapped = { let mut value = example(); value["commands"] = copy.clone(); value["slip"]["tap"] = json!("copy"); parse(&value) };    assert_eq!(serde_json::from_str::<TableDefinition>(&tapped.to_json()).unwrap(), tapped, "the key round-trips");    assert!(with(copy.clone(), "nowhere", None).is_err(), "a tap names one of the definition's commands");    let open = json!([{ "id": "open", "label": "Open", "kind": "open", "opens": "title" }]);    assert!(with(open, "open", None).is_err(), "only a copy is a tap");    assert!(with(copy, "copy", Some("title")).is_err(), "a slip that opens something else takes no tap");}/// RULE: A list's Paste button writes a pasted text only into a text or long text column a person writes — never a secret or a column the engine sets.#[test]fn a_lists_paste_writes_a_written_text_column() {    let with = |column: &str| {        let mut value = example();        value["paste"] = json!({ "column": column });        parse(&value).validate()    };    with("title").expect("a text column takes a paste");    let pasted = { let mut value = example(); value["paste"] = json!({ "column": "title" }); parse(&value) };    assert_eq!(serde_json::from_str::<TableDefinition>(&pasted.to_json()).unwrap(), pasted, "the key round-trips");    assert!(with("nowhere").is_err(), "a declared column");    assert!(with("due_date").is_err(), "a text column");    let mut secret = example();    secret["columns"][0]["secret"] = json!(true);    secret["paste"] = json!({ "column": secret["columns"][0]["key"].clone() });    assert!(parse(&secret).validate().is_err(), "never a secret");}/// RULE: No shipped definition carries `filters` (owner, 15 Oct 2026): narrowing a list is search's and voice's job, so a list draws no row of facet menus; the key is gone from the format, removed means removed.#[test]fn no_shipped_definition_carries_filters() {    for (id, json) in BUILTIN_DEFINITION_FILES {        let raw: Value = serde_json::from_str(json).expect("a shipped definition parses");        assert!(raw.get("filters").is_none(), "{id}.json names filters");    }    let mut value: Value = serde_json::from_str(BUILTIN_DEFINITION_FILES[0].1).expect("a shipped definition parses");    TableDefinition::authored(&value).expect("a shipped file is authored well");    value["filters"] = json!([]);    assert!(TableDefinition::authored(&value).is_err(), "a definition authored with filters is refused");}/// RULE: Producer authority must name one token identity in the known shape; malformed declarations must never broaden readonly access.#[test]fn producer_declaration_requires_one_token_identity() {    let mut raw = serde_json::to_value(super::builtin_table_definition("todo").unwrap()).unwrap();    raw["producer"] = serde_json::json!({"token_id":"synthetic-token"});    assert!(TableDefinition::authored(&raw).unwrap().validate().is_ok());    for producer in [serde_json::json!("script.py"), serde_json::json!({}), serde_json::json!({"token_id":1}),        serde_json::json!({"token_id":""}), serde_json::json!({"token_id":" token "}),        serde_json::json!({"token_id":"token", "script":"fold.py"})] {        raw["producer"] = producer;        assert!(TableDefinition::authored(&raw).and_then(|d| d.validate()).is_err(), "{raw}");    }}/// RULE: A list link shown only when it counts something is a count line, so its words come from the definition with the noun in its number form ("1 recording did not work"), never a label with a bare figure after it.#[test]fn a_link_shown_only_when_it_counts_carries_its_count_words() {    for definition in builtin_table_definitions() {        for link in definition.links.iter().flatten().filter(|link| link.hides_empty == Some(true)) {            let units = link.units.as_ref().unwrap_or_else(|| panic!("{}: link {:?} hides when empty but has no units", definition.id, link.label));            assert!(units.one.contains("{n}") && units.other.contains("{n}"), "{}: {:?} says its number", definition.id, link.label);        }    }}/// RULE: A view (rulings 03:55 and 10:52 17 Oct) names another table — shipped or made — holds no store of its own, names no engine (its computed columns are definitions, a rollup as much as a tile's summary), and orders its rows itself; a definition naming an engine on a made table is still refused.#[test]fn a_view_reads_another_table_and_holds_nothing() {    let view = |more: Value| {        let mut table = json!({            "id": "lesson_view", "name": "Lesson", "plural": "Lessons", "picture": null, "builtin": false, "engine": null,            "source": {"table": "lesson", "where": {"paid": false}}, "sort": {"column": "day"},            "columns": [                {"key": "title", "type": "text"}, {"key": "day", "type": "date"}, {"key": "paid", "type": "bool"},                {"key": "visits", "type": "number", "computed": {"rollup": {"table": "visit", "link": "lesson_id", "op": "count"}}}            ],            "title": "title", "date": "day", "project": null, "order": null,            "slip": {"title": "title", "subtitle": null, "trailing": null, "photo": null, "toggle": null},            "tile": {"face": "slip-list"}, "page": [{"heading": null, "columns": ["title"]}],            "instructions": "Unpaid lessons."        });        for (key, value) in more.as_object().unwrap() { table[key] = value.clone(); }        table    };    let read = |table: &Value| TableDefinition::from_json(&table.to_string()).and_then(|table| table.validate().map(|()| table));    // A view with a rollup over a made table stands.    let over_made = read(&view(json!({}))).expect("a view with a rollup over a made table");    assert_eq!((over_made.rows_table(), over_made.store_table()), ("lesson", None));    // And over a shipped one: People, kept by a where, its store People's.    let over_people = read(&view(json!({        "id": "people_here", "source": {"table": "person", "where": {"full_name": {"not": ["beta"]}}},        "sort": {"column": "full_name"}, "date": null,        "columns": [{"key": "title", "type": "text"}, {"key": "full_name", "type": "text"}]    }))).expect("a view over People");    assert_eq!((over_people.rows_table(), over_people.store_table()), ("person", Some("cotton_people")));    let refused = |more: Value, why: &str| {        let said = read(&view(more)).expect_err(why).to_string();        assert!(said.contains("source") || said.contains("sort"), "{why}: {said}");    };    refused(json!({"source": {"table": "lesson_view"}}), "a view of itself");    refused(json!({"source": {"table": "lesson", "where": {"Paid Up": false}}}), "a where over no column");    refused(json!({"engine": "money"}), "a view naming an engine");    refused(json!({"sort": null}), "a view with no order of its own");    // Package extraction says a view's tables as none; that is no store.    read(&view(json!({"tables": []}))).expect("a view whose tables are none");    // The engine refusal stands for what names an engine and is no built-in.    let mut engined = view(json!({"engine": "money"}));    engined.as_object_mut().unwrap().remove("source");    assert!(matches!(read(&engined), Err(DefinitionError::EngineOnUserTable(_))), "an engine on a made table");}/// RULE: Every shipped view reads a table this build ships, and every stored column it draws is that table's column of the same type — a view never invents a value its source does not hold.#[test]fn every_shipped_view_reads_a_built_in_with_its_columns() {    for view in builtin_table_definitions().iter().filter(|table| table.source.is_some()) {        let source = builtin_table_definition(view.rows_table())            .unwrap_or_else(|| panic!("{}: its source is a shipped table", view.id));        for column in view.columns.iter().filter(|column| column.computed.is_none()) {            let theirs = source.column(&column.key)                .unwrap_or_else(|| panic!("{}.{}: a column its source holds", view.id, column.key));            assert_eq!(column.column_type, theirs.column_type, "{}.{}: its source's type", view.id, column.key);        }    }}/// RULE: A slip's subtitle never says again the noun its record already is: the title names the record ("Morning edition"), so a subtitle reading that wraps its value in the table's own noun ("12 Oct 2026, 7:00 am edition") prints the word twice on every slip (walker294 row 35).#[test]fn a_slip_subtitle_reading_never_repeats_the_tables_noun() {    for definition in builtin_table_definitions() {        let Some(noun) = definition.name.split_whitespace().last().map(str::to_lowercase) else { continue };        let keys: Vec<&String> = match &definition.slip.subtitle {            Some(SlipSubtitle::One(key)) => vec![key],            Some(SlipSubtitle::Several(keys)) => keys.iter().collect(),            None => continue,        };        for key in keys {            let Some(reading) = definition.column(key).and_then(|column| column.reading.as_deref()) else { continue };            let words = reading.replace("{value}", " ").to_lowercase();            assert!(                !words.split(|c: char| !c.is_alphabetic()).any(|word| word == noun),                "{}.{key}: the subtitle's reading {reading:?} repeats the noun {noun:?}", definition.id            );        }    }}// RULE: Customer visibility is validated on the same save path as every definition; mine names a person link, and People can never be published as a directory.#[test]fn customer_visibility_requires_a_person_column_and_a_closed_policy() {    let mut value = example();    for policy in ["staff", "public", "mine(person)"] {        value["visibility"] = json!(policy);        let definition: TableDefinition = serde_json::from_value(value.clone()).unwrap();        definition.validate().unwrap();    }    for policy in ["everyone", "mine(title)", "mine(missing)", "mine()"] {        value["visibility"] = json!(policy);        let parsed = serde_json::from_value::<TableDefinition>(value.clone());        assert!(parsed.is_err() || parsed.unwrap().validate().is_err(), "{policy}");    }    let mut person = builtin_table_definition("person").unwrap().clone();    person.visibility = Some("public".into());    assert!(person.validate().is_err());    person.visibility = Some("mine(id)".into());    person.validate().unwrap();}// RULE: A package may bind mine through one own profile; missing, staff and deeper targets are refused before installation.#[test]fn customer_visibility_one_hop_graph_is_closed_and_shallow() {    let mut profile:TableDefinition=serde_json::from_value(example()).unwrap();    profile.id="profile".into();profile.visibility=Some("mine(person)".into());    let mut claim=profile.clone();claim.id="claim".into();claim.column("person").unwrap();    claim.columns.iter_mut().find(|c|c.key=="person").unwrap().link_to=Some("profile".into());    assert!(visibility::validate_tables(&[profile.clone(),claim.clone()]).is_ok());    assert!(visibility::validate_tables(&[claim.clone()]).is_err());    let mut staff=profile.clone();staff.visibility=Some("staff".into());    assert!(visibility::validate_tables(&[staff,claim.clone()]).is_err());    profile.columns.iter_mut().find(|c|c.key=="person").unwrap().link_to=Some("claim".into());    assert!(visibility::validate_tables(&[profile,claim]).is_err());}/// RULE (27 Oct 2026, the widgets left): a definition another build serves still reads when its views name a face this build no longer draws or keys only the widgets read (`sizes`, `everywhere`, `each`, `groups.widget`) — the view of the unknown face is left out, the rest read as they came, and the definition validates, so an object a rise behind never costs the phone a table.#[test]fn a_served_definition_with_the_widgets_keys_still_reads_without_them() {    let mut value = example();    value["views"] = json!([        { "face": "today", "name": "Today", "sizes": ["medium", "large"] },        { "face": "upcoming", "name": "Upcoming", "sizes": ["medium", "large"] },        { "face": "todayEverywhere", "name": "Today", "sizes": ["medium", "large"], "everywhere": true },    ]);    value["groups"] = json!({ "stack": "slips", "widget": { "face": "slips", "sizes": ["medium"] } });    let definition = TableDefinition::from_json(&value.to_string()).expect("the served definition reads");    definition.validate().expect("and validates");    let faces: Vec<&str> = definition.views.iter().flatten().map(|view| view.face.as_str()).collect();    assert_eq!(faces, ["today", "upcoming"]);    assert!(!serde_json::to_string(&definition).unwrap().contains("widget"), "nothing of the widgets is written back");}// ---- marks (owner, 3 Nov 2026: "marking a todo as done is just having a check mark") ----/// RULE: a table binds a mark the ink reads to one of its commands that runs on the record at once — the todo's check is `done`; a mark the ink does not read, a command the table does not declare, and one that deletes, picks, opens or creates are refused.#[test]fn a_mark_binds_a_command_that_runs_on_the_record_at_once() {    let todo = builtin_table_definitions().iter().find(|definition| definition.id == "todo").expect("the kit's todo").clone();    assert_eq!(todo.marks.as_ref().and_then(|marks| marks.get("check")).map(String::as_str), Some("done"));    todo.validate().expect("the todo's check binds done");    // The todo's tool block reads each of its views through the table, so a    // refusal is said under the view's slot: the words are what is held.    let bound = |mark: &str, id: &str| {        let mut table = todo.clone();        table.marks = Some([(mark.to_string(), id.to_string())].into());        table.validate().map_err(|error| error.to_string())    };    assert_eq!(bound("check", "drop"), Ok(()), "any update that runs at once");    let said = |error: DefinitionError| error.to_string();    let refused = bound("circle", "done").expect_err("a mark the ink does not read");    assert!(refused.ends_with(&said(DefinitionError::UnknownChoice { slot: "marks".into(), column: "marks".into(), value: "circle".into() })), "{refused}");    let refused = bound("check", "nowhere").expect_err("a command the table does not declare");    assert!(refused.ends_with(&said(DefinitionError::UnknownCommand { slot: "marks.check".into(), id: "nowhere".into() })), "{refused}");    for id in ["delete", "set-date", "open-people", "invite"] {        let refused = bound("check", id).expect_err(id);        assert!(            refused.ends_with(&said(DefinitionError::Requires { slot: "marks.check".into(), needs: "an_update_command_that_does_not_ask" })),            "{id}: {refused}"        );    }    // The bound command is the table's: its JSON round-trips the binding.    let json = todo.to_json();    assert_eq!(TableDefinition::from_json(&json).expect("reads back").marks, todo.marks);}/// Every uniform type a shipped kit's door names has media types a picker/// that takes them is handed (Android's): the shell maps nothing itself.#[test]fn every_door_type_has_its_media_types() {    use crate::definitions::file_type_mimes;    assert_eq!(file_type_mimes("org.idpf.epub-container"), Some(&["application/epub+zip"][..]));    assert_eq!(file_type_mimes("com.adobe.pdf"), Some(&["application/pdf"][..]));    assert_eq!(file_type_mimes("public.comma-separated-values-text"), Some(&["text/csv", "text/comma-separated-values"][..]));    assert_eq!(file_type_mimes("com.example.unheard-of"), None);}/// RULE (15 Nov 2026): a file shared into an app is of/// a door's type by its name's extension where a known type claims it (a/// provider that says only `application/octet-stream`, or calls an EPUB/// `application/zip`), else by its media type; every type but a folder has/// the extensions it is read by.#[test]fn a_shared_file_is_of_a_door_type_by_its_extension_then_its_media_type() {    use crate::definitions::{file_type_extensions, file_type_mimes, file_type_takes, FILE_TYPES};    for kind in FILE_TYPES {        assert!(file_type_mimes(kind).is_some(), "{kind} has its media types");        assert_eq!(file_type_extensions(kind).is_empty(), kind == "public.folder", "{kind}");    }    assert!(file_type_takes("org.matroska.mkv", Some("application/octet-stream"), Some("Harbour.MKV")));    assert!(file_type_takes("org.idpf.epub-container", Some("application/zip"), Some("a.epub")));    assert!(!file_type_takes("public.zip-archive", Some("application/zip"), Some("a.epub")), "an EPUB is no album");    assert!(file_type_takes("public.audio", Some("audio/flac; charset=binary"), Some("track")));    assert!(file_type_takes("public.audio", Some("audio/mpeg"), None));    assert!(!file_type_takes("public.audio", Some("video/mp4"), None));    assert!(file_type_takes("public.comma-separated-values-text", None, Some("goodreads_library_export.csv")));    assert!(!file_type_takes("org.opml.opml", Some("application/octet-stream"), Some("blob")), "octet-stream says nothing");    assert!(file_type_takes("org.opml.opml", Some("application/octet-stream"), Some("subs.opml")));    assert!(!file_type_takes("com.adobe.pdf", None, None));}/// RULE (Cotton Photos, 12 Nov 2026): a picture door opens the system's/// photo picker (many, photos and videos: only what the person chooses, never/// the library) or the camera (one at a time), and is written back as it was/// read; it names what it takes, each kind once, and is a door's one way in./// Its Files door takes any picture or any film.#[test]fn a_picture_door_opens_the_picker_or_the_camera() {    use crate::definitions::file_type_mimes;    assert_eq!(file_type_mimes("public.image"), Some(&["image/*"][..]));    assert_eq!(file_type_mimes("public.movie"), Some(&["video/*"][..]));    let doors = json!([        { "id": "library", "label": "Choose photos", "object": "picture", "pick": { "source": "library", "kinds": ["photo", "video"], "many": true } },        { "id": "camera", "label": "Take a photo", "object": "lens", "pick": { "source": "camera", "kinds": ["photo", "video"] } },        { "id": "files", "label": "From Files", "object": "folder", "files": { "types": ["public.image", "public.movie"], "many": true } },    ]);    let mut value = example();    set_top(&mut value, "create", json!({ "label": "Add photos", "doors": doors }));    let definition = parse(&value);    definition.validate().expect("three picture doors stand");    let create = definition.create.as_ref().expect("a create");    assert_eq!(create.doors[0].pick.as_ref().map(|pick| pick.source), Some(crate::definitions::PickSource::Library));    assert_eq!(serde_json::to_value(create).unwrap(), json!({ "label": "Add photos", "doors": doors }), "written back as read");    let bad = |why: &str, slot: &str| DefinitionError::BadSlot { slot: slot.into(), why: refusal_words(why) };    for (door, refused) in [        (json!({ "id": "camera", "label": "Take", "pick": { "source": "camera", "kinds": ["photo"], "many": true } }), bad("a_picture_door_names_what_it_takes", "create.doors.camera")),        (json!({ "id": "camera", "label": "Take", "pick": { "source": "camera", "kinds": [] } }), bad("a_picture_door_names_what_it_takes", "create.doors.camera")),        (json!({ "id": "camera", "label": "Take", "pick": { "source": "library", "kinds": ["photo", "video", "photo"] } }), bad("a_picture_door_names_what_it_takes", "create.doors.camera")),        (json!({ "id": "camera", "label": "Take", "pick": { "source": "camera", "kinds": ["photo"] }, "files": { "types": ["public.image"] } }), bad("a_door_types_words_or_chooses_files", "create.doors.camera")),    ] {        let mut value = example();        set_top(&mut value, "create", json!({ "label": "Add", "doors": [door] }));        assert_eq!(parse(&value).validate().unwrap_err(), refused);    }    let mut unheard = example();    set_top(&mut unheard, "create", json!({ "label": "Add", "doors": [{ "id": "x", "label": "X", "pick": { "source": "scanner", "kinds": ["photo"] } }] }));    assert!(serde_json::from_value::<crate::definitions::TableDefinition>(unheard).is_err(), "a source Cotton does not know is no door");}/// RULE: A podcast app's OPML subscription list is a type a door may name/// (`org.opml.opml`, the UTI the readers declare; Apple declares none), its/// picker handed OPML's own media type and plain XML's, which most pickers/// file an `.opml` under, and the untyped one Android's media store files it/// under.#[test]fn an_opml_door_names_its_type_and_its_media_types() {    use crate::definitions::file_type_mimes;    assert_eq!(file_type_mimes("org.opml.opml"), Some(&["text/x-opml", "text/xml", "application/xml", "application/octet-stream"][..]));    let mut value = example();    set_top(&mut value, "create", json!({ "label": "Add a podcast", "doors": [        { "id": "opml", "label": "Bring subscriptions in", "object": "stack", "files": { "types": ["org.opml.opml"] } },    ] }));    parse(&value).validate().expect("an OPML door stands");}