use super::*; use rusqlite::types::Value as SqlValue; use crate::shell::client::phone_tests::attached_on_a_clock; /// The catalogue's answer, asked again when its read ran past the short lane's /// deadline, as the app does (`could_not_read` with why `too_long`): a debug /// build at load 50 took over 3 s for one (rust-main 17168, "sqlite: /// interrupted"). Any other failure, or five cut reads in a row, fails. fn answered(client: &ClientController) -> Value { for _ in 0..5 { match call(client, &json!({})) { Ok(answer) => return answer, Err(_) if matches!(cotton_client::replica::take_read_refusal(), Some(cotton_client::replica::ReadRefused::TooLong)) => continue, Err(error) => panic!("the catalogue answers: {error:?}"), } } panic!("the catalogue's read ran past the short lane's deadline five times"); } fn repo_root() -> std::path::PathBuf { cotton_store::manifest_dir().join("../..") } /// Generate the app resource explicitly during a definition landing: /// cargo +1.98.1 test -p cotton-ffi --lib generate_shipped_catalogue -- --ignored #[test] #[ignore = "generation command writes the app resource; run as part of a definition landing"] fn generate_shipped_catalogue() { let path = repo_root().join(SNAPSHOT_PATH); let today = snapshot().expect("every shipped definition decodes and validates"); std::fs::create_dir_all(path.parent().expect("a parent")).expect("the snapshot's folder"); let themes = themes_of(&today).expect("the snapshot reads back"); std::fs::write(&path, today).expect("the snapshot is written"); let look = repo_root().join(THEMES_PATH); std::fs::create_dir_all(look.parent().expect("a parent")).expect("the themes' folder"); std::fs::write(&look, themes).expect("the look's themes are written"); let fixture = repo_root().join(FIXTURE_PATH); std::fs::write(&fixture, kit_household()).expect("the fixture is written"); } /// Where the synthetic household's catalogue lives, from the repo root: what /// the package's previews and tests draw (`DefinitionCatalogue.fixture`). const FIXTURE_PATH: &str = "apps/cotton/Sources/CottonUI/Resources/Fixtures/catalogue.json"; /// The catalogue of a synthetic database that took the kit /// (`import_kit_tools`, the one helper a synthetic household gets its tools /// by), pretty-printed, one newline at the end. fn kit_household() -> String { // `fixture::seeded` wrote the shell and imported the kit. let (_dir, client, _) = attached_on_a_clock(); let answer = answered(&client); let mut text = serde_json::to_string_pretty(&answer).expect("the answer serializes"); text.push('\n'); text } /// RULE: The look's shipped themes are the catalogue snapshot's own: `CottonPaper` draws `Theme.paper` from `THEMES_PATH` before any core answers, and a file that drifted from the snapshot would draw a theme the core does not ship. #[test] fn the_looks_themes_are_the_snapshots() { let snapshot = std::fs::read_to_string(repo_root().join(SNAPSHOT_PATH)).expect("the committed snapshot"); let look = std::fs::read_to_string(repo_root().join(THEMES_PATH)).expect("the look's themes"); assert_eq!(look, themes_of(&snapshot).expect("the snapshot reads"), "regenerate with generate_shipped_catalogue"); } /// RULE: Every table a catalogue carries travels with the page the core resolved for it, so the app draws the core's page and never derives one itself: a second derivation of a page is a second truth, as a second decoder is. #[test] fn every_table_in_a_catalogue_carries_the_page_the_core_resolved() { let (_dir, client, _) = attached_on_a_clock(); let todo = cotton_core::definitions::builtin_table_definition("todo").expect("todo's schema is code"); store_definition(&client, "todo", &serde_json::to_string(todo).unwrap()); let answer = answered(&client); let tables = answer["tables"].as_array().expect("tables"); assert_eq!(answer["pages"].as_object().expect("pages").len(), tables.len(), "one page per table, none extra"); let typed: Vec = tables.iter().map(|table| serde_json::from_value(table.clone()).expect("the core's own table reads back")).collect(); for table in &typed { assert_eq!(answer["pages"][&table.id], serde_json::to_value(page(table, slips_of(&typed))).unwrap(), "{}", table.id); } } /// RULE: Every board a catalogue carries has each part's settings resolved by the core — a fresh database's and a database's own answer alike — so a board's defaults live in one place (`board::default_of`) and the app keeps none of its own: an app default is a second truth of the board format. #[test] fn every_board_in_a_catalogue_arrives_resolved() { use cotton_core::definitions::board::BoardDefinition; let fresh = serde_json::to_value(fresh().expect("the last-resort answer decodes")).unwrap(); let (_dir, client, _) = attached_on_a_clock(); let answer = answered(&client); for catalogue in [&fresh, &answer] { let boards = catalogue["boards"].as_object().expect("boards"); assert!(!boards.is_empty()); for (id, board) in boards { let read: BoardDefinition = serde_json::from_value(board["definition"].clone()).expect("a board"); assert_eq!(read, read.resolved(), "{id} arrives with a setting left to the app"); } } let home = BoardDefinition::builtin("home").expect("home ships"); let tools = home.resolved().parts.into_iter().find(|part| part.kind == "tools").expect("home's tools"); assert!(tools.settings.contains_key("columns") && tools.settings.contains_key("size"), "a default is dealt"); } fn store_definition(client: &ClientController, id: &str, definition: &str) { let workspace = client.with_writer(|file| Ok(file.workspace_id.to_string())).expect("the workspace"); client .with_writer(|file| { let sql = "INSERT OR REPLACE INTO cotton_table_definitions \ (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) \ VALUES (?, ?, ?, 1, 0, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')"; let values = [SqlValue::Text(id.into()), SqlValue::Text(workspace.clone()), SqlValue::Text(definition.into())]; file.driver.run(sql, &values).map_err(|error| error.to_string())?; crate::fixture::receipted(file.driver, sql); Ok(()) }) .expect("a stored row"); } fn feedback_rows(client: &ClientController) -> i64 { client .with_writer(|file| { let row = file .driver .get("SELECT count(*) AS n FROM cotton_feedback", &[]) .map_err(|error| error.to_string())?; Ok(row.and_then(|row| row.int("n")).unwrap_or(0)) }) .expect("the count") } /// RULE: A definition the Mac writes is drawn by the phone of the same build: a row stored as this build writes it reads back through the phone's catalogue as itself, with nothing fallen back and nothing said in Feedback (294, walker293: a phone refused Personal's money_account on `account_number`). #[test] fn a_definition_the_mac_writes_is_drawn_on_the_phone() { let (_dir, client, _) = attached_on_a_clock(); let written = cotton_core::definitions::builtin_table_definition("person").expect("person's schema is code"); store_definition(&client, "person", &serde_json::to_string(written).unwrap()); let before = feedback_rows(&client); let answer = answered(&client); assert!(answer["fell_back"].as_array().unwrap().is_empty(), "{}", answer["fell_back"]); let drawn = answer["tables"].as_array().unwrap().iter().find(|table| table["id"] == "person").expect("drawn"); let mut here = written.clone(); here.for_database(cotton_core::definitions::DatabaseKind::Personal); assert_eq!(drawn, &serde_json::to_value(&here).unwrap(), "read back as written"); assert_eq!(feedback_rows(&client), before, "nothing to say"); } /// RULE: The shipped Home a device is served is this device's card and the tools (owner, 2 Nov 2026: Cotton's Home is the sync card alone), its `device` part first and naming this device's own record; a board that holds one — an object's own Home — is served naming that device's own record (`THIS_DEVICE_KEY`) on every size's list, so the phone draws the card the core says is its own and never works out which one; a device with no identity yet names none. #[test] fn the_served_home_is_this_devices_card_and_a_held_one_names_this_device() { use cotton_core::definitions::board::THIS_DEVICE_KEY; let (_dir, client, _) = attached_on_a_clock(); client.set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.into())); let answer = answered(&client); let parts = answer["boards"]["home"]["definition"]["parts"].as_array().expect("home's parts"); let kinds: Vec<&str> = parts.iter().map(|part| part["kind"].as_str().unwrap()).collect(); assert_eq!(kinds, ["device", "tools"], "the sync card and the tools: {parts:?}"); assert_eq!(parts[0][THIS_DEVICE_KEY], crate::fixture::SELF_DEVICE_ID, "naming this device"); let held = || cotton_tools::presentation::Resolved { definition: json!({"id": "home", "parts": [{"kind": "device"}, {"kind": "today"}], "variants": [{"parts": [{"kind": "device"}]}]}), drawn: cotton_tools::presentation::Drawn::Row, passed_over: None, }; let named = served_to(held(), Some(crate::fixture::SELF_DEVICE_ID)).definition; assert_eq!(named["parts"][0], json!({"kind": "device", THIS_DEVICE_KEY: crate::fixture::SELF_DEVICE_ID})); assert_eq!(named["variants"][0]["parts"][0][THIS_DEVICE_KEY], crate::fixture::SELF_DEVICE_ID, "every size's list"); assert!(served_to(held(), None).definition["parts"][0].get(THIS_DEVICE_KEY).is_none(), "no identity yet, no device named"); } /// RULE: A definition row with no face (no slip) — a storage table the object serves, its rows synced and read by the engines and the MCP, drawn by no tool — is left out of the catalogue's tables and pages and named in `kept_as_rows` with why, so every row served is drawn, kept as rows or refused and the phone's reader says each one it does not draw, never silently (tables-dropped, 28 Oct 2026: 35 of Personal's 144 rows reached the phone as nothing at all). #[test] fn a_faceless_row_is_kept_as_rows_and_named() { let (_dir, client, _) = attached_on_a_clock(); // The shape of Personal's storage tables (thread_mark's, read off a copy): // a built-in's keys with no slip, title, tile or page, every column readonly. let faceless = json!({ "format_version": 1, "id": "kept_mark", "name": "Kept mark", "plural": "Kept marks", "builtin": true, "visibility": "owner", "columns": [ { "key": "database_id", "type": "text", "readonly": true }, { "key": "marked_at", "type": "date", "format": "calendar-datetime", "readonly": true }, { "key": "on", "type": "bool", "readonly": true }, ], "instructions": "Rows the engines keep.", }); let workspace = client.with_writer(|file| Ok(file.workspace_id.to_string())).expect("the workspace"); let served = client .with_writer(|file| { let sql = "INSERT INTO cotton_table_definitions \ (id, workspace_id, definition, builtin, instructions_edited, created_at, updated_at) \ VALUES ('kept_mark', ?, ?, 0, 0, '2026-10-01T09:00:00.000Z', '2026-10-01T09:00:00.000Z')"; let values = [SqlValue::Text(workspace.clone()), SqlValue::Text(faceless.to_string())]; file.driver.run(sql, &values).map_err(|error| error.to_string())?; crate::fixture::receipted(file.driver, sql); let rows = file .driver .all("SELECT id FROM cotton_table_definitions WHERE workspace_id = ?", &[SqlValue::Text(workspace.clone())]) .map_err(|error| error.to_string())?; Ok(rows.iter().filter_map(|row| row.text("id").map(str::to_owned)).collect::>()) }) .expect("a stored row"); let answer = answered(&client); let tables = answer["tables"].as_array().expect("tables"); assert!(tables.iter().all(|table| table["id"] != "kept_mark"), "a faceless table is drawn nowhere"); assert!(answer["pages"].get("kept_mark").is_none(), "and has no page"); let kept = answer["kept_as_rows"].as_array().expect("kept_as_rows"); assert!(kept.contains(&json!({ "id": "kept_mark", "reason": KEPT_AS_ROWS })), "{kept:?}"); let said: std::collections::BTreeSet = tables .iter() .chain(kept) .chain(answer["refused"].as_array().expect("refused")) .filter_map(|table| table["id"].as_str().map(str::to_owned)) .collect(); assert_eq!(served, said, "every served row is drawn, kept as rows, or refused"); assert_eq!(answer["database"], json!(workspace), "the answer names its database"); let fresh = serde_json::to_value(fresh().expect("the last resort")).unwrap(); assert_eq!(fresh["kept_as_rows"], json!([]), "the last resort keeps no table"); } /// RULE: a column with no name of its own is read by its key as words, the /// store's own ending gone. #[test] fn a_nameless_column_reads_as_words() { assert_eq!(key_words("balance_minor"), "Balance"); assert_eq!(key_words("snoozed_until"), "Snoozed until"); assert_eq!(key_words("project_id"), "Project"); assert_eq!(key_words("archived_at"), "Archived"); assert_eq!(key_words("id"), "Id"); assert_eq!(key_words("_id"), " id"); } /// RULE: the list draws the capture bar unless the table is sealed, `add` /// is off, or nothing of it can be typed; a capture that is not page-only /// keeps the bar on a read-only list. #[test] fn a_list_takes_capture_by_what_can_be_typed() { let bare = cotton_core::definitions::builtin_table_definition("todo").unwrap().clone(); assert_eq!(table_said(&bare)["list_takes_capture"], true); let mut sealed = bare.clone(); sealed.sealed = Some(true); assert_eq!(table_said(&sealed)["list_takes_capture"], false); let mut no_add = bare.clone(); no_add.add = Some(false); assert_eq!(table_said(&no_add)["list_takes_capture"], false); let mut read_only = bare.clone(); for column in &mut read_only.columns { column.readonly = Some(true); } assert_eq!(table_said(&read_only)["list_takes_capture"], false); read_only.capture = Some(serde_json::from_value(json!({"table": "todo"})).unwrap()); assert_eq!(table_said(&read_only)["list_takes_capture"], true); } /// RULE: a name beginning with a vowel takes "an", and every column is named. #[test] fn a_table_says_its_article_and_labels() { let mut table = cotton_core::definitions::builtin_table_definition("todo").unwrap().clone(); table.name = "Alarm".to_string(); let said = table_said(&table); assert_eq!(said["takes_an"], true); assert!(said["labels"].as_object().unwrap().len() == table.columns.len()); table.name = "Mood".to_string(); assert_eq!(table_said(&table)["takes_an"], false); }