Cotton code
151 lines · 8.0 KB · RustRaw
//! The personal kit's tables as the object serves them, read the way a//! phone reads what it is served (`cotton-client`'s `drawable_tables`): one//! definition per table — the face the phone draws for every table it draws,//! none for a storage-only one, which is kept as rows and drawn nowhere.use cotton_core::definitions::TableDefinition;use serde_json::{json, Value};/// The tables the kit lists (its kit.json), which the object serves, in id/// order: only files listed by the kit are served.fn kit_tables() -> Vec<(String, String)> {    let kit = cotton_store::manifest_dir().join("kits/personal");    let listed: Value = serde_json::from_str(&std::fs::read_to_string(kit.join("kit.json")).expect("the personal kit")).unwrap();    let mut ids: Vec<String> = listed["tables"].as_array().expect("the kit lists its tables").iter().map(|id| id.as_str().unwrap().to_string()).collect();    ids.sort();    ids.into_iter().map(|id| {        let json = std::fs::read_to_string(kit.join("tables").join(format!("{id}.json"))).unwrap_or_else(|_| panic!("kits/personal/tables/{id}.json"));        (id, json)    }).collect()}fn read(json: &str) -> TableDefinition {    let definition = TableDefinition::from_json(json).unwrap_or_else(|error| panic!("reads: {error}"));    definition.validate().unwrap_or_else(|error| panic!("{} validates: {error}", definition.id));    definition}/// RULE (owner, 26 Oct 2026): every table the object serves reads on the/// phone — visibility `owner` is the personal database's own rows, and a/// table is never refused for having no face.#[test]fn every_personal_kit_table_reads_as_served() {    let tables = kit_tables();    assert!(tables.len() >= 117, "the kit's tables: {}", tables.len());    let mut faced = Vec::new();    for (file, json) in &tables {        let definition = read(json);        assert_eq!(&definition.id, file);        if definition.id == "media" {            // Photos now serves its engine's union as a kit definition. It            // owns no rows; its tool views carry owner visibility.            assert!(definition.physical_tables().unwrap().is_empty());            assert_eq!(definition.visibility, None);            assert!(definition.tool.as_ref().unwrap().views.iter()                .all(|view| view.visibility == "owner"));        } else {            assert_eq!(definition.visibility.as_deref(), Some("owner"), "{file}");        }        // A table kept by an engine names the one this build compiles there.        if let Some(engine) = &definition.engine {            assert!(definition.has_engine(), "{file} names {engine}, which this build keeps it under");        }        if definition.has_face() {            faced.push(file.as_str());        }    }    // The tables the owner's life.db drew that TABLE DROP kept, and the kit    // tables of Books and Films (meeting and mood were erased, 28 Nov 2026).    assert!(faced.len() >= 80, "faced: {}", faced.len());    for drawn in ["session", "todo", "note", "book", "film"] {        assert!(faced.contains(&drawn), "{drawn} has a face");    }}/// RULE: a storage-only table reads and says it has no face; the phone keeps/// its rows — in the table this build compiles for it (`storage.json`), else/// in the one its columns make — and draws nothing.#[test]fn a_storage_only_table_reads_with_no_face_and_keeps_its_rows() {    let compiled: Vec<Value> = serde_json::from_str(cotton_core::toolkits::PERSONAL_STORAGE).unwrap();    let compiled: Vec<&str> = compiled.iter().filter_map(|entry| entry["table"].as_str()).collect();    let mut made = Vec::new();    for (file, json) in kit_tables() {        let definition = read(&json);        if definition.has_face() {            continue;        }        assert!(definition.engine.is_none(), "{file}: a faceless table is data");        if compiled.contains(&file.as_str()) || ["secret", "device"].contains(&file.as_str()) {            continue;        }        made.push(file.clone());        let storage = definition.physical_tables().unwrap_or_else(|error| panic!("{file} derives its storage: {error}"));        assert_eq!(storage.len(), 1, "{file}");        assert_eq!(storage[0].name, format!("cotton_{file}"));        for column in &definition.columns {            assert!(storage[0].columns.iter().any(|c| c.name == column.key), "{file}.{} is kept", column.key);        }    }    assert_eq!(made, ["assistant_ask", "assistant_read", "email_account", "email_bin_cut", "email_cut", "email_draft", "email_read_cut", "face_settings", "group_origin", "handle_label", "mail_history", "mcp_token", "oauth_client", "oauth_code", "oauth_refresh", "outbox", "person_fact", "person_key", "person_pair", "person_state", "seal_key", "sender_merge", "site", "unlock_grant", "unlock_request", "voice_settings"]);    let participant: Value = json!({        "format_version": 1, "id": "email_participant", "name": "Email participant", "plural": "Email participants",        "visibility": "owner",        "columns": [{"key": "email_id", "type": "text"}, {"key": "address", "type": "text"}]    });    let definition = read(&participant.to_string());    assert!(!definition.has_face());    assert!(!definition.builtin);    assert_eq!(serde_json::to_value(&definition).unwrap().get("slip"), None, "no slip is said back");    // What a faceless table says of dates, projects and order is never    // drawn, so it is never what refuses it: the object's message table    // dates its rows by a text column, and the phone still keeps them.    let messages: Value = json!({        "format_version": 1, "id": "business_message", "name": "Message", "plural": "Messages", "builtin": true,        "visibility": "mine(person)", "date": "at",        "columns": [            {"key": "name", "type": "text", "required": true},            {"key": "person", "type": "link", "link_to": "person", "required": true},            {"key": "at", "type": "text", "required": true}        ]    });    let definition = read(&messages.to_string());    assert!(!definition.has_face());    assert_eq!(definition.date.as_deref(), Some("at"));}/// RULE: a built-in row that leaves its face out still draws the shipped one;/// a made table never takes a built-in's face by sharing its id.#[test]fn a_reduced_built_in_row_takes_the_shipped_face_and_a_made_one_does_not() {    let reduced = json!({"id": "todo", "name": "Todo", "plural": "Todos", "builtin": true, "engine": "todos", "columns": [{"key": "title", "type": "text"}]});    let definition = TableDefinition::from_json(&reduced.to_string()).expect("reads");    assert!(definition.has_face(), "the shipped todo's face");    let made = json!({"id": "todo", "name": "Todo", "plural": "Todos", "columns": [{"key": "title", "type": "text"}]});    let definition = TableDefinition::from_json(&made.to_string()).expect("reads");    assert!(!definition.has_face(), "a made row says its own face, here none");}/// RULE: `owner` is a visibility: the personal database's own rows.#[test]fn owner_is_a_visibility_and_a_stray_word_is_still_refused() {    use cotton_core::definitions::visibility::Visibility;    assert_eq!(Visibility::parse(Some("owner")), Ok(Visibility::Owner));    assert!(Visibility::parse(Some("everyone")).is_err());}/// RULE (owner, 25 Oct 2026, #77): memory has no review state, so a memory's/// card carries no state stamp (it said Unreviewed on every one). The card is/// the `memory` table's, the one the assistants write (2 Nov 2026), drawn on/// the memory face: its title, its body and the day it was written.#[test]fn a_memorys_card_carries_no_state_stamp() {    let (_, json) = kit_tables().into_iter().find(|(file, _)| file == "memory").expect("the memory table");    let definition: Value = serde_json::from_str(&json).unwrap();    assert_eq!(definition["card"]["face"], "memory");    let slots: Vec<(&str, &str)> = definition["card"]["fields"].as_array().unwrap().iter().filter_map(|field| Some((field["slot"].as_str()?, field["column"].as_str()?))).collect();    assert_eq!(slots, [("title", "title"), ("body", "body"), ("date", "created_at")]);    read(&json);}