use super::*; use crate::definitions::card::validate_openings; use crate::records::card::{resolve, Around}; use crate::records::page::Words; use crate::rules::shell_lines::LineSet; use serde_json::json; // RULE (owner, 17 Nov 2026): the old screenplay tables go; Cotton Story is // the one screenwriting app. No kit ships them or the Screenplays tool, and // no app installs it; an object or a copy that held them keeps their rows // and holds the definitions as retired (`crate::retired`). #[test] fn no_kit_ships_the_old_screenplay_tables() { assert!(!ids().contains(&"screenplays"), "Screenplays is no kit tool"); assert!(AppKit::named("screenplays").is_none(), "no Screenplays kit"); for kit in ["personal", "story"] { let tables = AppKit::tables_of(kit); for gone in crate::retired::GONE_TABLES { assert!(!tables.iter().any(|t| t == gone), "the {kit} kit ships no {gone}"); } } } fn kit_table(tool: &str, table: &str) -> crate::definitions::TableDefinition { let package = package(tool).expect("the kit holds the tool").expect("it decodes").package; package.tables.into_iter().find(|held| held.id == table).expect("the package carries the table") } // RULE: a book's card says its review on its endpaper and its pages, and a // film's says its director, who recommended it — the // linked person's name, else the name kept as text — and whom it was // watched with, each as kept; the faces draw the places and compose nothing. #[test] fn a_book_and_a_film_say_their_review_pages_director_recommender_and_company() { let now = chrono::DateTime::parse_from_rfc3339("2026-10-23T10:00:00+05:30").unwrap().with_timezone(&chrono::Utc); let cards = LineSet::shipped("cards").unwrap(); let book = kit_table("books", "book"); let read = |table: &crate::definitions::TableDefinition, data: serde_json::Value, around: Around| { resolve(table.card.as_ref().unwrap(), table, "r-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, around).unwrap() }; let said = read(&book, json!({"title": "An Invented Atlas", "review": "Every map leaves a coast out.", "progress": 40}), Around::default()); assert_eq!(said.fields["body"].as_str(), Some("Every map leaves a coast out.")); assert_eq!(said.fields["used"], json!(40), "how far through, which the jacket reads as a share of a hundred"); assert!(said.fields.get("limit").is_none(), "no limit: the share is of a hundred"); assert!(said.fields.get("quote").is_none() && said.fields.get("note").is_none(), "a quote is a highlight now, never the book's"); // The one-sheet reads how far in against how long: the resume point in // seconds over the film's minutes (the poster face's used and limit). let film = kit_table("cinemas", "film"); let halfway = read(&film, json!({"title": "An Invented Harbour", "position": 3360, "minutes": 112}), Around::default()); assert_eq!((halfway.fields["used"].clone(), halfway.fields["limit"].clone()), (json!(3360), json!(112))); } // RULE: a film's length reads as a clock from its minutes ("1:52:00"), an // episode's place says only the year it aired ("aired 2022"), and a book // says its state while it is being read or is read and the day it was // started; the faces draw the places and compose nothing. // RULE: a highlight's card says its passage, its note, its book and the // book's cover as kept, its author (looked up through the book), its place as the page ("p. 37") with the chapter // beside it, either standing alone, and its colour as the choice's stored // value (the ink the face draws by, never the label, which is copy); an ink // place reads a choice column and nothing else. #[test] fn a_highlight_says_its_passage_place_chapter_and_ink() { let now = chrono::DateTime::parse_from_rfc3339("2026-11-04T10:00:00+05:30").unwrap().with_timezone(&chrono::Utc); let cards = LineSet::shipped("cards").unwrap(); let highlight = kit_table("books", "highlight"); let card = highlight.card.as_ref().unwrap(); assert_eq!(card.face.as_str(), "highlight.passage"); let read = |data: serde_json::Value| { resolve(card, &highlight, "h-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let said = read(json!({"book": "b-1", "book_title": "An Invented Atlas", "book_author": "Ines Example", "cover": "covers/atlas.jpg", "text": "Every map leaves a coast out.", "note": "The whole book in a line.", "colour": "red", "page_label": "37", "chapter": "The Coast"})); assert_eq!(said.fields["quote"], json!("Every map leaves a coast out.")); assert_eq!(said.fields["note"], json!("The whole book in a line.")); assert_eq!(said.fields["source"], json!("An Invented Atlas")); assert_eq!(said.fields["subtitle"], json!("Ines Example"), "the book's author, looked up through the book, for the strip's line"); assert_eq!(highlight.column("book_author").unwrap().computed.is_some(), true, "the author is the book's, never typed on a highlight"); assert_eq!(said.fields["photo"], json!("covers/atlas.jpg")); assert_eq!(said.fields["place"], json!("p. 37")); assert_eq!(said.fields["crumb"], json!("The Coast")); assert_eq!(said.fields["ink"], json!("red"), "the stored value, never the label"); let unpaged = read(json!({"book": "b-1", "text": "A line.", "colour": "teal", "chapter": "Two"})); assert!(unpaged.fields.get("place").is_none(), "no page, no place"); assert_eq!(unpaged.fields["crumb"], json!("Two")); assert_eq!(unpaged.fields["ink"], json!("teal")); let bare = read(json!({"book": "b-1", "text": "A line.", "page_label": "ix"})); assert_eq!(bare.fields["place"], json!("p. ix")); assert!(bare.fields.get("crumb").is_none() && bare.fields.get("note").is_none() && bare.fields.get("ink").is_none()); for bad in [ json!({"slot": "ink", "column": "chapter"}), json!({"slot": "ink", "column": "colour", "line": "field.page"}), json!({"slot": "ink", "column": "colour", "also": ["chapter"]}), ] { let mut wrong = card.clone(); wrong.fields.retain(|field| field.slot != crate::definitions::card::CardSlot::Ink); wrong.fields.push(serde_json::from_value(bad.clone()).unwrap()); assert!(wrong.validate(&highlight, "card").is_err(), "{bad} is refused"); } } // RULE: a highlight's passage and place are the book's, kept by the app and // never edited by a person: the reader's create names them all, a token's // create and every patch are refused with the readonly line, the fan offers // no When for the moment it was marked, and the note stays the person's. #[test] fn a_highlights_passage_and_place_are_kept_by_the_app() { use crate::records::{validate_create_as, validate_patch_as, Author, RecordError}; let highlight = kit_table("books", "highlight"); let kept = ["text", "locator", "progress", "page_label", "chapter", "made_at"]; for key in kept { assert_eq!(highlight.column(key).unwrap().readonly, Some(true), "{key} is no person's to edit"); } assert_eq!(highlight.column("note").unwrap().readonly, None, "the note is the person's"); let made = json!({"book": "b-1", "text": "Every map leaves a coast out.", "colour": "red", "locator": "{\"href\":\"ch1.xhtml\"}", "progress": 12, "page_label": "37", "chapter": "The Coast", "made_at": "2026-11-04T10:00:00Z"}); assert!(validate_create_as(&highlight, &made, Author::App).is_ok(), "the reader keeps a highlight"); assert!(matches!(validate_create_as(&highlight, &made, Author::Token("synthetic-token")), Err(RecordError::Readonly { .. }))); for key in kept { let patch = json!({ key: made[key].clone() }); for author in [Author::App, Author::Token("synthetic-token"), Author::Other] { let refused = validate_patch_as(&highlight, &patch, author).unwrap_err(); assert_eq!(refused, RecordError::Readonly { column: key.to_string() }, "{key} by {author:?}"); } } assert!(validate_patch_as(&highlight, &json!({"note": "Why I marked it."}), Author::App).is_ok()); let fan = crate::rules::card_actions::offered(&highlight, made.as_object().unwrap(), &[], Default::default()); assert!(fan.iter().all(|action| action.id != "when"), "no When for the moment it was marked: {fan:?}"); } #[test] fn a_film_says_its_length_an_episode_its_year_and_a_book_its_state_and_start() { let now = chrono::DateTime::parse_from_rfc3339("2026-10-23T10:00:00+05:30").unwrap().with_timezone(&chrono::Utc); let cards = LineSet::shipped("cards").unwrap(); let read = |table: &crate::definitions::TableDefinition, data: serde_json::Value| { resolve(table.card.as_ref().unwrap(), table, "r-1", data.as_object().unwrap(), "Asia/Kolkata", now, Words::shipped(), &cards, Around::default()).unwrap() }; let episode = read(&kit_table("cinemas", "film_episode"), json!({"title": "Cicadas", "season_number": 1, "number": 4})); assert_eq!(episode.fields["subtitle"], "S1 E4"); let book = kit_table("books", "book"); let reading = read(&book, json!({"title": "An Invented Atlas", "status": "reading", "started_on": "2026-10-04"})); assert_eq!(reading.fields["state"], book.column("status").unwrap().choice_label("reading")); assert_eq!(reading.fields["started"], "Sun 4 Oct"); assert_eq!(book.card.as_ref().unwrap().pages, ["review"]); let stopped = read(&book, json!({"title": "An Invented Atlas", "status": "stopped"})); assert_eq!(stopped.fields["state"], book.column("status").unwrap().choice_label("stopped"), "a book put down says so"); } // RULE: the kit's fingerprint names every kit package's file and the shell's tables, boards and themes, so a changed, renamed or dropped file gives a new fingerprint and a fixture cached under the old one is never reused. #[test] fn a_changed_kit_or_shell_file_names_a_new_fingerprint() { let files: Vec<(&str, &str, Vec)> = fingerprinted().into_iter().map(|(set, name, bytes)| (set, name, bytes.to_vec())).collect(); // The kit's part by its digest, as the build works it out once; the shell's whole. let kit = KIT_FILES.len(); let view = |files: &[(&str, &str, Vec)]| { let files: Vec<(&str, &str, &[u8])> = files.iter().map(|(set, name, bytes)| (*set, *name, bytes.as_slice())).collect(); let kit_end = files.len() - (fingerprinted().len() - kit); fingerprint_over(&digest_of(&files[..kit_end]), &files[kit_end..]) }; assert_eq!(digest_of(&fingerprinted()[..kit]), KIT_FILES_DIGEST, "the build's digest is the carried files' own"); assert_eq!(view(&files), fingerprint(), "the same files, the same fingerprint"); let first = |set: &str| files.iter().position(|(at, _, _)| *at == set).unwrap_or_else(|| panic!("{set} is fingerprinted")); let package = files.iter().position(|(_, name, _)| *name == "manifest.json").expect("a kit package manifest"); for at in [package, first("shell/tables"), first("shell/boards"), first("shell/themes")] { let mut changed = files.clone(); changed[at].2.push(b' '); assert_ne!(view(&changed), fingerprint(), "{}/{} changed", files[at].0, files[at].1); } let mut renamed = files.clone(); renamed[package].1 = "renamed.json"; assert_ne!(view(&renamed), fingerprint()); let mut dropped = files.clone(); dropped.remove(package); assert_ne!(view(&dropped), fingerprint()); } /// RULE: one definition per table (owner, 26 Oct 2026): every kit tool's package carries every table its manifest names, each the kit's one definition of it (`kits/personal/tables`, the one the object serves) — no deck reads a table no package carries. #[test] fn every_kit_tool_carries_the_one_definition_of_each_table_it_names() { for id in super::ids() { let package = package(id).expect("a kit tool").expect("the kit decodes").package; let carried: Vec<&str> = package.tables.iter().map(|table| table.id.as_str()).collect(); assert_eq!(carried, package.tool.tables.iter().map(String::as_str).collect::>(), "{id} carries what it names"); for table in &package.tool.tables { let file = cotton_store::manifest_dir().join("kits/personal/tables").join(format!("{table}.json")); assert_eq!(table_file(table), Some(std::fs::read(&file).expect("the kit's table").as_slice()), "{id}: {table}"); } } } /// RULE (walk, 27 Oct 2026): a tool's views are read off its home table's tool block before its manifest (`shell.fan`), so Messages' home table carries the dial its manifest declares — All, WhatsApp, SMS, Instagram, Starred and Agents. The thread table kept only All, so the phone drew no ring over Messages and none of its other views could be reached. #[test] fn messages_home_table_carries_the_dial_its_manifest_declares() { let package = package("messages").expect("the kit holds Messages").expect("Messages decodes").package; let thread = kit_table("messages", "thread"); let home = thread.tool.as_ref().expect("the thread table is Messages' home"); assert_eq!(home.key.as_deref(), Some("messages")); let ids = |views: &[crate::definitions::tool_views::ToolView]| views.iter().map(|view| view.id.clone()).collect::>(); assert_eq!(ids(&home.views), ["all", "cotton", "whatsapp", "sms", "instagram", "starred", "agents", "devices"]); assert_eq!(serde_json::to_value(&home.views).unwrap(), serde_json::to_value(&package.tool.views).unwrap(), "the home table's dial is the manifest's"); } /// A narrowed view names its own empty line and counts the whole table to /// distinguish an empty selection from a database with no records yet. #[test] fn narrowed_kit_views_have_resolvable_empty_lines_and_whole_set_counts() { let lines = crate::rules::shell_lines::shipped_rows(); for id in crate::kit::ids() { let package = package(id).unwrap().unwrap().package; for view in &package.tool.views { if !view.read.contains_key("where") && !view.read.contains_key("section") { continue; } let empty = &view.read["empty"]; let line = empty["line"].as_str().unwrap_or_else(|| panic!("{id}/{} has no empty line", view.id)); assert!(crate::rules::shell_lines::resolve("cards", line, &lines, &[]).is_some(), "{id}/{}: {line}", view.id); assert_eq!(empty["table"], true, "{id}/{} counts its table", view.id); if let Some(counts) = empty["counts"].as_object() { for (related, line) in counts { assert!(package.tool.views.iter().any(|view| view.id == *related)); assert!(crate::rules::shell_lines::resolve("cards", line.as_str().unwrap(), &lines, &[("count", "150")]).is_some()); } } } } } // Each records file must survive the same package decoder used on-device, // and every row must be an ordinary create accepted by its shipped table. #[test] fn every_kit_records_file_validates_against_its_table() { let mut checked = std::collections::BTreeSet::new(); for (tool, path, bytes) in super::KIT_FILES { let Some(table) = path.strip_prefix("records/").and_then(|s| s.strip_suffix(".json")) else { continue }; let decoded = package(tool).expect("kit package").expect("package decodes").package; let definition = decoded.tables.iter().find(|d| d.id == table).expect("sample table is carried"); let rows: Vec = serde_json::from_slice(bytes).expect("array of create objects"); let results: Vec<_> = rows.iter().map(|row| crate::records::validate_create(definition, row)).collect(); assert!(results.iter().all(Result::is_ok), "{tool}/{path}: {results:?}"); assert_eq!(decoded.samples[table], rows, "{tool}/{path} is packed without changes"); checked.insert((*tool, *path)); } assert!(checked.contains(&("people", "records/person.json"))); assert!(checked.contains(&("notebook", "records/note.json"))); } /// The face choices are known by what their definition says they are /// (`face_choices`), and that definition is a valid keyed table. #[test] fn the_face_choice_tables_are_the_ones_their_definition_declares() { assert_eq!(face_choice_tables(), ["face_settings".to_string()]); let (_, json) = shell::SHELL_KIT_TABLES.iter().find(|(id, _)| *id == "face_settings").expect("every database's face choices"); let definition = crate::definitions::TableDefinition::from_json(json).unwrap(); assert_eq!(definition.face_choices, Some(true)); definition.validate().unwrap(); let mut unkeyed = definition.clone(); unkeyed.row_key = None; assert!(unkeyed.validate().is_err(), "a table of face choices names its table by its key"); } #[test] fn rigby_names_only_kit_tools() { let manifest: serde_json::Value = serde_json::from_str(include_str!("../../../apps/cotton/Tests/Fixtures/Flavours/rigby.json")).unwrap(); // Which tools Rigby carries is its manifest's to say; each must be a kit package. let ids = manifest["tools"].as_array().expect("Rigby names its tools"); assert!(!ids.is_empty()); for id in ids.iter().map(|id| id.as_str().expect("a tool id")) { assert!(package(id).expect("Rigby only names kit tools").is_ok(), "{id}"); } } /// RULE: every app kit's app is born with the kit's tools then the ones it folds, and lays only this phone's account /// acts, on the Account card — for every flavour manifest that names a kit, read from the tree, never listed. #[test] fn every_app_is_born_with_its_kits_tools_and_lays_only_the_account_acts() { let flavours = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours"); let mut checked = 0; for entry in std::fs::read_dir(&flavours).unwrap() { let path = entry.unwrap().path().join("flavour.json"); // A folder that holds only an app's icons so far (Post, Sites before their shells) has no manifest yet. let Ok(bytes) = std::fs::read(&path) else { continue }; let manifest: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); let Some(kit) = AppKit::of(Some(&manifest)).expect("reads") else { continue }; assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "{}", path.display()); let acts: Vec<&str> = kit.acts.iter().map(|act| act.id.as_str()).collect(); assert!(acts.is_empty() || acts == ACCOUNT_ACTS, "{}: {acts:?}", path.display()); checked += 1; } assert!(checked > 0, "no flavour names a kit"); } fn manifest(path: &str) -> serde_json::Value { let root = cotton_store::manifest_dir().join("../../apps/cotton/App"); serde_json::from_slice(&std::fs::read(root.join(path)).expect("a manifest")).expect("JSON") } /// RULE (coordinator, 5 Nov 2026): an app keeps to the kit its manifest names, one source only — Books and Music name their kits and no tools list, are born with the kit's tools, and keep its tables and the shell's; Cotton names none and keeps the whole object. #[test] fn an_app_keeps_to_the_kit_its_manifest_names() { let books = AppKit::of(Some(&manifest("Flavours/books/flavour.json"))).expect("reads").expect("Books names a kit"); assert_eq!(books.tables, ["book", "highlight", "record_group", "group_member", "media", "photo", "face_settings", "vault_key"]); assert!(books.keeps_table("book") && books.keeps_table("device") && !books.keeps_table("message") && !books.keeps_table("todo")); assert!(books.keeps_tool("books") && !books.keeps_tool("todos")); assert!(books.pulled().contains(&"device".to_string()) && books.pulled().windows(2).all(|pair| pair[0] < pair[1])); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest("Flavours/books/flavour.json"))).expect("reads").0, born_with(&books), "born with the kit's tools"); assert!(AppKit::of(Some(&manifest("Flavours/music/flavour.json"))).expect("reads").is_some(), "Music names a kit"); assert_eq!(AppKit::of(Some(&manifest("CottonManifest/flavour.json"))).expect("reads"), None, "Cotton keeps the whole object"); assert_eq!(AppKit::mark(None), "whole"); assert_eq!(AppKit::mark(Some(&books)), "books"); assert_eq!(AppKit::copy_mark(None), "whole"); assert_eq!(AppKit::copy_mark(Some(&books)), format!("books {}", books.pulled().join(",")), "a copy's mark names the kit's tables"); } #[test] fn a_manifest_naming_a_kit_and_tools_or_no_app_kit_is_refused() { let both = serde_json::json!({"kit": "books", "tools": ["books"]}); assert!(AppKit::of(Some(&both)).unwrap_err().contains("the kit names the tools")); assert!(crate::genesis::GenesisTools::of(Some(&both)).is_err()); for id in ["personal", "shell", "nope"] { assert!(AppKit::of(Some(&serde_json::json!({"kit": id}))).is_err(), "{id}"); } let dir = std::env::temp_dir().join(format!("app-kit-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); assert_eq!(AppKit::at(&dir).expect("reads"), None, "none kept is the whole object"); let books = AppKit::named("books"); AppKit::keep(books.as_ref(), &dir).expect("kept"); assert_eq!(AppKit::at(&dir).expect("reads"), books); AppKit::keep(None, &dir).expect("kept"); assert_eq!(AppKit::at(&dir).expect("reads"), None); let _ = std::fs::remove_dir_all(&dir); } /// A kit file, read from the crate's kits folder. fn kit_file(path: &str) -> serde_json::Value { serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join(path)).expect(path)).expect("JSON") } /// Every table the personal kit's `tools` draw on a phone: each view's table /// and each table a tool names, each table a view's or a table's card links /// to, the lists a table's records stack into, the lists a tool's own /// record's sheet opens, a person's picture, the media and face settings /// every app keeps, and the owning parent of each (`OWNING_REFS`: the phone /// holds no child without it). Never what a definition names but the phone /// neither draws nor needs (the mail a transaction came from). /// Whether a kit.json is one of Cotton's app kits: every table it names is a personal one (`personal/`), an app /// over the one object; a business kit (yoga, kitchen) names its own. fn over_personal(kit_json: &str) -> bool { let kit: serde_json::Value = serde_json::from_str(kit_json).expect("a kit.json"); kit["tables"].as_array().is_some_and(|tables| !tables.is_empty() && tables.iter().all(|table| table.as_str().is_some_and(|table| table.starts_with("personal/")))) } /// What a kit's app is born with: the kit's tools, then the ones it folds (whose columns its views read). fn born_with(kit: &AppKit) -> Vec { kit.tools.iter().chain(&kit.folds).cloned().collect() } fn drawn_by>(tools: &[S]) -> std::collections::BTreeSet { let table = |id: &str| kit_file(&format!("kits/personal/tables/{id}.json")); let link = |table: &serde_json::Value, column: &str| -> Option { table["columns"].as_array()?.iter().find(|one| one["key"] == column)?["link_to"].as_str().map(str::to_string) }; let mut drawn = std::collections::BTreeSet::new(); let mut own: Vec = Vec::new(); for id in tools.iter().map(AsRef::as_ref) { let tool_id = id; let tool = kit_file(&format!("kits/personal/tools/{id}/manifest.json")); let named: Vec = tool["tables"].as_array().expect("a tool names its tables").iter().filter_map(serde_json::Value::as_str).map(str::to_string).collect(); let views = tool["views"].as_array().cloned().unwrap_or_default(); let mut read: Vec<(String, serde_json::Value)> = views.iter().map(|view| (view["read"]["table"].as_str().expect("a view reads a table").to_string(), view["card"].clone())).collect(); read.extend(named.iter().map(|id| (id.clone(), serde_json::Value::Null))); // A person's sheet is People's: a tool that names `person` only to // keep its people (Health's family records) owns the row, never the // sheet's lists (calls, threads, todos). own.extend(named.into_iter().filter(|table| table != "person" || id == "people")); for (id, card) in read { drawn.insert(id.clone()); let definition = table(&id); for card in [&card, &definition["card"]] { for field in card["fields"].as_array().into_iter().flatten() { if let Some(target) = field["column"].as_str().and_then(|column| link(&definition, column)) { drawn.insert(target); } } } // A person's groups are People's too. if definition["groups"].is_object() && (id != "person" || tool_id == "people") { drawn.extend(["record_group".to_string(), "group_member".to_string()]); } } } for id in drawn.clone() { let definition = table(&id); // The lists a tool's own record's sheet opens (a statement's lines); a // person's sheet is People's, which an app on other tools does not draw. let lists = if own.contains(&id) { definition["parts"]["lists"].as_array().cloned().unwrap_or_default() } else { Vec::new() }; for list in &lists { drawn.insert(list["table"].as_str().expect("a list names its table").to_string()); } if link(&definition, "avatar_photo_id").as_deref() == Some("photo") { drawn.insert("photo".to_string()); } } drawn.extend(["media".to_string(), "face_settings".to_string()]); let storage: Vec = serde_json::from_str(crate::toolkits::PERSONAL_STORAGE).expect("the storage map reads"); let store_of = |table: &str| storage.iter().find(|entry| entry["table"] == table).and_then(|entry| entry["from"].as_str()).map(str::to_string); let table_of = |store: &str| storage.iter().find(|entry| entry["from"] == store).and_then(|entry| entry["table"].as_str()).map(str::to_string); for id in drawn.clone() { let Some(store) = store_of(&id) else { continue }; for (_, _, parent) in cotton_store::schema::table_specs::OWNING_REFS.iter().filter(|(child, _, _)| *child == store) { drawn.insert(table_of(parent).unwrap_or_else(|| parent.to_string())); } } drawn } /// RULE (owner, 11 Nov 2026): Cotton Keys is where password management /// lives. Passwords folds into Keys as a second tool, after Keys, as the /// personal kit ships it: its secret is the keys kit's too, add-only (the /// personal kit already lays it on every object), /// and the account acts stay on Keys, on the Account card left of it. Two tools rather than views of one: /// Passwords' seven views and Keys' four stay as Cotton draws them, and /// Cotton keeps Passwords. #[test] fn cotton_keys_keeps_passkeys_and_passwords() { let manifest = manifest("Flavours/keys/flavour.json"); let keys = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton Keys names a kit"); assert_eq!(keys.tools, ["keys", "passwords"]); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&keys), "born with the kit's tools"); let drawn = drawn_by(&keys.tools); assert!(drawn.contains("secret"), "Passwords draws its secrets"); let personal = AppKit::tables_of("personal"); for table in &keys.tables { assert!(personal.contains(table), "the personal kit already lays {table} on every object"); } let cottons: Vec = kit_file("kits/personal/kit.json")["tools"].as_array().unwrap().iter().filter_map(|tool| tool.as_str().map(str::to_string)).collect(); assert!(cottons.contains(&"passwords".to_string()) && cottons.contains(&"keys".to_string()), "Cotton keeps Keys and Passwords"); for id in drawn.iter().filter(|id| !crate::retired::is_gone_table(id)) { assert!(keys.keeps_table(id), "Cotton Keys keeps {id}, which Keys or Passwords draws"); } // Beyond what the two tools draw, the kit keeps the photo table it // listed before Passwords came (206df83ba6), beside media, and what the // unlock card answers from (window-phone): the requests, the windows and // the person key that signs them. let beyond: Vec<&String> = keys.tables.iter().filter(|table| !drawn.contains(*table)).collect(); assert_eq!(beyond, ["photo", "unlock_request", "unlock_grant", "assistant_read", "person_key"], "the keys kit holds the tables Keys and Passwords draw, photo, and the unlock card's"); for never in ["email_thread", "message", "todo", "transaction", "book"] { assert!(!keys.keeps_table(never), "{never}"); } assert_eq!(keys.aside, [ACCOUNT_CARD], "Cotton Keys lays the account acts, on the Account card left of the first"); assert_eq!(keys.acts.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); let definition = |id: &str| -> crate::definitions::ToolDefinition { serde_json::from_value(kit_file(&format!("kits/personal/tools/{id}/manifest.json"))).expect("a shipped tool reads") }; let mut tools = vec![definition("keys"), definition("passwords")]; keys.lay_acts(&mut tools); let acts = |tool: &crate::definitions::ToolDefinition| tool.acts.iter().map(|act| act.id.clone()).collect::>(); assert!(acts(&tools[0]).contains(&"account_sign_in".to_string()), "the account acts stand on Keys, the first tool"); assert!(acts(&tools[1]).iter().all(|act| !act.starts_with("account_")), "Passwords offers no account"); } /// A kit keeps the owning parent of every table it keeps: the phone's file /// holds a child under an owning parent that is not there as a dormant /// receipt with no row (`cotton_store::fold`, 3.7 points 7-8), so a kit that /// pulls a child without its parent never shows the child — and parks /// nothing to say so (Cotton Money Dev, 6 Nov 2026: two statements and ten /// lines held as receipts, no row, `document` not in the kit). #[test] fn every_kit_keeps_the_owning_parent_of_each_table_it_keeps() { let storage: Vec = serde_json::from_str(crate::toolkits::PERSONAL_STORAGE).expect("the storage map reads"); let store_of = |table: &str| storage.iter().find(|entry| entry["table"] == table).and_then(|entry| entry["from"].as_str()).map(str::to_string); let table_of = |store: &str| storage.iter().find(|entry| entry["from"] == store).and_then(|entry| entry["table"].as_str()).map(str::to_string); let mut missing = Vec::new(); for (id, _) in APP_KITS.iter().filter(|(id, _)| *id != "personal" && *id != "shell") { let kit = AppKit::named(id).expect("a shipped kit"); for table in &kit.tables { let Some(store) = store_of(table) else { continue }; for (_, column, parent) in cotton_store::schema::table_specs::OWNING_REFS.iter().filter(|(child, _, _)| *child == store) { let parent_table = table_of(parent).unwrap_or_else(|| parent.to_string()); if !kit.keeps_table(&parent_table) { missing.push(format!("kits/{id} keeps {table} ({store}.{column}) but not its owning parent {parent_table} ({parent})")); } } } } assert!(missing.is_empty(), "{}", missing.join("\n")); } /// RULE (coordinator, 6 Nov 2026): moving an expected payment moves its /// payment date only (`occurred_on`, the receipt's date slot), so Future's /// caption reads the payment date first, the due date only where none is set. #[test] fn moneys_future_reads_the_payment_date_first() { let tool: serde_json::Value = serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join("kits/personal/tools/money/manifest.json")).expect("manifest")).expect("JSON"); let future = tool["views"].as_array().expect("views").iter().find(|view| view["id"] == "future").expect("Future"); assert_eq!(future["slip"]["caption"]["dates"], serde_json::json!(["occurred_on", "due_date"])); let table: serde_json::Value = serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join("kits/personal/tables/transaction.json")).expect("table")).expect("JSON"); let date = table["card"]["fields"].as_array().expect("fields").iter().find(|field| field["slot"] == "date").expect("a date slot"); assert_eq!(date["column"], "occurred_on", "the receipt's date is the payment date, the one When moves"); } /// RULE (copy-installer-cpu, 7 Nov 2026): the kit decoded once from its files /// is the kit an import decodes from its archive, package by package. #[test] fn the_kit_decoded_from_its_files_is_the_kit_its_archives_decode_to() { for id in ids() { let archived = crate::definitions::package::decode_package(&archive(id).expect("a kit id").expect("its archive")).expect("it decodes"); let decoded = decoded(id).expect("a kit id").expect("it decodes"); assert_eq!(format!("{:?}", decoded), format!("{archived:?}"), "{id}"); assert!(std::ptr::eq(decoded, decoded_again(id)), "{id} is decoded once and shared"); } fn decoded_again(id: &str) -> &'static crate::definitions::package::ImportedPackage { decoded(id).expect("a kit id").expect("it decodes") } } /// RULE (8 Nov 2026): Cotton Downloads keeps to its kit: /// the one Downloads tool, born with it, the two tables its views draw and /// the lists, media and face settings every app keeps. The records a fetch /// lands live in the tools that play them, which this app does not hold, and /// the account acts stand on Active, where the app opens. #[test] fn cotton_downloads_keeps_its_queue_and_opens_on_active() { let manifest = manifest("Flavours/downloads/flavour.json"); let kit = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton Downloads names a kit"); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "born with the kit's tools"); for id in ["fetch", "fetch_file", "record_group", "group_member", "media", "photo", "face_settings"] { assert!(kit.keeps_table(id), "Cotton Downloads keeps {id}"); } for never in ["page", "film", "song", "book", "document", "todo", "transaction"] { assert!(!kit.keeps_table(never), "{never}"); } let tool: serde_json::Value = serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join("kits/personal/tools/downloads/manifest.json")).expect("reads")).expect("JSON"); let laid = &kit.acts; assert_eq!(kit.aside, [ACCOUNT_CARD], "Cotton Downloads lays the account acts, on the Account card left of the first"); assert!(tool["views"].as_array().unwrap().iter().any(|view| view["id"] == "active" && view["is_default"] == true), "Active is where the app opens"); assert_eq!(laid.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); } /// RULE (owner, 11 Nov 2026): Cotton Notes keeps to its kit: the one Notebook /// tool, born with it, as the personal kit ships it (its one view, All, and /// the note's own face and reader), the note and every table a note's columns /// link to (the project on its page, the people it names), and the lists, /// media and face settings every app keeps. A Notes copy pulls only those and /// the shell's. The kit is drawn from the personal kit and reshapes nothing, /// so the keep that lays the personal kit on an existing object already holds /// every part of it: nothing new reaches the object, add-only by /// construction, and Cotton keeps Notebook. The account acts stand on All, /// where the app opens. #[test] fn cotton_notes_keeps_the_notebook_and_what_a_note_links() { let manifest = manifest("Flavours/notes/flavour.json"); let kit = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton Notes names a kit"); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "born with the kit's tools"); let read = |path: &str| -> serde_json::Value { serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join(path)).expect(path)).expect("JSON") }; let note = read("kits/personal/tables/note.json"); assert_eq!(note["card"]["face"], "note.page", "Notes keeps the note's face"); // And what the assistant wrote (owner, 21 Nov 2026): its memory, the memories' project links, and of the documents the web pages alone. let mut wanted: Vec = ["note", "note_attachment", "record_group", "group_member", "media", "photo", "face_settings", "vault_key", "memory", "project_link", "document"].map(str::to_string).to_vec(); for column in note["columns"].as_array().expect("columns") { if let Some(target) = column["link_to"].as_str() { wanted.push(target.to_string()); } } wanted.sort(); wanted.dedup(); let mut kept = kit.tables.clone(); kept.sort(); assert_eq!(kept, wanted, "the note, what it links (project, person), and what every app keeps"); assert_eq!(kit.only_query().as_deref(), Some("document.mime:text%2Fhtml"), "of the documents, the web pages alone"); // TABLE DROP 1 (kit gap): Words reads old notes' pictures and keeps attached files, so it carries note_attachment. for never in ["todo", "event", "thought", "transaction", "book", "song", "film", "message"] { assert!(!kit.keeps_table(never) && !kit.pulled().contains(&never.to_string()), "a Notes copy never pulls {never}"); } let personal = AppKit::tables_of("personal"); for table in &kit.tables { assert!(personal.contains(table), "the personal kit already lays {table} on every object"); } let personal_kit = read("kits/personal/kit.json"); assert!(personal_kit["tools"].as_array().unwrap().iter().any(|tool| tool.as_str().is_some_and(|tool| tool.rsplit('/').next() == Some("notebook"))), "Cotton keeps Notebook"); let tool = read("kits/personal/tools/notebook/manifest.json"); assert_eq!(tool["views"].as_array().unwrap().iter().map(|view| view["id"].as_str().unwrap()).collect::>(), ["all"], "Notebook's views as they are"); let laid = &kit.acts; assert_eq!(kit.aside, [ACCOUNT_CARD], "Cotton Notes lays the account acts, on the Account card left of the first"); assert!(tool["views"].as_array().unwrap().iter().any(|view| view["id"] == "all" && view["is_default"] == true), "All is where the app opens"); assert_eq!(laid.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); } /// RULE (owner, 11 Nov 2026): Cotton People keeps to its kit: the one People /// tool, born with it, as the personal kit ships it (its view All first, the /// fan's centre card; the person's rolodex face, with Import contacts on Plus /// as the person table offers it), the person and every table People owns, /// and the lists, media, photo and face settings every app keeps. A People /// copy pulls only those and the shell's. Every part is the personal kit's, /// so the keep that lays the personal kit on an existing object already /// holds it: add-only by construction, and Cotton keeps People and Birthdays. /// The account acts stand on All, where the app opens. Birthdays reads only /// the person and adds two columns to it, so it adds no table to the kit. #[test] fn cotton_people_keeps_people_and_what_a_person_holds() { let manifest = manifest("Flavours/people/flavour.json"); let kit = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton People names a kit"); assert_eq!(kit.folds, ["birthdays"], "Birthdays is People's views, never a tool of its own here"); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "born with the kit's tool and the one it folds, whose columns its views read"); assert!(kit.keeps_tool("birthdays"), "a People copy keeps Birthdays' definition, as the object serves it"); let read = |path: &str| -> serde_json::Value { serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join(path)).expect(path)).expect("JSON") }; let tool = read("kits/personal/tools/people/manifest.json"); let person = read("kits/personal/tables/person.json"); assert_eq!(person["card"]["face"], "person.rolodex", "People keeps the person's face"); let mut wanted: Vec = ["record_group", "group_member", "media", "photo", "face_settings", "vault_key"].map(str::to_string).to_vec(); for table in tool["tables"].as_array().expect("People's tables") { let table = table.as_str().expect("a table id"); wanted.push(table.to_string()); for column in read(&format!("kits/personal/tables/{table}.json"))["columns"].as_array().expect("columns") { if let Some(target) = column["link_to"].as_str() { wanted.push(target.to_string()); } } } wanted.retain(|table| !crate::retired::is_gone_table(table)); wanted.sort(); wanted.dedup(); let mut kept = kit.tables.clone(); kept.sort(); assert_eq!(kept, wanted, "People's tables, what they link (photo), and what every app keeps"); for never in ["todo", "note", "event", "message", "email", "book", "song", "film", "transaction"] { assert!(!kit.keeps_table(never) && !kit.pulled().contains(&never.to_string()), "a People copy never pulls {never}"); } let personal = AppKit::tables_of("personal"); for table in &kit.tables { assert!(personal.contains(table), "the personal kit already lays {table} on every object"); } let personal_kit = read("kits/personal/kit.json"); for kept_tool in ["people", "birthdays"] { assert!(personal_kit["tools"].as_array().unwrap().iter().any(|tool| tool.as_str().is_some_and(|tool| tool.rsplit('/').next() == Some(kept_tool))), "Cotton keeps {kept_tool}"); } assert_eq!(tool["views"][0]["id"], "all", "All is first: the fan's centre card"); let laid = &kit.acts; assert_eq!(kit.aside, [ACCOUNT_CARD], "Cotton People lays the account acts, on the Account card left of the first"); assert!(tool["views"].as_array().unwrap().iter().any(|view| view["id"] == "all" && view["is_default"] == true), "All is where the app opens"); assert_eq!(laid.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); } /// RULE (owner, 11 Nov 2026): Cotton Messages keeps to its kit: the one /// Messages tool, born with it, as the personal kit ships it (its six views, /// All first and where it opens; the thread's slips and the chat screen), the /// tables the tool names, every table their columns link to (the people and /// contacts a thread's face names, and the project and todo an agent session /// links), and the lists, media and face settings every app keeps. The kit is /// drawn from the personal kit and reshapes nothing: the keep that lays the /// personal kit on an existing object already holds every part, add-only by /// construction, and Cotton keeps Messages. Shape only: nothing is imported /// into these tables until they are sealed on the device. #[test] fn cotton_messages_keeps_its_threads_and_what_they_link() { let manifest = manifest("Flavours/messages/flavour.json"); let kit = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton Messages names a kit"); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "born with the kit's tools"); let read = |path: &str| -> serde_json::Value { serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join(path)).expect(path)).expect("JSON") }; let tool = read("kits/personal/tools/messages/manifest.json"); let mut wanted: Vec = ["record_group", "group_member", "media", "photo", "face_settings", "vault_key"].map(str::to_string).to_vec(); // RULE (owner, 11 Nov 2026, 16:55 IST): the Agents view moved to Cotton // Developer, so its session table, and the project and todo a session // links, are Developer's; Cotton's Messages keeps the view. for table in tool["tables"].as_array().expect("the tool's tables").iter().filter(|table| *table != "session") { let table = table.as_str().unwrap(); wanted.push(table.to_string()); for column in read(&format!("kits/personal/tables/{table}.json"))["columns"].as_array().expect("columns") { if let Some(target) = column["link_to"].as_str() { wanted.push(target.to_string()); } } } // RULE (chat-calls, 9876dd042): Cotton Chat places calls from a // conversation, so Messages carries the call table its calls are kept in. wanted.push("call".to_string()); // RULE (owner, 21 Nov 2026, MAIL.md): Comms holds mail, a person's in their // conversation, the rest in its Mail tab: the threads of mail, their // messages, and the email handles that say whose mail is whose. // Since the Email app retired (22 Nov 2026) Comms' tool draws them, with // the senders and each conversation's addresses; a conversation's payment // or event stays on the object, never pulled to a Comms copy. // COMMS WITHOUT MAIL (fbda68018f, 26 Nov 2026): Cotton Post holds the mail now; Comms keeps only the handles // that say whose a chat is. wanted.push("person_handle".to_string()); // A call's meeting likewise (the tool draws the call table since Calling retired, 22 Nov 2026). wanted.retain(|table| !["event", "transaction", "meeting"].contains(&table.as_str())); // RULE (DECISIONS "The Downloads chat", 22 Nov 2026): the phone queues a link itself, so Comms keeps the // download queue and what it landed. wanted.extend(["fetch", "fetch_file"].map(str::to_string)); // RULE (owner, 23 Nov 2026; chat DECISIONS "Recordings"): Comms keeps the recordings (Calls lists them), and the // to-dos and notes they become (Add to to-dos, Save as note). wanted.extend(["meetings_meeting", "meetings_speaker", "meetings_line", "meetings_action", "todo", "note"].map(str::to_string)); // The tool still draws the mail tables, which Post keeps; Comms' copy keeps none of them. let mail = ["email", "email_thread", "email_participant", "email_sender", "email_draft", "mail_history", "email_account", "email_cut", "email_bin_cut", "email_read_cut"]; wanted.retain(|table| !mail.contains(&table.as_str())); // COMMS PULLS ITS BLOCKED LIST (eb13eda6e9): You's Blocked row counts what every device blocked. wanted.push("blocked_sender".to_string()); // TABLE DROP 1 (kit gap): Comms writes reactions, so its kit carries them and they reach the other phones. wanted.push("message_reaction".to_string()); // With its mail gone to Post, nothing of Comms comes late, and no mail table is kept. assert!(kit.late.is_empty(), "nothing of Comms is late: {:?}", kit.late); for mail in mail { assert!(!kit.keeps_table(mail), "Comms keeps no {mail}: Post holds the mail"); } wanted.sort(); wanted.dedup(); let mut kept = kit.tables.clone(); kept.sort(); assert_eq!(kept, wanted, "the tool's tables, what they link, and what every app keeps"); assert_eq!(read("kits/personal/tables/thread.json")["card"]["face"], "thread.slips", "Messages keeps the thread's face"); for never in ["event", "transaction", "book", "song", "film", "passkey", "secret", "session", "project"] { assert!(!kit.keeps_table(never) && !kit.pulled().contains(&never.to_string()), "a Messages copy never pulls {never}"); } let dealt: Vec<&str> = tool["views"].as_array().unwrap().iter() .filter(|view| kit.deals_view(view["read"]["table"].as_str())) .map(|view| view["id"].as_str().unwrap()).collect(); assert_eq!(dealt, ["all", "cotton", "whatsapp", "sms", "instagram", "starred", "devices"], "the Messages app deals no Agents view: the session table is Developer's; Devices is dealt so the app that founded the vault can let a device in"); let personal = AppKit::tables_of("personal"); for table in &kit.tables { assert!(personal.contains(table), "the personal kit already lays {table} on every object"); } let personal_kit = read("kits/personal/kit.json"); assert!(personal_kit["tools"].as_array().unwrap().iter().any(|tool| tool.as_str().is_some_and(|tool| tool.rsplit('/').next() == Some("messages"))), "Cotton keeps Messages"); assert_eq!(tool["views"].as_array().unwrap().iter().map(|view| view["id"].as_str().unwrap()).collect::>(), ["all", "cotton", "whatsapp", "sms", "instagram", "starred", "agents", "devices"], "Messages' views as they are"); let laid = &kit.acts; assert_eq!(kit.aside, [ACCOUNT_CARD], "Cotton Messages lays the account acts, on the Account card left of the first"); assert!(tool["views"].as_array().unwrap().iter().any(|view| view["id"] == "all" && view["is_default"] == true), "All is where the app opens"); assert_eq!(laid.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); } /// RULE (owner, 11 Nov 2026): Cotton Calendar keeps to its kit: the one /// Calendar tool, born with it, as the personal kit ships it (Today, Upcoming, /// Recurring and All, Today the fan's centre card; the event's rolodex face; /// its Google acts), the event and its attendees, the project and the people /// an event's page links, and the lists, media, photo and face settings every /// app keeps. An event's From mail link (email_thread) stays on the object, as /// a todo's thought does in Todos: mail is another app's. A Calendar copy /// pulls only those and the shell's. The kit is drawn from the personal kit /// and reshapes nothing, so the keep that lays the personal kit on an existing /// object already holds every part of it: add-only by construction, and /// Cotton keeps Calendar. The account acts stand on Today, where the app opens. #[test] fn cotton_calendar_keeps_the_calendar_and_what_an_event_links() { // The manifest Cotton Calendar shipped: Days took its identity (20 Nov 2026) and its folder left the tree; the calendar kit stays. let manifest: serde_json::Value = serde_json::from_str(r#"{"genesis":"personal","flavour":"calendar","name":"Cotton Calendar","ground":"kitchenTile","databases":"single","database":"personal","business":{"server":{"real":"https://cottondb.com","dev":"https://dev.example.invalid"}},"fan":{"home":false,"tools":false,"opens":"calendar"},"kit":"calendar"}"#).expect("JSON"); let kit = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton Calendar names a kit"); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "born with the kit's tools"); let read = |path: &str| -> serde_json::Value { serde_json::from_slice(&std::fs::read(cotton_store::manifest_dir().join(path)).expect(path)).expect("JSON") }; let event = read("kits/personal/tables/event.json"); assert_eq!(event["card"]["face"], "event.rolodex", "Calendar keeps the event's face"); let mut wanted: Vec = ["event", "event_attendee", "record_group", "group_member", "media", "photo", "face_settings", "vault_key"].map(str::to_string).to_vec(); for column in event["columns"].as_array().expect("columns") { if let Some(target) = column["link_to"].as_str().filter(|target| *target != "email_thread") { wanted.push(target.to_string()); } } wanted.sort(); wanted.dedup(); let mut kept = kit.tables.clone(); kept.sort(); assert_eq!(kept, wanted, "the event, its attendees, what it links (project, person), and what every app keeps"); for never in ["email_thread", "meeting", "todo", "note", "thought", "transaction", "book", "song", "film", "message"] { assert!(!kit.keeps_table(never) && !kit.pulled().contains(&never.to_string()), "a Calendar copy never pulls {never}"); } let personal = AppKit::tables_of("personal"); for table in &kit.tables { assert!(personal.contains(table), "the personal kit already lays {table} on every object"); } let personal_kit = read("kits/personal/kit.json"); assert!(personal_kit["tools"].as_array().unwrap().iter().any(|tool| tool.as_str().is_some_and(|tool| tool.rsplit('/').next() == Some("calendar"))), "Cotton keeps Calendar"); let tool = read("kits/personal/tools/calendar/manifest.json"); assert_eq!(tool["views"].as_array().unwrap().iter().map(|view| view["id"].as_str().unwrap()).collect::>(), ["today", "upcoming", "recurring", "all"], "Calendar's views as they are"); assert_eq!(tool["acts"].as_array().unwrap().iter().map(|act| act["id"].as_str().unwrap()).collect::>(), ["google_connect", "google_disconnect"], "Google Calendar connect as it is"); let laid = &kit.acts; assert_eq!(kit.aside, [ACCOUNT_CARD], "Cotton Calendar lays the account acts, on the Account card left of the first"); assert!(tool["views"].as_array().unwrap().iter().any(|view| view["id"] == "today" && view["is_default"] == true), "Today is where the app opens"); assert_eq!(laid.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); } /// RULE (owner, 12 Nov 2026): Cotton Photos keeps to its kit: the one Photos /// tool, born with it, as the personal kit ships it (its views, the print and /// the album's faces), and every table Photos draws: the library (media) and /// the photos and videos it reads, the albums and what they hold, the /// duplicates, sightings and faces the tool names, the person a print or a /// face names, and the lists and face settings every app keeps. The kit is /// drawn from the personal kit and reshapes nothing, so the keep that lays /// the personal kit on an existing object already holds every part of it: /// add-only by construction, and Cotton keeps Photos. The account acts stand /// on the Account card left of the first. #[test] fn cotton_photos_keeps_the_library_and_its_albums() { let manifest = manifest("Flavours/photos/flavour.json"); let kit = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton Photos names a kit"); assert_eq!(kit.tools, ["photos"]); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "born with the kit's tools"); assert_eq!(manifest["fan"]["opens"], "photos", "the fan opens on Photos"); let mut kept = kit.tables.clone(); kept.sort(); assert_eq!(kept, drawn_by(&kit.tools).into_iter().collect::>(), "what Photos draws and what every app keeps"); assert_eq!(kit_file("kits/personal/tables/photo.json")["card"]["face"], "photo.print", "a photo is its print"); assert_eq!(kit_file("kits/personal/tables/album.json")["card"]["face"], "album.carousel", "an album is its slide carousel"); assert_eq!(kit_file("kits/personal/tables/album.json")["card"]["offers"], json!(["album.carousel", "album.board"]), "and the hand still offers its board"); for never in ["thread", "message", "email", "note", "todo", "book", "song", "film", "transaction", "secret", "passkey", "document"] { assert!(!kit.keeps_table(never) && !kit.pulled().contains(&never.to_string()), "a Photos copy never pulls {never}"); } let personal = AppKit::tables_of("personal"); for table in &kit.tables { assert!(personal.contains(table), "the personal kit already lays {table} on every object"); } let personal_kit = kit_file("kits/personal/kit.json"); assert!(personal_kit["tools"].as_array().unwrap().iter().any(|tool| tool == "photos"), "Cotton keeps Photos"); assert_eq!(kit.aside, [ACCOUNT_CARD], "Cotton Photos deals the Account card left of its first card"); assert_eq!(kit.acts.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); } /// RULE (owner, 12 Nov 2026): Cotton Health keeps to its kit: the one Health /// tool, born with it, over the three health tables (the day's numbers, the /// main table; workouts; measurements), with its views in the fan's order /// (Today, where it opens, Trends, Workouts, Sleep, Body) and the vault's /// Devices, so the phone that founds the vault can let another device in; /// the media and face settings every app keeps and the vault's rows a sealed /// app reads. Every health table is sealed from the first build: only its key /// and its day stay clear on the object, and a row is keyed (row_key) so a /// re-read lands on the row it wrote. A reading is read-only: no person edits /// it. A Health copy never pulls a chat, a mail, a note or a journal page. /// The kit names the face its days are to stand in, a pocket pedometer on /// slate, while its cards keep the plain face the app draws today. #[test] fn cotton_health_keeps_its_sealed_readings_and_daily_views() { let manifest = manifest("Flavours/health/flavour.json"); let kit = AppKit::of(Some(&manifest)).expect("reads").expect("Cotton Health names a kit"); assert_eq!(kit.tools, ["health"]); assert_eq!(crate::genesis::GenesisTools::of(Some(&manifest)).expect("reads").0, born_with(&kit), "born with the kit's tools"); assert_eq!(manifest["fan"]["opens"], "health", "the fan opens on Health"); let mut kept = kit.tables.clone(); kept.sort(); assert_eq!(kept, drawn_by(&kit.tools).into_iter().collect::>(), "what Health draws and what every app keeps"); let tool = kit_file("kits/personal/tools/health/manifest.json"); let views: Vec<&str> = tool["views"].as_array().unwrap().iter().map(|view| view["id"].as_str().unwrap()).collect(); assert_eq!(views, ["today", "trends", "workouts", "sleep", "body", "labs", "reports", "people", "devices"]); assert!(tool["views"][0]["is_default"] == true, "Today is where the app opens"); assert_eq!(tool["views"][0]["read"]["where"], serde_json::json!({ "day": { "on": "today" } })); for table in ["health_day", "health_workout", "health_measurement", "lab_report", "lab_result", "health_person"] { let file = kit_file(&format!("kits/personal/tables/{table}.json")); let definition: crate::definitions::TableDefinition = serde_json::from_value(file.clone()).expect("the table reads"); definition.validate().unwrap_or_else(|error| panic!("{table} validates: {error:?}")); let seal = definition.seal.as_ref().unwrap_or_else(|| panic!("{table} is sealed from the first build")); // health_person's link to its person stays sealed (PEOPLE BUILD 1b): the server never learns which of his // people have health records; a merge repoints it on the phone, which reads it. let clear: &[&str] = if table == "health_person" { &["key"] } else { &["key", "day"] }; assert_eq!(seal.clear, clear, "{table}: only the key and the day stay clear"); assert_eq!(definition.row_key.as_deref(), Some("key"), "{table} is keyed"); for column in &definition.columns { if column.key != "key" { assert_eq!(column.readonly, Some(true), "{table}.{} is a reading no person edits", column.key); } if !clear.contains(&column.key.as_str()) { assert!(seal.seals(&column.key), "{table}.{} is sealed", column.key); } } } let day = kit_file("kits/personal/tables/health_day.json"); let metrics: Vec<&str> = day["columns"].as_array().unwrap().iter().find(|column| column["key"] == "metric").unwrap()["choices"].as_array().unwrap().iter().map(|choice| choice.as_str().unwrap()).collect(); assert_eq!(metrics, crate::health::catalog::METRICS.iter().map(|metric| metric.key).collect::>(), "the day's measures are the catalogue's"); let sleep: Vec<&str> = tool["views"][3]["opened"]["where"]["metric"].as_array().unwrap().iter().map(|metric| metric.as_str().unwrap()).collect(); assert!(!sleep.is_empty() && sleep.iter().all(|metric| metric.starts_with("sleep_")), "Sleep reads the night's stages, narrowed on the phone once they open"); // The object orders and narrows a health view by its clear columns alone // (coordinator, 12 Nov 2026): a sealed column stands only in what the // phone does once the rows are open, never in a view's read or sort. let tables: Vec = ["health_day", "health_workout", "health_measurement", "lab_report", "lab_result", "health_person"] .iter().map(|table| serde_json::from_value(kit_file(&format!("kits/personal/tables/{table}.json"))).unwrap()).collect(); for view in tool["views"].as_array().unwrap() { let Some(table) = tables.iter().find(|table| view["read"]["table"] == table.id.as_str()) else { continue }; let clear = |key: &str| !table.seal.as_ref().unwrap().seals(key); let read: Vec<&str> = view["read"]["where"].as_object().map(|filter| filter.keys().map(String::as_str).collect()).unwrap_or_default(); assert!(read.iter().all(|key| clear(key)), "{}: its read narrows by clear columns alone", view["id"]); for slot in ["column", "tie"] { if let Some(key) = view["sort"][slot].as_str() { assert!(clear(key), "{}: its sort.{slot} is clear", view["id"]); } } } let views: Vec = serde_json::from_value(tool["views"].clone()).unwrap(); crate::definitions::tool_views::validate_public_reads(&views, &tables).expect("Health's views stand"); let workout = kit_file("kits/personal/tables/health_workout.json"); let kinds: Vec<&str> = workout["columns"].as_array().unwrap().iter().find(|column| column["key"] == "kind").unwrap()["choices"].as_array().unwrap().iter().map(|choice| choice.as_str().unwrap()).collect(); for (_, kind) in crate::health::catalog::WORKOUT_KINDS { assert!(kinds.contains(kind), "a {kind} workout is a choice"); } for never in ["thread", "message", "email", "note", "journal_entry", "todo", "secret"] { assert!(!kit.keeps_table(never) && !kit.pulled().contains(&never.to_string()), "a Health copy never pulls {never}"); } // Labs keep records for the owner's family too, each a `person` the // whole database shares (owner, 20 Nov 2026): Health keeps person. assert!(kit.keeps_table("person"), "every report and result names its person"); let personal = AppKit::tables_of("personal"); for table in &kit.tables { assert!(personal.contains(table), "the personal kit lays {table} on every object"); } let personal_kit = kit_file("kits/personal/kit.json"); assert!(personal_kit["tools"].as_array().unwrap().iter().any(|tool| tool == "health"), "Cotton keeps Health"); assert_eq!(kit.aside, [ACCOUNT_CARD], "Cotton Health deals the Account card left of its first card"); assert_eq!(kit.acts.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); let face = kit.face.expect("the kit names the face it is to stand in"); assert_eq!((face.id.as_str(), face.ground.as_str()), ("health.pedometer", "slate")); } /// RULE (Cotton Story contract, 17 Nov 2026): Cotton Story keeps to its kit: /// the one Story tool over its five fresh tables — the story (`story_story`, /// for `story` is Social's), its scenes, characters, places and notes — with /// the views in the contract's order: Script, Scenes (where it opens), /// Characters, Places, Notes, Stories; the Account card left of them. Every /// view but Stories shows the current story's rows alone (`current`: the /// story most lately chosen). All five are sealed: links, order, status and /// the worked-out figures stay clear, every word a person writes is sealed. /// Nothing in it is named screenplay. Its samples are one short invented /// story of five scenes, four characters, three places and two notes, and a /// tiny second story whose speech is in Telugu, each row naming its sample /// story. #[test] fn cotton_story_keeps_its_stories_and_views_on_the_current_one() { let kit = AppKit::named("story").expect("Cotton Story names a kit"); assert_eq!(kit.tools, ["story"]); let mut kept = kit.tables.clone(); kept.sort(); assert_eq!(kept, drawn_by(&kit.tools).into_iter().collect::>(), "what Story draws and what every app keeps"); let tool = kit_file("kits/personal/tools/story/manifest.json"); let views: Vec<&str> = tool["views"].as_array().unwrap().iter().map(|view| view["id"].as_str().unwrap()).collect(); assert_eq!(views, ["script", "scenes", "characters", "places", "notes", "stories"]); let default: Vec<&str> = tool["views"].as_array().unwrap().iter().filter(|view| view["is_default"] == true).map(|view| view["id"].as_str().unwrap()).collect(); assert_eq!(default, ["scenes"], "Story opens on its scenes"); for view in tool["views"].as_array().unwrap() { let current = &view["current"]; if view["id"] == "stories" { assert!(current.is_null(), "Stories lists every story"); } else { assert_eq!(*current, serde_json::json!({ "column": "story", "by": "chosen_at" }), "{} shows the current story", view["id"]); } } for (file, clear) in [ ("story_story", vec!["language", "translation_of", "format", "made_at", "chosen_at", "scenes", "pages", "interval_at"]), ("story_scene", vec!["story", "position", "setting", "place", "status", "words", "pages", "minutes", "answer", "day"]), ("story_character", vec!["story", "picture", "scenes", "lines", "tint"]), ("story_place", vec!["story", "scenes", "picture"]), ("story_note", vec!["story", "scene"]), ("story_line", vec!["story", "scene", "position", "character"]), ("story_answer", vec!["story", "skipped", "answered_at"]), ("story_sequence", vec!["story", "position", "folded"]), ("story_picture", vec!["story", "picture", "position", "character", "place", "scene", "costume", "thing", "day"]), ("story_thing", vec!["story", "kind", "picture"]), ("story_costume", vec!["story", "character", "day", "picture"]), ("story_use", vec!["story", "scene", "thing", "costume", "character"]), ("story_draft", vec!["story", "made_at", "scenes", "pages"]), ] { let raw = kit_file(&format!("kits/personal/tables/{file}.json")); let definition: crate::definitions::TableDefinition = serde_json::from_value(raw).expect("the table reads"); definition.validate().expect("the table validates"); let seal = definition.seal.as_ref().expect("sealed from the first build"); assert_eq!(seal.clear, clear, "{file}'s clear columns"); if file != "story_story" { let story = definition.columns.iter().find(|column| column.key == "story").expect("each names its story"); assert_eq!((story.link_to.as_deref(), story.required), (Some("story_story"), Some(true))); } } for id in &kit.tables { assert!(!id.contains("screenplay"), "nothing new is named screenplay: {id}"); } assert_eq!(kit.aside, [ACCOUNT_CARD]); assert_eq!(kit.acts.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); let rows = |table: &str| kit_file(&format!("kits/personal/tools/story/records/{table}.json")).as_array().unwrap().clone(); let stories = rows("story_story"); assert_eq!(stories.len(), 2); let of_first = |table: &str| rows(table).iter().filter(|row| row["story"] == "sample:story_story#0").count(); assert_eq!((of_first("story_scene"), of_first("story_character"), of_first("story_place"), of_first("story_note")), (5, 4, 3, 2)); let telugu = rows("story_scene").iter().any(|row| row["story"] == "sample:story_story#1" && row["body"].as_str().unwrap().chars().any(|c| ('\u{0C00}'..='\u{0C7F}').contains(&c))); assert!(telugu, "the second story speaks Telugu"); let samples: std::collections::BTreeMap> = ["story_story", "story_scene", "story_character", "story_place", "story_note"].iter().map(|table| (table.to_string(), rows(table))).collect(); let order: Vec<&str> = crate::definitions::package::sample_order(&samples).into_iter().map(|(table, _)| table.as_str()).collect(); assert_eq!(order, ["story_story", "story_character", "story_place", "story_scene", "story_note"], "a story before what it holds, a scene before the note on it"); } /// RULE (voice plan, 17 Nov 2026): Cotton Meetings keeps to its kit: the one /// Meetings tool over three fresh tables, the recording (`meetings_meeting`, /// for `meeting` holds the Mac era's rows, kept as they are), its voices /// (`meetings_speaker`) and its words (`meetings_line`), with the views /// Recent (where it opens), Meetings, Memos and On this phone, lists before /// the last; and the actions a meeting said /// (`meetings_action`) with the todos Add to todos makes. All are sealed: /// links, times, states and the worked-out counts stay clear; what was said, /// the title, the summary, an action's words and a speaker's name are sealed /// and found by blind tokens. A meeting is a row from the /// first second (status recording); a recording's audio here is this /// device's to say, never a stored value. #[test] fn cotton_meetings_keeps_its_recordings_their_voices_and_words() { let kit = AppKit::named("meetings").expect("Cotton Meetings names a kit"); assert_eq!(kit.tools, ["meetings"]); let tool = kit_file("kits/personal/tools/meetings/manifest.json"); let views: Vec<&str> = tool["views"].as_array().unwrap().iter().map(|view| view["id"].as_str().unwrap()).collect(); assert_eq!(views, ["recent", "meetings", "memos", "on_phone"]); let default: Vec<&str> = tool["views"].as_array().unwrap().iter().filter(|view| view["is_default"] == true).map(|view| view["id"].as_str().unwrap()).collect(); assert_eq!(default, ["recent"], "Meetings opens on the latest recordings"); for table in ["meetings_meeting", "meetings_speaker", "meetings_line", "meetings_action", "todo", "record_group", "group_member"] { assert!(kit.tables.iter().any(|kept| kept == table), "Meetings keeps {table}"); } for (file, blind) in [ ("meetings_meeting", vec!["title", "summary"]), ("meetings_speaker", vec!["name"]), ("meetings_line", vec!["text"]), ("meetings_action", vec!["words"]), ] { let raw = kit_file(&format!("kits/personal/tables/{file}.json")); let definition: crate::definitions::TableDefinition = serde_json::from_value(raw).expect("the table reads"); definition.validate().expect("the table validates"); let seal = definition.seal.as_ref().expect("sealed from the first build"); assert_eq!(seal.blind, blind, "{file}'s words are sealed and found blind"); if file != "meetings_meeting" { let meeting = definition.columns.iter().find(|column| column.key == "meeting").expect("each names its meeting"); assert_eq!((meeting.link_to.as_deref(), meeting.required), (Some("meetings_meeting"), Some(true))); } } let meeting = kit_file("kits/personal/tables/meetings_meeting.json"); let status = meeting["columns"].as_array().unwrap().iter().find(|column| column["key"] == "status").unwrap(); assert_eq!(status["choices"], serde_json::json!(["recording", "waiting", "transcribing", "ready", "failed"])); assert_eq!(status["default"], "recording", "a recording is a row from the first second"); assert!(crate::definitions::is_device_answered_column("meetings_meeting", "on_phone")); assert_eq!(kit.aside, [ACCOUNT_CARD]); assert_eq!(kit.acts.iter().map(|act| act.id.as_str()).collect::>(), ACCOUNT_ACTS); } fn manifest_tools(path: &str) -> Vec { manifest(path)["tools"].as_array().into_iter().flatten().filter_map(serde_json::Value::as_str).map(str::to_string).collect() } /// RULE (owner, 11 Nov 2026): a kit of several tools lays its acts over its /// first, the one its app opens on, and over no other: Cotton Developer's /// Sign in is Memories', standing on the Account card (11 Nov 2026), never /// Machines' or Artifacts'. #[test] fn a_kit_of_several_tools_lays_its_acts_over_the_first() { let kit = AppKit::named("developer").expect("the developer kit ships"); let definition = |id: &str| -> crate::definitions::ToolDefinition { serde_json::from_value(kit_file(&format!("kits/personal/tools/{id}/manifest.json"))).expect("a shipped tool reads") }; let mut tools = vec![definition("agents"), definition("memories")]; kit.lay_acts(&mut tools); let acts = |tool: &crate::definitions::ToolDefinition| tool.acts.iter().map(|act| act.id.clone()).collect::>(); assert_eq!(acts(&tools[1]), ACCOUNT_ACTS); assert!(tools[1].views.iter().all(|view| view.acts.iter().all(|act| !act.starts_with("account_"))), "no deck's view names them: they stand on the Account card"); assert!(acts(&tools[0]).iter().all(|act| !act.starts_with("account_")), "Agents offers no account"); } /// RULE (owner, 11 Nov 2026): in Cotton People, Birthdays is no tool of its /// own: its views, Birthday wishes and Everyone, each with its birthday face /// and slip as Birthdays draws them, stand on People after People's own (All /// first, the fan's centre card, still the one default), on the person /// table's People that the phone draws, and Birthdays leaves the tools the /// app draws. Any other kit draws the definitions as stored: Notes folds /// nothing, and Cotton (no kit) keeps Birthdays its own tool. #[test] fn cotton_people_draws_birthdays_as_peoples_views() { let kit = AppKit::named("people").expect("the people kit ships"); let person = crate::kit::table("person").expect("the person table ships"); let shipped = |id: &str| crate::kit::package(id).expect(id).expect("decodes").package.tool; let birthdays = shipped("birthdays"); let mut tables = vec![person.clone()]; let mut tools = vec![shipped("people"), birthdays.clone()]; kit.fold(&mut tables, &mut tools); assert_eq!(tools.iter().map(|tool| tool.id.as_str()).collect::>(), ["people"], "Birthdays is drawn as no tool"); let views = &tables[0].tool.as_ref().expect("the person heads People").views; let own: Vec<&str> = person.tool.as_ref().unwrap().views.iter().map(|view| view.id.as_str()).collect(); assert_eq!(&views.iter().map(|view| view.id.as_str()).collect::>()[..own.len()], own.as_slice(), "People's own views first, as they are"); assert_eq!(views[0].id, "all", "All is the fan's centre card"); assert_eq!(views.iter().filter(|view| view.is_default).map(|view| view.id.as_str()).collect::>(), ["all"], "All is still the one default"); for wanted in &birthdays.views { let laid = views.iter().find(|view| view.id == wanted.id).unwrap_or_else(|| panic!("People draws {}", wanted.id)); assert_eq!((&laid.label, &laid.read, &laid.card, &laid.slip, &laid.sort), (&wanted.label, &wanted.read, &wanted.card, &wanted.slip, &wanted.sort), "{} as Birthdays draws it", wanted.id); } assert!(views.iter().any(|view| view.card.as_ref().is_some_and(|card| card.face.as_str() == "birthday")), "the birthday face comes with them"); crate::definitions::tool_views::validate(views).expect("People's views, folded, are views"); let (stored_tables, stored_tools) = (vec![person.clone()], vec![shipped("people"), birthdays.clone()]); assert_eq!(kit.unfolded("people/wishes", &stored_tables, &stored_tools), Some(Unfolded::Named("birthdays/wishes".into())), "a folded view reads as Birthdays reads it"); assert_eq!(kit.unfolded("people/all", &stored_tables, &stored_tools), None, "People's own views are People's"); assert_eq!(AppKit::named("notes").unwrap().unfolded("people/wishes", &stored_tables, &stored_tools), None); let mut stored = vec![person.clone()]; let mut whole = vec![shipped("people"), birthdays.clone()]; AppKit::named("notes").expect("notes").fold(&mut stored, &mut whole); assert_eq!((stored[0].clone(), whole.len()), (person, 2), "a kit that folds nothing draws the definitions as stored"); } /// RULE (owner, 11 Nov 2026: "the fan menu is just views, and a view can be /// of a specific tool"): a Cotton app draws every tool its kit lists as views /// of its first, in kit order. A tool that declares no view is one view of /// its home table under its own name; a view whose id is taken is /// `__`; two tools' views under one name each say whose they are, /// the tool's name where the view is the one the tool opens on, else the /// tool's name with it. The stored tools stay as they are. #[test] fn a_cotton_app_draws_every_kit_tool_as_views_of_its_first() { // A personal kit tool, or a business package a kit carries (Developer's Feedback). let shipped = |id: &str| match crate::kit::package(id) { Some(package) => package.expect("decodes").package.tool, None => crate::toolkits::kit_packages().iter().find(|package| package.tool.id == id).expect(id).tool.clone(), }; let said = |kit: &str, heads: &[&str]| -> Vec<(String, String, Option)> { let kit = AppKit::named(kit).expect("the kit ships"); let ids: Vec<&str> = kit.tools.iter().map(String::as_str).collect(); let mut tables: Vec<_> = heads.iter().map(|id| crate::kit::table(id).expect("the table ships")).collect(); let mut tools: Vec<_> = ids.iter().map(|id| shipped(id)).collect(); kit.fold(&mut tables, &mut tools); assert_eq!(tools.iter().map(|tool| tool.id.as_str()).collect::>(), [ids[0]], "the other tools are drawn as no tool"); let views = tables.iter().filter_map(|table| table.tool.as_ref().filter(|home| home.key.as_deref().unwrap_or(&table.id) == ids[0])).find(|home| !home.views.is_empty()).map(|home| home.views.clone()).unwrap_or_else(|| tools[0].views.clone()); crate::definitions::tool_views::validate(&views).expect("folded, they are views"); assert_eq!(views.iter().filter(|view| view.is_default).count(), 1, "one default, the first tool's"); views.iter().filter(|view| view.partition.is_none()).map(|view| (view.id.clone(), view.label.clone(), view.read.get("table").and_then(|table| table.as_str()).map(str::to_string))).collect() }; let row = |id: &str, label: &str, table: &str| (id.to_string(), label.to_string(), Some(table.to_string())); // Subscriptions declares no view: one view of its table, under its name, after Money's own. let money = said("money", &[]); assert_eq!(money.first(), Some(&row("past", "Past", "transaction"))); assert_eq!(money.last(), Some(&row("subscriptions", "Subscriptions", "subscription"))); // Keys and Passwords both open on All: each says whose it is by its tool's name. let keys = said("keys", &["secret"]); assert!(keys.contains(&row("all", "Keys", "passkey")), "{keys:?}"); assert!(keys.contains(&row("passwords__all", "Passwords", "secret")), "{keys:?}"); assert!(keys.contains(&row("codes", "Codes", "secret")) && keys.contains(&row("health", "Health", "secret")), "{keys:?}"); assert!(keys.contains(&row("logins", "Logins", "secret")), "{keys:?}"); // Developer: Memories opens on All; Agents has one view. let developer = said("developer", &[]); assert_eq!(developer.iter().map(|(id, label, _)| (id.as_str(), label.as_str())).collect::>(), [("all", "Memories"), ("archived", "Archived"), ("agents", "Agents"), ("new", "New"), ("replied", "Replied"), ("fixed", "Fixed"), ("app_reports__all", "Feedback All")]); let stored: Vec<_> = ["keys", "passwords"].iter().map(|id| shipped(id)).collect(); let tables = vec![crate::kit::table("secret").expect("ships")]; let kit = AppKit::named("keys").unwrap(); assert_eq!(kit.unfolded("keys/passwords__all", &tables, &stored), Some(Unfolded::Named("passwords/all".into()))); assert_eq!(kit.unfolded("keys/logins", &tables, &stored), Some(Unfolded::Named("passwords/logins".into()))); assert_eq!(kit.unfolded("keys/all", &tables, &stored), None, "Keys' own"); let money = AppKit::named("money").unwrap(); let stored: Vec<_> = ["money", "subscriptions"].iter().map(|id| shipped(id)).collect(); assert_eq!(money.unfolded("money/subscriptions", &[], &stored), Some(Unfolded::Whole), "a tool with no view is its table whole"); } /// RULE (Developer Dev, 12 Nov 2026: a fresh install's fan was unreadable, Artifacts' Made for you read the document table the copy did not hold): for every app kit, each view of each tool it holds reads a table the kit lists — or one its kit leaves to another app, which the app never deals (`AppKit::deals_view`) — and every table a dealt view reads is carried by one of the kit's own tool packages, so a copy started on the phone before sign-in, which holds its tools' packages alone, holds it too. #[test] fn every_kit_view_reads_a_table_its_kit_lists_and_its_copy_holds() { let mut checked = 0; for (id, _) in APP_KITS.iter() { let Some(kit) = AppKit::named(id) else { continue }; let packages: Vec<&crate::definitions::package::ImportedPackage> = kit.held().iter() .filter(|tool| super::ids().contains(&tool.as_str())) .map(|tool| decoded(tool).expect("a kit tool").expect("the package decodes")).collect(); let tables: Vec = packages.iter().flat_map(|package| package.package.tables.iter().cloned()).collect(); let carried: Vec<&str> = tables.iter().map(|table| table.id.as_str()).collect(); for package in &packages { let tool = &package.package.tool; for view in AppKit::views_of(tool, &tables) { let Some(table) = view.read.get("table").and_then(serde_json::Value::as_str).filter(|table| !table.is_empty()) else { continue }; assert!(shipped_table(table).is_some(), "kits/{id}: {}/{} reads {table}, which no kit table defines", tool.id, view.id); if !kit.deals_view(Some(table)) { continue; } assert!(kit.tables.iter().any(|listed| listed == table) || crate::kit::shell::SHELL_KIT_TABLES.iter().any(|(shell, _)| *shell == table), "kits/{id}: {}/{} reads {table}, which the kit does not list", tool.id, view.id); assert!(carried.contains(&table) || crate::kit::shell::SHELL_KIT_TABLES.iter().any(|(shell, _)| *shell == table), "kits/{id}: {}/{} reads {table}, which none of the kit's tool packages carries: a copy started before sign-in would not hold it", tool.id, view.id); checked += 1; } } } assert!(checked > 0, "no kit view was read"); } /// Every kit table, read through the kit as the phone reads it. fn every_kit_table() -> Vec { let dir = cotton_store::manifest_dir().join("kits/personal/tables"); let mut ids: Vec = std::fs::read_dir(dir).expect("the kit's tables").filter_map(|e| e.ok()?.path().file_stem()?.to_str().map(str::to_string)).collect(); ids.sort(); let dir = cotton_store::manifest_dir().join("kits/personal/tables"); ids.iter().map(|id| serde_json::from_slice(&std::fs::read(dir.join(format!("{id}.json"))).unwrap()).unwrap_or_else(|e| panic!("{id} reads: {e}"))).collect() } // RULE (Send, owner 13 Nov 2026): a send shape is sound across the whole kit // (what `with` and `carry` name in other tables included); the book, highlight, // list, note, recipe, person, song, album and film tables declare one, so the // rule is proven generic; a table of secrets never does. A table sealed on // the object may (ruling R5: the sender's device lays the send from its plain // copy and seals it to the receiver). #[test] fn the_kits_send_shapes_hold_across_the_kit() { let tables = every_kit_table(); let shapes: cotton_rules::send::Tables = tables.iter().map(|t| (t.id.clone(), t.send_shape())).collect(); for table in &tables { cotton_rules::send::validate(&table.id, &shapes).unwrap_or_else(|r| panic!("{}", r.words)); if table.sealed == Some(true) { assert!(table.send.is_none(), "{} keeps secrets and declares a send shape", table.id); } } for id in ["book", "highlight", "record_group", "note", "person", "song", "music_album", "film", "todo", "journal_entry", "photo", "message"] { assert!(cotton_rules::send::sendable(id, &shapes).is_ok(), "{id} is sendable"); } // A message and a photo are sent sealed to the receiver (R5); mail, health and secrets never. for id in ["email", "health_measurement", "secret", "thread"] { assert!(cotton_rules::send::sendable(id, &shapes).is_err(), "{id} is never sendable"); } let book = tables.iter().find(|t| t.id == "book").unwrap().send.clone().unwrap(); for own in ["status", "rating", "review", "position", "progress", "started_on", "finished_on", "read_count", "on_phone", "added_on"] { assert!(!book.columns.iter().any(|c| c == own), "a book never sends {own}"); } } /// RULE (15 Nov 2026): a core built for one kit carries only /// that kit's pictures, so it serves that kit's app alone: another app's /// manifest, or Cotton's whole object, is refused at the door, never drawn /// with blanks. The whole core serves every app. This build is a whole one. #[test] fn a_kits_core_serves_that_kit_alone() { assert_eq!(super::CORE_KIT, None, "tests build the whole core"); for named in [None, Some("books"), Some("money")] { assert_eq!(super::core_serves(None, named), Ok(())); } assert_eq!(super::core_serves(Some("books"), Some("books")), Ok(())); let other = super::core_serves(Some("books"), Some("money")).expect_err("Money on the Books core"); assert!(other.contains("\"books\"") && other.contains("\"money\""), "{other}"); let whole = super::core_serves(Some("books"), None).expect_err("Cotton on the Books core"); assert!(whole.contains("the whole object"), "{whole}"); } // RULE (R5): sealing a table on the object never stops its // records being sent (the device lays the send from its plain copy and seals // it to the receiver); a table of secrets is never sent. #[test] fn a_table_sealed_on_the_object_may_send_and_a_table_of_secrets_never_does() { let mut note = every_kit_table().into_iter().find(|t| t.id == "note").expect("the note table"); note.seal = Some(crate::definitions::SealSpec { clear: vec!["archived_at".into(), "trashed_at".into(), "updated_at".into(), "project_id".into()], ..Default::default() }); assert!(!note.send_refused()); let shapes: cotton_rules::send::Tables = [(note.id.clone(), note.send_shape())].into(); assert!(cotton_rules::send::sendable("note", &shapes).is_ok(), "a note sealed on the object is sendable"); note.sealed = Some(true); assert!(note.send_refused()); let shapes: cotton_rules::send::Tables = [(note.id.clone(), note.send_shape())].into(); assert!(cotton_rules::send::sendable("note", &shapes).is_err(), "a table of secrets is never sendable"); } /// RULE (MAIL ALL ON PHONE, 24 Nov 2026; COMMS WITHOUT MAIL, fbda68018f): a manifest switch keeps windowed tables /// whole, and names only a table its kit windows. No shipped kit windows a table since Comms let go of mail, so the /// switch is refused on every kit, and the copy mark with it is held to what it was: off as before, on naming the /// tables (a window set on the kit here, as a kit that windows one would). #[test] fn the_all_history_switch_drops_the_windows_it_names_and_marks_the_copy() { let manifest = json!({"kit": "messages"}); let off = AppKit::of(Some(&manifest)).expect("reads").expect("a kit"); assert!(off.windows().is_empty(), "Comms windows nothing now: {:?}", off.windows()); assert_eq!(AppKit::copy_mark(Some(&off)), format!("messages {}", off.pulled().join(",")), "off, the mark is as it was"); assert!(AppKit::of(Some(&json!({"kit": "messages", "all_history": ["email", "email_thread"]}))).is_err(), "Comms keeps no window of mail to switch off"); assert!(AppKit::of(Some(&json!({"kit": "messages", "all_history": ["message"]}))).is_err(), "a table with no window is refused"); let mut on = off.clone(); on.window.insert("message".into(), 90); on.all_history = vec!["message".into()]; assert!(on.windows().get("message").is_none(), "on, the table has no window"); let mark = AppKit::copy_mark(Some(&on)); assert_eq!(mark, format!("messages {} all:message", on.pulled().join(","))); assert_eq!(AppKit::read_copy_mark(&mark), ("messages".to_string(), on.pulled(), vec!["message".to_string()])); assert_eq!(AppKit::read_copy_mark("messages a,b"), ("messages".to_string(), vec!["a".to_string(), "b".to_string()], vec![])); } /// RULE (PEOPLE BUILD 1, C7): every app downloads the owner's contacts (`person`, `person_handle`, sealed), so every /// app names a number by who holds it, and never shows a bare number where his contacts know the name. #[test] fn every_app_pulls_the_contacts_that_name_a_number() { let mut checked = 0; for entry in std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/kits")).expect("the kits") { let id = entry.expect("an entry").file_name().to_string_lossy().to_string(); let Some(kit) = AppKit::named(&id) else { continue }; for table in ["person", "person_handle", "shared_handle"] { assert!(kit.keeps_table(table) && kit.pulled().contains(&table.to_string()), "{id} pulls {table}"); } checked += 1; } assert!(checked >= 10, "the apps were read: {checked}"); } /// RULE (PEOPLE BUILD 1b): the contacts every app pulls to name a number change no look: an app whose own kit does not /// list them deals no view over them and opens no link to them; an app that lists them still does. #[test] fn the_contacts_every_app_pulls_are_shown_only_where_they_were() { let books = AppKit::named("books").expect("books"); assert!(books.keeps_table("person") && books.pulled().contains(&"person".to_string())); assert!(!books.deals_view(Some("person")) && !books.deals_table("person_handle") && !books.deals_table("shared_handle")); let people = AppKit::named("people").expect("people"); assert!(people.deals_view(Some("person")) && people.deals_table("person_handle")); }