mod support; use serde_json::{json, Value}; use support::harness::Harness; use support::mcp::{call_tool, call_tool_as_owner, call_tool_raw, mint_token}; fn setup() -> (Harness, String) { let mut h = Harness::new(); let token = mint_token(&mut h, &["read", "write"], "Synthetic theme assistant"); // Creation wrote the database's own theme (its cap); every save here is newer. h.clock.advance(chrono::Duration::minutes(1)); (h, token) } /// A theme setting `token` to just past its range's top, from the core's /// one list of ranges. fn past_range(token: &str) -> (String, f64, cotton_core::definitions::theme::ThemeRange, Value) { let range = cotton_core::definitions::theme::theme_token_range(token).expect("a token with a range"); let value = range.max + 1.0; (format!("scale.tokens.{token}"), value, range, json!({"id":"database","scale":{"tokens":{token: value}}})) } /// RULE: Preview names every changed theme key and every invalid key without writing rows, receipts or history, so an assistant can inspect an unsafe theme before applying it. #[test] fn preview_names_changes_and_refusals_without_writing() { let (h, token) = setup(); let counts = || ["cotton_theme_definitions", "cotton_changes", "_writes"].map(|table| h.count(&format!("SELECT count(*) AS c FROM {table}"), &[])); let before = counts(); let (measure, _, _, mut definition) = past_range("radius"); let (weight, _, _, weighted) = past_range("type_weight_bold"); definition["scale"]["tokens"]["type_weight_bold"] = weighted["scale"]["tokens"]["type_weight_bold"].clone(); definition["family"] = json!("neon"); definition["mystery"] = json!(12); let preview = call_tool(&h, &token, "save_theme", json!({"dry_run":true,"definition":definition})); assert_eq!(counts(), before); let changes = preview["changes"].as_array().unwrap(); for key in [measure.as_str(), weight.as_str(), "family", "mystery"] { assert!(changes.iter().any(|change| change["key"] == key), "{preview}"); assert!(preview["refused"].as_array().unwrap().iter().any(|refusal| refusal["key"] == key), "{preview}"); } for key in [measure.as_str(), weight.as_str()] { let refusal = preview["refused"].as_array().unwrap().iter().find(|refusal| refusal["key"] == key).unwrap(); assert!(refusal["value"].is_number() && refusal["range"]["min"].is_number() && refusal["range"]["max"].is_number(), "{refusal}"); } assert_eq!(preview["valid"], false); } /// RULE: A theme with any number outside its range in the core is refused whole before any write, and the refusal names every such key with its value and range, so an assistant learns every fix at once and nothing partial is saved. #[test] fn out_of_range_keys_refuse_the_whole_save() { let (h, token) = setup(); let (radius, value, range, mut definition) = past_range("radius"); let (weight, _, _, weighted) = past_range("type_weight_bold"); definition["scale"]["tokens"]["type_weight_bold"] = weighted["scale"]["tokens"]["type_weight_bold"].clone(); definition["name"] = json!("Would be saved if partial"); let own = || h.one("SELECT definition FROM cotton_theme_definitions WHERE id = 'database' AND builtin = 0", &[]); let before = own(); let refused = call_tool_raw(&h, &token, "save_theme", json!({"definition":definition})); assert!(refused.is_error); assert!(refused.text.contains(&format!("{radius} is {}, outside {} to {}", json!(value), range.min, range.max)), "{}", refused.text); assert!(refused.text.contains(&weight), "{}", refused.text); assert_eq!(h.count("SELECT count(*) AS c FROM cotton_changes WHERE table_id = 'theme'", &[]), 0); assert_eq!(own(), before, "nothing partial is saved"); } /// RULE: Theme saves use record history and one undo restores the exact previous definition bytes, so two saves then undo leaves the middle state without a second history. #[test] fn undo_restores_the_middle_definition_bytes() { let (h, token) = setup(); let save = |definition: Value| call_tool(&h, &token, "save_theme", json!({"definition":definition})); call_tool(&h, &token, "update_record", json!({"table":"theme","id":"database","patch":{"definition":"{ \"id\": \"database\", \"name\": \"First\", \"family\": \"plain\" }\n"}})); let row = || h.one("SELECT definition, builtin, builtin_hash, builtin_stamp, created_at, updated_at FROM cotton_theme_definitions WHERE id = 'database'", &[]).unwrap(); let middle = row(); let second = save(json!({"id":"database","name":"Second","family":"paper"})); assert_eq!(second["change"]["undoable"], true, "{second}"); let undone = call_tool_as_owner(&h, "device:phone", "undo", json!({"change_id":second["change"]["id"]})); assert!(!undone.is_error, "{}", undone.text); assert_eq!(row(), middle); } /// RULE: Undo of the first theme override restores the row creation wrote (the database's cap) exactly, so it cannot hide a different theme the database was already wearing. #[test] fn first_override_undo_restores_what_creation_wrote() { let (h, token) = setup(); let created = h.one("SELECT definition, updated_at FROM cotton_theme_definitions WHERE id = 'database'", &[]); assert!(created.is_some(), "creation gave the database its own theme"); call_tool(&h, &token, "save_theme", json!({"definition":{"id":"plain","family":"plain"}})); let saved = call_tool(&h, &token, "save_theme", json!({"definition":{"id":"database","family":"paper"}})); let undone = call_tool_as_owner(&h, "device:phone", "undo", json!({"change_id":saved["change"]["id"]})); assert!(!undone.is_error, "{}", undone.text); assert_eq!(h.one("SELECT definition, updated_at FROM cotton_theme_definitions WHERE id = 'database'", &[]), created); let worn = h.with(|db| cotton_tools::presentation::theme(db, &h.workspace_id)).unwrap(); assert_eq!(worn.definition["id"], "plain"); } /// RULE: Saving an unchanged shipped value stores no override for that key, so later shipped changes reach the database while owner differences still win. #[test] fn saves_store_only_differences_and_mcp_reads_the_app_resolution() { let (h, token) = setup(); let mut definition: Value = serde_json::from_str(cotton_core::definitions::theme::BUILTIN_THEME_FILES[0].1).unwrap(); definition["scale"]["tokens"]["radius"] = json!(9); let unchanged = definition["scale"]["tokens"]["spacing"].clone(); call_tool(&h, &token, "save_theme", json!({"definition":definition})); let row = h.one("SELECT definition FROM cotton_theme_definitions WHERE id = 'paper'", &[]).unwrap(); let stored: Value = serde_json::from_str(row["definition"].as_str().unwrap()).unwrap(); assert!(stored["scale"]["tokens"].get("spacing").is_none(), "{stored}"); assert_eq!(stored["scale"]["tokens"]["radius"], json!(9)); let worn = h.with(|db| cotton_tools::presentation::theme(db, &h.workspace_id)).unwrap(); assert_eq!(worn.definition["scale"]["tokens"]["spacing"], unchanged); let read = call_tool(&h, &token, "get_record_by_table", json!({"table":"theme","id":"paper"})); let read: Value = serde_json::from_str(read["data"]["definition"].as_str().unwrap()).unwrap(); assert_eq!(read, worn.definition); } /// RULE: An existing full-copy theme receives shipped additions through both app and MCP reads, without a seed or a migration rewriting the database's own row. #[test] fn legacy_full_copies_resolve_identically_for_app_and_mcp() { let (h, token) = setup(); let mut old: Value = serde_json::from_str(cotton_core::definitions::theme::BUILTIN_THEME_FILES[0].1).unwrap(); let added = old["scale"]["tokens"].as_object_mut().unwrap().remove("fan_open_fade_ms").unwrap(); old["scale"]["tokens"]["radius"] = json!(9); old["scale"]["tokens"]["retired_knob"] = json!(7); call_tool(&h, &token, "save_theme", json!({"definition":{"id":"paper"}})); h.run("UPDATE cotton_theme_definitions SET definition = ?, builtin = 0 WHERE id = 'paper'", &[rusqlite::types::Value::Text(old.to_string())]); let worn = h.with(|db| cotton_tools::presentation::theme(db, &h.workspace_id)).unwrap(); assert_eq!(worn.definition["scale"]["tokens"]["fan_open_fade_ms"], added); assert_eq!(worn.definition["scale"]["tokens"]["radius"], json!(9)); assert!(worn.definition["scale"]["tokens"].get("retired_knob").is_none()); let read = call_tool(&h, &token, "get_record_by_table", json!({"table":"theme","id":"paper"})); let read: Value = serde_json::from_str(read["data"]["definition"].as_str().unwrap()).unwrap(); assert_eq!(read, worn.definition); let stored = h.one("SELECT definition FROM cotton_theme_definitions WHERE id = 'paper'", &[]).unwrap(); assert_eq!(serde_json::from_str::(stored["definition"].as_str().unwrap()).unwrap(), old); } /// RULE: A sparse theme preview compares resolved values, so inherited shipped keys are never reported as removals by an edit that leaves them untouched. #[test] fn sparse_preview_does_not_report_inherited_values_as_removed() { let (h, token) = setup(); let preview = call_tool(&h, &token, "save_theme", json!({"dry_run":true,"definition":{"id":"paper","scale":{"tokens":{"radius":9}}}})); assert_eq!(preview["valid"], true); let changes = preview["changes"].as_array().unwrap(); assert!(changes.iter().any(|change| change["key"] == "scale.tokens.radius")); assert!(changes.iter().all(|change| change["key"] == "scale.tokens.radius"), "{preview}"); }