use super::*; use crate::definitions::{builtin_table_definition, builtin_table_definitions}; use serde_json::{json, Value}; fn with(table: &str, change: impl FnOnce(&mut TableDefinition)) -> TableDefinition { let mut definition = builtin_table_definition(table).expect("a built-in").clone(); change(&mut definition); definition } fn chats_with(change: impl FnOnce(&mut Vec)) -> TableDefinition { with("thread", |chats| { change(chats.commands.as_mut().expect("chats have commands")) }) } fn command(value: Value) -> RecordCommand { serde_json::from_value(value).expect("a command of a known kind") } /// RULE: A command is one of five kinds — create, update, delete, open, copy — and a definition naming any other kind, or none, does not parse, because the file picks from a closed list and never programs an action. #[test] fn a_command_is_one_of_four_kinds() { for kind in ["create", "update", "delete", "open", "copy"] { let parsed: CommandKind = serde_json::from_value(json!(kind)).expect(kind); assert_eq!(parsed.as_str(), kind); } for kind in ["set", "several", "sheet", "script", "navigate", "run", ""] { assert!( serde_json::from_value::(json!(kind)).is_err(), "{kind:?} is not a kind" ); } let no_kind = json!({ "id": "pin", "label": "Pin", "verb": "set_thread_pinned", "receipt": "Pinned" }); assert!( serde_json::from_value::(no_kind).is_err(), "a command says its kind" ); for key in ["runs"] { let mut extra = json!({ "id": "x", "label": "X", "kind": "update", "verb": "set_thread_pinned" }); extra[key] = json!("history"); assert!( super::super::tolerant::authored::(&extra).is_err(), "{key} is not a command key" ); } } /// RULE: Each kind carries what it needs and nothing another kind owns: create, update and delete name an engine verb (a verb-less one is refused), open names a link or url column and no verb, bindings or receipt — never a plain text column. #[test] fn each_kind_carries_its_own_keys_and_no_other() { let refused: Vec<(&str, Value)> = vec![ ( "update without a verb", json!({ "id": "x", "label": "X", "kind": "update", "receipt": "Done" }), ), ( "create without a verb", json!({ "id": "x", "label": "X", "kind": "create" }), ), ( "update that opens", json!({ "id": "x", "label": "X", "kind": "update", "verb": "set_thread_pinned", "opens": "member_people" }), ), ( "open with a verb", json!({ "id": "x", "label": "X", "kind": "open", "opens": "member_people", "verb": "set_thread_pinned" }), ), ( "open with bindings", json!({ "id": "x", "label": "X", "kind": "open", "opens": "member_people", "bindings": { "threadId": "$id" } }), ), ( "open without a column", json!({ "id": "x", "label": "X", "kind": "open" }), ), ( "open on a plain text column", json!({ "id": "x", "label": "X", "kind": "open", "opens": "title" }), ), ( "open on an undeclared column", json!({ "id": "x", "label": "X", "kind": "open", "opens": "nowhere" }), ), ( "open with a receipt", json!({ "id": "x", "label": "X", "kind": "open", "opens": "member_people", "receipt": "Opened" }), ), ( "a blank receipt", json!({ "id": "x", "label": "X", "kind": "update", "verb": "set_thread_pinned", "receipt": " " }), ), ( "a receipt naming braces other than the record's name", json!({ "id": "x", "label": "X", "kind": "update", "verb": "set_thread_pinned", "receipt": "Moved {title} away" }), ), ( "a confirmation on a command that does not ask", json!({ "id": "x", "label": "X", "kind": "update", "verb": "set_thread_pinned", "confirm": "Sure?" }), ), ]; for (what, bad) in refused { let chats = chats_with(|commands| commands.push(command(bad))); assert!(chats.validate().is_err(), "{what} must be refused"); } let taken = [ json!({ "id": "x", "label": "Mute", "kind": "update", "verb": "set_thread_pinned" }), json!({ "id": "x", "label": "Open the people", "kind": "open", "opens": "member_people" }), json!({ "id": "x", "label": "Move", "kind": "update", "verb": "set_thread_pinned", "receipt": "Moved {name} away" }), ]; for good in taken { let chats = chats_with(|commands| commands.push(command(good.clone()))); chats .validate() .unwrap_or_else(|error| panic!("{good}: {error}")); } // The same column, once it is a web address, opens. let address = with("thread", |chats| { chats .columns .iter_mut() .find(|column| column.key == "description") .unwrap() .column_type = ColumnType::Url; let open = command( json!({ "id": "x", "label": "Open the site", "kind": "open", "opens": "description" }), ); chats.commands.as_mut().unwrap().push(open); }); address.validate().expect("a url column opens its address"); } /// RULE: A copy names what it copies — a column of its table, or `$sealed` for the record's sealed value (a password's password, which no column carries) — and nothing else: no verb, pick, confirm, receipt or `does`, because it is the device's own act and never reaches the core (architect, 13 Oct 2026: Copy password is a client act). #[test] fn a_copy_names_what_it_copies_and_nothing_else() { for good in [ json!({ "id": "x", "label": "Copy", "kind": "copy", "copies": "description" }), json!({ "id": "x", "label": "Copy password", "kind": "copy", "copies": "$sealed" }), ] { chats_with(|commands| commands.push(command(good.clone()))).validate().unwrap_or_else(|error| panic!("{good}: {error}")); } for (what, bad) in [ ("a copy naming nothing", json!({ "id": "x", "label": "Copy", "kind": "copy" })), ("a copy of an undeclared column", json!({ "id": "x", "label": "Copy", "kind": "copy", "copies": "nowhere" })), ("a copy with a verb", json!({ "id": "x", "label": "Copy", "kind": "copy", "copies": "description", "verb": "set_thread_pinned" })), ("a copy with a receipt", json!({ "id": "x", "label": "Copy", "kind": "copy", "copies": "description", "receipt": "Copied" })), ("a copy that asks", json!({ "id": "x", "label": "Copy", "kind": "copy", "copies": "description", "destructive": true })), ("copies on an update", json!({ "id": "x", "label": "X", "kind": "update", "verb": "set_thread_pinned", "copies": "description" })), ] { assert!(chats_with(|commands| commands.push(command(bad))).validate().is_err(), "{what} must be refused"); } let copy = command(json!({ "id": "x", "label": "Copy", "kind": "copy", "copies": "description" })); assert!(!copy.offered_on(&json!({})), "nothing to copy, no Copy"); assert!(copy.offered_on(&json!({ "description": "words" }))); } /// RULE: Commands that change records provide a definition-owned receipt; only navigation, copying and quiet on-open stamps may omit one, so the app never invents an acknowledgement. Opening the reader (`reader.open`, a kept page's Read) is navigation: it changes no record. #[test] fn changing_commands_supply_their_own_receipt() { for definition in builtin_table_definitions() { for command in definition.commands.iter().flatten() { if matches!(command.kind, CommandKind::Open | CommandKind::Copy) || command.method.as_deref() == Some("reader.open") || definition.on_open.as_deref() == Some(command.id.as_str()) { continue; } assert!(command.receipt.as_ref().is_some_and(|receipt| !receipt.trim().is_empty()), "{}.{} needs a receipt", definition.id, command.id); } } } /// RULE: A command's undo is another update command of the same table that does not ask first, and built-in undos come in pairs (Pin undone by Unpin, Unpin by Pin), so the receipt's Undo always has something to run. #[test] fn an_undo_names_the_command_that_takes_it_back() { let mut pairs = 0; for definition in builtin_table_definitions() { for command in definition.commands.iter().flatten() { let Some(undo) = &command.undo else { continue }; let back = definition .command(undo) .unwrap_or_else(|| panic!("{}.{undo}", definition.id)); assert_eq!( back.undo.as_deref(), Some(command.id.as_str()), "{}.{} and {undo} undo each other", definition.id, command.id ); pairs += 1; } } assert!(pairs >= 8, "only {pairs} undos were read"); let chats = builtin_table_definition("thread").unwrap(); assert_eq!( chats.command("pin").and_then(|pin| pin.undo.as_deref()), Some("unpin") ); for (what, undo) in [ ("itself", "pin"), ("a command that asks first", "clear"), ("no command", "nowhere"), ] { let bad = chats_with(|commands| { commands .iter_mut() .find(|command| command.id == "pin") .unwrap() .undo = Some(undo.into()) }); assert!( bad.validate().is_err(), "an undo naming {what} must be refused" ); } let asks = chats_with(|commands| { commands .iter_mut() .find(|command| command.id == "clear") .unwrap() .undo = Some("pin".into()) }); assert!( asks.validate().is_err(), "a command that asks first has no undo" ); } /// RULE: A delete command running the generic verb on its own table is that table's Delete, named for the page's away act: it stands beside the generic Delete, never on a table whose Delete is refused, and one on another table or verb still takes its place. #[test] fn a_generic_delete_command_is_the_tables_own_delete() { let notes = builtin_table_definition("note").expect("a built-in"); let delete = notes.command("delete").expect("the note page's Delete"); assert!(delete.is_generic_delete("note") && delete.asks_first() && delete.undo.is_none()); assert_eq!(notes.delete, None, "the generic Delete still stands beside it"); assert_eq!(notes.resolved_parts().acts.away.as_deref(), Some("delete")); let refused = |change: fn(&mut TableDefinition)| { let mut bad = notes.clone(); change(&mut bad); bad.validate().is_err() }; assert!(refused(|notes| notes.delete = Some(false)), "a refused Delete is never offered as a command"); assert!( refused(|notes| notes.commands.as_mut().unwrap().iter_mut().find(|c| c.id == "delete").unwrap().data = Some(serde_json::from_value(json!({ "table": "todo" })).unwrap())), "another table's delete takes the generic Delete's place" ); assert!( refused(|notes| notes.commands.as_mut().unwrap().iter_mut().find(|c| c.id == "delete").unwrap().verb = Some("delete_event".into())), "another verb takes the generic Delete's place" ); assert!(refused(|notes| notes.commands.as_mut().unwrap().iter_mut().find(|c| c.id == "delete").unwrap().confirm = None), "it asks first, in its own words"); } /// A data table with one command, by id. fn data_table_with_a_command(id: &str) -> TableDefinition { serde_json::from_value(serde_json::json!({ "id": id, "name": "Domain", "plural": "Domains", "picture": null, "builtin": false, "engine": null, "columns": [{ "key": "name", "name": "Name", "type": "text", "required": true }], "title": "name", "date": null, "project": null, "order": null, "slip": { "title": "name", "subtitle": ["name"], "trailing": null, "photo": null, "toggle": null }, "tile": { "face": "slip-list" }, "page": [{ "heading": null, "columns": ["name"], "commands": ["check_price"] }], "commands": [{ "id": "check_price", "label": "Check the price", "kind": "update", "method": "domains.checkPrice", "bindings": { "id": "$id" } }], "instructions": "One row per domain." })) .expect("the table parses") } /// RULE: Only a table of a package Cotton itself carries may declare commands while being data; any other data table is refused, and so is the same table arriving in an imported package, whatever it is called. /// /// This is the line between a tool Cotton ships and a tool that arrives as a /// file. A command runs an engine act — Register spends the owner's money — /// so a definition a person, an assistant or a saved kit can write must never /// be able to declare one, and calling its table `domain` must not buy it /// the exception. #[test] fn only_a_table_cotton_itself_carries_declares_commands_as_data() { assert!(!CARRIED_COMMAND_TABLES.is_empty(), "Cotton carries its command tables explicitly"); for table in CARRIED_COMMAND_TABLES { data_table_with_a_command(table).validate().expect("the carried table may"); } let refused = data_table_with_a_command("unshipped").validate().expect_err("any other data table may not"); assert!(refused.to_string().contains("built-in table"), "{refused}"); // The same carried table, arriving as a file. let carried = CARRIED_COMMAND_TABLES[0]; let table = data_table_with_a_command(carried); let package = crate::definitions::package::ToolPackage { board: None, tool: serde_json::from_value(serde_json::json!({ "id": "domains", "name": "Domains", "picture": "tool-domains", "tables": [carried], "instructions": "Domains.", "automations": [], "author": { "device": "someone", "name": "Someone" }, "signature": null })) .expect("the tool parses"), tables: vec![table], pictures: Default::default(), samples: Default::default(), }; let refused = crate::definitions::package::encode_unsigned_package(&package).expect_err("an imported package declares no command"); // Package validation may reject at the table boundary before inspecting // the individual key; either way an imported command must be forbidden. let sentence = refused.to_string(); assert!(sentence.contains("forbidden") && sentence.contains("commands"), "{refused}"); } /// RULE: A command picks a database only to tell an app method which other database it reaches into; a verb is never handed one. #[test] fn a_database_is_picked_only_for_an_app_method() { let mut table = data_table_with_a_command("domain"); let command = &mut table.commands.as_mut().unwrap()[0]; command.pick = Some(CommandPick { argument: "database".into(), kind: PickKind::Database, label: None, table: None, database_by: None, filter: None, choices_from: None, optional: None, min: None, default: None, max: None, labels: None, accept: None }); table.validate().expect("a method takes a picked database"); let command = &mut table.commands.as_mut().unwrap()[0]; command.pick.as_mut().unwrap().table = Some("project".into()); assert!(table.validate().is_err(), "a database pick names no table"); } /// RULE: Validating a definition parses no JSON — a command pick's target is the process's parsed built-in, read once, never a fresh parse inside validation — because validation runs on every page open and a whole-definition parse inside it overflowed a debug build's worker stack opening a todo page (14 Oct 2026). #[test] fn validating_a_definition_parses_no_json() { // Warm the process's parsed set first, as any page open does. let mut pick_fixture = builtin_table_definition("todo") .expect("a built-in") .clone(); pick_fixture.commands.as_mut().expect("todo commands").push(command(json!({ "id": "pick_a_bank", "label": "Pick a bank", "kind": "update", "verb": "update_todo", "pick": {"kind": "record", "argument": "account_id", "table": "money_account", "where": {"kind": "bank"}} }))); let picks = [pick_fixture]; assert!( picks.iter().any(|definition| definition.commands.iter().flatten().any(|command| { command.pick.as_ref().is_some_and(|pick| pick.filter.is_some()) })), "the pick-with-where fixture is what this validates" ); let before = crate::definitions::builtin_parses_on_this_thread(); for definition in builtin_table_definitions_cached() { definition.validate().unwrap_or_else(|error| panic!("{}: {error}", definition.id)); } assert_eq!(crate::definitions::builtin_parses_on_this_thread(), before, "validation parsed the built-ins again"); // And no validation source decodes a definition of its own. for (file, source) in [("commands.rs", include_str!("commands.rs")), ("parts.rs", include_str!("parts.rs"))] { let code = source.split("#[cfg(test)]").next().unwrap_or_default(); for (n, line) in code.lines().enumerate() { let line = line.split("//").next().unwrap_or_default(); assert!( !line.contains("serde_json::from_str") && !line.contains("serde_json::from_value"), "{file}:{} decodes JSON inside validation", n + 1 ); } } } fn builtin_table_definitions_cached() -> Vec<&'static TableDefinition> { crate::definitions::BUILTIN_DEFINITION_FILES .iter() .filter_map(|(id, _)| builtin_table_definition(id)) .collect() } // RULE: Number picks carry numeric defaults and inclusive bounds; malformed ranges or values cannot reach an act as strings or out-of-range quantities. #[test] fn number_picks_validate_bounds_defaults_and_values() { let mut table: TableDefinition = serde_json::from_str(include_str!( "../../../cotton-tools/tests/fixtures/classroom/tables/student.json" )).unwrap(); let act = serde_json::json!({"id":"book","label":"Book","kind":"create","verb":"reserve_record", "pick":{"kind":"number","argument":"data.quantity","min":1,"default":2,"max":5}}); table.acts = Some(vec![serde_json::from_value(act.clone()).unwrap()]); assert!(table.validate().is_ok()); let pick = table.acts.as_ref().unwrap()[0].pick.as_ref().unwrap(); for value in [serde_json::json!(1), serde_json::json!(5), serde_json::json!(2.5)] { assert_eq!(pick.number_value(Some(&value)).unwrap(), value); } assert_eq!(pick.number_value(None).unwrap(), serde_json::json!(2)); for value in [serde_json::json!(0), serde_json::json!(6), serde_json::json!("2"), serde_json::json!(null), serde_json::json!(true)] { assert!(pick.number_value(Some(&value)).is_err()); } for bad in [serde_json::json!({"min":5,"max":1}), serde_json::json!({"min":3,"default":2}), serde_json::json!({"max":1,"default":2}), serde_json::json!({"kind":"text","min":1})] { let mut bad_act = act.clone(); let pick = bad_act["pick"].as_object_mut().unwrap(); pick.remove("min"); pick.remove("max"); pick.remove("default"); for (key, value) in bad.as_object().unwrap() { pick.insert(key.clone(), value.clone()); } table.acts = Some(vec![serde_json::from_value(bad_act).unwrap()]); assert!(table.validate().is_err()); } } // RULE: A number pick may name its values, each a card of its own (a book's stars): only a number pick does, each named value is a number in its range with words, a value it does not name is refused, and only a labelled number pick may be optional (its Skip sends nothing). #[test] fn a_number_pick_names_its_values() { let mut table: TableDefinition = serde_json::from_str(include_str!( "../../../cotton-tools/tests/fixtures/classroom/tables/student.json" )).unwrap(); let stars = serde_json::json!({"1": "★", "2": "★★", "3": "★★★", "4": "★★★★", "5": "★★★★★"}); let act = serde_json::json!({"id":"rate","label":"Rate","kind":"create","verb":"reserve_record", "pick":{"kind":"number","argument":"data.quantity","min":1,"max":5,"optional":true,"labels":stars}}); table.acts = Some(vec![serde_json::from_value(act.clone()).unwrap()]); table.validate().expect("a labelled number pick stands"); let pick = table.acts.as_ref().unwrap()[0].pick.as_ref().unwrap(); assert_eq!(pick.labelled_value(&serde_json::json!(4)).unwrap(), serde_json::json!(4)); assert_eq!(pick.labelled_value(&serde_json::json!(4.0)).unwrap(), serde_json::json!(4.0)); for value in [serde_json::json!(2.5), serde_json::json!(6), serde_json::json!("4")] { assert!(pick.labelled_value(&value).is_err(), "{value}"); } for bad in [ serde_json::json!({"kind":"text","argument":"data.name","labels":{"1":"one"}}), serde_json::json!({"kind":"number","argument":"data.quantity","min":1,"max":5,"labels":{"9":"nine"}}), serde_json::json!({"kind":"number","argument":"data.quantity","labels":{"x":"ex"}}), serde_json::json!({"kind":"number","argument":"data.quantity","labels":{"1":" "}}), serde_json::json!({"kind":"number","argument":"data.quantity","optional":true}), ] { let mut bad_act = act.clone(); bad_act["pick"] = bad.clone(); table.acts = Some(vec![serde_json::from_value(bad_act).unwrap()]); assert!(table.validate().is_err(), "{bad}"); } } // RULE: the kit names objects from one closed vocabulary; an unknown picture // is invalid rather than an invisible or substituted object. #[test] fn act_objects_are_a_closed_kit_vocabulary() { for object in super::ACT_OBJECTS { let table = with("todo", |table| table.commands.as_mut().unwrap()[0].object = Some((*object).into())); table.validate().unwrap_or_else(|error| panic!("{object}: {error}")); } for object in ["", "restore", "edit-act-when", "unknown"] { let table = with("todo", |table| table.commands.as_mut().unwrap()[0].object = Some(object.into())); assert!(table.validate().is_err(), "{object}"); } } // RULE: every personal table's declared rank names valid whole-record acts, // with destructive acts kept out of main and more. #[test] fn personal_act_rank_is_valid_and_field_edits_are_not_acts() { let folder = cotton_store::manifest_dir().join("kits/personal/tables"); let tables = std::fs::read_dir(folder).expect("the personal kit tables"); for entry in tables { let path = entry.expect("a kit table").path(); if path.extension().and_then(|extension| extension.to_str()) != Some("json") { continue; } let json = std::fs::read_to_string(&path).expect("a kit table's JSON"); let table = TableDefinition::from_json(&json).unwrap_or_else(|error| panic!("{}: {error}", path.display())); table.validate().unwrap_or_else(|error| panic!("{}: {error}", table.id)); let acts = table.resolved_parts().acts; for id in acts.main.iter().chain(acts.more.iter()) { let Some(command) = table.command(id) else { continue }; assert!(!command.edits_field(&table), "{}.{id}", table.id); assert!(!command.is_away_act(), "{}.{id}", table.id); } } let field = with("todo", |table| { let command = &mut table.commands.as_mut().unwrap()[0]; command.does = None; command.pick = Some(serde_json::from_value(json!({"argument":"title","kind":"text"})).unwrap()); }); assert!(field.validate().is_err()); let destructive = with("todo", |table| table.parts.as_mut().unwrap().acts.main = Some("delete".into())); assert!(destructive.validate().is_err()); } /// RULE (6 Nov 2026): A command lands on another table's record only by an app method's answer, naming one table and one answer key, never beside a revealed record; and its signed-out words belong to an act at the object alone. #[test] fn a_landing_and_a_signed_out_line_are_an_object_act_s() { let landing = |change: Value| { let mut table = data_table_with_a_command("page"); let mut value = serde_json::to_value(&table.commands.as_ref().unwrap()[0]).unwrap(); for (key, said) in change.as_object().unwrap() { if said.is_null() { value.as_object_mut().unwrap().remove(key); } else { value[key] = said.clone(); } } table.commands = Some(vec![command(value)]); table.validate() }; landing(json!({ "method": "object.act", "lands": { "table": "fetch", "answer": "fetch" }, "signed_out": "Sign in first." })).expect("an object act lands and says its own words"); let refused = landing(json!({ "kind": "update", "method": null, "verb": "set_page", "lands": { "table": "fetch", "answer": "fetch" } })).expect_err("a verb lands nowhere"); assert!(refused.to_string().contains("lands"), "{refused}"); let refused = landing(json!({ "lands": { "table": "", "answer": "fetch" } })).expect_err("a landing names its table"); assert!(refused.to_string().contains("lands.table"), "{refused}"); let refused = landing(json!({ "signed_out": "Sign in first." })).expect_err("only an act at the object is signed out"); assert!(refused.to_string().contains("signed_out"), "{refused}"); let refused = landing(json!({ "method": "object.act", "signed_out": " " })).expect_err("signed-out words are words"); assert!(refused.to_string().contains("signed_out"), "{refused}"); assert!(serde_json::from_value::(json!({ "id": "f", "label": "F", "kind": "create", "method": "object.act", "lands": { "table": "fetch", "answer": "fetch", "opens": "x" } })).is_err(), "a landing says its table and answer key, nothing else"); } // RULE (SUBTITLE FILE, 25 Nov 2026): a file pick names what it accepts, lowercase extensions with no dot; only a file pick names one; its value is the picked copy's path, refused by name when its extension is not accepted. #[test] fn a_file_pick_names_what_it_accepts_and_takes_only_that() { let pick = |kind: PickKind, accept: Option>| CommandPick { argument: "path".into(), kind, label: None, table: None, database_by: None, filter: None, choices_from: None, optional: None, min: None, default: None, max: None, labels: None, accept: accept.map(|list| list.into_iter().map(str::to_string).collect()) }; assert!(pick(PickKind::File, Some(vec!["srt", "vtt"])).validate_file().is_ok()); assert!(pick(PickKind::File, None).validate_file().is_err(), "a file pick names what it accepts"); assert!(pick(PickKind::File, Some(vec![])).validate_file().is_err()); assert!(pick(PickKind::File, Some(vec![".srt"])).validate_file().is_err(), "no dot"); assert!(pick(PickKind::File, Some(vec!["SRT"])).validate_file().is_err(), "lowercase"); assert!(pick(PickKind::Text, Some(vec!["srt"])).validate_file().is_err(), "only a file pick accepts"); let subtitles = pick(PickKind::File, Some(vec!["srt", "vtt"])); assert_eq!(subtitles.file_value(&serde_json::json!("/tmp/picked/a/Night.Ferry.en.SRT")).as_deref(), Ok("/tmp/picked/a/Night.Ferry.en.SRT")); assert_eq!(subtitles.file_value(&serde_json::json!("/tmp/picked/a/Night.Ferry.ass")), Err("this takes only a .srt, .vtt file".to_string())); assert!(subtitles.file_value(&serde_json::json!(" ")).is_err()); }