usesuper::*;#[path = "../tests/support/mod.rs"]mod support;use support::Harness;fn now() -> chrono::DateTime<chrono::Utc> {"2026-11-02T00:00:00Z".parse().unwrap()}fn random() -> Arc<dyncrate::random::Random> {Arc::new(crate::random::SystemRandom)}fn genesis() -> cotton_core::genesis::GenesisTools {let manifest: Value = serde_json::from_str(include_str!("../../../apps/cotton/Tests/Fixtures/Flavours/rigby.json" )) .unwrap(); cotton_core::genesis::GenesisTools::of(Some(&manifest)).unwrap()}fn write(db: &Driver, table: &str, doc: Value) { put(db, table, doc, false)}fn put(db: &Driver, table: &str, doc: Value, exists: bool) {let file = cotton_store::file_identity::read_file_identity(db) .unwrap() .unwrap();let owner = db .get("SELECT owner_id FROM _meta", &[]) .unwrap() .unwrap() .text("owner_id") .unwrap() .to_string();let services = ToolServices::none();let audit = |_: &str, _: &str| {};let actor = cotton_store::mint::Actor::DeviceJob(cotton_store::mint::JobName::named("kit").unwrap());letmut ctx = Ctx::for_worker( db, &file, &owner, actor,"fixture", now(), random(), &services, &audit, );let patch = json!({"id":id(&doc),"definition":doc,"builtin":false}) .as_object() .unwrap() .clone();if exists { update_row(&mut ctx, table, id(&doc), patch).unwrap(); } else { insert_row(&mut ctx, table, id(&doc), patch).unwrap(); } ctx.commit().unwrap();}fn pass(h: &Harness, kit: &Kit, version: &str) -> usize { keep_kit(&h.db, now(), random(), kit, version).unwrap()}fn snapshot(db: &Driver) -> Vec<(String, String, String)> { [TOOL, BOARD, TABLE] .into_iter() .flat_map(|t| { db.all( &format!("SELECT id, definition, _hlc FROM {t} ORDER BY id"), &[], ) .unwrap() .into_iter() .map(|r| { ( r.text("id").unwrap().into(), r.text("definition").unwrap().into(), r.text("_hlc").unwrap().into(), ) }) .collect::<Vec<_>>() }) .collect()}/// Real Rigby 10 JSON, copied verbatim with git show 1ad3986bc. Definitions/// are written as receipts, not just patched over the materialized rows.#[test]fn rigby_10_copy_keeps_all_tables_drawable_and_preserves_persons_rows() {let h = Harness::new();let root = cotton_store::manifest_dir().join("tests/fixtures/rigby-10-kit");let token = support::mcp::mint_token_ref(&h, &["read", "write"], "kit-keep");let made = support::mcp::call_tool_raw( &h, &token,"create_todo", json!({"title":"Synthetic retained todo"}), ); assert!(!made.is_error, "{}", made.text);let founded_tables = held(&h.db, TABLE).unwrap();// A table a Rigby 10 tool drew was on a Rigby 10 phone, though this// build's kit gives it no more (Music's track and playlist, 4 Nov 2026).letmut drawn = BTreeSet::new();for entry in std::fs::read_dir(root.join("personal/tools")).unwrap() {let path = entry.unwrap().path().join("manifest.json");ifletOk(bytes) = std::fs::read(path) {let tool: Value = serde_json::from_slice(&bytes).unwrap(); drawn.extend(tool["tables"].as_array().into_iter().flatten().filter_map(|t| t.as_str().map(str::to_owned))); drawn.extend(tool["views"].as_array().into_iter().flatten().filter_map(|v| view_reads(v).map(str::to_owned))); } }for kit in ["personal", "shell"] {for entry in std::fs::read_dir(root.join(kit).join("tables")).unwrap() {let path = entry.unwrap().path();let doc: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();// Overwrite the definitions this database was founded with.// The source tree also carries Mac-only tables no phone kit gives.// A table an engine kept that this build retired (memory_entry,// 3 Nov 2026) was founded on a Rigby 10 phone too: it is held.let retired = doc["engine"].is_string() && !Kit::compiled(&genesis()).unwrap().tables.contains_key(id(&doc));if founded_tables.contains_key(id(&doc)) || retired || drawn.contains(id(&doc)) { write(&h.db, TABLE, doc); } } }for entry in std::fs::read_dir(root.join("personal/tools")).unwrap() {let path = entry.unwrap().path().join("manifest.json");if path.exists() { write( &h.db, TOOL, serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(), ); } }for entry in std::fs::read_dir(root.join("shell/boards")).unwrap() {let doc = serde_json::from_slice(&std::fs::read(entry.unwrap().path()).unwrap()).unwrap(); write(&h.db, BOARD, doc); }let rows = h.db.all("SELECT id, title, _hlc FROM cotton_todos ORDER BY id", &[]) .unwrap(); assert!(rows .iter() .any(|r| r.text("title") == Some("Synthetic retained todo"))); assert!( held(&h.db, TABLE).unwrap().values().any(|doc| { cotton_core::definitions::TableDefinition::from_json(&doc.to_string()) .and_then(|definition| definition.validate()) .is_err() }),"the historical fixture must reproduce the refused definitions" );let kit = Kit::compiled(&genesis()).unwrap(); assert!(pass(&h, &kit, "new") > 0);let tables = held(&h.db, TABLE).unwrap();let retired = Retired { held: &tables, kit: &kit.tables };for doc in tables.values() {// A table this build retired stays held (rows may name it) and is// drawn by no kit tool: the pass moved every one off it. A tool the// kit no longer gives (Screenplays, Quotas, Moods and Meetings, 3 Nov// 2026) is held as it was until the definition act removes it.if retired.contains(id(doc)) {let reader = held(&h.db, TOOL).unwrap().into_iter() .find(|(tool, doc)| kit.tools.contains_key(tool) && reads_retired(doc, &retired)); assert!(reader.is_none(), "{:?} still reads a retired table", reader.map(|(tool, _)| tool));continue; } cotton_core::definitions::TableDefinition::from_json(&doc.to_string()) .and_then(|definition| definition.validate()) .unwrap_or_else(|e| panic!("{}: {e}", id(doc))); }for (id, doc) in held(&h.db, TOOL).unwrap() {// A tool this build no longer ships at all (Screenplays, Quotas,// Moods and Meetings, 3 Nov 2026) is held as the old kit left it,// its tables too, until the definition act removes it.if !kit.tools.contains_key(&id) {continue; }let tool = cotton_core::definitions::ToolDefinition::from_json(&doc.to_string()).unwrap(); tool.validate().unwrap();// A package also names auxiliary native-service tables. Its decks// read the tables named by its views, just as the phone does.let deck_tables: BTreeSet<_> = tool .views .iter() .map(|view| view.read["table"].as_str().unwrap()) .collect();for table in deck_tables {let result = support::mcp::call_tool_raw( &h, &token,"list_records", json!({"table":table,"limit":1,"today":"2026-11-02"}), ); assert!(!result.is_error, "{} / {table}: {}", tool.id, result.text); } }let after = h.db.all("SELECT id, title, _hlc FROM cotton_todos ORDER BY id", &[]) .unwrap(); assert_eq!(format!("{rows:?}"), format!("{after:?}"));}#[test]fn edited_tool_keeps_its_arrangement_and_takes_view_cards_including_removals() {let h = Harness::new();letmut kit = Kit::compiled(&genesis()).unwrap();letmut tool = held(&h.db, TOOL).unwrap()["todos"].clone(); tool["views"][0]["label"] = json!("My next steps"); tool["views"][0]["card"] = json!({"face":"old"});// The phone's actual definition handler, with the owner's actor. h.db.run("INSERT INTO cotton_devices (id, workspace_id, device_id, name, approved_at, approved_by_device, created_at, updated_at) VALUES ('synthetic-phone', ?, 'synthetic-phone', 'Test phone', '2026-11-02', 'self', '2026-11-02', '2026-11-02')", &[SqlValue::Text(h.workspace_id.clone())]).unwrap();let actor = cotton_store::actor::Actor::owner( cotton_store::actor::DeviceId::in_file(&h.db, "synthetic-phone").unwrap(), );let services = ToolServices::none();letmut ctx = Ctx::phone( &h.db, &h.file, &h.owner_id,"synthetic-phone", actor, cotton_store::mint::Held::Served, now(), random(), &services, ); update_row( &mut ctx, TOOL,"todos", json!({"definition":tool}).as_object().unwrap().clone(), ) .unwrap(); ctx.commit().unwrap(); assert!( cotton_store::receipts::of_row(&h.db, TOOL, "todos") .unwrap() .iter() .any(|r| r.actor == "owner:synthetic-phone" && r.receipt.fields.contains_key("definition")) ); kit.tools.get_mut("todos").unwrap()["views"][0] .as_object_mut() .unwrap() .remove("card"); pass(&h, &kit, "new");let got = held(&h.db, TOOL).unwrap()["todos"].clone(); assert_eq!(got["views"][0]["label"], "My next steps"); assert!(got["views"][0].get("card").is_none());let card = kit.tables["todo"]["card"].clone(); kit.tools.get_mut("todos").unwrap()["views"][0]["card"] = card.clone(); pass(&h, &kit, "next");let got = held(&h.db, TOOL).unwrap()["todos"].clone(); assert_eq!(got["views"][0]["label"], "My next steps"); assert_eq!(got["views"][0]["card"], card);}/// RULE (3 Nov 2026): a held tool reading a table the kit retired (one an/// engine kept that the kit no longer ships) is the kit's old tool: it takes the kit's views and tables, keeping the person's own/// views and its other keys; a view on a table the person made stays.#[test]fn a_tool_on_a_retired_table_takes_the_kits_views_and_keeps_the_persons_own() {let h = Harness::new();let kit = Kit::compiled(&genesis()).unwrap(); assert!(kit.tools.contains_key("books"), "the kit gives Books"); assert!(!kit.tools["books"]["tables"].as_array().unwrap().contains(&json!("note")), "Books draws no note of its own");letmut tool = kit.tools["books"].clone(); tool["name"] = json!("My books"); tool["tables"] = json!(["retired_entry", "note"]); tool["views"] = json!([ {"id": "all", "label": "All", "visibility": "owner", "is_default": true, "read": {"table": "retired_entry"}, "face": "cards"}, {"id": "by_project", "label": "By project", "visibility": "owner", "is_default": false, "read": {"table": "retired_entry"}, "face": "cards"}, {"id": "mine", "label": "Mine", "visibility": "owner", "is_default": false, "read": {"table": "note"}, "face": "cards"} ]); write(&h.db, TABLE, json!({"id": "retired_entry", "name": "Retired entry", "plural": "Retired entries", "builtin": true, "engine": "memory", "columns": [{"key": "title", "type": "text"}], "title": "title"}));let exists = held(&h.db, TOOL).unwrap().contains_key("books"); put(&h.db, TOOL, tool, exists); pass(&h, &kit, "retired");let got = held(&h.db, TOOL).unwrap()["books"].clone(); assert_eq!(got["name"], "My books", "its other keys stay held");let views: Vec<&str> = got["views"].as_array().unwrap().iter().map(|v| v["id"].as_str().unwrap()).collect();letmut wanted: Vec<&str> = kit.tools["books"]["views"].as_array().unwrap().iter().map(|v| v["id"].as_str().unwrap()).collect(); wanted.push("mine"); assert_eq!(views, wanted, "the kit's views, then the person's own"); assert_eq!(got["views"][0]["read"], kit.tools["books"]["views"][0]["read"]);letmut tables = kit.tools["books"]["tables"].as_array().unwrap().clone(); tables.push(json!("note")); assert_eq!(got["tables"], Value::Array(tables), "the kit's tables, then the person's own"); assert_eq!(pass(&h, &kit, "again"), 0, "a second pass changes nothing");}#[test]fn removed_stays_removed_and_a_new_tool_arrives_whole() {let h = Harness::new();letmut kit = Kit::compiled(&genesis()).unwrap(); stamp_fresh(&h.db, &genesis()).unwrap();let token = support::mcp::mint_token_ref(&h, &["read", "write"], "kit-keep");let removed = support::mcp::call_tool_raw(&h, &token, "remove_tool", json!({"tool_id":"todos"})); assert!(!removed.is_error, "{}", removed.text);letmut added = kit.tools["todos"].clone(); added["id"] = json!("future_todos"); kit.tools.insert("future_todos".into(), added.clone()); kit.giving.insert("future_todos".into()); pass(&h, &kit, "future");let tools = held(&h.db, TOOL).unwrap(); assert!(!tools.contains_key("todos")); assert_eq!(tools["future_todos"], added);}#[test]fn an_unstamped_copy_keeps_a_removed_tool_removed_from_its_retract_receipt() {let h = Harness::new();let token = support::mcp::mint_token_ref(&h, &["read", "write"], "kit-keep");let removed = support::mcp::call_tool_raw(&h, &token, "remove_tool", json!({"tool_id":"todos"})); assert!(!removed.is_error, "{}", removed.text); assert!(cotton_store::receipts::retract_stamp(&h.db, TOOL, "todos") .unwrap() .is_some()); pass(&h, &Kit::compiled(&genesis()).unwrap(), "new"); assert!(!held(&h.db, TOOL).unwrap().contains_key("todos"));}#[test]fn tables_grow_and_shell_keeps_held_only_rows_at_end() {let h = Harness::new();letmut kit = Kit::default();let held_engine = json!({"id":"todo","engine":"yesterday","columns":[{"key":"extra","type":"text"}],"commands":[{"object":"done"}]});// These test the merge in the real store using actual kit definitions.let shipped: Value = serde_json::from_slice(cotton_core::kit::table_file("todo").unwrap()).unwrap();letmut extra = shipped.clone(); extra["name"] = json!("Yesterday"); extra["columns"] .as_array_mut() .unwrap() .push(held_engine["columns"][0].clone()); write(&h.db, TABLE, extra); kit.tables.insert("todo".into(), shipped.clone());letmut table: Value = serde_json::from_slice(cotton_core::kit::table_file("book").unwrap()).unwrap(); table.as_object_mut().unwrap().remove("engine");letmut held_table = table.clone(); held_table["name"] = json!("My books"); held_table["columns"] .as_array_mut() .unwrap() .push(json!({"key":"my_column","type":"text"})); held_table["columns"] .as_array_mut() .unwrap() .retain(|c| c["key"] != "review"); write(&h.db, TABLE, held_table);// One row: the held book stays add-only (an empty one is the kit's whole).if !h.db.table_exists("cotton_book").unwrap() { h.db.exec("CREATE TABLE cotton_book (id TEXT PRIMARY KEY, workspace_id TEXT)").unwrap(); } h.db.exec("INSERT INTO cotton_book (id, workspace_id) VALUES ('a-book', 'w')").unwrap(); kit.tables.insert("book".into(), table.clone());// The kit last laid the book's look as it ships: "My books" is the person's. laid_tables_as(&h.db, &[&table]);let board = json!({"id":"settings","parts":[{"kind":"list","table":"settings","rows":[{"id":"new"}]}]}); write( &h.db, BOARD, json!({"id":"settings","parts":[{"kind":"list","table":"settings","rows":[{"id":"held"},{"id":"new"}]}]}), ); kit.boards.insert("settings".into(), board); pass(&h, &kit, "new");let tables = held(&h.db, TABLE).unwrap(); assert_eq!(tables["todo"]["name"], shipped["name"]); assert_eq!( tables["todo"]["columns"] .as_array() .unwrap() .last() .unwrap()["key"],"extra" ); assert_eq!(tables["book"]["name"], "My books"); assert_eq!( tables["book"]["columns"] .as_array() .unwrap() .last() .unwrap()["key"],"review" ); assert_eq!(tables["book"]["card"], table["card"]); assert!(tables["book"]["columns"] .as_array() .unwrap() .iter() .any(|c| c["key"] == "my_column")); assert_eq!( held(&h.db, BOARD).unwrap()["settings"]["parts"][0]["rows"], json!([{"id":"new"},{"id":"held"}]) );}/// A Home the person edited since the kit last laid it stays through the/// next kit; one they did not edit follows it (coordinator, 2 Nov 2026).#[test]fn an_edited_shell_board_stays_and_an_unedited_one_follows_the_kit() {let last = json!({"id":"home","parts":[{"kind":"head"},{"kind":"tools","size":"large"}]});let next = json!({"id":"home","parts":[{"kind":"head"},{"kind":"today"},{"kind":"tools","size":"large"}]});let kit = |home: &Value| {letmut kit = Kit::default(); kit.boards.insert("home".into(), home.clone()); kit };let edited = json!({"id":"home","parts":[{"kind":"head"},{"kind":"tools","size":"small"}]});for (held, wanted) in [(Some(&edited), &edited), (None, &next)] {let h = Harness::new(); pass(&h, &kit(&last), "last"); assert_eq!(held_board(&h), last);ifletSome(held) = held { put(&h.db, BOARD, held.clone(), true); } pass(&h, &kit(&next), "next"); assert_eq!(&held_board(&h), wanted, "edited: {}", held.is_some());let laid: Value = serde_json::from_str(&meta(&h.db, KIT_LAID).unwrap().unwrap()).unwrap(); assert_eq!(laid["home"], next, "the kit's Home of this pass is recorded"); }// Home as an object serves it, naming the tools it works out as empty, is no edit.let h = Harness::new(); pass(&h, &kit(&last), "last");letmut served = last.clone(); served["parts"][1]["empty"] = json!(["books"]); put(&h.db, BOARD, served, true); pass(&h, &kit(&next), "next"); assert_eq!(held_board(&h), next);}/// As if the last keep laid these tables' looks.fn laid_tables_as(db: &Driver, tables: &[&Value]) { db.exec(DDL).unwrap();let laid: BTreeMap<String, Value> = tables.iter().map(|t| (id(t).to_string(), look(t))).collect(); db.run("INSERT INTO _kit_keep (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", &[SqlValue::Text(KIT_LAID_TABLES.into()), SqlValue::Text(serde_json::to_string(&laid).unwrap())], ) .unwrap();}/// RULE (5 Nov 2026, KEEP_RULE 9): a held table whose look the person never/// edited takes the kit's look whole — the owner's Books drew one "Find a/// book" field and "No books yet" weeks after the kit's book named its doors./// Storage stays the table's, an edited look stays, a second keep changes/// nothing.#[test]fn a_held_tables_look_is_the_kits_unless_the_person_edited_it() {let shipped: Value = serde_json::from_slice(cotton_core::kit::table_file("book").unwrap()).unwrap();// The book as the kit laid it before Books' doors (c2682a0ed6), one// command short and with a look key the kit no longer carries.letmut stale = shipped.clone(); stale["create"] = json!({"label":"Find a book","act":{"name":"find_book","argument":"query"}}); stale["empty"] = json!({"title":"No books yet"}); stale["banner"] = json!("an older build's word"); stale["commands"].as_array_mut().unwrap().retain(|c| c["id"] != "add_file");let kit = || {letmut kit = Kit::default(); kit.tables.insert("book".into(), shipped.clone()); kit };let doors = |book: &Value| -> Vec<String> { book["create"]["doors"].as_array().into_iter().flatten().map(|d| d["id"].as_str().unwrap().to_string()).collect() };for record in [false, true] {let h = Harness::new(); write(&h.db, TABLE, stale.clone()); hold_a_row(&h.db, "book");if record { laid_tables_as(&h.db, &[&stale]); } pass(&h, &kit(), "new");let book = held(&h.db, TABLE).unwrap()["book"].clone(); assert_eq!(doors(&book), ["find", "file", "folder", "goodreads"], "record: {record}"); assert_eq!(book["empty"], shipped["empty"]); assert!(book.get("banner").is_none(), "a look key the kit no longer carries is removed"); assert_eq!(look(&book), look(&shipped)); assert_eq!(book["commands"], shipped["commands"], "commands are the build's (KEEP_RULE 10)"); assert_eq!(book["columns"], stale["columns"]); cotton_core::definitions::TableDefinition::from_json(&book.to_string()) .and_then(|definition| definition.validate()) .unwrap();let laid: Value = serde_json::from_str(&meta(&h.db, KIT_LAID_TABLES).unwrap().unwrap()).unwrap(); assert_eq!(laid["book"], look(&shipped), "what the kit laid now is its current look");let before = snapshot(&h.db); assert_eq!(pass(&h, &kit(), "again"), 0, "a second keep changes nothing"); assert_eq!(snapshot(&h.db), before); }// The person edited the look since the kit laid it: it stays.let h = Harness::new();letmut mine = stale.clone(); mine["name"] = json!("Volume"); write(&h.db, TABLE, mine.clone()); hold_a_row(&h.db, "book"); laid_tables_as(&h.db, &[&stale]); pass(&h, &kit(), "new");let book = held(&h.db, TABLE).unwrap()["book"].clone(); assert_eq!(book["name"], "Volume"); assert_eq!(book["create"], stale["create"]); assert_eq!(book["commands"], shipped["commands"]);let laid: Value = serde_json::from_str(&meta(&h.db, KIT_LAID_TABLES).unwrap().unwrap()).unwrap(); assert_eq!(laid["book"], look(&stale), "told from the look the kit last laid");let before = snapshot(&h.db); assert_eq!(pass(&h, &kit(), "again"), 0, "a second keep changes nothing"); assert_eq!(snapshot(&h.db), before);}/// RULE (5 Nov 2026, KEEP_RULE 10): a held table's commands and acts are the/// build's — the owner's book held 8 of the kit's 12 commands (rate, review,/// find_details, add_file missing). Every keep lays them as the kit has them;/// the look rule stands beside it.#[test]fn a_held_tables_commands_and_acts_are_the_kits() {let shipped: Value = serde_json::from_slice(cotton_core::kit::table_file("book").unwrap()).unwrap();let missing = ["rate", "review", "find_details", "add_file"];letmut fewer = shipped.clone(); fewer["commands"].as_array_mut().unwrap().retain(|c| !missing.contains(&c["id"].as_str().unwrap())); fewer["acts"] = json!([{"id":"old_act"}]); assert_eq!(fewer["commands"].as_array().unwrap().len(), shipped["commands"].as_array().unwrap().len() - 4);let kit = || {letmut kit = Kit::default(); kit.tables.insert("book".into(), shipped.clone()); kit };for name in [None, Some("Volume")] {let h = Harness::new();letmut held_book = fewer.clone();ifletSome(name) = name { held_book["name"] = json!(name); } write(&h.db, TABLE, held_book); hold_a_row(&h.db, "book"); laid_tables_as(&h.db, &[&shipped]); pass(&h, &kit(), "new");let book = held(&h.db, TABLE).unwrap()["book"].clone(); assert_eq!(book["commands"], shipped["commands"], "the kit's commands, edited look: {name:?}"); assert_eq!(book.get("acts"), shipped.get("acts"), "the kit's acts");match name {None => assert_eq!(look(&book), look(&shipped), "the look rule: unedited, the kit's"),Some(name) => assert_eq!(book["name"], name, "the look rule: edited, kept"), } cotton_core::definitions::TableDefinition::from_json(&book.to_string()) .and_then(|definition| definition.validate()) .unwrap();let before = snapshot(&h.db); assert_eq!(pass(&h, &kit(), "again"), 0, "a second keep changes nothing"); assert_eq!(snapshot(&h.db), before); }// A kept look's mark on a command the kit no longer lays takes the kit's marks.let held_a = json!({"id":"a","name":"Mine","columns":[],"commands":[{"id":"tick","kind":"update"}],"marks":{"check":"tick"}});let kit_a = json!({"id":"a","columns":[],"commands":[{"id":"done","kind":"update"}],"marks":{"check":"done"}});letmut out = merged(&held_a, &kit_a); assert!(!marks_bound(&out)); assert_eq!(out["commands"], kit_a["commands"]); out["marks"] = kit_a["marks"].clone(); assert!(marks_bound(&out));}fn held_board(h: &Harness) -> Value { held(&h.db, BOARD).unwrap()["home"].clone()}#[test]fn second_pass_and_fresh_start_change_nothing_and_move_no_receipt() {let h = Harness::new();let kit = Kit::compiled(&genesis()).unwrap(); pass(&h, &kit, "new");let before = snapshot(&h.db);let stamp = meta(&h.db, KIT_VERSION).unwrap(); assert_eq!(pass(&h, &kit, "new"), 0); assert_eq!(snapshot(&h.db), before); assert_eq!(meta(&h.db, KIT_VERSION).unwrap(), stamp); stamp_fresh(&h.db, &genesis()).unwrap();let before = snapshot(&h.db); assert_eq!(keep(&h.db, now(), random(), &genesis()).unwrap(), 0); assert_eq!(snapshot(&h.db), before);}#[test]fn failed_keep_rolls_back_definitions_receipts_and_stamp() {let h = Harness::new();letmut kit = Kit::compiled(&genesis()).unwrap(); kit.tables.get_mut("todo").unwrap()["commands"] = json!([{"object":"done"}]);let before = snapshot(&h.db);let writes = |db: &Driver| db.get("SELECT count(*) AS n FROM _writes", &[]).unwrap().unwrap().int("n").unwrap();let receipts = writes(&h.db); assert!(keep_kit(&h.db, now(), random(), &kit, "bad").is_err()); assert_eq!(snapshot(&h.db), before); assert_eq!(writes(&h.db), receipts, "no receipt of the failed pass stays"); assert!( !h.db.table_exists("_kit_keep").unwrap() || meta(&h.db, KIT_VERSION).unwrap().is_none(),"no stamp of the failed pass stays" );}/// One synthetic row in `table`: the held table stays add-only (an empty one/// is the kit's whole).fn hold_a_row(db: &Driver, table: &str) {let made = format!("cotton_{table}");if !db.table_exists(&made).unwrap() { db.exec(&format!("CREATE TABLE {made} (id TEXT PRIMARY KEY, workspace_id TEXT)")).unwrap(); } db.exec(&format!("INSERT INTO {made} (id, workspace_id) VALUES ('a-{table}', 'w')")).unwrap();}/// RULE: a kit table's retired column is laid on a held table only once the/// held table no longer holds it: an add-only keep never retires a column/// the database still holds (the owner's film table keeps `notes` until its/// reshape, 5 Nov 2026), and a table that no longer holds it takes it.#[test]fn a_retired_column_is_laid_only_once_the_held_table_no_longer_holds_it() {let h = Harness::new();letmut kit = Kit::default();let shipped: Value = serde_json::from_slice(cotton_core::kit::table_file("film").unwrap()).unwrap(); assert_eq!(shipped["retired"], json!([{"key":"notes","type":"longtext"}]), "the kit's film retires notes");// The film table as the owner's object holds it: notes still a column, no backdrop yet.letmut held_film = shipped.clone(); held_film.as_object_mut().unwrap().remove("retired");let cols = held_film["columns"].as_array_mut().unwrap(); cols.retain(|c| c["key"] != "backdrop"); cols.push(json!({"key":"notes","name":"Notes","type":"longtext"})); write(&h.db, TABLE, held_film); hold_a_row(&h.db, "film"); kit.tables.insert("film".into(), shipped.clone());// A table retiring a column it no longer holds.letmut season: Value = serde_json::from_slice(cotton_core::kit::table_file("film_season").unwrap()).unwrap();let held_season = season.clone(); season["retired"] = json!([{"key":"old_words","type":"text"}]); write(&h.db, TABLE, held_season); hold_a_row(&h.db, "film_season"); kit.tables.insert("film_season".into(), season); pass(&h, &kit, "new");let tables = held(&h.db, TABLE).unwrap();let film = &tables["film"];let keys: Vec<&str> = film["columns"].as_array().unwrap().iter().map(|c| c["key"].as_str().unwrap()).collect(); assert!(keys.contains(&"notes"), "the held column stays: {keys:?}"); assert!(keys.contains(&"backdrop"), "the kit's new column is added: {keys:?}"); assert!(film.get("retired").is_none(), "no retired notes while notes is a column: {}", film["retired"]); cotton_core::definitions::TableDefinition::from_json(&film.to_string()) .and_then(|definition| definition.validate()) .unwrap(); assert_eq!(tables["film_season"]["retired"], json!([{"key":"old_words","type":"text"}]));}/// RULE (5 Nov 2026): a held choice column takes each choice the kit adds,/// after its own and with the kit's label, so the kit's card naming the new/// ones stays drawable; no held choice is taken.#[test]fn a_held_choice_column_takes_the_kits_new_choices_and_keeps_its_own() {let h = Harness::new();letmut kit = Kit::default();let shipped: Value = serde_json::from_slice(cotton_core::kit::table_file("film").unwrap()).unwrap();// The film table as an older phone holds it: status watchlist or watched.letmut held_film = shipped.clone(); held_film.as_object_mut().unwrap().remove("retired");for c in held_film["columns"].as_array_mut().unwrap() {if c["key"] == "status" { c["choices"] = json!(["watchlist", "watched"]); c["labels"] = json!({"watchlist": "To watch", "watched": "Watched"}); c["default"] = json!("watchlist"); } } write(&h.db, TABLE, held_film); hold_a_row(&h.db, "film"); kit.tables.insert("film".into(), shipped); pass(&h, &kit, "new");let film = &held(&h.db, TABLE).unwrap()["film"];let status = film["columns"].as_array().unwrap().iter().find(|c| c["key"] == "status").unwrap(); assert_eq!(status["choices"], json!(["watchlist", "watched", "want_to_watch", "watching", "stopped"])); assert_eq!(status["labels"], json!({"watchlist": "To watch", "watched": "Watched", "want_to_watch": "Want to watch", "watching": "Watching", "stopped": "Stopped"})); cotton_core::definitions::TableDefinition::from_json(&film.to_string()) .and_then(|definition| definition.validate()) .unwrap();}/// RULE (KEEP_RULE 12, 13 Nov 2026): a held column takes the kit's `until`/// and `default` where it says nothing of them, and keeps its own: a phone/// holding albums from an older build reads one given only its first day/// as running until its last, and a highlight made bare is yellow (Trips,/// the rule's first tables, retired 22 Nov 2026).#[test]fn a_held_column_takes_the_kits_until_and_default_where_it_says_nothing_of_them() {let h = Harness::new();letmut kit = Kit::default();letmut held_tables = Vec::new();for table in ["album", "highlight"] {let shipped: Value = serde_json::from_slice(cotton_core::kit::table_file(table).unwrap()).unwrap();letmut older = shipped.clone();for c in older["columns"].as_array_mut().unwrap() {let c = c.as_object_mut().unwrap();if c["key"] == "starts_at" { c.remove("until"); }if c["key"] == "colour" { c.remove("default"); }if c["key"] == "progress" { c.insert("default".into(), json!(7)); } } write(&h.db, TABLE, older); hold_a_row(&h.db, table); kit.tables.insert(table.into(), shipped); held_tables.push(table); } pass(&h, &kit, "new");let tables = held(&h.db, TABLE).unwrap();let column = |table: &str, key: &str| tables[table]["columns"].as_array().unwrap().iter().find(|c| c["key"] == key).unwrap().clone(); assert_eq!(column("album", "starts_at")["until"], json!("ends_at")); assert_eq!(column("highlight", "colour")["default"], json!("yellow")); assert_eq!(column("highlight", "progress")["default"], json!(7), "a default the copy says stays");for table in held_tables { cotton_core::definitions::TableDefinition::from_json(&tables[table].to_string()) .and_then(|definition| definition.validate()) .unwrap(); }}/// A row written as the kit job writes it.fn record(h: &Harness, table: &str, id: &str, data: Value) {let file = cotton_store::file_identity::read_file_identity(&h.db).unwrap().unwrap();let services = ToolServices::none();let audit = |_: &str, _: &str| {};let actor = cotton_store::mint::Actor::DeviceJob(cotton_store::mint::JobName::named("kit").unwrap());letmut ctx = Ctx::for_worker(&h.db, &file, &h.owner_id, actor, "fixture", now(), random(), &services, &audit); insert_row(&mut ctx, &crate::mcp::handlers::tables::made_table(table), id, data.as_object().unwrap().clone()).unwrap(); ctx.commit().unwrap();}/// A copy as an older build left its screenplays (Rigby 10's fixture): the/// seven old tables' and the Screenplays tool's definitions, and one/// synthetic row in three of the tables.fn old_screenplays(h: &Harness) {let root = cotton_store::manifest_dir().join("tests/fixtures/rigby-10-kit/personal");for t in cotton_core::retired::GONE_TABLES.iter().copied().filter(|t| t.starts_with("screenplay")) {let doc: Value = serde_json::from_slice(&std::fs::read(root.join(format!("tables/{t}.json"))).unwrap()).unwrap();let exists = held(&h.db, TABLE).unwrap().contains_key(t); put(&h.db, TABLE, doc, exists); }let tool: Value = serde_json::from_slice(&std::fs::read(root.join("tools/screenplays/manifest.json")).unwrap()).unwrap();let exists = held(&h.db, TOOL).unwrap().contains_key("screenplays"); put(&h.db, TOOL, tool, exists);let (_, refused) = cotton_store::schema::package_shape::step_file(&h.db).unwrap(); assert!(refused.is_empty(), "{refused:?}");// The engine's own table, as the screenplay engine kept it, and a made one. stored(h, "cotton_screenplays", "synthetic-screenplay", json!({"title": "Invented script"})); record(h, "screenplay_place", "synthetic-place", json!({"name": "Invented orchard"}));}fn stored(h: &Harness, sql_table: &str, id: &str, data: Value) {let file = cotton_store::file_identity::read_file_identity(&h.db).unwrap().unwrap();let services = ToolServices::none();let audit = |_: &str, _: &str| {};let actor = cotton_store::mint::Actor::DeviceJob(cotton_store::mint::JobName::named("kit").unwrap());letmut ctx = Ctx::for_worker(&h.db, &file, &h.owner_id, actor, "fixture", now(), random(), &services, &audit); insert_row(&mut ctx, sql_table, id, data.as_object().unwrap().clone()).unwrap(); ctx.commit().unwrap();}fn count(h: &Harness, sql_table: &str) -> i64 { h.db.get(&format!("SELECT COUNT(*) AS n FROM {sql_table}"), &[]).unwrap().and_then(|r| r.int("n")).unwrap()}/// RULE (KEEP_RULE 13, 17 Nov 2026, the object's rule 15): the old/// screenplay tables go. A copy defining them keeps every row and holds the/// seven definitions and the Screenplays tool as retired: no definition row/// is served, each is kept under `KIT_RETIRED`. A fresh copy never has them,/// Story's tables are the kit's throughout, and a second pass changes nothing.#[test]fn a_copy_holding_the_old_screenplay_tables_keeps_their_rows_and_retires_their_definitions() {use cotton_core::retired::{GONE_TABLES, GONE_TOOLS};const STORY: [&str; 5] = ["story_story", "story_scene", "story_character", "story_place", "story_note"];let kit = Kit::compiled(&genesis()).unwrap();for t in GONE_TABLES { assert!(!kit.tables.contains_key(t), "the kit ships no {t}"); }for t in GONE_TOOLS { assert!(!kit.tools.contains_key(t), "the kit ships no {t} tool"); }let fresh = Harness::new(); pass(&fresh, &kit, "fresh");let tables = held(&fresh.db, TABLE).unwrap();for t in GONE_TABLES { assert!(!tables.contains_key(t), "a fresh copy never has {t}"); }// A kept tool's files may still name a retired table until its definition leaves the tree (People's// person_note, TABLE DROP 1): a fresh copy laid from them holds it as retired from its first pass.let retired_fresh: Option<Value> = meta(&fresh.db, KIT_RETIRED).unwrap().map(|m| serde_json::from_str(&m).unwrap());for t in retired_fresh.iter().flat_map(|r| r["table"].as_object().unwrap().keys()) { assert!(GONE_TABLES.contains(&t.as_str()), "a fresh copy retires only a retired table, never {t}"); }// The old copy here is Rigby 10's: it held the screenplays, never Recipes' tables (retired too, 22 Nov 2026).let screenplays: Vec<&str> = GONE_TABLES.iter().copied().filter(|t| t.starts_with("screenplay")).collect();let h = Harness::new(); pass(&h, &kit, "first");let story_before: Vec<Value> = STORY.iter().map(|t| held(&h.db, TABLE).unwrap()[*t].clone()).collect(); old_screenplays(&h);let place = crate::mcp::handlers::tables::made_table("screenplay_place");let rows_before: Vec<i64> = ["cotton_screenplays", place.as_str()].iter().map(|t| count(&h, t)).collect(); assert_eq!(rows_before, [1, 1]);// Another kit version: the pass runs again. assert!(pass(&h, &kit, "retire") >= screenplays.len() + 1);let tables = held(&h.db, TABLE).unwrap();for &t in &screenplays { assert!(!tables.contains_key(t), "{t}'s definition is no longer served"); assert!(cotton_store::receipts::retract_stamp(&h.db, TABLE, t).unwrap().is_some(), "{t}'s definition is retracted"); } assert!(!held(&h.db, TOOL).unwrap().contains_key("screenplays"), "the Screenplays tool is no longer served");let retired: Value = serde_json::from_str(&meta(&h.db, KIT_RETIRED).unwrap().unwrap()).unwrap();// The first pass retired what this build retired besides (TABLE DROP 1); the screenplays are this pass's.letmut kept: Vec<&str> = retired["table"].as_object().unwrap().keys().map(String::as_str).filter(|t| t.starts_with("screenplay")).collect(); kept.sort();letmut gone = screenplays.clone(); gone.sort(); assert_eq!(kept, gone, "every definition is held as retired"); assert!(retired["tool"].as_object().unwrap().contains_key("screenplays"), "the Screenplays tool is held as retired"); assert_eq!( ["cotton_screenplays", place.as_str()].iter().map(|t| count(&h, t)).collect::<Vec<_>>(), rows_before,"every row stays in storage" );let story_after: Vec<Value> = STORY.iter().map(|t| held(&h.db, TABLE).unwrap()[*t].clone()).collect(); assert_eq!(story_after, story_before, "Story's tables are unaffected");let before = snapshot(&h.db); assert_eq!(pass(&h, &kit, "again"), 0, "a second pass retires nothing more");let after = snapshot(&h.db); assert_eq!(before, after);}/// The tool's carried picture names in this file.fn assets_of(db: &Driver, tool: &str) -> BTreeSet<String> { db.all("SELECT name FROM cotton_tool_assets WHERE tool_id = ?", &[SqlValue::Text(tool.into())]) .unwrap() .iter() .map(|row| row.text("name").unwrap().to_string()) .collect()}/// A copy holding `held` as its Cinemas, the kit having last laid the old/// tool of Cotton Cinemas 1.0 (2) (the object's fixture), with none of the/// tile's pictures.fn cinemas_held_as(h: &Harness, held: &Value) {let exists = super::held(&h.db, TOOL).unwrap().contains_key("cinemas"); put(&h.db, TOOL, held.clone(), exists); h.db.run("DELETE FROM cotton_tool_assets WHERE tool_id = 'cinemas'", &[]).unwrap();let old: Value = serde_json::from_str(include_str!("../../../apps/business/test/fixtures/cinemas-old/cinemas.json")).unwrap(); h.db.exec(DDL).unwrap(); h.db.run("INSERT INTO _kit_keep (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value", &[SqlValue::Text(KIT_LAID_TOOLS.into()), SqlValue::Text(json!({"cinemas": old}).to_string())], ) .unwrap();}/// RULE (KEEP_RULE 11, 6 Nov 2026, the object's rule 9): a held tool the/// person has not edited since the kit laid it is the kit's whole — Cotton/// Cinemas' letterboard fan tile with it — and takes the pictures its package/// carries that the copy lacks, so the tile's stock and pictograms draw/// before sign-in; one the person edited stays as they left it, its pictures/// untouched.#[test]fn an_unedited_held_tool_takes_the_kits_whole_with_its_tile_pictures() {let h = Harness::new();let kit = Kit::compiled(&genesis()).unwrap();let old: Value = serde_json::from_str(include_str!("../../../apps/business/test/fixtures/cinemas-old/cinemas.json")).unwrap(); assert!(old.get("fan_tile").is_none(), "the old tool had no tile");let tile = kit.tools["cinemas"]["fan_tile"].clone(); assert_eq!(tile["type"], "letterboard");let carried: BTreeSet<String> = Kit::pictures("cinemas").into_keys().collect();let named: BTreeSet<String> = [&tile["stock"]] .into_iter() .chain(["pictures", "views", "acts", "doors"].iter().flat_map(|part| tile[*part].as_object().unwrap().values())) .map(|photo| format!("{}.png", photo["photo"].as_str().unwrap().trim_start_matches("photo:"))) .collect(); assert!(named.is_subset(&carried), "the package carries every picture its tile names"); cinemas_held_as(&h, &old); pass(&h, &kit, "letterboard");let got = held(&h.db, TOOL).unwrap()["cinemas"].clone(); assert_eq!(got, kit.tools["cinemas"], "unedited since the kit laid it: the kit's whole"); assert!(named.is_subset(&assets_of(&h.db, "cinemas")), "the tile's pictures are the copy's to draw");let laid: Value = serde_json::from_str(&meta(&h.db, KIT_LAID_TOOLS).unwrap().unwrap()).unwrap(); assert_eq!(laid["cinemas"], kit.tools["cinemas"], "what the kit laid now is the new tool"); assert_eq!(pass(&h, &kit, "letterboard again"), 0, "a second pass changes nothing");let edited_copy = Harness::new();letmut edited = old.clone(); edited["name"] = json!("My cinema"); cinemas_held_as(&edited_copy, &edited); pass(&edited_copy, &kit, "letterboard"); assert_eq!(held(&edited_copy.db, TOOL).unwrap()["cinemas"], edited, "edited: the person's, with no tile"); assert!(assets_of(&edited_copy.db, "cinemas").is_empty(), "no picture is laid on a tool the person edited");}