Cotton code
1059 lines · 50.3 KB · RustRaw
//! The databases a device holds, as the app's windows see them.//!//! A device holds several database files — its own (personal) one and every//! shared one it was admitted to — and a window draws ONE of them at a time.//! Four things are answered here://!//! * `read.databases` — the switcher's rows://!   `{"databases":[{"databaseId","name","kind":"personal"|"shared","people":[]}],"shown":[id…]}`,//!   the personal one first; `theirs: true` on one joined at another person's Mac. Read off the connection record alone, so an idle//!   database is listed without its file being opened.//! * `databases.show {"databaseId"}` / `databases.hide {"databaseId"}` — one//!   window's pin on the database it is drawing. Counted, so two windows on//!   one database keep it open until both have turned away.//! * a top-level `database` on every method names the database the call is//!   about (`methods::dispatch`); absent is the personal one.//! * `database: "all"` on the three feeds that read ACROSS databases — the day//!   (todos and events), search and "asked of you" — answered by [`read_all`].//!   Nothing else merges: a list, a board and a record belong to one database.use serde_json::{json, Map, Value};use super::reads;use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;/// The top-level key that names a call's database.pub const DATABASE: &str = "database";/// Its one value that is not an id: every database this device holds.pub const ALL_DATABASES: &str = "all";/// One feed that reads across databases, and how its answers join.pub struct Feed {    /// The read's method name.    pub method: &'static str,    /// The lists whose rows are joined, each row stamped with the database it    /// came from — a dotted path, as `questions.groups`.    pub lists: &'static [&'static str],    /// The counts summed across databases: a number, or an object of counts    /// summed field by field — a dotted path too.    pub sums: &'static [&'static str],    /// Maps of sections (`{hits, total}` under a key), joined section by    /// section: each section's hits stamped and appended, its totals summed.    pub sections: &'static [&'static str],    /// Answered from the feeds' index for a database not open    /// (`shell::feed_index`), so the feed opens no idle file. Search is not:    /// it asks each file's own full-text index in turn.    pub indexed: bool,}/// The only reads `database: "all"` is answered for.pub const FEEDS: [Feed; 3] = [    Feed {        method: "read.day",        lists: &["occurrences", "invites", "todos"],        sums: &[],        sections: &[],        indexed: true,    },    Feed {        method: "read.decide",        lists: &["questions.groups"],        sums: &["questions.total"],        sections: &[],        indexed: true,    },    Feed {        method: "read.find",        lists: &["hits"],        sums: &["totals"],        // An imported table's section, by table id (`find`'s `defined`).        sections: &["defined"],        indexed: false,    },];/// The name a database is drawn under, when it has one of its own: the name/// the person gave it on its cap (an explicit appearance name wins), and for/// the personal database with none, its workspace row's name IN FULL ("Garden/// Three", never "Garden") — the database's own name, which renaming the owner/// person does not touch (Spec 10 (d)). `None` leaves the connection record's/// name. One answer for the list of databases/// and for every row a feed across them names, so a search hit never says/// "Personal" beside a cap that says "Walker".fn drawn_name(    client: &ClientController,    appearances: &std::collections::BTreeMap<String, Value>,    id: &str,    personal: bool,) -> Result<Option<String>, String> {    if let Some(name) = appearances.get(id).and_then(|appearance| appearance.get("name")).and_then(Value::as_str) {        return Ok(Some(name.to_string()));    }    if !personal || client.arriving(id).is_some() {        return Ok(None);    }    client.glance_in(id, |driver, workspace| {        let row = driver            .get(                "SELECT name FROM cotton_workspaces WHERE id = ?",                &[rusqlite::types::Value::Text(workspace.to_string())],            )            .map_err(|error| error.to_string())?;        Ok(row            .as_ref()            .and_then(|row| row.text("name"))            .and_then(reads::database_own_name))    })}/// The name the list of databases draws for `id` — what the owner knows it/// by — or `None` for a database this device does not hold.pub(crate) fn name_of(client: &ClientController, id: &str) -> Result<Option<String>, String> {    let Some(held) = client.databases()?.into_iter().find(|database| database.id == id) else { return Ok(None) };    let appearances = super::database_appearance::listed(client)?.appearances;    Ok(Some(drawn_name(client, &appearances, id, held.personal)?.unwrap_or(held.name)))}/// `read.databases` lists live files. `includeArchived` adds the serving/// Mac's archive facts without opening a retained database.pub fn list(client: &ClientController, args: &Map<String, Value>) -> Result<Value, String> {    let super::database_appearance::Listed { appearances, mut unreadable } =        super::database_appearance::listed(client)?;    let mut databases: Vec<Value> = client        .scoped_databases()?        .into_iter()        .map(|database| -> Result<Value, String> {            let mut listed = json!({                "databaseId": database.id,                "name": database.name,                "kind": if database.personal { "personal" } else { "shared" },                // Who else is in it. Empty until the roster is read without                // opening the file: listing must not wake an idle database.                "people": [],            });            if let Some(appearance) = appearances.get(&database.id) {                listed["colour"] = appearance.get("colour").cloned().unwrap_or(Value::Null);            }            // Only on a database whose copy has not arrived on this device —            // the device's own included, while its copy comes in or is put in            // place: where its arrival stands — waiting, arriving with how            // far, or failed with why — which the cap and the page draw. A            // file that is not here is not unreadable: it is on its way.            let arrival = client.arrival(&database.id);            // A file that cannot be read is listed under the record's name,            // with its reason — never dropped, and never the whole list.            match drawn_name(client, &appearances, &database.id, database.personal) {                Ok(Some(name)) => listed["name"] = json!(name),                Ok(None) => {}                Err(reason) => {                    unreadable.entry(database.id.clone()).or_insert(reason);                }            }            if let (None, Some(reason)) = (&arrival, unreadable.get(&database.id)) {                listed["unreadable"] = json!(reason);            }            // Only on a database made here that the server has not taken yet.            if database.pending {                listed["pending"] = Value::from(true);            }            // Only on a database joined at another person's Mac: its page            // names no Mac, because this device holds no name for theirs.            if database.theirs {                listed["theirs"] = Value::from(true);            }            if let Some(arrival) = arrival {                listed["arrival"] = arrival;            }            Ok(listed)        })        .collect::<Result<_, _>>()?;    if args.get("includeArchived").and_then(Value::as_bool).unwrap_or(false) {        databases.extend(client.archived_databases()?);    }    // The places the person holds on ANOTHER device and not on this one:    // the switcher offers each, and `databases.present` fetches it.    let elsewhere: Vec<Value> = super::joined_places::elsewhere(client)        .unwrap_or_default()        .iter()        .map(super::joined_places::Elsewhere::to_json)        .collect();    Ok(json!({ "databases": databases, "shown": client.shown_databases(), "elsewhere": elsewhere }))}fn database_id(request: &Value) -> Result<&str, MethodError> {    request        .get("databaseId")        .and_then(Value::as_str)        .map(str::trim)        .filter(|id| !id.is_empty())        .ok_or_else(|| {            MethodError::new(                "bad_request",                "`databaseId` is the database the window draws",            )        })}/// `databases.create {"name"}` — a shared database was made here and handed/// to the household's server by this device's signed transport; this device/// signs no request to a server, so it makes none.pub fn create(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    // A RUNNER MAKES NO DATABASE: a new one is a copy this device would hold.    if cotton_client::connection::holds_no_copy(handle.layout()) {        return Err(MethodError::new("runner_holds_no_copy", cotton_client::replica::RUNNER_HOLDS_NO_COPY));    }    if request.get("name").and_then(Value::as_str).map(str::trim).is_none_or(str::is_empty) {        return Err(MethodError::new("bad_request", "Give the database a name."));    }    Err(MethodError::new(        "device_key_unreadable",        "this device has no device identity to sign with",    ))}/// A SHARED DATABASE MADE ON THIS DEVICE, for the tests of what reads and/// writes every held database: the act `databases.create` ran while this/// device had a signed transport to hand it to its household's server.#[cfg(test)]pub(crate) fn made_here(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    // A RUNNER MAKES NO DATABASE: a new one is a copy this device would hold.    if cotton_client::connection::holds_no_copy(handle.layout()) {        return Err(MethodError::new("runner_holds_no_copy", cotton_client::replica::RUNNER_HOLDS_NO_COPY));    }    let text = |key: &str| {        request            .get(key)            .and_then(Value::as_str)            .map(str::trim)            .filter(|value| !value.is_empty())    };    let Some(name) = text("name") else {        return Err(MethodError::new("bad_request", "Give the database a name."));    };    let layout = handle.layout().clone();    let device_key_id = handle.identity().device_id.clone();    // Verify the creator can sign before making any file.    let _ = super::founding::creator(&handle.client(), "creation-preflight")?;    let made = cotton_client::start_place(cotton_client::StartPlace {        layout: &layout,        connection: &cotton_client::connection::ConnectionFile::at(layout.connection_json()),        clock: &cotton_client::seams::SystemClock,        random: &cotton_client::seams::SystemRandom,        name,        receipt_signer: handle.client().receipt_signer_slot(),        device_key_id: device_key_id.as_deref(),        device_name: text("deviceName").unwrap_or("This device"),        platform: super::commands::asked_platform(text("platform")),        app_version: text("appVersion").or(Some(handle.app_version())),    })    .map_err(|error| MethodError::new(error.code(), error.to_string()))?;    let client = handle.client();    let founder = super::founding::creator(&client, &made.id)?;    // The maker is a person in the database they make, claimed as theirs    // (architect, 11 Oct 2026: "a member is a person in every database they    // are in"): Me's name, or the name the proof carries while Me is unlinked.    // The claim travels in the founder proof; the person row is an ordinary    // write, so it leaves with the database's first exchange.    let maker = cotton_client::seams::uuid_v4(&cotton_client::seams::SystemRandom);    let maker_name = super::owner_face::me_name(&client).unwrap_or_else(|| founder.person_name.clone());    let founder = founder        .claiming(&made.id, &maker, |message| {            super::vault::sign_as_person(&client, message)                .map(|(_, signature)| signature)                .map_err(|error| cotton_store::StoreError::refused(error.message))        })        .map_err(|error| MethodError::new("start_failed", error.to_string()))?;    {        let db = cotton_store::Driver::open(&made.replica).map_err(|error| MethodError::new("start_failed", error.to_string()))?            .sharing_signer(client.receipt_signer_slot());        let mut ids = cotton_client::seams::op_ids(std::sync::Arc::new(cotton_client::seams::SystemRandom));        founder.record(&db, &made.id, client.now().timestamp_millis(), &mut ids)            .map_err(|error| MethodError::new("start_failed", error.to_string()))?;    }    {        let _made = client.name_database(Some(&made.id)).map_err(|error| MethodError::new("start_failed", error))?;        client            .write_rows("databases.create", &mut |ctx| {                let mut fields = Map::new();                fields.insert("workspace_id".to_string(), Value::from(made.id.clone()));                fields.insert("full_name".to_string(), Value::from(maker_name.clone()));                cotton_tools::mcp::handlers::common::insert_row(ctx, "cotton_people", &maker, fields)                    .map_err(|failure| failure.to_string())?;                Ok(Value::Null)            })            .map_err(|error| MethodError::new("start_failed", error))?;    }    // The pass that hands it to the server, now rather than at the minute.    handle.client().nudge_sync();    Ok(json!({        "id": made.id,        "databaseId": made.id,        "name": made.name,        "kind": "shared",        "people": [],        "pending": true,    }))}/// `databases.show` — this window draws `databaseId` from now on.pub fn show(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let database = database_id(request)?;    let client = handle.client();    client        .show_database(database)        .map_err(|reason| MethodError::new("database_not_held", reason))?;    Ok(json!({ "databaseId": database, "shown": client.shown_databases() }))}/// `databases.leave` — a shared database was left by telling the Mac that/// served it; this device signs no request to one, so it leaves none.pub fn leave(_handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    database_id(request)?;    Err(MethodError::new("device_key_unreadable", "this device has no device identity"))}/// `databases.hide` — this window stopped drawing `databaseId`.pub fn hide(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let database = database_id(request)?;    let client = handle.client();    client.hide_database(database);    Ok(json!({ "databaseId": database, "shown": client.shown_databases() }))}/// One feed, over every database this device holds.////// The read runs once per database, in the list's order (personal first), and/// the answers are joined: each row of the feed's lists gains `databaseId` and/// `databaseName`, and every other field is the personal database's own. Rows/// stay grouped by database — the screen orders them, as it orders sections.////// A database that cannot answer is named in `skippedDatabases`, while every/// readable held file still contributes to the feed.////// Today and "Asked of you" read a database that is not open from the feeds'/// index while its file is unchanged, so they open no idle file.pub fn read_all(    handle: &CottonHandle,    method: &str,    request: &Value,) -> Result<Value, MethodError> {    let answer = read_all_in(&handle.client(), method, request)?;    if let Some(skipped) = answer.get("skippedDatabases").and_then(Value::as_array) {        for database in skipped {            let filename = database["filename"]                .as_str()                .unwrap_or("unknown database/replica.db");            let schema = database["schemaVersion"].as_u64().map_or_else(                || "unreadable".to_string(),                |version| version.to_string(),            );            let build = database["build"].as_str().unwrap_or("unknown");            let bundle = database["bundleId"].as_str().unwrap_or("unknown");            let refusal = database["refusal"]                .as_str()                .unwrap_or("Could not read this database.");            let reason = database["reason"]                .as_str()                .unwrap_or("an unreadable database");            crate::shell::diagnostics::method_failed(                handle.log(),                handle.events(),                method,                &format!(                    "{filename} · schema {schema} · build {build} · bundle {bundle} · {refusal} · {reason}"                ),            );        }    }    Ok(answer)}/// [`read_all`] on a controller.pub fn read_all_in(    client: &ClientController,    method: &str,    request: &Value,) -> Result<Value, MethodError> {    // Today across every database reads each on its short lane, as Today on    // one does (`ShortRead`).    if let Some(short) = crate::shell::client::ShortRead::named(method) {        return crate::shell::client::on_short_lane(short, || read_all_in_on(client, method, request));    }    read_all_in_on(client, method, request)}fn read_all_in_on(    client: &ClientController,    method: &str,    request: &Value,) -> Result<Value, MethodError> {    let Some(feed) = FEEDS.iter().find(|feed| feed.method == method) else {        let feeds: Vec<&str> = FEEDS.iter().map(|feed| feed.method).collect();        return Err(MethodError::new(            "not_a_feed",            format!(                "`{method}` is about one database — only {} read across all of them",                feeds.join(", ")            ),        ));    };    let entry = reads::read_for(method).expect("every feed is a declared read");    let args = super::read_args(request);    let unreadable = |reason: String| MethodError::new("unreadable", reason);    // A row names its database as the person named it ("Garden Three"), the name    // `read.databases` lists it under — never the connection record's own.    let super::database_appearance::Listed {        appearances,        unreadable: mut appearance_failures,    } = super::database_appearance::listed(client).map_err(unreadable)?;    let mut joined: Option<Map<String, Value>> = None;    let mut skipped: Vec<Value> = Vec::new();    let mut arriving: Vec<Value> = Vec::new();    // The feeds cross only what this app shows (`shell::scope`).    for mut database in client.scoped_databases().map_err(unreadable)? {        if let Some(arrival) = client.arrival(&database.id) {            arriving.push(json!({"databaseId": database.id, "databaseName": database.name, "arrival": arrival}));            continue;        }        if let Some(reason) = appearance_failures.remove(&database.id) {            skipped.push(skipped_database(client, &database.id, &database.name, reason));            continue;        }        match drawn_name(client, &appearances, &database.id, database.personal) {            Ok(Some(name)) => database.name = name,            Ok(None) => {}            Err(reason) => {                skipped.push(skipped_database(client, &database.id, &database.name, reason));                continue;            }        }        let read = || {            let _named = client.name_database(Some(&database.id))?;            super::answer_read(client, entry, &args)        };        let answer = if feed.indexed && !database.personal {            client.indexed_read(&database.id, &crate::shell::feed_index::key(method, &args), read)        } else {            read()        };        let answer = match answer {            Ok(Value::Object(answer)) => answer,            Ok(other) => {                skipped.push(skipped_database(                    client,                    &database.id,                    &database.name,                    format!("{method} answered {other}, not an object"),                ));                continue;            }            Err(reason) => {                skipped.push(skipped_database(client, &database.id, &database.name, reason));                continue;            }        };        crate::shell::refused_copies::forget(client, &database.id);        join(feed, &mut joined, answer, &database.id, &database.name);    }    let mut joined = joined.unwrap_or_default();    joined.insert("skippedDatabases".to_string(), Value::Array(skipped));    joined.insert("arrivingDatabases".to_string(), Value::Array(arriving));    Ok(Value::Object(joined))}/// One file's evidence in a cross-database refusal. The stamp is a read-only/// SQLite query, so diagnosing a copy never migrates or mutates it.fn skipped_database(client: &ClientController, id: &str, name: &str, reason: String) -> Value {    crate::shell::refused_copies::observe(client, id, name, &reason);    let path = client.layout().replica(id);    let said = crate::shell::diagnostics::said();    json!({        "databaseId": id,        "databaseName": name,        "refusal": format!("Could not read {name} on this device."),        "reason": reason,        "filename": format!("{id}/replica.db"),        "schemaVersion": crate::shell::database_files::stamp(&path).ok(),        "bundleId": said.bundle_id,        "build": said.build,    })}/// Fold one database's answer into the feed's.fn join(    feed: &Feed,    joined: &mut Option<Map<String, Value>>,    mut answer: Map<String, Value>,    id: &str,    name: &str,) {    for list in feed.lists {        if let Some(Value::Array(rows)) = at_mut(&mut answer, list) {            for row in rows.iter_mut().filter_map(Value::as_object_mut) {                row.insert("databaseId".to_string(), json!(id));                row.insert("databaseName".to_string(), json!(name));            }        }    }    for map in feed.sections {        if let Some(Value::Object(sections)) = at_mut(&mut answer, map) {            for rows in sections.values_mut().filter_map(|section| section.get_mut("hits")).filter_map(Value::as_array_mut) {                for row in rows.iter_mut().filter_map(Value::as_object_mut) {                    row.insert("databaseId".to_string(), json!(id));                    row.insert("databaseName".to_string(), json!(name));                }            }        }    }    let Some(joined) = joined else {        *joined = Some(answer);        return;    };    for list in feed.lists {        if let Some(Value::Array(mut rows)) = take(&mut answer, list) {            match at_mut(joined, list) {                Some(Value::Array(all)) => all.append(&mut rows),                _ => place(joined, list, Value::Array(rows)),            }        }    }    for map in feed.sections {        let Some(Value::Object(sections)) = take(&mut answer, map) else { continue };        if !matches!(at_mut(joined, map), Some(Value::Object(_))) {            place(joined, map, json!({}));        }        let Some(Value::Object(all)) = at_mut(joined, map) else { continue };        for (key, mut section) in sections {            let Some(held) = all.get_mut(&key) else {                all.insert(key, section);                continue;            };            if let (Some(Value::Array(rows)), Some(Value::Array(more))) = (held.get_mut("hits"), section.get_mut("hits")) {                rows.append(more);            }            let total = held.get("total").and_then(Value::as_i64).unwrap_or(0) + section.get("total").and_then(Value::as_i64).unwrap_or(0);            held["total"] = json!(total);        }    }    for sums in feed.sums {        match (at_mut(joined, sums), take(&mut answer, sums)) {            (Some(Value::Object(all)), Some(Value::Object(counts))) => {                for (field, count) in counts {                    let sum = all.get(&field).and_then(Value::as_i64).unwrap_or(0)                        + count.as_i64().unwrap_or(0);                    all.insert(field, json!(sum));                }            }            (Some(all @ Value::Number(_)), Some(Value::Number(count))) => {                *all = json!(all.as_i64().unwrap_or(0) + count.as_i64().unwrap_or(0));            }            (None, Some(counts)) => place(joined, sums, counts),            _ => {}        }    }}/// The value at a dotted path.fn at_mut<'a>(map: &'a mut Map<String, Value>, path: &str) -> Option<&'a mut Value> {    let mut keys = path.split('.');    let mut value = map.get_mut(keys.next()?)?;    for key in keys {        value = value.as_object_mut()?.get_mut(key)?;    }    Some(value)}/// Take the value at a dotted path out of its object.fn take(map: &mut Map<String, Value>, path: &str) -> Option<Value> {    match path.rsplit_once('.') {        None => map.remove(path),        Some((parent, key)) => at_mut(map, parent)?.as_object_mut()?.remove(key),    }}/// Put a value at a dotted path, making the objects on the way.fn place(map: &mut Map<String, Value>, path: &str, value: Value) {    let mut keys: Vec<&str> = path.split('.').collect();    let last = keys.pop().expect("a path has a key");    let mut at = map;    for key in keys {        let next = at.entry(key.to_string()).or_insert_with(|| json!({}));        if !next.is_object() {            *next = json!({});        }        at = next.as_object_mut().expect("made an object just above");    }    at.insert(last.to_string(), value);}#[cfg(test)]mod tests {    use super::*;    // RULE: The person key is read from the personal database whichever database a call names, so in a shared one with no person key the owner reading it is still "me", never another member.    #[test]    fn the_person_key_is_the_personal_databases_in_every_database() {        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};        let dir = tempfile::tempdir().unwrap();        let handle = crate::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("Etc/UTC".into()),            device_secret: Some(URL_SAFE_NO_PAD.encode([19u8; 32])),            vault_secret: None,            flavor: cotton_core::flavor::Flavor::Dev,            manifest: None,        }).unwrap();        crate::methods::dispatch(&handle, "workspace.startLocal", &json!({})).unwrap();        prepare_creator(&handle, false);        let garden = super::made_here(&handle, &json!({"name": "Garden"})).unwrap();        let client = handle.client();        let own = crate::phone::vault::person_public_key(&client).expect("the personal database holds the person key");        let garden_id = garden["id"].as_str().unwrap();        let held = client.with_file_in(garden_id, |file| {            file.driver.get("SELECT count(*) AS c FROM cotton_person_keys", &[]).map_err(|error| error.to_string())        }).unwrap();        assert_eq!(held.and_then(|row| row.int("c")), Some(0), "a shared database holds no person key");        let _garden = client.name_database(Some(garden_id)).unwrap();        assert_eq!(crate::phone::vault::person_public_key(&client).ok(), Some(own), "read with Garden named");    }    // RULE: an app whose manifest names one database (Cotton Project: its id and host) shows no Personal row anywhere — Personal is not in the list of databases, a call naming no database is the named one's, "all" is the named one alone, a call naming Personal or any other held database is refused, and it makes no database. Personal stays held: the person's own facts are read from it (architect's ruling (A), 19 Oct 2026).    #[test]    fn an_app_that_names_one_database_shows_no_personal_row() {        // Before it has joined anything, a scoped app's calls answer as any        // unjoined app's — not "Cotton has not arrived" — so Start and Join draw.        let fresh = tempfile::tempdir().unwrap();        let unjoined = crate::handle::CottonHandle::open(crate::handle::phone_config(fresh.path())).unwrap();        let named = |id: &str| crate::shell::scope::DatabaseScope::One { id: id.into(), name: Some("Cotton".into()) };        unjoined.client().limit_to(named("db-not-joined")).unwrap();        let listed = crate::methods::dispatch(&unjoined, "read.databases", &json!({})).unwrap();        assert_eq!(listed["databases"], json!([]));        let early = crate::methods::dispatch(&unjoined, "records.list", &json!({"table": "note"}));        assert!(early.as_ref().err().is_none_or(|error| !error.message.contains("has not arrived")), "{early:?}");        let (_dir, handle) = a_phone_with_a_key();        let personal = handle.client().databases().unwrap().into_iter().find(|held| held.personal).unwrap().id;        let note = |request: Value| crate::methods::dispatch(&handle, "records.create", &request);        note(json!({"table": "note", "data": {"title": "Synthetic personal note"}})).unwrap();        let cotton = super::made_here(&handle, &json!({"name": "Cotton"})).unwrap()["databaseId"].as_str().unwrap().to_string();        let allotment = super::made_here(&handle, &json!({"name": "Allotment"})).unwrap()["databaseId"].as_str().unwrap().to_string();        // A made database holds no tool until one is imported: both take the Notebook.        for made in [&cotton, &allotment] {            crate::methods::dispatch(&handle, "write", &json!({"database": made, "tool": "add_tool", "args": {"tool_id": "notebook"}}))                .expect("the Notebook is imported");        }        handle.client().limit_to(named(&cotton)).unwrap();        assert!(handle.client().limit_to(crate::shell::scope::DatabaseScope::Every).is_err(), "a scope is never widened");        let listed = crate::methods::dispatch(&handle, "read.databases", &json!({})).unwrap();        let ids: Vec<&str> = listed["databases"].as_array().unwrap().iter().map(|row| row["databaseId"].as_str().unwrap()).collect();        assert_eq!(ids, vec![cotton.as_str()], "only Cotton is listed");        // Joined, its database not here yet: the list is empty, and a read of        // records waits — never Personal's.        let (_waiting_dir, waiting) = a_phone_with_a_key();        waiting.client().limit_to(named(&cotton)).unwrap();        assert_eq!(crate::methods::dispatch(&waiting, "read.databases", &json!({})).unwrap()["databases"], json!([]));        crate::methods::dispatch(&waiting, "bootstrap.status", &json!({})).expect("and says how it stands");        for boot in ["read.boot", "read.syncStatus"] {            let answered = crate::methods::dispatch(&waiting, boot, &json!({}));            assert!(answered.as_ref().err().is_none_or(|error| !error.message.contains("has not arrived")), "{boot}: {answered:?}");        }        let early = crate::methods::dispatch(&waiting, "records.list", &json!({"table": "note"})).unwrap_err();        assert!(early.message.contains("has not arrived"), "{}", early.message);        note(json!({"table": "note", "data": {"title": "Synthetic project note"}})).unwrap();        let titles = |request: Value| -> Vec<String> {            crate::methods::dispatch(&handle, "records.list", &request).unwrap()["records"].as_array().unwrap()                .iter().map(|row| row["data"]["title"].as_str().unwrap_or_default().to_string()).collect()        };        assert_eq!(titles(json!({"table": "note"})), vec!["Synthetic project note"], "no database named is Cotton's");        assert_eq!(titles(json!({"table": "note", "database": cotton})), vec!["Synthetic project note"]);        for other in [&personal, &allotment] {            let refused = crate::methods::dispatch(&handle, "records.list", &json!({"table": "note", "database": other})).unwrap_err();            assert_eq!(refused.code, "not_shown", "{other}");        }        assert_eq!(crate::methods::dispatch(&handle, "databases.create", &json!({"name": "Another"})).unwrap_err().code, "not_shown");        assert!(crate::phone::vault::person_public_key(&handle.client()).is_ok(), "Personal is still held for the person's own facts");    }    // RULE: Cotton (a manifest naming "personal") shows Personal alone: no other database is listed, a call naming one it already holds is refused, and it makes none — the project's database is never opened by Cotton (owner, 19 Oct 2026).    #[test]    fn an_app_that_names_personal_never_opens_another_database() {        let (_dir, handle) = a_phone_with_a_key();        let cotton = super::made_here(&handle, &json!({"name": "Cotton"})).unwrap()["databaseId"].as_str().unwrap().to_string();        handle.client().limit_to(crate::shell::scope::DatabaseScope::Personal).unwrap();        let listed = crate::methods::dispatch(&handle, "read.databases", &json!({})).unwrap();        let rows = listed["databases"].as_array().unwrap();        assert_eq!(rows.len(), 1);        assert_eq!(rows[0]["kind"], "personal");        let refused = crate::methods::dispatch(&handle, "records.list", &json!({"table": "note", "database": cotton})).unwrap_err();        assert_eq!(refused.code, "not_shown");        assert_eq!(crate::methods::dispatch(&handle, "databases.create", &json!({"name": "Another"})).unwrap_err().code, "not_shown");        crate::methods::dispatch(&handle, "records.list", &json!({"table": "note"})).expect("no database named is Personal's");        let client = handle.client();        assert!(!client.held_databases().unwrap().contains(&cotton), "a database outside the scope is not held");        assert!(!client.household_databases().contains(&cotton), "nor synced");        assert_eq!(crate::shell::scope::kept(handle.layout()), crate::shell::scope::DatabaseScope::Personal, "kept beside the record");    }    // RULE: read.you is the personal database's owner whichever database the    // call names — through the FULL dispatch, which scopes the call to    // `database` before the read runs. A shared database's `owner_person_id`    // stays unset (a walk at 08:33Z: it got one named after the shared    // database), and making it makes exactly one person, the maker, claimed as    // theirs and never named after the database (architect, 11 Oct 2026: "a    // member is a person in every database they are in").    #[test]    fn read_you_naming_a_shared_database_answers_the_personal_ones_owner() {        let (_dir, handle) = a_phone_with_a_key();        let garden = super::made_here(&handle, &json!({"name": "Garden"})).unwrap();        let garden_id = garden["databaseId"].as_str().unwrap().to_string();        let client = handle.client();        // The personal database's owner, linked as the serving Mac leaves it.        client            .with_writer(|replica| {                for sql in [                    "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \                     SELECT 'person-the-owner', id, 'Tarun Invented', '2026-09-01T00:00:00.000Z', \                     '2026-09-01T00:00:00.000Z' FROM cotton_workspaces",                    "UPDATE cotton_workspaces SET owner_person_id = 'person-the-owner'",                ] {                    replica.driver.run(sql, &[]).map_err(|error| error.to_string())?;                    crate::fixture::receipted(replica.driver, sql);                }                Ok(())            })            .unwrap();        let answer =            crate::methods::dispatch(&handle, "read.you", &json!({"database": garden_id})).unwrap();        assert_eq!(answer["database_id"], json!(crate::fixture::WORKSPACE));        assert_eq!(answer["person_id"], json!("person-the-owner"));        let in_file = |id: &str, sql: &str| {            client                .with_file_in(id, |file| {                    file.driver.get(sql, &[]).map_err(|error| error.to_string())                })                .unwrap()                .and_then(|row| row.text("v").map(str::to_string))        };        assert_eq!(            in_file(&garden_id, "SELECT owner_person_id AS v FROM cotton_workspaces"),            None,            "the shared database is given no owner person"        );        assert_eq!(            in_file(&garden_id, "SELECT CAST(COUNT(*) AS TEXT) AS v FROM cotton_people").as_deref(),            Some("1"),            "making the database makes exactly one person, the maker"        );        let key = crate::phone::vault::person_public_key(&client).unwrap();        let bound = client            .with_file_in(&garden_id, |file| {                cotton_store::member_person::bound_person(file.driver, &garden_id, &key)                    .map_err(|error| error.to_string())            })            .unwrap()            .expect("the maker's person is claimed as theirs");        let named = in_file(            &garden_id,            &format!("SELECT full_name AS v FROM cotton_people WHERE id = '{}'", bound.person_id),        );        assert_ne!(named.as_deref(), Some("Garden"), "never named after the database");    }    // RULE: Me's name and picture are carried ONE WAY to the owner's person in    // a shared database — the row the owner's signed claim binds, never one    // found by name — and nothing in the shared database is read back into Me    // (Me brief piece 2; owner and architect, 11 Oct 2026).    #[test]    fn me_is_carried_one_way_to_the_owners_claimed_person_in_a_shared_database() {        let (dir, handle) = a_phone_with_a_key();        crate::phone::owner_face::forget_carried();        let garden = super::made_here(&handle, &json!({"name": "Garden"})).unwrap();        let garden_id = garden["databaseId"].as_str().unwrap().to_string();        let client = handle.client();        client            .with_writer(|replica| {                for sql in [                    "INSERT INTO cotton_people (id, workspace_id, full_name, created_at, updated_at) \                     SELECT 'person-the-owner', id, 'Tarun Invented', '2026-09-01T00:00:00.000Z', \                     '2026-09-01T00:00:00.000Z' FROM cotton_workspaces",                    "UPDATE cotton_workspaces SET owner_person_id = 'person-the-owner'",                ] {                    replica.driver.run(sql, &[]).map_err(|error| error.to_string())?;                    crate::fixture::receipted(replica.driver, sql);                }                Ok(())            })            .unwrap();        // Me's picture, picked on this device.        let picked = dir.path().join("me.jpg");        std::fs::write(&picked, b"a synthetic picture of nobody").unwrap();        crate::methods::dispatch(            &handle,            "capture.avatar",            &json!({"personId": "person-the-owner", "path": picked.to_string_lossy(), "filename": "me.jpg", "mime": "image/jpeg"}),        )        .unwrap();        // Making Garden made the owner's person there, claimed — under the        // name the proof carried, since Me was linked afterwards.        let key = crate::phone::vault::person_public_key(&client).unwrap();        let garden_me = client            .with_file_in(&garden_id, |file| {                cotton_store::member_person::bound_person(file.driver, &garden_id, &key)                    .map_err(|error| error.to_string())            })            .unwrap()            .expect("the maker is claimed")            .person_id;        crate::phone::owner_face::forget_carried();        assert_eq!(crate::phone::owner_face::carry(&client).unwrap(), vec![garden_id.clone()]);        let in_file = |id: &str, sql: &str| {            client                .with_file_in(id, |file| file.driver.get(sql, &[]).map_err(|error| error.to_string()))                .unwrap()                .and_then(|row| row.text("v").map(str::to_string))        };        assert_eq!(            in_file(&garden_id, &format!("SELECT full_name AS v FROM cotton_people WHERE id = '{garden_me}'")).as_deref(),            Some("Tarun Invented")        );        let mine = in_file(crate::fixture::WORKSPACE, "SELECT avatar_key AS v FROM cotton_people WHERE id = 'person-the-owner'")            .expect("Me has a picture");        let theirs = in_file(&garden_id, &format!("SELECT avatar_key AS v FROM cotton_people WHERE id = '{garden_me}'"))            .expect("the picture was carried");        assert_ne!(mine, theirs, "each database keys its own copy");        assert_eq!(            crate::phone::owner_face::picture_name(&mine),            crate::phone::owner_face::picture_name(&theirs),            "the same bytes"        );        // Carried once: a second pass with nothing new writes nothing, even        // with the latch forgotten.        crate::phone::owner_face::forget_carried();        assert!(crate::phone::owner_face::carry(&client).unwrap().is_empty());        // One way: a rename in Garden is never read back into Me.        {            let _garden = client.name_database(Some(&garden_id)).unwrap();            client                .with_writer(|replica| {                    let sql = format!("UPDATE cotton_people SET full_name = 'Renamed In Garden' WHERE id = '{garden_me}'");                    replica.driver.run(&sql, &[]).map_err(|error| error.to_string())?;                    crate::fixture::receipted(replica.driver, &sql);                    Ok(())                })                .unwrap();        }        crate::phone::owner_face::forget_carried();        crate::phone::owner_face::carry(&client).unwrap();        assert_eq!(            in_file(crate::fixture::WORKSPACE, "SELECT full_name AS v FROM cotton_people WHERE id = 'person-the-owner'")                .as_deref(),            Some("Tarun Invented")        );        assert_eq!(            in_file(&garden_id, &format!("SELECT full_name AS v FROM cotton_people WHERE id = '{garden_me}'")).as_deref(),            Some("Tarun Invented"),            "Me's name is carried back over the shared rename"        );    }    // RULE: Person-owned voice writes and reads use the personal file despite a shared name.    #[test]    fn person_scoped_methods_naming_a_shared_database_read_and_write_the_personal_one() {        let (_dir, handle) = a_phone_with_a_key();        let garden = super::made_here(&handle, &json!({"name": "Garden"})).unwrap();        let garden_id = garden["databaseId"].as_str().unwrap().to_string();        let client = handle.client();        let count = |id: &str, table: &str| -> i64 {            client                .with_file_in(id, |file| {                    file.driver                        .get(&format!("SELECT COUNT(*) AS n FROM {table}"), &[])                        .map_err(|error| error.to_string())                })                .unwrap()                .and_then(|row| row.int("n"))                .unwrap_or_default()        };        let personal = crate::fixture::WORKSPACE;        let call = |method: &str, mut request: Value| {            request["database"] = json!(garden_id);            crate::methods::dispatch(&handle, method, &request)                .unwrap_or_else(|error| panic!("{method}: {error:?}"))        };        call("settings.voiceTerm", json!({"term": "Quokka"}));        assert_eq!(count(&garden_id, "cotton_voice_vocabulary"), 0);        assert_eq!(count(personal, "cotton_voice_vocabulary"), 1);        let words = call("read.voiceVocabulary", json!({}));        assert_eq!(words["terms"][0]["term"], "Quokka", "{words}");    }    fn a_phone_with_a_key() -> (tempfile::TempDir, crate::handle::CottonHandle) {        use base64::engine::general_purpose::URL_SAFE_NO_PAD;        use base64::Engine;        let dir = tempfile::tempdir().expect("a temp container");        let layout = cotton_client::layout::Layout::new(dir.path());        std::fs::create_dir_all(layout.client_dir()).expect("the client folder");        std::fs::write(            layout.connection_json(),            serde_json::to_vec_pretty(&json!({                "mode": "remote",                "baseUrl": "https://server.invalid",                "workspaceId": crate::fixture::WORKSPACE,                "ownerId": crate::fixture::OWNER,                "connectedAt": "2026-10-04T09:00:00.000Z",            }))            .expect("json"),        )        .expect("the connection record");        let replica = layout.replica(crate::fixture::WORKSPACE);        std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");        drop(crate::fixture::seeded(&replica));        let handle = crate::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(URL_SAFE_NO_PAD.encode([9u8; 32])),            vault_secret: None,            flavor: cotton_core::flavor::Flavor::Real,            manifest: None,        })        .expect("an open core");        prepare_creator(&handle, true);        (dir, handle)    }    fn prepare_creator(handle: &crate::handle::CottonHandle, snapshot: bool) {        use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};        let public = URL_SAFE_NO_PAD.encode(cotton_core::vault::wrap::public_of(&[31u8;32]));        if snapshot {            let slot = handle.client().receipt_signer_slot();            let signer = slot.get().unwrap();            handle.client().with_writer(|file| {                crate::fixture::device_row(file.driver, &signer.device_key());                cotton_client::founding::personal(file.driver, file.workspace_id, signer.as_ref(), &public, "Synthetic Owner", "2026-10-04T00:00:00.000Z", 1_791_072_000_000,                    &mut cotton_client::seams::op_ids(std::sync::Arc::new(cotton_client::seams::SystemRandom)))                    .map_err(|error|error.to_string())            }).unwrap();        }        crate::methods::dispatch(handle, "vault.publishKey", &json!({"publicKey":public})).unwrap();        crate::methods::dispatch(handle, "vault.unlock", &json!({"privateKey":URL_SAFE_NO_PAD.encode([31u8;32])})).unwrap();    }    /// RULE: The keyboard and templates write to the personal database even while a project is the one on screen — showing a database never changes where an unnamed write lands.    #[test]    fn deferred_surfaces_write_to_mine_by_id() {        let (_dir, handle) = a_phone_with_a_key();        // A PAIRED phone: its personal copy holds this key's own row, which an        // unnamed write at the screen is authored by.        let made = super::made_here(&handle, &json!({ "name": "A synthetic project" }),        )        .expect("a database");        let project = made["id"].as_str().expect("an id").to_string();        crate::methods::dispatch(&handle, "databases.show", &json!({ "databaseId": project }))            .expect("the project is on screen");        // The keyboard's write and the share sheet's write, neither naming a        // database — exactly as the extensions send them.        crate::methods::dispatch(            &handle,            "dictation.create",            &json!({ "text": "a synthetic take from the keyboard", "source": "take" }),        )        .expect("the dictation lands");        let count = |database: &str, sql: &str| {            let db = cotton_store::Driver::open(handle.layout().replica(database)).expect("the file");            db.get(sql, &[])                .expect("a count")                .and_then(|row| row.int("n"))                .unwrap_or(0)        };        const DICTATIONS: &str = "SELECT COUNT(*) AS n FROM cotton_dictations \             WHERE text = 'a synthetic take from the keyboard'";        assert_eq!(count(crate::fixture::WORKSPACE, DICTATIONS), 1, "the dictation is in Mine");        assert_eq!(count(&project, DICTATIONS), 0, "and not in the project on screen");    }    #[test]    fn a_feed_joins_its_lists_stamped_and_sums_its_counts() {        let feed = &FEEDS[2];        let mut joined = None;        let answer = |id: &str| {            json!({ "hits": [{ "id": id }], "totals": { "notes": 2 }, "query": id })                .as_object()                .cloned()                .expect("an object")        };        join(feed, &mut joined, answer("a"), "mine", "Personal");        join(feed, &mut joined, answer("b"), "team", "Team");        assert_eq!(            Value::Object(joined.expect("joined")),            json!({                "hits": [                    { "id": "a", "databaseId": "mine", "databaseName": "Personal" },                    { "id": "b", "databaseId": "team", "databaseName": "Team" },                ],                "totals": { "notes": 4 },                "query": "a",            })        );    }    #[test]    fn a_feed_joins_its_sections_by_key() {        let mut joined = None;        let answer = |id: &str| {            json!({ "hits": [], "defined": { "dish": { "label": "Dishes", "hits": [{ "id": id }], "total": 1 } } })                .as_object()                .cloned()                .expect("an object")        };        join(&FEEDS[2], &mut joined, answer("a"), "mine", "Personal");        join(&FEEDS[2], &mut joined, json!({ "hits": [] }).as_object().cloned().unwrap(), "empty", "Empty");        join(&FEEDS[2], &mut joined, answer("b"), "team", "Team");        let joined = Value::Object(joined.expect("joined"));        assert_eq!(            joined["defined"],            json!({ "dish": { "label": "Dishes", "total": 2, "hits": [                { "id": "a", "databaseId": "mine", "databaseName": "Personal" },                { "id": "b", "databaseId": "team", "databaseName": "Team" },            ] } })        );    }    /// RULE: Asked of you across databases keeps every database's comment questions and their total, so a question from the second database cannot vanish from the route.    #[test]    fn a_question_feed_keeps_the_questions_from_every_database() {        let mut joined = None;        for database in ["mine", "garden"] {            let answer = json!({"questions":{"total":1,"groups":[{"recordId":format!("note-{database}")}]}})                .as_object().unwrap().clone();            join(&FEEDS[1], &mut joined, answer, database, database);        }        let answer = Value::Object(joined.unwrap());        assert_eq!(answer["questions"]["total"], 2);        assert_eq!(answer["questions"]["groups"].as_array().unwrap().len(), 2);        assert!(answer.get("sessionQuestions").is_none(), "the session inbox is gone");    }}