Cotton code
1045 lines · 67.9 KB · RustRaw
//! Cotton Data on a phone over a fake object that keeps the routes CONTRACT.md//! "The Worker" names, holding invented rows sealed with the phone's own data//! key, as the real object holds them. Every name, title and number invented.use std::collections::HashMap;use std::io::Read;use std::sync::{Arc, Mutex};use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::wire::Origin;use cotton_client::transport::{http1::Http1Request, Answer, Exchange};use serde_json::{json, Map, Value};use super::call;use crate::handle::CottonHandle;use crate::phone::passwords::tests::phone;use crate::phone::personal_object::ObjectDoor;fn defs() -> Vec<Value> {    vec![        json!({ "id": "book", "name": "Book", "plural": "Books", "title": "title", "date": "bought_on",            "columns": [                { "key": "title", "type": "text" }, { "key": "author", "type": "link", "link_to": "person" },                { "key": "format", "type": "choice", "choices": ["hardback", "paperback"] }, { "key": "bought_on", "type": "date" },                { "key": "shop", "type": "url" }, { "key": "cover", "type": "photo" }, { "key": "notes", "type": "longtext" }            ],            "slip": { "title": "title", "subtitle": "author", "trailing": "format" } }),        json!({ "id": "person", "name": "Person", "plural": "People", "title": "name", "columns": [{ "key": "name", "type": "text" }], "slip": { "title": "name" } }),        json!({ "id": "memory", "name": "Memory", "plural": "Memories", "title": "text", "columns": [{ "key": "text", "type": "text" }, { "key": "project", "type": "link", "link_to": "project" }], "slip": { "title": "text" } }),        json!({ "id": "project", "name": "Project", "plural": "Projects", "title": "name", "columns": [{ "key": "name", "type": "text" }], "slip": { "title": "name" } }),        json!({ "id": "device", "name": "Device", "plural": "Devices", "title": "name", "internal": true, "columns": [{ "key": "name", "type": "text" }], "slip": { "title": "name" } }),        json!({ "id": "screenplay", "name": "Screenplay", "plural": "Screenplays", "title": "title", "columns": [{ "key": "title", "type": "text" }], "slip": { "title": "title" } }),        json!({ "id": "kite_log", "name": "Kite log", "plural": "Kite logs", "title": "word", "columns": [{ "key": "word", "type": "text" }], "slip": { "title": "word" } }),        json!({ "id": "secret", "name": "Secret", "plural": "Secrets", "title": "name", "columns": [{ "key": "name", "type": "text" }, { "key": "value", "type": "text", "secret": true }], "slip": { "title": "name", "subtitle": "value" } }),    ]}/// The fake object: rows by table, each `(id, created_at, open data)`, sealed as they are served.#[derive(Default)]struct Object {    rows: HashMap<String, Vec<(String, String, Map<String, Value>)>>,    measured: bool,    /// Before the first measure: Some(true) answers the counts alone (`row_counts` ready: rows, no room), Some(false)    /// answers no table at all (the server still counting), as `tables()` in apps/business/src/data_routes.ts.    counted: Option<bool>,    asked: Mutex<Vec<String>>,    /// A server deployed before the `/v1/data/*` routes: each answers 404 as the Worker does.    older_server: bool,    /// Tables this object defines beside `defs()` (Cinemas' family, for HIDDEN).    more_defs: Vec<Value>,    /// What points at a film, by its id (`/v1/data/points?table=film`).    film_points: HashMap<String, Vec<Value>>,    /// A table whose pages the object fails to answer (500).    failing: Option<String>,}struct Door {    object: Arc<Object>,    sealer: Arc<cotton_client::seal::Sealer>,}impl std::fmt::Debug for Door {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str("Door")    }}impl Door {    fn sealed(&self, table: &str, id: &str, made: &str, row: &Map<String, Value>) -> Value {        let def = defs().into_iter().chain(self.object.more_defs.clone()).find(|d| d["id"] == json!(table)).unwrap();        let spec = match cotton_core::data::seal_of(&def) {            cotton_core::data::Seal::Sealed { clear } => cotton_core::definitions::seal::SealSpec { clear, blind: cotton_core::kit::shipped_table(table).and_then(|d| serde_json::to_value(d).ok()).and_then(|d| cotton_client::seal::spec_of_definition(&d).ok().flatten()).map(|s| s.blind).unwrap_or_default(), ..Default::default() },            _ => return json!({ "table": table, "id": id, "data": row, "created_at": made, "updated_at": made }),        };        let sealed = self.sealer.seal(table, id, &spec, row, None).expect("an invented row seals");        json!({ "table": table, "id": id, "data": sealed.data, "version": 1, "created_at": made, "updated_at": made })    }    fn route(&self, path: &str) -> (u16, Value) {        self.object.asked.lock().unwrap().push(path.to_string());        let (path, query) = path.split_once('?').unwrap_or((path, ""));        let path = &path[path.find("/v1/").unwrap_or(0)..];        let q: HashMap<String, String> = url::form_urlencoded::parse(query.as_bytes()).into_owned().collect();        let rows_of = |t: &str| self.object.rows.get(t).cloned().unwrap_or_default();        if self.object.older_server && path.starts_with("/v1/data/") {            return (404, json!({ "code": "not_found", "message": format!("nothing answers GET {path}") }));        }        match path {            "/v1/definitions" => (200, json!({ "tables": defs().into_iter().chain(self.object.more_defs.clone()).collect::<Vec<_>>() })),            "/v1/data/tables" if self.object.measured => (200, json!({                "database": { "bytes": 6_540_000_000u64, "cap": 9_500_000_000u64 },                "measured": { "at": "2026-11-25T09:00:00Z" },                // The file's parts as the Worker measures them (apps/business/src/storage_parts.ts): each store table                // and index with the bytes its entries carry.                "parts": { "file": 6_540_000_000u64, "carried": 5_812_000_000u64, "overhead": 728_000_000u64, "parts": [                    { "name": "change", "kind": "table", "entries": 99_930, "bytes": 2_700_000_000u64 },                    { "name": "rows", "kind": "table", "entries": 120_000, "bytes": 1_420_000_000u64 },                    { "name": "blind_rid", "kind": "table", "entries": 30_000_000, "bytes": 830_000_000u64 },                    { "name": "blind", "kind": "table", "entries": 34_600_000, "bytes": 550_000_000u64 },                    { "name": "change_at", "kind": "index", "of": "change", "entries": 99_930, "bytes": 160_000_000u64 },                    { "name": "rows_table_made", "kind": "index", "of": "rows", "entries": 120_000, "bytes": 100_000_000u64 },                    { "name": "links", "kind": "table", "entries": 400_000, "bytes": 50_000_000u64 },                    { "name": "definitions", "kind": "table", "entries": 300, "bytes": 2_000_000u64 }                ] },                "tables": [                    { "table": "book", "rows": 412, "tombstones": 9, "bytes": 2_100_000, "oldest": "2019-03-03T10:00:00Z", "newest": "2026-11-24T10:00:00Z" },                    { "table": "person", "rows": 2311, "tombstones": 0, "bytes": 3_200_000, "oldest": "2018-01-01T10:00:00Z", "newest": "2026-11-20T10:00:00Z" },                    { "table": "memory", "rows": 2904, "tombstones": 0, "bytes": 64_000_000, "oldest": "2026-01-01T10:00:00Z", "newest": "2026-11-25T10:00:00Z" },                    { "table": "kite_log", "rows": 1204, "tombstones": 0, "bytes": 1_100_000, "oldest": "2022-01-01T10:00:00Z", "newest": "2023-04-01T10:00:00Z" },                    { "table": "screenplay", "rows": 3, "tombstones": 0, "bytes": 40_000, "oldest": null, "newest": null }                ]            })),            "/v1/data/tables" if self.object.counted.is_some() => (200, json!({                "database": { "bytes": 4_300_000_000u64, "cap": 9_500_000_000u64 },                "measured": null,                "parts": null,                "tables": if self.object.counted == Some(true) { json!([                    { "table": "book", "rows": 412, "tombstones": null, "bytes": null, "oldest": null, "newest": null },                    { "table": "person", "rows": 2311, "tombstones": null, "bytes": null, "oldest": null, "newest": null }                ]) } else { json!([]) },                "measuring": { "since": "2026-11-25T16:49:58Z", "done": 0.13 }            })),            "/v1/data/page" if self.object.failing.is_some() && q.get("table") == self.object.failing.as_ref() => (500, json!({ "code": "internal", "message": "the object failed" })),            "/v1/data/page" => {                let t = q.get("table").cloned().unwrap_or_default();                let mut rows = rows_of(&t);                rows.sort_by(|a, b| b.1.cmp(&a.1));                // The made range as the Worker keeps it: from inclusive, to exclusive.                rows.retain(|(_, made, _)| q.get("from").is_none_or(|f| made.as_str() >= f.as_str()) && q.get("to").is_none_or(|t| made.as_str() < t.as_str()));                let served: Vec<Value> = rows.iter().map(|(id, made, data)| self.sealed(&t, id, made, data)).collect();                (200, json!({ "table": t, "order": q.get("order").cloned().unwrap_or_else(|| "made".into()), "rows": served, "more": false }))            }            "/v1/data/years" => {                let t = q.get("table").cloned().unwrap_or_default();                let mut years: std::collections::BTreeMap<String, u64> = Default::default();                for (_, made, _) in rows_of(&t) {                    *years.entry(made[..4].to_string()).or_default() += 1;                }                let years: Vec<Value> = years.into_iter().rev().map(|(y, n)| json!({ "year": y.parse::<u64>().unwrap(), "rows": n })).collect();                (200, json!({ "table": t, "years": years }))            }            // The blind index, as the Worker answers it with rows: here every row of the table (the phone keeps only            // the rows that truly hold the words, `blind::row_match`).            "/v1/blind" => {                let t = q.get("table").cloned().unwrap_or_default();                let served: Vec<Value> = rows_of(&t).iter().map(|(id, made, data)| self.sealed(&t, id, made, data)).collect();                (200, json!({ "rows": served }))            }            "/v1/rows" => {                let t = q.get("table").cloned().unwrap_or_default();                let ids: Vec<String> = q.get("ids").map(|s| s.split(',').map(str::to_string).collect()).unwrap_or_default();                let served: Vec<Value> = rows_of(&t).iter().filter(|(id, _, _)| ids.contains(id)).map(|(id, made, data)| self.sealed(&t, id, made, data)).collect();                (200, json!({ "table": t, "rows": served }))            }            "/v1/data/points" if q.get("table").map(String::as_str) == Some("film") => (200, json!({ "points": self.object.film_points.get(q.get("id").map(String::as_str).unwrap_or_default()).cloned().unwrap_or_default() })),            "/v1/data/points" if q.get("table").map(String::as_str) == Some("person") => (200, json!({ "points": [{ "table": "book", "column": "author", "count": 1, "ids": ["b1"] }] })),            "/v1/data/points" => (200, json!({ "points": [] })),            "/v1/data/changes" if q.get("who").map(String::as_str) == Some("assistants") && q.contains_key("table") => (200, json!({ "changes": [], "more": false })),            "/v1/data/changes" if q.get("who").map(String::as_str) == Some("apps") => (200, json!({ "changes": [                { "id": 4, "at": "2026-11-25T08:00:00Z", "actor": "Asha", "actor_kind": "app", "via": "seal", "table": "watch", "record": "w1", "kind": "update" },                { "id": 3, "at": "2026-11-25T08:00:00Z", "actor": "Asha", "actor_kind": "app", "via": "seal", "table": "watch", "record": "w2", "kind": "update" }            ], "more": false })),            "/v1/data/changes" => (200, json!({ "changes": [                { "id": 9, "at": "2026-11-25T10:12:00Z", "actor": "Claude", "actor_kind": "assistant", "via": "remember", "table": "memory", "record": "m3", "kind": "insert" },                { "id": 8, "at": "2026-11-25T10:11:00Z", "actor": "Claude", "actor_kind": "assistant", "via": "remember", "table": "memory", "record": "m2", "kind": "insert" },                { "id": 7, "at": "2026-11-25T10:10:00Z", "actor": "Claude", "actor_kind": "assistant", "via": "remember", "table": "memory", "record": "m1", "kind": "insert" },                { "id": 6, "at": "2026-11-25T09:30:00Z", "actor": "Asha", "actor_kind": "person", "via": "event.move", "table": "event", "record": "e1", "kind": "update" },                // A phone's own state on its device row, written in his name every few minutes.                { "id": 61, "at": "2026-11-25T09:20:00Z", "actor": "Asha", "actor_kind": "person", "via": "update", "table": "device", "record": "d1", "kind": "update" },                { "id": 60, "at": "2026-11-25T09:15:00Z", "actor": "Asha", "actor_kind": "person", "via": "update", "table": "device", "record": "d1", "kind": "update" },                { "id": 5, "at": "2026-11-24T19:40:00Z", "actor": "ChatGPT", "actor_kind": "assistant", "via": "create_record", "table": "note", "record": "n1", "kind": "insert" }            ], "more": false })),            "/v1/data/leftovers" => (200, json!({ "retired": [], "dangling": [{ "table": "note", "column": "notebook", "target": "notebook", "count": 11 }] })),            _ => (404, json!({ "code": "not_found", "message": "no such route" })),        }    }}struct Answered {    status: u16,    body: std::io::Cursor<Vec<u8>>,}impl Read for Answered {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        self.body.read(buf)    }}impl Answer for Answered {    fn status(&self) -> u16 {        self.status    }    fn header(&self, name: &str) -> Option<String> {        name.eq_ignore_ascii_case("content-type").then(|| "application/json".into())    }    fn content_length(&self) -> Option<u64> {        Some(self.body.get_ref().len() as u64)    }    fn set_read_timeout(&mut self, _: std::time::Duration) -> std::io::Result<()> {        Ok(())    }}impl Exchange for Door {    fn send(&self, _: &Origin, request: &Http1Request<'_>, _: std::time::Duration) -> Result<Box<dyn Answer>, String> {        let (status, answer) = self.route(request.path);        Ok(Box::new(Answered { status, body: std::io::Cursor::new(answer.to_string().into_bytes()) }))    }    fn send_stream(&self, origin: &Origin, request: &Http1Request<'_>, body: &mut dyn Read, length: u64, ceiling: std::time::Duration) -> Result<Box<dyn Answer>, String> {        let mut bytes = Vec::new();        body.take(length).read_to_end(&mut bytes).map_err(|e| e.to_string())?;        self.send(origin, &Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request }, ceiling)    }}fn row(v: Value) -> Map<String, Value> {    v.as_object().cloned().unwrap()}fn invented() -> Object {    let mut o = Object { measured: true, ..Default::default() };    o.rows.insert("book".into(), vec![        ("b1".into(), "2026-10-03T12:42:00Z".into(), row(json!({ "title": "The Salt Monsoon", "author": "p1", "format": "paperback", "bought_on": "2026-10-03", "shop": "https://www.kitabkhana.example.in/b/salt-monsoon", "cover": "db/photos/abc.jpg", "notes": "one\ntwo\nthree\nfour" }))),        ("b2".into(), "2026-11-21T09:00:00Z".into(), row(json!({ "title": "Lantern Street", "author": "p2", "format": "hardback" }))),    ]);    o.rows.insert("person".into(), vec![("p1".into(), "2026-10-03T12:40:00Z".into(), row(json!({ "name": "Meera Joshi" }))), ("p2".into(), "2026-11-21T08:00:00Z".into(), row(json!({ "name": "Kofi Mensah" })))]);    o.rows.insert("secret".into(), vec![("s1".into(), "2026-11-01T08:00:00Z".into(), row(json!({ "name": "Stripe test key", "value": "sk_test_INVENTED_4f2a" })))]);    o}fn on(object: Object) -> (tempfile::TempDir, CottonHandle, Arc<Object>) {    on_with(object, true)}/// A phone on the fake object; `key_here` false is a new phone whose key has not arrived (the object's rows stay sealed).fn on_with(object: Object, key_here: bool) -> (tempfile::TempDir, CottonHandle, Arc<Object>) {    on_phone(object, key_here, phone())}/// A phone whose copy holds Cinemas' tables, so a film can be laid in it as a pass lays one.fn cinemas_phone() -> (tempfile::TempDir, CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let manifest = json!({ "genesis": "personal", "flavour": "cinemas", "name": "Cotton Cinemas", "ground": "velvet", "databases": "single", "database": "personal", "fan": { "home": false, "tools": false, "opens": "cinemas" }, "kit": "cinemas" });    let handle = CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started");    (dir, handle)}fn on_phone(object: Object, key_here: bool, (dir, handle): (tempfile::TempDir, CottonHandle)) -> (tempfile::TempDir, CottonHandle, Arc<Object>) {    let client = handle.client();    let mut bytes = [0u8; 32];    rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut bytes);    let database = client.current_database().unwrap();    let held = cotton_client::seal::HeldDataKeys::new();    held.hold(&database, &cotton_core::seal::DataKey::from_bytes(bytes));    if key_here {        client.data_keys().hold(&database, &cotton_core::seal::DataKey::from_bytes(bytes));    }    let keys: Arc<dyn cotton_client::seal::DataKeyStore> = held;    let sealer = cotton_client::seal::Sealer::new(database, keys);    sealer.learned_all();    let object = Arc::new(object);    let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").unwrap(), exchange: Arc::new(Door { object: object.clone(), sealer }), credential: "ctd_11111111-1111-4111-8111-111111111111_test-credential".into() };    client.set_object_door(Some(Arc::new(door)));    (dir, handle, object)}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    call(&handle.client(), method, &request).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message))}#[test]fn tables_are_grouped_by_app_with_rows_and_room() {    let (_d, handle, _) = on(invented());    let t = ask(&handle, "data.tables", json!({}));    assert_eq!(t["count"], json!(8));    assert_eq!(t["room"]["line"], json!("6.5 GB of 9.5 GB"));    let titles: Vec<&str> = t["groups"].as_array().unwrap().iter().filter_map(|g| g["title"].as_str()).collect();    assert!(titles.contains(&"Assistants"), "{titles:?}");    assert!(titles.contains(&"Cotton itself"), "{titles:?}");    let all: Vec<&Value> = t["groups"].as_array().unwrap().iter().flat_map(|g| g["tables"].as_array().unwrap()).collect();    let book = all.iter().find(|l| l["table"] == json!("book")).unwrap();    assert_eq!(book["rows_line"], json!("412 rows"));    assert_eq!(book["room_line"], json!("2.1 MB"));    let memory = all.iter().find(|l| l["table"] == json!("memory")).unwrap();    assert_eq!(memory["mark"], json!("server_reads"), "memory is still read by the server");    // Measured, a table with no row says so alone: no "0 bytes" beside it.    let empty = all.iter().find(|l| l["rows_line"] == json!("No rows")).expect("a table with no row");    assert!(empty["room_line"].is_null(), "{empty}");    assert!(all.iter().all(|l| l["table"] != json!("kite_log") && l["table"] != json!("screenplay")), "leftovers are their own line");    assert_eq!(t["leftovers"]["line"], json!("2 tables no app uses, 1 of them retired"));    assert_eq!(t["foot"], json!("Still read by the server. Every other table is sealed."));    let biggest = ask(&handle, "data.tables", json!({ "by": "biggest" }));    assert_eq!(biggest["groups"][0]["tables"][0]["table"], json!("memory"));    let found = ask(&handle, "data.tables", json!({ "q": "boo" }));    assert_eq!(found["groups"].as_array().unwrap().iter().flat_map(|g| g["tables"].as_array().unwrap()).count(), 1);}#[test]fn counting_is_said_until_the_object_has_measured() {    let (_d, handle, _) = on(Object { measured: false, ..invented() });    let t = ask(&handle, "data.tables", json!({}));    let first = &t["groups"][0]["tables"][0];    assert_eq!(first["rows_line"], json!("Counting…"));    assert!(t["room"].is_null());}/// The owner's find of 26 Nov: right after sign-in, with the server's first measure still under way, a table with no/// row read "No rows · 0 bytes". Its rows are known from the counts; its room is not, so none is said.#[test]fn before_the_first_measure_no_room_is_said_and_counting_is_said_until_counted() {    let (_d, handle, _) = on(Object { measured: false, counted: Some(true), ..invented() });    let t = ask(&handle, "data.tables", json!({}));    let all: Vec<&Value> = t["groups"].as_array().unwrap().iter().flat_map(|g| g["tables"].as_array().unwrap()).collect();    let book = all.iter().find(|l| l["table"] == json!("book")).unwrap();    assert_eq!(book["rows_line"], json!("412 rows"));    assert!(book["room_line"].is_null(), "{book}");    let memory = all.iter().find(|l| l["table"] == json!("memory")).unwrap();    assert_eq!(memory["rows_line"], json!("No rows"));    assert!(memory["room_line"].is_null(), "no room before a measure: {memory}");    // The server still counting answers no table: every table is Counting…, never No rows.    let (_d2, handle, _) = on(Object { measured: false, counted: Some(false), ..invented() });    let t = ask(&handle, "data.tables", json!({}));    let all: Vec<&Value> = t["groups"].as_array().unwrap().iter().flat_map(|g| g["tables"].as_array().unwrap()).collect();    assert!(!all.is_empty());    assert!(all.iter().all(|l| l["rows_line"] == json!("Counting…")), "{all:?}");}/// A table every app keeps (`media`) would list ten apps after "also": up to three are named, more are two and a count.#[test]fn the_other_apps_beside_a_table_stay_short() {    assert_eq!(super::also_line(&["Words", "Story"]), "also Words and Story");    assert_eq!(super::also_line(&["Words", "Story", "Comms"]), "also Words, Story and Comms");    assert_eq!(super::also_line(&["Words", "Story", "Comms", "Post", "Books", "Cinemas", "Meetings", "Downloads"]), "also Words, Story and 6 more");    let every: Vec<&str> = cotton_core::data::FAMILY.iter().skip(1).map(|(label, _)| *label).collect();    assert_eq!(super::also_line(&every), "also every other app");}#[test]fn a_tables_rows_read_as_sentences_with_links_named() {    let (_d, handle, _) = on(invented());    let r = ask(&handle, "data.rows", json!({ "table": "book" }));    assert_eq!(r["lead"], json!("412 rows · used by Books"), "{}", r["lead"]);    let groups = r["groups"].as_array().unwrap();    assert_eq!(groups[0]["title"], json!("November 2026"));    assert_eq!(groups[0]["rows"][0]["title"], json!("Lantern Street"));    assert_eq!(groups[1]["rows"][0]["title"], json!("The Salt Monsoon"));    let line = groups[1]["rows"][0]["line"].as_str().unwrap();    assert!(line.contains("Meera Joshi"), "the author's name, not its id: {line}");    assert!(r["foot"].as_str().unwrap().contains("author"));}#[test]fn one_row_has_every_field_points_here_and_its_trail() {    let (_d, handle, _) = on(invented());    let r = ask(&handle, "data.row", json!({ "table": "book", "id": "b1" }));    assert_eq!(r["title"], json!("The Salt Monsoon"));    assert!(r["lead"].as_str().unwrap().starts_with("A row in book · made 3 Oct 2026"), "{}", r["lead"]);    let field = |c: &str| r["fields"].as_array().unwrap().iter().find(|f| f["column"] == json!(c)).unwrap().clone();    assert_eq!(field("author")["value_line"], json!("Meera Joshi"));    assert_eq!(field("author")["link"], json!({ "table": "person", "id": "p1" }));    assert_eq!(field("shop")["url"], json!("https://www.kitabkhana.example.in/b/salt-monsoon"));    assert_eq!(field("cover")["media"], json!("db/photos/abc.jpg"));    assert_eq!(field("bought_on")["clear"], json!(true), "the date the table sorts by stays clear");    assert_eq!(field("title")["clear"], json!(false));    assert_eq!(r["trail"], json!([{ "table": "book", "id": "b1", "name": "The Salt Monsoon" }]));    assert_eq!(r["foot"], json!("Read only. This row is changed in Books."));    // Following the author: the trail grows, and the book points here.    let p = ask(&handle, "data.row", json!({ "table": "person", "id": "p1", "trail": r["trail"] }));    assert_eq!(p["trail"].as_array().unwrap().len(), 2);    assert_eq!(p["points_here"][0]["table"], json!("book"));    assert_eq!(p["points_here"][0]["rows"][0]["title"], json!("The Salt Monsoon"));    let stored = ask(&handle, "data.stored", json!({ "table": "book", "id": "b1" }));    assert!(stored["fields"].as_array().unwrap().contains(&json!({ "column": "author", "stored": "p1" })));    let link = ask(&handle, "data.link", json!({ "table": "book", "id": "b1", "column": "shop" }));    assert_eq!(link["site"], json!("www.kitabkhana.example.in"));    assert_eq!(link["from_line"], json!("From shop on The Salt Monsoon"));}#[test]fn a_secret_value_never_reaches_an_answer() {    let (_d, handle, _) = on(invented());    for (method, request) in [("data.rows", json!({ "table": "secret" })), ("data.row", json!({ "table": "secret", "id": "s1" })), ("data.stored", json!({ "table": "secret", "id": "s1" }))] {        let answer = ask(&handle, method, request).to_string();        assert!(!answer.contains("sk_test") && !answer.contains("4f2a"), "{method}: {answer}");    }    let about = ask(&handle, "data.about", json!({ "table": "secret" }));    assert!(about.to_string().contains("No assistant may read it"));}#[test]fn about_columns_links_and_leftovers_say_the_table_plainly() {    let (_d, handle, _) = on(invented());    let a = ask(&handle, "data.about", json!({ "table": "book" }));    assert_eq!(a["title"], json!("About book"));    assert!(a["lead"].as_str().unwrap().starts_with("412 rows, 2.1 MB. Oldest from 3 Mar 2019"), "{}", a["lead"]);    assert_eq!(a["facts"][0]["title"], json!("Sealed"));    assert!(a["facts"][0]["line"].as_str().unwrap().contains("bought_on"));    assert!(a.to_string().contains("9 deleted rows waiting"));    let c = ask(&handle, "data.columns", json!({ "table": "book" }));    assert!(c["columns"].as_array().unwrap().contains(&json!({ "name": "author", "type_line": "Link to person", "clear": true, "link": "person" })));    let l = ask(&handle, "data.links", json!({ "table": "person" }));    assert_eq!(l["in"][0]["table"], json!("book"));    let left = ask(&handle, "data.leftovers", json!({}));    assert_eq!(left["unused"]["tables"][0]["table"], json!("kite_log"), "mood is retired since TABLE DROP 1: an invented table no app uses");    assert!(left["unused"]["tables"][0]["line"].as_str().unwrap().contains("1,204 rows"));    assert_eq!(left["retired"]["tables"][0]["table"], json!("screenplay"));    assert_eq!(left["dangling"]["items"][0]["line"], json!("11 notes point at a missing notebook"));    assert_eq!(left["foot"], json!("This app only shows them. Nothing here can be erased from it."));}#[test]fn room_and_keep_say_what_it_costs() {    let (_d, handle, _) = on(invented());    let room = ask(&handle, "data.room", json!({}));    assert_eq!(room["lead"], json!("6.5 GB of the 9.5 GB your database may grow to. A warning comes at 80%."));    assert!(room["parts"].as_array().unwrap().iter().any(|p| p["id"] == json!("rows") && p["stays_on_server"] == json!(false)));    // ANDROID READY 1 core fault 6: each part from the server's own measure of the file, never Free alone.    let sizes: Vec<(String, String)> = room["parts"].as_array().unwrap().iter().map(|p| (p["id"].as_str().unwrap().to_string(), p["size_line"].as_str().unwrap().to_string())).collect();    let size = |id: &str| sizes.iter().find(|(i, _)| i == id).map(|(_, s)| s.clone()).unwrap_or_else(|| panic!("no {id} part: {sizes:?}"));    assert_eq!(size("changes"), "2.9 GB", "the change log and its index");    assert_eq!(size("rows"), "1.4 GB");    assert_eq!(size("search"), "1.4 GB", "both blind tables");    assert_eq!(size("links"), "150 MB", "links and the rows' order");    assert_eq!(size("other"), "730 MB", "the rest of the file");    let keep = ask(&handle, "data.keep", json!({ "free": 41_000_000_000u64 }));    assert_eq!(keep["on"], json!(true), "room to spare: on by default");    assert_eq!(keep["why_line"], json!("Only your rows come down. History and the server's search index stay on the server, which is why 6.5 GB becomes 4.3 GB."), "the copy keeps the rows and its own search index of them: three times the rows");    let small = ask(&handle, "data.keep", json!({ "free": 3_000_000_000u64 }));    assert_eq!(small["on"], json!(false));    assert!(small["too_small_line"].as_str().unwrap().contains("3 GB free"));    let set = ask(&handle, "data.keep.set", json!({ "on": false, "free": 41_000_000_000u64 }));    assert_eq!(set["on"], json!(false), "his choice stands over the default");}#[test]fn sort_and_dates_say_what_the_server_can_order_and_pick() {    let (_d, handle, object) = on(invented());    handle.client().pin_clock(chrono::DateTime::parse_from_rfc3339("2026-11-25T12:00:00Z").unwrap().with_timezone(&chrono::Utc));    let d = ask(&handle, "data.dates", json!({ "table": "book" }));    assert_eq!(d["sorts"][0]["id"], json!("made"));    assert_eq!(d["sorts"][0]["on"], json!(true));    assert_eq!(d["sorts"][1]["title"], json!("Recently changed"));    assert_eq!(d["columns"].as_array().unwrap().len(), 1, "made alone: other dates may be sealed");    assert_eq!(d["years"], json!([{ "year": 2026, "rows": 2, "rows_line": "2 rows", "share": 1.0 }]));    let ids: Vec<&str> = d["ranges"].as_array().unwrap().iter().filter_map(|r| r["id"].as_str()).collect();    assert_eq!(ids, ["any", "month", "2026", "pick"]);    assert_eq!(d["ranges"][1]["from"], json!("2026-11-01"));    // The sheet's button counts what it would show where that is known: any time is the table's measure, a year its bar.    assert_eq!(d["show"], json!("Show 412 rows"));    let y = ask(&handle, "data.dates", json!({ "table": "book", "from": "2026-01-01", "to": "2026-12-31" }));    assert_eq!(y["show"], json!("Show 2 rows"));    assert_eq!(ask(&handle, "data.dates", json!({ "table": "book", "from": "2026-11-01" }))["show"], Value::Null);    // This month, passed back as the sheet gave it: November's book only, and the line says so.    let r = ask(&handle, "data.rows", json!({ "table": "book", "from": "2026-11-01" }));    assert_eq!(r["date_line"], json!("This month"));    let titles: Vec<&str> = r["groups"].as_array().unwrap().iter().flat_map(|g| g["rows"].as_array().unwrap()).filter_map(|r| r["title"].as_str()).collect();    assert_eq!(titles, ["Lantern Street"]);    assert!(object.asked.lock().unwrap().iter().any(|p| p.contains("from=2026-11-01T00%3A00%3A00.000Z") || p.contains("from=2026-11-01T00:00:00.000Z")), "{:?}", object.asked.lock().unwrap());    // A picked day is kept whole; a year reads as the year.    let r = ask(&handle, "data.rows", json!({ "table": "book", "from": "2026-01-01", "to": "2026-12-31" }));    assert_eq!(r["date_line"], json!("2026"));    let r = ask(&handle, "data.rows", json!({ "table": "book", "sort": "changed" }));    assert_eq!(r["sort"], json!("changed"));    assert_eq!(r["sort_line"], json!("Recently changed"));    assert!(object.asked.lock().unwrap().iter().any(|p| p.contains("order=changed")));    // A sort the server can't keep is refused in words, never drawn unsorted.    let why = call(&handle.client(), "data.rows", &json!({ "table": "book", "sort": "title" })).unwrap_err();    assert_eq!(why.code, "no_sort");    assert!(why.message.contains("sealed"));}#[test]fn export_writes_one_table_opened_and_never_a_secret() {    let (_d, handle, _) = on(invented());    let plan = ask(&handle, "data.export.plan", json!({ "table": "book" }));    assert_eq!(plan["options"][0]["as"], json!("csv"));    assert_eq!(plan["not_sealed"], json!("The file is not sealed"));    assert_eq!(plan["lead"], json!("All 412 rows, opened, as one file."));    let csv = ask(&handle, "data.export", json!({ "table": "book", "as": "csv" }));    assert_eq!(csv["rows"], json!(2));    let text = std::fs::read_to_string(csv["path"].as_str().unwrap()).unwrap();    let mut lines = text.lines();    assert!(lines.next().unwrap().starts_with("id,created_at,updated_at,"));    assert!(text.contains("The Salt Monsoon"), "opened, not sealed: {text}");    assert!(text.contains("\"one\ntwo\nthree\nfour\""), "a cell with new lines is quoted whole");    let json_file = ask(&handle, "data.export", json!({ "table": "book", "as": "json" }));    let doc: Value = serde_json::from_slice(&std::fs::read(json_file["path"].as_str().unwrap()).unwrap()).unwrap();    assert_eq!(doc["rows"].as_array().unwrap().len(), 2);    assert!(doc["rows"].as_array().unwrap().iter().any(|r| r["author"] == json!("p1")), "links kept as ids");    assert!(!std::path::Path::new(csv["path"].as_str().unwrap()).exists(), "one Data export is kept, the earlier removed");    let why = call(&handle.client(), "data.export", &json!({ "table": "secret", "as": "json" })).unwrap_err();    assert_eq!(why.code, "secret");    let (_d2, keyless, _) = on_with(invented(), false);    assert_eq!(call(&keyless.client(), "data.export.plan", &json!({ "table": "book" })).unwrap_err().code, "no_key");    // About offers Export only where it may be made: never for a Secrets table, nor a sealed one without the key.    let has_export = |h: &CottonHandle, table: &str| ask(h, "data.about", json!({ "table": table }))["rows"].as_array().unwrap().iter().any(|r| r["id"] == json!("export"));    assert!(has_export(&handle, "book"));    assert!(!has_export(&handle, "secret"));    assert!(!has_export(&keyless, "book"));}#[test]fn lately_says_each_run_of_writes_as_one_line() {    let (_d, handle, _) = on(invented());    // The invented change log is of 24 and 25 Nov 2026: read it on the 25th, not by the wall clock.    handle.client().pin_clock(chrono::DateTime::parse_from_rfc3339("2026-11-25T12:00:00Z").unwrap().with_timezone(&chrono::Utc));    let l = ask(&handle, "data.lately", json!({}));    let days = l["days"].as_array().unwrap();    assert_eq!(days[0]["title"], json!("Today"));    assert_eq!(days[0]["items"][0]["line"], json!("Claude added 3 rows to memory"));    assert_eq!(days[0]["items"][1]["line"], json!("You changed a row in event"));    // ANDROID READY 1 core fault 10: a phone's own device-row writes are Cotton's, never "You changed 2 rows in device".    assert_eq!(days[0]["items"][2]["line"], json!("Cotton itself changed 2 rows in device"));    assert_eq!(days[0]["count_line"], json!("6 changes"));    let you = ask(&handle, "data.lately", json!({ "who": "you" }));    assert!(!you.to_string().contains("in device"), "under You, a device's own writes are left out: {you}");    assert_eq!(days[1]["title"], json!("Yesterday"));    assert_eq!(days[1]["items"][0]["line"], json!("ChatGPT added a row to note"));    assert_eq!(l["foot"], json!("Changes are kept for 90 days. Which phone made a change isn't recorded."));    assert!(l["empty"].is_null());    // A machine's write is Cotton's own, never said as the person it was done for.    let apps = ask(&handle, "data.lately", json!({ "who": "apps" }));    assert_eq!(apps["days"][0]["items"][0]["line"], json!("Cotton itself changed 2 rows in watch"));    // Nothing for a filter is said for that filter.    let none = ask(&handle, "data.lately", json!({ "who": "assistants", "table": "watch" }));    assert_eq!(none["days"], json!([]));    assert_eq!(none["empty"], json!("No assistant has changed anything in the last 90 days."));}#[test]fn a_phone_without_the_key_sees_only_what_the_server_sees() {    let (_d, handle, _) = on_with(invented(), false);    let r = ask(&handle, "data.rows", json!({ "table": "book" }));    assert_eq!(r["sealed_view"], json!(true));    assert_eq!(r["locked"]["title"], json!("Locked"));    let rows = r["rows"].as_array().unwrap();    assert_eq!(rows.len(), 2);    let salt = rows.iter().find(|r| r["id"] == json!("b1")).unwrap();    assert_eq!(salt["made_line"], json!("Made 3 Oct 2026"));    assert!(salt["clear_line"].as_str().unwrap().contains("bought_on 2026-10-03"), "{}", salt["clear_line"]);    assert_eq!(salt["points_line"], json!("links to a person"));    let text = r.to_string();    assert!(!text.contains("Salt Monsoon") && !text.contains("paperback"), "nothing sealed is said: {text}");}#[test]fn one_sealed_row_without_the_key_is_said_in_the_servers_facts() {    let (_d, handle, _) = on_with(invented(), false);    let r = ask(&handle, "data.row", json!({ "table": "book", "id": "b1" }));    assert_eq!(r["sealed_view"], json!(true), "{r}");    assert_eq!(r["band"]["title"], json!("This phone doesn't have your key yet"));    let fact = |label: &str| r["facts"].as_array().unwrap().iter().find(|f| f["label"] == json!(label)).map(|f| f["value"].as_str().unwrap().to_string());    assert_eq!(fact("Table").as_deref(), Some("book"));    assert_eq!(fact("Row").as_deref(), Some("b1"));    assert_eq!(fact("Made").as_deref(), Some("3 Oct 2026"));    assert!(fact("Clear fields").unwrap().contains("bought_on 2026-10-03"), "{r}");    assert_eq!(fact("Points at").as_deref(), Some("links to a person"));    assert_eq!(r["acts"][1]["title"], json!("Use a recovery code"));    let text = r.to_string();    assert!(!text.contains("Salt Monsoon") && !text.contains("paperback"), "nothing sealed is said: {text}");}#[test]fn a_picture_is_named_with_where_it_came_from() {    let (_d, handle, _) = on(invented());    let m = ask(&handle, "data.media", json!({ "table": "book", "id": "b1", "column": "cover" }));    assert_eq!(m["name"], json!("abc.jpg"));    assert_eq!(m["key"], json!("db/photos/abc.jpg"));    assert_eq!(m["from_line"], json!("cover on The Salt Monsoon"));}#[test]fn a_server_without_the_data_routes_is_said_in_words() {    let (_d, handle, _) = on(Object { older_server: true, ..invented() });    let why = call(&handle.client(), "data.lately", &json!({})).unwrap_err();    assert_eq!(why.message, "Your database's server doesn't answer this yet. It will after its next update.");    assert!(!why.message.contains("nothing answers"));}#[test]fn keep_says_its_state_and_a_keyless_phone_is_told_how_to_unlock() {    let (_d, handle, _) = on(invented());    let k = ask(&handle, "data.keep.set", json!({ "on": true, "free": 50_000_000_000u64 }));    assert_eq!(k["state"], json!("waiting_wifi"));    assert_eq!(k["state_line"], json!("Waiting for Wi-Fi to start filling."));    assert_eq!(k["acts"][0]["method"], json!("data.keep.mobile_once"));    // Started (its whole copy begun, as a Wi-Fi connect marks it) on a phone holding a few KB of the rows' 1.4 GB:    // filling, with how far and how long.    let path = handle.client().layout().root().join("data-keep.json");    std::fs::write(&path, r#"{"on":true,"started":true}"#).unwrap();    let k = ask(&handle, "data.keep", json!({ "free": 50_000_000_000u64 }));    assert_eq!(k["state"], json!("filling"), "{k}");    assert_eq!(k["state_line"], json!("Filling this phone, 0%"));    assert_eq!(k["progress"]["left_line"], json!("About 2 hours left"), "1.4 GB of rows at the measured 0.21 MB a second");    // The first filling answer marks where the fill was first seen, so later answers pace it (the Tables strip asks    // data.keep as Keep's own page does: on the seeded account it said "About 24 minutes left" for 40 minutes).    let kept: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();    assert!(kept["began"].is_i64() && kept["began_percent"] == json!(0), "{kept}");    // A start above where the fill stands now is taken again, so the minutes left can follow the pace.    std::fs::write(&path, r#"{"on":true,"started":true,"began":1,"began_percent":85}"#).unwrap();    ask(&handle, "data.keep", json!({ "free": 50_000_000_000u64 }));    let kept: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();    assert_eq!(kept["began_percent"], json!(0), "{kept}");    assert!(kept["began"].as_i64().unwrap() > 1, "{kept}");    assert_eq!(k["acts"][0]["method"], json!("data.keep.pause"));    // Pause: the state says so, the copy's pulls stop (the room guard answers a reason), Carry on lets them go.    let k = ask(&handle, "data.keep.pause", json!({ "free": 50_000_000_000u64 }));    assert_eq!(k["state"], json!("paused"), "{k}");    assert_eq!(k["state_line"], json!("Paused at 0%. Everything already here works. Carry on when you're ready."));    assert_eq!(k["acts"][0]["method"], json!("data.keep.resume"));    let guard = crate::phone::data_app::room_guard(handle.client().layout().root().to_path_buf());    assert!(guard().is_some_and(|why| why.starts_with("paused")));    let k = ask(&handle, "data.keep.resume", json!({ "free": 50_000_000_000u64 }));    assert_eq!(k["state"], json!("filling"), "{k}");    assert!(!guard().is_some_and(|why| why.starts_with("paused")));    // Mobile data once starts a fill that waited for Wi-Fi.    std::fs::write(&path, r#"{"on":true}"#).unwrap();    let k = ask(&handle, "data.keep.mobile_once", json!({ "free": 50_000_000_000u64 }));    assert_eq!(k["state"], json!("filling"), "{k}");    assert!(crate::phone::data_app::keeps_everything(handle.client().layout().root(), false));    let (_d2, keyless, _) = on_with(invented(), false);    let r = ask(&keyless, "data.rows", json!({ "table": "book" }));    assert_eq!(r["locked"]["acts"][0]["title"], json!("Approve from your other phone"));    assert!(r["locked"]["no_key_line"].as_str().unwrap().contains("recovery code"));}#[test]fn the_fill_follows_the_sync_pass_and_ends_when_it_has_caught_up() {    use cotton_client::transport::object::PassState;    let rows = 131_000_000;    let pass = |caught_up: bool, done: i64| {        let mut p = PassState::default();        (p.caught_up, p.total, p.done) = (caught_up, Some(14_100), Some(done));        p    };    // Halfway through its rows: half, with the rest's minutes.    let half = pass(false, 7_050);    assert_eq!(super::fill(Some(rows), Some(&half), || 0, |_| 0), Some((50, 6)));    // Caught up: whole, though the copy on the phone (58 MB) is smaller than the server's measure (131 MB).    let whole = pass(true, 14_100);    assert_eq!(super::fill(Some(rows), Some(&whole), || 58_000_000, |_| 0), None);    // Every row counted but a page still to come: 99%, never 100%.    let last = pass(false, 14_100);    assert_eq!(super::fill(Some(rows), Some(&last), || 0, |_| 0).map(|f| f.0), Some(99));    // No pass yet: the copy's size against the rows' room.    assert_eq!(super::fill(Some(rows), None, || 65_500_000, |_| 0), Some((50, 6)));    // A pass carrying the tables from their start over a copy that holds most of them (the owner's build 2: 0% with    // 6 hours left on a full phone): the rows held count, not only the rows this pass has carried.    let again = pass(false, 141);    assert_eq!(super::fill(Some(rows), Some(&again), || 0, |_| 0).map(|f| f.0), Some(1));    assert_eq!(super::fill(Some(rows), Some(&again), || 0, |_| 12_550 - 141).map(|f| f.0), Some(89));}#[test]fn one_letter_names_at_most_thirty_tables_and_columns_and_counts_the_rest() {    // "e" is in nearly every column name of a real database: the phone froze drawing thousands (Data walk, 26 Nov 2026).    let mut names: Vec<Value> = (0..45).map(|i| json!({ "table": "t", "column": format!("e{i}") })).collect();    let (all, more) = super::capped(&mut names);    assert_eq!((all, names.len()), (45, 30));    assert_eq!(more.as_deref(), Some("15 more match. Type more of the name."));    let mut few: Vec<Value> = (0..3).map(|i| json!({ "column": format!("e{i}") })).collect();    assert_eq!(super::capped(&mut few), (3, None));    // The answer carries the count of all beside the names shown.    let (_d, handle, _) = on(invented());    let a = ask(&handle, "data.search", json!({ "q": "e" }));    assert_eq!(a["columns_count"].as_u64().unwrap() as usize, a["columns"].as_array().unwrap().len());    assert!(a["columns_more"].is_null());}#[test]fn rows_are_searched_by_their_words_and_never_in_a_secret_table() {    let (_d, handle, _) = on(invented());    let all = ask(&handle, "data.search", json!({ "q": "monsoon" }));    let groups = all["groups"].as_array().unwrap();    assert_eq!(groups.len(), 1, "{all}");    assert_eq!(groups[0]["table"], json!("book"));    assert_eq!(groups[0]["rows"][0]["title"], json!("The Salt Monsoon"));    assert!(all["searched_line"].as_str().unwrap().contains("on the server"), "{}", all["searched_line"]);    let one = ask(&handle, "data.rows", json!({ "table": "book", "q": "lantern" }));    let rows = one["groups"][0]["rows"].as_array().unwrap();    assert_eq!(rows.len(), 1);    assert_eq!(rows[0]["id"], json!("b2"));    let secret = ask(&handle, "data.search", json!({ "q": "stripe" }));    assert!(!secret.to_string().contains("sk_test") && secret["groups"].as_array().unwrap().is_empty(), "{secret}");    let none = ask(&handle, "data.rows", json!({ "table": "book", "q": "zebra" }));    assert_eq!(none["empty"]["title"], json!("Nothing for \"zebra\""));}#[test]fn offline_is_said_in_words() {    let (_d, handle) = phone();    let refused = call(&handle.client(), "data.rows", &json!({ "table": "book" })).unwrap_err();    assert!(refused.message.contains("can't be reached") || refused.code == "not_attached" || refused.code == "unreadable" || refused.code == "no_table", "{} {}", refused.code, refused.message);}/// Every file under the phone's container, but this device's own Keep choice and SQLite's scratch files.fn snapshot(dir: &std::path::Path) -> Vec<(String, Vec<u8>)> {    let mut out = Vec::new();    let mut stack = vec![dir.to_path_buf()];    while let Some(d) = stack.pop() {        for entry in std::fs::read_dir(&d).into_iter().flatten().flatten() {            let path = entry.path();            let name = path.to_string_lossy().to_string();            if path.is_dir() {                stack.push(path);            } else if !name.ends_with("data-keep.json") && !name.ends_with("-shm") && !name.ends_with("-wal") && !name.ends_with(".lock") {                out.push((name, std::fs::read(&path).unwrap_or_default()));            }        }    }    out.sort();    out}#[test]fn reading_changes_nothing() {    let (dir, handle, object) = on(invented());    // Warm what a first read sets up on its own (the read pool), then take the picture.    let _ = ask(&handle, "data.tables", json!({}));    let before = snapshot(dir.path());    for (method, request) in [        ("data.welcome", json!({ "free": 41_000_000_000u64 })),        ("data.tables", json!({})),        ("data.room", json!({})),        ("data.rows", json!({ "table": "book" })),        ("data.row", json!({ "table": "book", "id": "b1" })),        ("data.stored", json!({ "table": "book", "id": "b1" })),        ("data.link", json!({ "table": "book", "id": "b1", "column": "shop" })),        ("data.about", json!({ "table": "book" })),        ("data.columns", json!({ "table": "book" })),        ("data.links", json!({ "table": "book" })),        ("data.search", json!({ "q": "book" })),        ("data.assistants", json!({})),        ("data.leftovers", json!({})),        ("data.dates", json!({ "table": "book" })),        ("data.rows", json!({ "table": "book", "sort": "changed", "from": "2026-11-01" })),        ("data.keep", json!({})),        ("data.you", json!({})),        ("data.lately", json!({})),        ("data.media", json!({ "table": "book", "id": "b1", "column": "cover" })),    ] {        ask(&handle, method, request);    }    assert_eq!(before, snapshot(dir.path()), "a data.* read wrote to the phone's files");    // And nothing it asked the object was a write.    assert!(object.asked.lock().unwrap().iter().all(|p| p.contains("/v1/data/") || p.contains("/v1/definitions") || p.contains("/v1/rows") || p.contains("/v1/older") || p.contains("/v1/blind")));    // 24: the reads above; Keep everything's four device choices (set, pause, resume, mobile data once), which write    // only this phone's data-keep.json; and Export, which writes only its file in the exports folder. Never the database.    assert_eq!(super::METHODS.len(), 24);}/// Minutes left during a fill come from the pace it has kept: 10% in five minutes leaves 45 for the other 90%.#[test]fn minutes_left_follow_the_fills_own_pace() {    assert_eq!(super::paced_minutes(30_000, 0, 5), None, "under a minute the estimate stands");    assert_eq!(super::paced_minutes(300_000, 20, 20), None, "nothing moved");    assert_eq!(super::paced_minutes(300_000, 0, 10), Some(45));    assert_eq!(super::paced_minutes(120_000, 50, 90), Some(1));}/// Cinemas' family as the kit defines it, with its clear columns, and an invented library. Hidden by the category/// when `categories` (with `marks`, the same rows also carry an older build's `in_hidden`, which hides nothing): Edit Reel Four, Ferry Cut (also in the open Ferries), the/// series Harbour Diaries with its season, its episode Reeds and an episode linked only through its season, and the/// download of Edit Reel Four with its file; the category My edit videos. Open: Night Ferry, a song's download.fn cinemas_library(categories: bool, marks: bool) -> Object {    let hidden = categories;    let mut o = invented();    let mark = |data: Value, marked: bool| {        let mut data = row(data);        if marks && marked {            data.insert("in_hidden".into(), Value::Bool(true));        }        data    };    let mk = |id: &str, plural: &str, title: &str, columns: Value, clear: Value| json!({ "id": id, "name": id, "plural": plural, "title": title, "columns": columns, "seal": { "clear": clear, "blind": [title] }, "slip": { "title": title } });    o.more_defs = vec![        mk("film", "Films", "title", json!([{ "key": "title", "type": "text" }, { "key": "kind", "type": "text" }, { "key": "in_hidden", "type": "bool" }]), json!(["kind"])),        mk("film_season", "Seasons", "title", json!([{ "key": "film", "type": "link", "link_to": "film" }, { "key": "number", "type": "number" }, { "key": "title", "type": "text" }, { "key": "in_hidden", "type": "bool" }]), json!(["film", "number"])),        mk("film_episode", "Episodes", "title", json!([{ "key": "series", "type": "link", "link_to": "film" }, { "key": "season", "type": "link", "link_to": "film_season" }, { "key": "title", "type": "text" }, { "key": "in_hidden", "type": "bool" }]), json!(["series", "season"])),        mk("fetch", "Fetches", "title", json!([{ "key": "title", "type": "text" }, { "key": "in_hidden", "type": "bool" }]), json!([])),        mk("fetch_file", "Fetched files", "name", json!([{ "key": "fetch", "type": "link", "link_to": "fetch" }, { "key": "name", "type": "text" }, { "key": "film", "type": "link", "link_to": "film" }, { "key": "in_hidden", "type": "bool" }]), json!(["fetch", "film"])),        mk("record_group", "Lists", "name", json!([{ "key": "table_id", "type": "text" }, { "key": "name", "type": "text" }, { "key": "hidden", "type": "bool" }]), json!(["table_id"])),        mk("group_member", "List members", "record_id", json!([{ "key": "group", "type": "link", "link_to": "record_group" }, { "key": "record_id", "type": "text" }]), json!(["group", "record_id"])),        mk("watch", "Plays", "film_title", json!([{ "key": "film", "type": "link", "link_to": "film" }, { "key": "episode", "type": "link", "link_to": "film_episode" }, { "key": "film_title", "type": "text" }]), json!(["film", "episode"])),    ];    let at = |n: u32| format!("2026-11-{n:02}T10:00:00Z");    o.rows.insert("film".into(), vec![        ("f1".into(), at(21), mark(json!({ "title": "Edit Reel Four", "kind": "film" }), true)),        ("f2".into(), at(22), mark(json!({ "title": "Ferry Cut", "kind": "film" }), true)),        ("f3".into(), at(23), mark(json!({ "title": "Night Ferry", "kind": "film" }), false)),        ("s1".into(), at(20), mark(json!({ "title": "Harbour Diaries", "kind": "series" }), true)),    ]);    o.rows.insert("film_season".into(), vec![("se1".into(), at(20), mark(json!({ "film": "s1", "number": 1, "title": "Harbour Diaries, season 1" }), true))]);    o.rows.insert("film_episode".into(), vec![        ("e1".into(), at(20), mark(json!({ "series": "s1", "season": "se1", "title": "Reeds" }), true)),        // Linked only through its season (NEXT-HIDDEN3.md 4): marked all the same.        ("e2".into(), at(20), mark(json!({ "season": "se1", "title": "Tidewater" }), true)),        // A new episode a writer that is not updated added: no mark of its own, its series hidden (NEXT-HIDDEN4.md H1).        ("e3".into(), at(26), row(json!({ "series": "s1", "title": "Saltmarsh" }))),    ]);    o.rows.insert("fetch".into(), vec![        ("x1".into(), at(21), mark(json!({ "title": "Edit Reel Four" }), true)),        ("x2".into(), at(21), mark(json!({ "title": "Low Tide" }), false)),    ]);    o.rows.insert("fetch_file".into(), vec![        ("y1".into(), at(21), mark(json!({ "fetch": "x1", "name": "edit-reel-four.mp4", "film": "f1" }), true)),        ("y2".into(), at(21), mark(json!({ "fetch": "x2", "name": "low-tide.m4a" }), false)),    ]);    o.rows.insert("record_group".into(), vec![        ("g1".into(), at(19), row(json!({ "table_id": "film", "name": "My edit videos", "hidden": hidden }))),        ("g2".into(), at(18), row(json!({ "table_id": "film", "name": "Ferries", "hidden": false }))),    ]);    o.rows.insert("group_member".into(), vec![        ("m1".into(), at(19), row(json!({ "group": "g1", "record_id": "f1" }))),        ("m2".into(), at(19), row(json!({ "group": "g1", "record_id": "f2" }))),        ("m3".into(), at(19), row(json!({ "group": "g1", "record_id": "s1" }))),        ("m4".into(), at(18), row(json!({ "group": "g2", "record_id": "f2" }))),        ("m5".into(), at(18), row(json!({ "group": "g2", "record_id": "f3" }))),    ]);    o.rows.insert("watch".into(), vec![        ("w1".into(), at(24), row(json!({ "film": "f1", "film_title": "Edit Reel Four" }))),        ("w2".into(), at(24), row(json!({ "film": "f3", "film_title": "Night Ferry" }))),        // A play naming only its episode (NEXT-HIDDEN3.md 4).        ("w3".into(), at(25), row(json!({ "episode": "e2", "film_title": "Tidewater" }))),    ]);    // What points at Night Ferry: a hidden play beside an open one.    o.film_points.insert("f3".into(), vec![json!({ "table": "watch", "column": "film", "count": 2, "ids": ["w1", "w2"] })]);    o}fn row_ids(answer: &Value) -> Vec<String> {    answer["groups"].as_array().into_iter().flatten().flat_map(|g| g["rows"].as_array().cloned().unwrap_or_default()).filter_map(|r| r["id"].as_str().map(str::to_string)).collect()}const NOTE: &str = "Some rows are hidden in Cinemas. They show here again when you stop hiding them there.";// RULE (HIDDEN, owner via the coordinator, 26 Nov 2026, NEXT-HIDDEN2.md 6 and NEXT-HIDDEN3.md 3, 4, 7, 9): Data reads// what the hidden categories hide (films, seasons, episodes, downloads and their files), and hides a play or a list's link naming a marked title, and a hidden category. Never in a table's// rows, a row, a search (one table or every table), what points at a row, or an export (json or csv); the line says// some are hidden. With nothing hidden, every row and no line.#[test]fn data_leaves_out_what_is_hidden_in_cinemas_and_says_so() {    let (_d, handle, _) = on(cinemas_library(true, true));    let hidden_titles = ["Edit Reel Four", "Ferry Cut", "Harbour Diaries", "Reeds", "Tidewater", "Saltmarsh", "My edit videos", "edit-reel-four"];    let films = ask(&handle, "data.rows", json!({ "table": "film" }));    assert_eq!(row_ids(&films), ["f3"], "{films}");    assert_eq!(films["hidden_note"], json!(NOTE));    for (table, shown) in [("record_group", vec!["g2"]), ("group_member", vec!["m5"]), ("film_episode", vec![]), ("film_season", vec![]), ("watch", vec!["w2"]), ("fetch", vec!["x2"]), ("fetch_file", vec!["y2"])] {        let page = ask(&handle, "data.rows", json!({ "table": table }));        assert_eq!(row_ids(&page), shown, "{table}: {page}");        assert_eq!(page["hidden_note"], json!(NOTE), "{table} says some rows are hidden");        for name in hidden_titles {            assert!(!page.to_string().contains(name), "{table} names {name}: {page}");        }    }    assert!(ask(&handle, "data.rows", json!({ "table": "book" }))["hidden_note"].is_null(), "a table outside the family says nothing of it");    // A hidden row is not there to open, nor its plain view.    for (table, id) in [("film", "f1"), ("film", "f2"), ("film_episode", "e2"), ("film_episode", "e3"), ("record_group", "g1"), ("watch", "w3"), ("fetch", "x1"), ("fetch_file", "y1")] {        assert_eq!(call(&handle.client(), "data.row", &json!({ "table": table, "id": id })).unwrap_err().code, "no_row", "{table} {id}");        assert!(call(&handle.client(), "data.stored", &json!({ "table": table, "id": id })).is_err());    }    // Points here: Night Ferry's open play alone, counted alone.    let night = ask(&handle, "data.row", json!({ "table": "film", "id": "f3" }));    assert_eq!(night["title"], json!("Night Ferry"));    let points = &night["points_here"][0];    assert_eq!((points["count"].clone(), points["rows"].as_array().unwrap().len()), (json!(1), 1), "{night}");    assert_eq!(points["rows"][0]["id"], json!("w2"));    // Search, in one table and across every table.    assert_eq!(row_ids(&ask(&handle, "data.rows", json!({ "table": "film", "q": "ferry" }))), ["f3"]);    for q in ["ferry", "edit", "reeds", "tidewater"] {        let every = ask(&handle, "data.search", json!({ "q": q }));        for name in hidden_titles {            assert!(!every.to_string().contains(name), "search {q} names {name}: {every}");        }    }    // Export, json and csv: the open rows alone.    for (table, rows, open) in [("film", 1, "Night Ferry"), ("fetch_file", 1, "low-tide.m4a")] {        for kind in ["json", "csv"] {            let file = ask(&handle, "data.export", json!({ "table": table, "as": kind }));            assert_eq!(file["rows"], json!(rows), "{table} {kind}");            let text = std::fs::read_to_string(file["path"].as_str().unwrap()).unwrap();            assert!(text.contains(open), "{table} {kind}: {text}");            for name in hidden_titles {                assert!(!text.contains(name), "{table} {kind} names {name}: {text}");            }        }    }    // Nothing hidden: every row, no line.    let (_d2, open, _) = on(cinemas_library(false, false));    let films = ask(&open, "data.rows", json!({ "table": "film" }));    let mut ids = row_ids(&films);    ids.sort();    assert_eq!(ids, ["f1", "f2", "f3", "s1"], "{films}");    assert!(films["hidden_note"].is_null());    assert_eq!(row_ids(&ask(&open, "data.rows", json!({ "table": "group_member" }))).len(), 5);    assert_eq!(row_ids(&ask(&open, "data.rows", json!({ "table": "watch" }))).len(), 3);    assert_eq!(row_ids(&ask(&open, "data.rows", json!({ "table": "film_episode" }))).len(), 3);    assert_eq!(ask(&open, "data.row", json!({ "table": "film", "id": "f1" }))["title"], json!("Edit Reel Four"));}// RULE (NEXT-HIDDEN3.md 7, NEXT-HIDDEN4.md H1): when Data cannot tell what is hidden (the object fails a read it// needs, not offline), no family table shows a row, and it says why; a table outside the family is unaffected.#[test]fn data_shows_no_family_rows_it_cannot_tell_and_says_why() {    let mut library = cinemas_library(true, true);    library.failing = Some("film_season".into());    let (_d, handle, _) = on(library);    let plays = ask(&handle, "data.rows", json!({ "table": "watch" }));    assert_eq!(row_ids(&plays), Vec::<String>::new(), "{plays}");    assert_eq!(plays["hidden_note"], json!("These rows are not shown: Data could not tell which of them are hidden in Cinemas. Try again in a moment."));    for table in ["group_member", "film", "fetch_file", "record_group"] {        assert_eq!(row_ids(&ask(&handle, "data.rows", json!({ "table": table }))), Vec::<String>::new(), "{table}");    }    assert_eq!(row_ids(&ask(&handle, "data.rows", json!({ "table": "book" }))).len(), 2, "a book is not his films'");}// RULE (HIDE FROM THE SCREEN, owner 27 Nov 2026): a row is hidden when the categories say so, worked out at read: a// hidden category hides its titles and everything down the chain. A leftover `in_hidden` mark (an older build's) with// no hidden category hides nothing.#[test]fn data_hides_by_the_categories_down_the_chain_and_ignores_old_marks() {    let everything_hidden = |handle: &CottonHandle, category_shown: bool| {        for (table, shown) in [("film", vec!["f3"]), ("film_season", vec![]), ("film_episode", vec![]), ("watch", vec!["w2"]), ("fetch", vec!["x2"]), ("fetch_file", vec!["y2"]), ("group_member", vec!["m5"])] {            let page = ask(handle, "data.rows", json!({ "table": table }));            assert_eq!(row_ids(&page), shown, "{table}: {page}");        }        let lists = row_ids(&ask(handle, "data.rows", json!({ "table": "record_group" })));        assert_eq!(lists.contains(&"g1".to_string()), category_shown, "{lists:?}");    };    // The category alone: no row carries a mark.    let (_d, by_category, _) = on(cinemas_library(true, false));    everything_hidden(&by_category, false);    assert_eq!(call(&by_category.client(), "data.row", &json!({ "table": "film_episode", "id": "e3" })).unwrap_err().code, "no_row", "the new episode of a hidden series");    // Old marks alone: no category says hidden, so nothing is.    let (_d2, by_mark, _) = on(cinemas_library(false, true));    let films = ask(&by_mark, "data.rows", json!({ "table": "film" }));    let mut ids = row_ids(&films);    ids.sort();    assert_eq!(ids, ["f1", "f2", "f3", "s1"], "{films}");    assert!(films["hidden_note"].is_null());}#[test]fn a_phone_without_the_key_shows_nothing_of_cinemas_tables() {    // The reviewers' Hidden rules: Data shows nothing of a Cinemas table when it cannot tell what is hidden.    let (_d, handle, _) = on_with(cinemas_library(true, true), false);    for table in ["film", "film_episode", "record_group", "fetch_file"] {        let r = ask(&handle, "data.rows", json!({ "table": table }));        assert_eq!(r["sealed_view"], json!(true), "{table}: {r}");        assert_eq!(r["rows"], json!([]), "{table}: no row, not even as the server holds it: {r}");        assert_eq!(r["hidden_note"], json!("These rows are not shown until this phone has your key: some of them may be hidden in Cinemas."));    }    let refused = crate::methods::dispatch(&handle, "data.row", &json!({ "table": "film", "id": "f1" })).expect_err("not shown");    assert_eq!(refused.code, "no_row");    // Another sealed table is still listed as the server holds it.    assert_eq!(ask(&handle, "data.rows", json!({ "table": "book" }))["rows"].as_array().map(Vec::len), Some(2));}/// DATA iPhone 3 (the owner's build 2: with his first sync running, every table he opened stood blank while each read/// went to a server answering his pass in seconds). With Keep everything holding the whole object, a table's rows and/// one row come from this phone's copy, and the server is asked for no page of them.#[test]fn a_kept_tables_rows_come_from_this_phone_without_asking_the_server() {    let mut object = invented();    object.more_defs = vec![json!({ "id": "film", "name": "film", "plural": "Films", "title": "title", "columns": [{ "key": "title", "type": "text" }, { "key": "kind", "type": "text" }, { "key": "in_hidden", "type": "bool" }], "seal": { "clear": ["kind"], "blind": ["title"] }, "slip": { "title": "title" } })];    let (_d, handle, object) = on_phone(object, true, cinemas_phone());    let client = handle.client();    std::fs::write(client.layout().root().join("data-keep.json"), r#"{"on":true,"started":true}"#).unwrap();    // The row as it sits on this phone: opened, in the copy's own table.    let answer = client        .write_rows("test.kept", &mut |ctx| {            let mut row = Map::new();            row.insert("title".into(), json!("Harbour Lights"));            row.insert("kind".into(), json!("film"));            Ok(json!({ "id": super::super::songs::made(ctx, "film", row)? }))        })        .unwrap_or_else(|why| panic!("the kept row: {why}"));    let id = crate::authoring::own_answer(answer)["id"].as_str().expect("an id").to_string();    object.asked.lock().unwrap().clear();    let r = ask(&handle, "data.rows", json!({ "table": "film" }));    let titles: Vec<&str> = r["groups"].as_array().unwrap().iter().flat_map(|g| g["rows"].as_array().unwrap()).filter_map(|row| row["title"].as_str()).collect();    assert_eq!(titles, vec!["Harbour Lights"], "{r}");    let one = ask(&handle, "data.row", json!({ "table": "film", "id": id }));    assert!(one.to_string().contains("Harbour Lights"), "{one}");    let asked = object.asked.lock().unwrap().clone();    let rows_asked = |path: &String| path.contains("/v1/rows") || path.contains("/v1/older") || (path.contains("/v1/data/page?table=film&limit=50") && !path.contains("limit=500"));    assert!(!asked.iter().any(rows_asked), "the server was asked for the rows this phone holds: {asked:?}");    // Keep everything off: the server's pages, as before.    std::fs::write(client.layout().root().join("data-keep.json"), r#"{"on":false}"#).unwrap();    let _ = ask(&handle, "data.rows", json!({ "table": "film" }));    assert!(object.asked.lock().unwrap().iter().any(|path| path.contains("/v1/data/page?table=film&limit=50")));}/// ANDROID READY 1 core faults 4 and 5. Stopped to leave room, Keep everything offers no Pause and says no "Filling":/// it starts again by itself. While the whole copy has not come (filling, or stopped part way), search never says it/// searched every table on this phone: sealed tables are asked of the server's blind index too. Once the copy's first/// pull has ended, the phone alone answers, and short of room a whole copy is kept, not stopped.#[test]fn stopped_for_room_offers_no_pause_and_search_never_claims_a_copy_it_does_not_hold() {    #[derive(Debug)]    struct Free(u64);    impl crate::phone::disk::Disk for Free {        fn size_of(&self, _: &std::path::Path) -> u64 {            0        }        fn free_bytes(&self, _: &std::path::Path) -> Option<u64> {            Some(self.0)        }    }    let (_d, handle, object) = on(invented());    let client = handle.client();    client.set_disk(Arc::new(Free(1_500_000_000)));    std::fs::write(client.layout().root().join("data-keep.json"), r#"{"on":true,"started":true}"#).unwrap();    let k = ask(&handle, "data.keep", json!({ "free": 1_500_000_000u64 }));    assert_eq!(k["state"], json!("stopped_room"), "{k}");    assert!(k["progress"].is_null(), "no percent and no minutes left while stopped: {k}");    assert_eq!(k["acts"], json!([]), "no Pause: it goes on by itself: {k}");    assert!(k["state_line"].as_str().unwrap().contains("1.5 GB free"), "{k}");    let you = ask(&handle, "data.you", json!({}));    assert_eq!(you["rows"][0]["value_line"], json!("Stopped to leave room"), "{you}");    object.asked.lock().unwrap().clear();    let s = ask(&handle, "data.search", json!({ "q": "monsoon" }));    let line = s["searched_line"].as_str().unwrap();    assert!(!line.starts_with("Searched every word in all") && line.contains("on the server"), "{line}");    assert!(object.asked.lock().unwrap().iter().any(|p| p.contains("/v1/blind")), "the server's blind index was asked");    // The whole copy's first pull ended: the phone answers alone, and short of room the copy is kept up to date.    client        .with_writer(|file| cotton_store::cursors::advance_cursor(file.driver, cotton_client::transport::object::CURSOR_KEY, "v0000000000000009", "2026-11-28T10:00:00Z").map(|_| ()).map_err(|e| e.to_string()))        .expect("the cursor of a pull that ended");    object.asked.lock().unwrap().clear();    let s = ask(&handle, "data.search", json!({ "q": "monsoon" }));    assert!(s["searched_line"].as_str().unwrap().starts_with("Searched every word in all"), "{}", s["searched_line"]);    assert!(!object.asked.lock().unwrap().iter().any(|p| p.contains("/v1/blind")));}