Cotton code
1925 lines · 109.6 KB · RustRaw
//! COTTON ON THE PERSON'S OWN PERSONAL OBJECT.//!//! The Cotton app's database is its person's personal object on the Worker//! (`apps/business`, kind `personal`), at the one address every person shares//! (the open host, `ObjectAddress::open`): `personal.code` asks for a code by//! number, and the Worker's directory finds the number's database or makes//! it (owner, 26 Oct 2026: Cotton opens to everyone) and says its id;//! `personal.signIn` proves the code at that database and is granted a//! credential that names it. Swift keeps the credential and the database id//! together in the Keychain, and hands both to `personal.connect` on every//! launch.//!//! `personal.connect` makes this phone's copy of the object's database the one//! the decks read: an empty file of the object's `database_id` the first time,//! `connection.json` naming the object as Mine's server, and the sync loop's//! far end the object itself//! (`cotton_client::transport::object::ObjectTransport`). From then on the//! loop pulls the object's rows into the copy since its cursor and posts every//! write the phone makes; every `read.*`, `records.*` and deck reads the copy//! as it always did.//!//! **A copy is the object's cache, made again rather than moved**: a copy//! another build stamped, or one `connection.json` does not name as this//! object's (a sign-in at another address of the same database), is made//! again from the object, its unsent writes posted first; the device row//! says when (`copy_remade_at`). Nothing here moves a copy in place.//!//! **Before anyone signs in, the phone's own database is the authority**//! (owner, 1 Nov 2026): Cotton starts locally as Rigby does//! (`workspace.startLocal`, `ConnectionMode::Local`), and Backup is a sign-in//! that connects. `personal.connect` reads what the phone holds first://!//! - a LOCAL database that is this object's own copy (a phone that stopped//!   backing up, `personal.standLocal`) is the object's cache again, opened//!   with no network and its unsent writes posted by the loop;//! - a local database holding no row a person made (only the shell, the//!   genesis tools and what the app writes for itself) gives way: the//!   object's copy is made, and only once it is connected is the local one//!   removed;//! - a local database holding rows a person made is never connected over://!   it is ADOPTED (`personal.adopt`, [`crate::phone::adopt`]): its writes//!   are posted to the object first, on their own thread, and only then is//!   the object's copy made as a sign-in makes it and the local database//!   removed. Nothing a person made is lost, and nothing is sent twice.//!//! `personal.standLocal` keeps whatever copy the phone holds as its local//! database (it is the person's data) and `personal.remove` deletes it so the//! phone starts fresh.use std::sync::Arc;use cotton_client::connection::{ConnectionFile, ConnectionMode, StoredConnection};use cotton_client::media::ObjectMediaTransport;use cotton_client::transport::object::{bearer, copy_kit, kept_to, lay_served_definitions, make_copy, mark_copy_kit, rendition, routes, DeviceNamed, HeldDefinitions, MediaBacklog, ObjectAddress, ObjectTables, ObjectTransport, SignedOut, SyncProgress, THUMB_WIDTH};use cotton_client::transport::{Exchange, SocketExchange};use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;/// The methods this module answers.pub const METHODS: &[&str] = &["personal.code", "personal.signIn", "personal.connect", "personal.adopt", "personal.adoptStatus", "personal.standLocal", "personal.remove"];/// The stage of the event that says the object no longer takes this phone's/// credential.pub const SIGNED_OUT: &str = "signed_out";pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    call_with(handle, method, request, Arc::new(SocketExchange))}pub fn call_with(handle: &CottonHandle, method: &str, request: &Value, exchange: Arc<dyn Exchange>) -> Result<Value, MethodError> {    match method {        "personal.code" => code(handle, request, exchange.as_ref()),        "personal.signIn" => sign_in(handle, request, exchange.as_ref()),        "personal.connect" => {            // The gate starts no open while the copy is being moved.            let home = handle.home();            home.connecting(true);            // A PHONE SIGNED IN STAYS SIGNED IN WHILE ITS COPY IS CONNECTED            // AGAIN (owner's iPhone, Chat build 14, 21 Nov 2026: the copy made            // again after an update, the Account card offered Sign in and said            // Cotton could not be reached, and You showed no name): a connect            // over the copy of the very database it asks for — one this phone            // was signed in to — keeps the phone signed in while it runs, and            // after one that did not take, until a connect takes or the person            // signs out. A first sign-in, over a database of the phone's own,            // is not one.            let client = handle.client();            let asked = request["databaseId"].as_str().unwrap_or_default();            let held = ConnectionFile::at(client.layout().connection_json()).read();            if !asked.is_empty() && held.is_some_and(|held| held.workspace_id.as_deref() == Some(asked)) && client.layout().replica(asked).exists() {                client.keep_signed_in(Some(asked.to_string()));            }            client.set_connecting(true);            let connected = connect(handle, request, exchange);            client.set_connecting(false);            if connected.is_ok() {                client.keep_signed_in(None);            }            // A SIGN-IN THE OBJECT TOOK AND THIS PHONE DID NOT FINISH IS SAID            // (signin-sticks, 11 Nov 2026: the owner's phone kept its            // credential, stayed signed out and said nothing): the refusal            // stands until a connect takes, and `shell.home` stands failed            // on it with its words.            handle.client().note_connect_refused(connected.as_ref().err().map(|refused| (refused.code.clone(), refused.message.clone())));            if let Err(refused) = &connected {                handle.client().note_trouble_coded(&refused.code, Some(refused.message.clone()));            }            home.connecting(false);            connected        }        "personal.adopt" => crate::phone::adopt::adopt(handle, request, exchange),        "personal.adoptStatus" => Ok(crate::phone::adopt::status(handle)),        "personal.standLocal" => stand_local(handle, request),        "personal.remove" => remove(handle),        other => Err(MethodError::new("unknown_method", format!("{other} is not a personal method"))),    }}/// The number a code or an ask goes to. None typed is `bad_phone`, which the phones say in the person's words ("That/// is not a phone number Days can send a code to."): Send code on an empty field said "could not do that just now. Try/// again." (the launch walk, 22 Nov 2026), and trying again changed nothing.pub(crate) fn phone(request: &Value) -> Result<&str, MethodError> {    text(request, "phone").map_err(|_| MethodError::new("bad_phone", "no phone number was typed"))}fn text<'a>(request: &'a Value, field: &str) -> Result<&'a str, MethodError> {    request        .get(field)        .and_then(Value::as_str)        .map(str::trim)        .filter(|value| !value.is_empty())        .ok_or_else(|| MethodError::new("bad_request", format!("`{field}` is missing")))}fn open(server: &str) -> Result<ObjectAddress, MethodError> {    ObjectAddress::open(server).map_err(|reason| MethodError::new("bad_request", reason))}fn device_id(handle: &CottonHandle) -> Result<String, MethodError> {    handle.client().self_device_id().ok_or_else(|| MethodError::new("device_key_unreadable", "this device has no device identity"))}/// The database an answer names, or the refusal that it named none.fn database_of(answer: &Value) -> Result<String, MethodError> {    answer["database_id"]        .as_str()        .filter(|id| !id.is_empty())        .map(str::to_string)        .ok_or_else(|| MethodError::new("no_database_id", "the sign-in named no database"))}/// `personal.code { server, phone }`: a code for the number, from its own/// database — made by the Worker now when the number has none. Answers/// `{challengeId, expiresIn, known, databaseId, sentTo}`; the code is the person's to/// type, and `sentTo` the line saying where it went, the number masked.fn code(handle: &CottonHandle, request: &Value, exchange: &dyn Exchange) -> Result<Value, MethodError> {    let address = open(text(request, "server")?)?;    let body = json!({"phone": phone(request)?, "device_id": device_id(handle)?});    let answer = address.send(exchange, "POST", routes::CODE, Vec::new(), Some(&body))?;    let challenge = answer["challenge_id"].as_str().ok_or_else(|| MethodError::new("refused", "the object sent no challenge"))?;    let mut said = json!({"challengeId": challenge, "expiresIn": answer["expires_in"], "databaseId": database_of(&answer)?, "sentTo": sent_to(phone(request)?)});    if let Some(known) = answer["known"].as_bool() {        said["known"] = json!(known);    }    Ok(said)}/// The line under the code field, the number in it masked (`masked_number`): both phones say the same.pub(crate) fn sent_to(phone: &str) -> String {    let masked = masked_number(phone);    cotton_core::rules::shell_lines::resolve("board", "customer.sent_to", &[], &[("number", masked.as_str())]).unwrap_or_default()}/// A number as a sign-in card shows it back (NEXT-SIGNIN, owner, 28 Nov 2026): its country code and its last two/// digits, every digit between them a dot. "+91 98765 43210" is "+91 ••••••••10". A number typed without its `+`/// keeps only the last two. The country code is read by E.164's own rule: 1 and 7 are one digit, the zones' two-digit/// codes are listed, every other code is three.pub fn masked_number(phone: &str) -> String {    const TWO: &[&str] = &[        "20", "27", "30", "31", "32", "33", "34", "36", "39", "40", "41", "43", "44", "45", "46", "47", "48", "49", "51", "52", "53", "54", "55", "56",        "57", "58", "60", "61", "62", "63", "64", "65", "66", "81", "82", "84", "86", "90", "91", "92", "93", "94", "95", "98",    ];    let digits: String = phone.chars().filter(char::is_ascii_digit).collect();    let international = phone.trim_start().starts_with('+');    let country = if !international || digits.is_empty() {        0    } else if digits.starts_with('1') || digits.starts_with('7') {        1    } else if TWO.iter().any(|code| digits.starts_with(code)) {        2    } else {        3    };    let country = country.min(digits.len());    let kept = 2.min(digits.len() - country);    let hidden = digits.len() - country - kept;    let mut said = String::new();    if international {        said.push('+');        said.push_str(&digits[..country]);        said.push(' ');    }    said.extend(std::iter::repeat_n('•', hidden));    said.push_str(&digits[digits.len() - kept..]);    said}/// `personal.signIn { server, databaseId, challengeId, code, name?, nameAfter? }`: the/// code proved at its database; with `nameAfter` and no name, a new account answers `{nameNeeded: true}`. Answers `{credential, person, expiresIn,/// databaseId}` — the credential crosses to Swift, once, for the Keychain.fn sign_in(handle: &CottonHandle, request: &Value, exchange: &dyn Exchange) -> Result<Value, MethodError> {    let address = open(text(request, "server")?)?;    let mut body = json!({        "database_id": text(request, "databaseId")?,        "challenge_id": text(request, "challengeId")?,        "code": text(request, "code")?,        "device_id": device_id(handle)?,    });    if let Some(name) = request.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()) {        body["name"] = json!(name);    }    // THE NAME AFTER THE CODE: a card that asks the name only of a new account says `nameAfter`, sends the code alone,    // and is answered `nameNeeded` when the proved number has no account; it then sends the same code with the name.    if request.get("nameAfter").and_then(Value::as_bool) == Some(true) {        body["name_after"] = json!(true);    }    let answer = address.send(exchange, "POST", routes::SIGN_IN, Vec::new(), Some(&body))?;    if answer["name_needed"].as_bool() == Some(true) {        return Ok(json!({"nameNeeded": true}));    }    let credential = answer["credential"].as_str().filter(|c| !c.is_empty()).ok_or_else(|| MethodError::new("refused", "the object granted no credential"))?;    let mut said = json!({"credential": credential, "person": answer["person"], "expiresIn": answer["expires_in"], "databaseId": database_of(&answer)?});    // An account set to be deleted (its thirty days, `phone::account_delete`): the app connects nothing and asks    // Keep my account or Leave it to be deleted, in these words, before anything else.    if let Some(erase_at) = answer["deleting"]["erase_at"].as_str() {        said["deleting"] = crate::phone::account_delete::pending(erase_at);    }    Ok(said)}/// `personal.connect { server, databaseId, credential, windows?, deviceName?,/// appVersion?, dataKey? }`: `databaseId` is the one the sign-in named, kept with the/// credential; `windows` is the manifest's `{table: days}` — the tables the/// phone keeps only the newest days of (the owner's messages); the device's/// name and version file this phone in its copy's device list.fn connect(handle: &CottonHandle, request: &Value, exchange: Arc<dyn Exchange>) -> Result<Value, MethodError> {    let server = text(request, "server")?;    let asked = text(request, "databaseId")?.to_string();    // THE DATA KEY THE SHELL KEEPS FOR THIS DATABASE, held before the copy's    // first pass pulls a page (launch-fast, 21 Nov 2026): handed over after    // the gate, the sealed rows of a launch's first pages were parked and    // opened only on a later page, and a first fill's opened after it.    if let Some(key) = request.get("dataKey").and_then(Value::as_str).filter(|key| !key.is_empty()) {        handle.client().data_keys().hold(&asked, &crate::phone::seal::data_key_of(key)?);    }    let layout = handle.client().layout().clone();    let base_url = cotton_client::transport::normalize_server_url(server).unwrap_or_else(|| server.to_string());    let connection = ConnectionFile::at(layout.connection_json());    // THE TURN TO SWAP, taken where this sign-in lets go of the database the    // phone stands on and held until the object's copy stands (end of this    // call): a read meanwhile waits for it, never answering that this phone    // has no database (`shell::swap`). A first sign-in over a database of    // the phone's own takes none: that one stands until the copy replaces it.    let swapper = handle.client();    let mut swap = None;    // A COPY OF ANOTHER OBJECT belongs to that object (one copy, one object,    // 14 Nov 2026, `phone::copy_aside`): another person's sign-in never    // adopts, merges or sends it — it is set aside, kept for its own person,    // and this object's copy is made fresh. Only the same person (the same    // number, as both objects say) signing in to a new object, their old one    // gone, brings it whole (restore-from-phone, 10 Nov 2026): it stands    // local and is adopted whole below.    if let Some(held) = connection.read() {        let held_id = held.workspace_id.clone().unwrap_or_default();        let whose = if held_id.is_empty() || held_id == asked || !layout.replica(&held_id).exists() { None } else { crate::phone::copy_aside::belongs(&layout, &held)? };        if let Some(whose) = whose.filter(|whose| whose.database != asked) {            let same_person = match &whose.person {                Some(person) => asked_person(handle, request, exchange.as_ref())?.as_deref() == Some(person.as_str()),                None => false,            };            crate::phone::adopt::stop(handle);            swap.get_or_insert_with(|| swapper.swapping());            handle.client().detach();            let_go_of_the_object(&handle.client());            if same_person {                if held.mode.has_server() {                    connection                        .write(StoredConnection { mode: ConnectionMode::Local, base_url: String::new(), ..held })                        .map_err(|error| MethodError::new("io", error.to_string()))?;                }            } else {                crate::phone::copy_aside::set_aside(&layout, &held)?;            }        }    }    // THIS OBJECT'S OWN COPY, set aside when its person signed out (or a    // database whose writes were going into it): taken back, and opened as    // the object's below with its unsent writes. It takes the place of an    // empty local database the phone stood on meanwhile; a local database    // holding rows a person made stays, and is adopted below.    let _taken_back = match crate::phone::copy_aside::aside_for(&layout, &asked) {        Some(name) => {            let current = connection.read();            let replaces = match current.as_ref().and_then(|mine| mine.workspace_id.clone().filter(|id| !id.is_empty()).map(|id| (mine, id))) {                None => Some(None),                Some((mine, id)) if !mine.mode.has_server() && empty_local(&layout, mine, &id)? => Some(Some(id)),                Some(_) => None,            };            match replaces {                Some(empty) => {                    swap.get_or_insert_with(|| swapper.swapping());                    let kept = crate::phone::copy_aside::take_back(&layout, &name)?;                    if let Some(kept) = kept {                        handle.client().detach();                        let_go_of_the_object(&handle.client());                        let opened = if name == asked { StoredConnection { mode: ConnectionMode::Remote, base_url: base_url.clone(), ..kept } } else { kept };                        connection.write(opened).map_err(|error| MethodError::new("io", error.to_string()))?;                        if let Some(empty) = empty {                            give_way(&layout, &empty, &name, "an empty local database gave way to a copy taken back");                        }                    }                }                // The copy of this very object comes back where copies are                // opened: the adopt's copy is made again from it, its unsent                // writes posted first.                None if name == asked => {                    crate::phone::copy_aside::take_back(&layout, &name)?;                }                None => {}            }            true        }        None => false,    };    // WHAT THE PHONE HOLDS BEFORE THIS SIGN-IN, read before any request.    let mut gives_way = None;    if let Some(local) = connection.read().filter(|mine| !mine.mode.has_server()) {        let held_id = local.workspace_id.clone().unwrap_or_default();        if held_id == asked {            // This object's own copy, kept as the local database when the            // phone stopped backing up: the object's cache again. Its handle            // was opened as a local database's, which no pass pushes from, so            // it is let go and the copy opens again as the object's: the            // writes made while it stood local go up.            windows_of(request)?;            swap.get_or_insert_with(|| swapper.swapping());            handle.client().detach();            connection                .write(StoredConnection { mode: ConnectionMode::Remote, base_url: base_url.clone(), ..local })                .map_err(|error| MethodError::new("io", error.to_string()))?;        } else if !held_id.is_empty() {            // A row a person made, or a choice of theirs (a face, a tool            // changed), is adopted; only a database holding neither gives way.            // A former object's copy holding any live row goes whole.            let path = layout.replica(&held_id);            if !persons_rows(&path)?.is_empty() || crate::phone::adopt::underway(&layout, &held_id) || crate::phone::adopt::holds_rows(&layout, &path)? {                return crate::phone::adopt::adopt(handle, request, exchange);            }            gives_way = Some(held_id);        }    }    let phone = Phone::of(handle);    let connected = connect_copy(&phone, request, Arc::clone(&exchange), None)?;    // A sign-in and every Back up now (`topUp`): the object is asked what    // it holds and every row it lacks goes up, on a thread of its own.    if request["topUp"] == json!(true) {        crate::phone::adopt::top_up_beside(phone.clone(), request.clone(), Arc::clone(&exchange));    }    // An old copy restored whole into this object whose removal a launch did    // not see through goes once this copy has pulled through.    crate::phone::adopt::finish_left(&phone, &asked);    // A backup that connected this copy to take its data key and has not    // sent its rows yet (the app closed while it waited) goes on.    crate::phone::adopt::resume_waiting(handle, request, exchange);    // The empty local database the object's copy replaced goes now, once the    // copy is connected: never before, so a sign-in that fails part way    // leaves the phone on the database it had.    if let Some(local) = gives_way {        give_way(&layout, &local, &asked, "an empty local database gave way to the signed-in copy");    }    drop(swap);    Ok(connected)}/// Whether the local database `id` is one this phone started, never signed/// in, holding nothing a person made: it gives way to an object's copy.fn empty_local(layout: &cotton_client::layout::Layout, held: &StoredConnection, id: &str) -> Result<bool, MethodError> {    let path = layout.replica(id);    Ok(crate::phone::copy_aside::belongs(layout, held)?.is_none()        && persons_rows(&path)?.is_empty()        && !crate::phone::adopt::underway(layout, id)        && !crate::phone::adopt::holds_rows(layout, &path)?)}/// The person the object this sign-in names is, as a copy is marked/// (`copy_aside::person_in`): asked of the object only when a copy of another/// object stands here and says whose it is.pub(crate) fn asked_person(handle: &CottonHandle, request: &Value, exchange: &dyn Exchange) -> Result<Option<String>, MethodError> {    let address = open(text(request, "server")?)?;    let credential = text(request, "credential")?;    let me = address.send(exchange, "GET", routes::ME, bearer(credential), None)?;    Ok(crate::phone::copy_aside::person_in(&me, &device_id(handle).unwrap_or_default()))}/// What [`connect_copy`] needs of the phone, owned, so an adopt's own thread/// can connect the copy once the local database's writes are in the object.#[derive(Clone)]pub(crate) struct Phone {    pub client: Arc<crate::shell::client::ClientController>,    pub events: Arc<crate::events::EventBus>,    pub device_key: Option<String>,    pub app_version: String,}impl Phone {    pub fn of(handle: &CottonHandle) -> Phone {        Phone { client: handle.client(), events: Arc::clone(handle.events()), device_key: handle.identity().device_id.clone(), app_version: handle.app_version().to_string() }    }}/// The tables the manifest keeps only the newest days of, each one this/// phone keeps.fn windows_of(request: &Value) -> Result<Vec<(String, u32)>, MethodError> {    let windows = windows(request)?;    let tables = ObjectTables::personal();    for (table, _) in &windows {        if tables.object(table).is_none() {            return Err(MethodError::new("bad_request", format!("{table} is not a table this phone keeps")));        }    }    Ok(windows)}/// What an adopt lays into a copy made fresh, given the copy's path and its/// database (`phone::adopt`'s media ledger).pub(crate) type Carry<'a> = &'a dyn Fn(&std::path::Path, &str) -> Result<(), MethodError>;/// Make this phone's copy of the object the one the decks read, and start/// its loop, its door, its picture fetch and its media drain. `carry` runs/// on a copy made fresh here, before it is attached: an adopt's media/// ledger goes in there, so the drain's first pass finds it.pub(crate) fn connect_copy(phone: &Phone, request: &Value, exchange: Arc<dyn Exchange>, carry: Option<Carry<'_>>) -> Result<Value, MethodError> {    let server = text(request, "server")?;    let address = open(server)?;    let asked = text(request, "databaseId")?.to_string();    let credential = text(request, "credential")?.to_string();    let windows = windows_of(request)?;    let tables = ObjectTables::personal();    let client = Arc::clone(&phone.client);    let layout = client.layout().clone();    // The kit this app keeps to: its copy holds the kit's tools and tables    // alone, and its pulls ask for those (`ObjectTransport::keeping_to`). The account's own switches apply to it    // (`with_account_switches`: MAIL ALL ON PHONE for one account).    let kit = cotton_core::kit::AppKit::at(layout.root()).map_err(|reason| MethodError::new("io", reason))?.map(|kit| with_account_switches(kit, &layout.replica(&asked))).map(Arc::new);    // KEEP EVERYTHING ON THIS PHONE (Cotton Data, assets/design/data/CONTRACT.md row 7): this device's own choice makes    // Data's copy the whole object with no window, as Cotton's is. Its mark then differs, so the small copy is made    // again whole; switched off, it is made again on Data's kit, and the rows it filled leave this phone.    let keeps_everything = kit.as_ref().is_some_and(|kit| kit.id == crate::phone::data_app::KIT) && crate::phone::data_app::keeps_everything(layout.root(), request["unmetered"] == json!(true));    let kit = kit.filter(|_| !keeps_everything);    let windows = if keeps_everything { Vec::new() } else { windows };    // Keep everything's room guard: its fill stops while the phone has less than 2 GB free (or the person paused it), and    // goes on from where it stopped once there is room again (Cotton Data, DECISIONS question 3). Only the fill: writes    // still go up and a copy that has come whole keeps syncing (`ObjectTransport::stopping_for`).    let room_guard: Option<Arc<dyn Fn() -> Option<String> + Send + Sync>> = keeps_everything.then(|| crate::phone::data_app::room_guard(layout.root().to_path_buf()));    // The kit's own windows (Comms' 90 days of mail) beside the shell's; the shell's own wins for a table both name.    let mut windows = windows;    for (table, days) in kit.as_ref().map(|kit| kit.windows()).unwrap_or_default() {        if !windows.iter().any(|(held, _)| *held == table) {            windows.push((table, days));        }    }    let base_url = cotton_client::transport::normalize_server_url(server).unwrap_or_else(|| server.to_string());    let connection = ConnectionFile::at(layout.connection_json());    // A phone whose copy is already the object's opens it without asking the    // object anything: a launch with no network still reads its copy.    let held = connection.read().filter(|mine| mine.base_url == base_url && mine.workspace_id.as_deref() == Some(asked.as_str()));    // A COPY ANOTHER BUILD WROTE IS REMADE FROM THE OBJECT (29 Oct 2026): the    // copy is the object's cache, and one stamped with another schema than    // this build's is never moved in place — a move held every pass and every    // read of a table not yet moved for as long as it ran, and a 5 GB copy    // moved for hours or stopped part way for good (the owner's phone, 331    // over a copy its 32x build wrote: a fan of Home, Tools and Settings, and    // no request to the object again). It is made again below, as a sign-in    // makes it, its unsent writes posted to the object first.    //    // BUT A COPY WHOSE BUILD ONLY ADDED IS MOVED IN PLACE (21 Nov 2026): every    // live change is add-only by rule (new tables, columns, indexes, a search    // index), and made again, the owner's copy was empty for the 25 minutes    // the whole object took to come down, after every update. Such a move    // makes and appends, copies no row and runs in moments in one    // transaction (`move_copy_if_it_only_adds`), and the copy goes on from its    // cursor. Only a copy a move would rebuild is made again.    let moved = match held.as_ref() {        Some(_) => cotton_client::unsent::move_copy_if_it_only_adds(&layout.replica(&asked)).unwrap_or_else(|reason| {            eprintln!("[object] this phone's copy did not move in place ({reason}): it is made again from the object");            false        }),        None => false,    };    let stale = held.as_ref().filter(|_| !moved).and_then(|_| cotton_client::unsent::stamped_by_another_build(&layout.replica(&asked)));    // A COPY PULLED FOR ANOTHER KIT IS REMADE ON THIS ONE (5 Nov 2026): Cotton    // Books on the owner's phone had pulled his whole object; its copy is made    // again on the Books kit's tables, its unsent writes sent first, as a copy    // another build wrote is. So is a copy pulled for this kit before it    // gained a table (Cotton Money taking Subscriptions, 11 Nov 2026): the    // mark names the kit's tables (`AppKit::copy_mark`).    let pulled_for = copy_kit(&layout.replica(&asked));    let mut other_kit = held.is_some() && pulled_for != cotton_core::kit::AppKit::copy_mark(kit.as_deref());    // BUT A COPY OF THIS VERY KIT, PULLED BEFORE THE KIT GAINED A TABLE, IS    // KEPT AND PULLED AGAIN FROM THE START IN PLACE (launch-fast, 20 Nov    // 2026): made again, the copy was empty for as long as the whole object    // took to come down, and Cotton Story on the owner's phone showed no    // scripts for minutes on the first open after an update. Pulled from the    // start, the rows written before its cursor come down all the same, and    // every row the copy holds stays on screen meanwhile.    if other_kit && stale.is_none() && same_kit(&pulled_for, kit.as_deref()) {        pull_again_in_place(&layout.replica(&asked), kit.as_deref())?;        other_kit = false;    }    let held = held.filter(|_| stale.is_none() && !other_kit);    let mut remade_at = None;    let (database, owner) = match held {        Some(mine) => (mine.workspace_id.unwrap_or_default(), mine.owner_id.unwrap_or_default()),        None => {            // Which database, and whose: the object the credential names says both.            let served = address.send(exchange.as_ref(), "GET", routes::DEFINITIONS, bearer(&credential), None)?;            if served["business"]["kind"] != json!("personal") {                return Err(MethodError::new("not_personal", "this object is a business's, not your personal database"));            }            let database = served["business"]["database_id"]                .as_str()                .filter(|id| !id.is_empty())                .ok_or_else(|| MethodError::new("no_database_id", "the personal object names no database yet"))?                .to_string();            if database != asked {                return Err(MethodError::new("wrong_database", format!("the sign-in named database {asked}, and the object is {database}")));            }            let me = address.send(exchange.as_ref(), "GET", routes::ME, bearer(&credential), None)?;            if me["person"]["role"] != json!("owner") {                return Err(MethodError::new("owner_only", "only the owner's phone keeps a copy of the personal database"));            }            let owner = me["person"]["id"].as_str().unwrap_or_default().to_string();            let path = layout.replica(&database);            client.detach();            let now = client.clock().now_iso();            // THE MEDIA LEDGER OF THE COPY MADE AGAIN goes into the new one            // (`kept_ledger`): it is device-local, never on the object, and it            // alone says which files in this database's media folder are this            // phone's and which of them have still to go up.            let mut ledger = Vec::new();            // A copy here that is not this sign-in's own — another build's,            // or one made under another address of this database — is made            // again, never synced over or moved.            if path.exists() {                ledger = kept_ledger(&path)?;                let why = match stale {                    Some(stamped) => format!("was written at schema {stamped} and this build reads {}", cotton_store::migrate::SCHEMA_VERSION),                    None if other_kit => format!("was pulled for {pulled_for} and this app keeps to {}", cotton_core::kit::AppKit::copy_mark(kit.as_deref())),                    None => "was made under another address of this database".to_string(),                };                remake(&layout, &path, &database, &address, &exchange, &credential, &tables, &windows, sealer_of(&client, &database), &why, &now)?;                remade_at = Some(now.clone());            }            let author = cotton_client::replica::resolve_device_id(&layout, client.clock().as_ref(), client.random().as_ref())                .map_err(|error| MethodError::new("io", error.to_string()))?;            let tools = cotton_core::genesis::GenesisTools::at(layout.root()).map_err(|reason| MethodError::new("io", reason))?;            make_copy(&path, &database, &owner, &author, &now, &tools, client.receipt_signer_slot()).map_err(|reason| MethodError::new("io", reason))?;            if let Err(reason) = mark_copy_kit(&path, kit.as_deref()) {                remove_copy(&layout, &database, &path);                return Err(MethodError::new("io", reason));            }            // The first paint is the object's: the definitions it just served            // are laid into the new copy, so the fan, the decks and the boards            // draw whole before the first page of the catch-up answers. A copy            // that cannot take them is no copy: it goes, and the sign-in says why.            let now_ms = cotton_store::protocol::js::parse_date_ms(&now).unwrap_or_else(|| chrono::Utc::now().timestamp_millis());            if let Err(reason) = lay_served_definitions(&path, &database, &kept_to(&served, kit.as_deref()), now_ms) {                remove_copy(&layout, &database, &path);                return Err(MethodError::new("io", reason));            }            if let Err(refused) = carry_ledger(&path, &ledger, &now) {                remove_copy(&layout, &database, &path);                return Err(refused);            }            // What an adopt carries into the copy, before the connection names            // it: a carry that fails leaves the phone on the database it had.            if let Some(carry) = carry {                if let Err(refused) = carry(&path, &database) {                    remove_copy(&layout, &database, &path);                    return Err(refused);                }            }            // Whose this copy is, beside it: another person's sign-in sets it            // aside, never sends it (`phone::copy_aside`).            if let Err(refused) = crate::phone::copy_aside::mark(&path, &database, crate::phone::copy_aside::person_in(&me, &client.self_device_id().unwrap_or_default()).as_deref()) {                remove_copy(&layout, &database, &path);                return Err(refused);            }            connection                .write(StoredConnection {                    device_scope: None,                    takes_placements: false,                    mode: ConnectionMode::Remote,                    base_url: base_url.clone(),                    workspace_id: Some(database.clone()),                    owner_id: Some(owner.clone()),                    connected_at: Some(now),                })                .map_err(|error| MethodError::new("io", error.to_string()))?;            (database, owner)        }    };    let path = layout.replica(&database);    let named = device_named(phone, request);    own_device_row(phone.device_key.clone(), &named, &path, &database, &owner)?;    // What asks the object itself rather than syncing with it — Google    // Calendar's sign-in and status (`phone::google`) — goes through the same    // address and credential, held for this launch.    client.set_object_door(Some(Arc::new(ObjectDoor { address: address.clone(), exchange: Arc::clone(&exchange), credential: credential.clone() })));    // The pictures come from the object too: an original, or a rendition the    // object resizes to the width the card draws it at.    // A person's own files are sealed going up and opened coming down with    // the file key their data key makes (R6, `cotton_client::media::sealed`).    let person_files = person_files_of(&client, &database);    client.set_media_fetch(Some(Arc::new(ObjectMedia {        transport: ObjectMediaTransport::new(address.clone(), Arc::clone(&exchange), credential.clone()).sealing(Arc::clone(&person_files)),        replica: path.clone(),        stories: Some(StoryKeys { keys: Arc::clone(client.data_keys()), database: database.clone() }),    })));    // And the thumbnails ahead of the screens: after every pass, and once    // below, the 256 px renditions this copy names and this phone lacks    // (`phone::media_sweep`), through the same fetch.    client.set_pictures_sweep(Some(crate::phone::media_sweep::PicturesSweep::new(Arc::clone(&phone.events))));    // A credential the object stops taking (a 401 to a pass) signs this phone    // out: no pass dials with it again, the copy stays, and the app is told    // once (`client` `{phase: personal, stage: signed_out, code}`) so it    // forgets the credential and asks for a sign-in; a new sign-in connects    // the copy again under a new credential.    let events = std::sync::Arc::clone(&phone.events);    let refused_client = Arc::downgrade(&client);    client.note_signed_out(None);    let signed_out = SignedOut::new(move |refusal| {        if let Some(client) = refused_client.upgrade() {            client.keep_signed_in(None);            client.note_signed_out(Some(refusal.code.clone()));            client.note_trouble(Some(refusal.message.clone()));        }        // The person deleted the account (another phone, or the website): the app forgets this phone's copy        // (`account.forget`) and says why, in the words carried here (`phone::account_delete`).        let mut said = json!({"phase": "personal", "stage": SIGNED_OUT, "code": refusal.code, "message": refusal.message});        if refusal.deleted() {            said["deleted"] = json!(true);            said["words"] = crate::phone::account_delete::elsewhere(&refusal.message);        }        events.emit(crate::events::EventKind::Client, said);    });    // What only this phone knows of its passes — the bytes they received and    // a pass that has stopped moving — written on its own device row, which    // the object names in every answer (`SyncProgress`): the row of the    // device id its credential was granted to, which the object files from    // what each pass's first page says this phone is (`DeviceNamed`) when it    // holds none. Held across passes.    let progress = SyncProgress::system();    if let Some(at) = remade_at {        progress.remade(at);    }    // AND THE CAPTURES GO UP: the `_media` queue drains to the object's media    // door under the same credential (`PUT /v1/media/<key>`, or the file in    // parts), after every pass and on its own minute; its counts ride the    // device row with the next pass (`MediaBacklog`). The bytes stay on this    // phone: the object is the backup.    let told = Arc::clone(&progress);    client.set_media_upload(Some(crate::shell::client::MediaUpload {        deps: Arc::new(ObjectMediaTransport::new(address.clone(), Arc::clone(&exchange), credential.clone()).sealing(person_files)),        on_status: Some(Arc::new(move |status: &cotton_client::media::MediaDrainStatus| {            told.media(MediaBacklog { waiting_bytes: status.pending_bytes, waiting: status.pending, failed: status.failed });        })),        // A COPY OF A PHOTOS ORIGINAL leaves once the object holds it (KEEP 1e).        after_uploads: {            let releasing = Arc::downgrade(&client);            Some(Arc::new(move || {                if let Some(client) = releasing.upgrade() {                    match client.release_photos_copies() {                        Ok(released) if released.files > 0 => tracing::info!("media: {} Photos copies released, {} bytes", released.files, released.bytes),                        Ok(_) => {}                        Err(reason) => tracing::warn!("media: Photos copies stay for now: {reason}"),                    }                }            }))        },    }));    let state_client = Arc::downgrade(&client);    client.set_sync_progress(Some(Arc::clone(&progress)));    // The object's tools and boards, which the fan draws: written into the    // copy from the first page of this launch and again whenever the object    // moves its definitions (`ObjectTransport::taking_definitions`), the    // etag the copy matches held across the passes.    let definitions = HeldDefinitions::new();    client.set_served_definitions(Some(Arc::clone(&definitions)));    // A copy whose passes are stuck on one page — three running failed there    // for one reason while the object answered — is made again from the    // object, as a copy another build wrote is, at most once a launch    // (`ClientController::set_sync_heal`).    let heal = Heal {        client: Arc::downgrade(&client),        layout: layout.clone(),        path: layout.replica(&database),        database: database.clone(),        owner: owner.clone(),        address: address.clone(),        exchange: Arc::clone(&exchange),        credential: credential.clone(),        tables: Arc::clone(&tables),        windows: windows.clone(),        kit: kit.clone(),        progress: Arc::clone(&progress),        definitions: Arc::clone(&definitions),        device_key: phone.device_key.clone(),        named: named.clone(),    };    let heal = Arc::new(heal);    let restore = Arc::clone(&heal);    client.set_sync_heal(Some(Arc::new(move |why: &str| heal.run(why))));    // The server put back to an earlier time (RESTORE 2): the copy is set aside and made again from it.    client.set_restore_heal(Some(Arc::new(move |restored| restore.run_restored(restored))));    // The loop's far end: the object, for every pass from now on. A copy this    // launch attached already runs its loop again over it; any other file    // still attached (the local database this sign-in replaces, opened again    // by a read while the copy was made) is let go for the copy.    let attached = client.attached_database().as_deref() == Some(database.as_str());    let replica = path.clone();    let discard_layout = client.layout().clone();    let discard_database = database.clone();    // The database's sealing on this device: the data key the shell handed    // over (`phone::seal`), and each sealed table's version, for every pass.    let sealer = sealer_of(&client, &database);    // A copy an earlier build wrote that waits for the data key (`remake`)    // goes up sealed at the start of the first pass once the key is held,    // before that pass pulls (`send_waiting`).    let waiting_client = Arc::downgrade(&client);    let waiting_database = database.clone();    client.set_transport(Some(Arc::new(move || {        if let Some(client) = waiting_client.upgrade() {            send_waiting(&client, &waiting_database, &address, &exchange, &credential, &tables, &windows, &sealer);        }        Ok(Box::new(            ObjectTransport::new(address.clone(), Arc::clone(&exchange), credential.clone(), Arc::clone(&tables), replica.clone(), windows.clone())                .discarding_to(discard_layout.clone(), discard_database.clone())                .signing_out_to(Arc::clone(&signed_out))                .reporting_to(Arc::clone(&progress))                .reporting_state_to(Arc::new({                    let client = state_client.clone();                    move || client.upgrade().and_then(|client| client.device_state())                }))                .naming(named.clone())                .keeping_to(kit.clone())                .stopping_for(room_guard.clone())                .taking_definitions(Arc::clone(&definitions))                .sealing_with(Arc::clone(&sealer)),        ) as Box<dyn cotton_client::transport::SyncingTransport>)    })));    if attached {        client.restart_sync_loop();    } else {        client.detach();        client.attach_now().map_err(|reason| MethodError::new("not_attached", reason))?;    }    crate::phone::media_sweep::kick(&client);    Ok(json!({"databaseId": database, "ownerId": owner}))}/// MAIL ALL ON PHONE for one account (coordinator, 24 Nov 2026): an object whose switch is on (`POST/// /v1/admin/mail-all`) says `mail_all` on every sync page, which the copy keeps beside its cursor; at the next/// launch the kit keeps its mail tables whole past their window, as the manifest's `all_history` would for every/// account. The copy's mark then differs, so the mail tables come again whole (`pull_again_in_place`); switched off,/// the window stands again from the launch after.pub(crate) fn with_account_switches(mut kit: cotton_core::kit::AppKit, copy: &std::path::Path) -> cotton_core::kit::AppKit {    if cotton_client::transport::object::account_features(copy).iter().any(|name| name == "mail_all") {        for table in ["email", "email_thread"] {            if kit.window.contains_key(table) && !kit.all_history.iter().any(|held| held == table) {                kit.all_history.push(table.to_string());            }        }    }    kit}/// Whether a copy marked `pulled_for` was pulled for this very kit (its/// tables then, whatever they are now): the mark's first word is the kit's id.fn same_kit(pulled_for: &str, kit: Option<&cotton_core::kit::AppKit>) -> bool {    kit.is_some_and(|kit| pulled_for.split_once(' ').map_or(pulled_for, |(id, _)| id) == kit.id)}/// The copy at `path` pulls again from the start on its next pass, keeping/// every row it holds: its record of the tables its cursor went past goes/// ([`cotton_client::transport::object::PASSED_KEY`]), which a pass reads as/// owing a pull from the start, and it is marked as the kit's as it ships.fn pull_again_in_place(path: &std::path::Path, kit: Option<&cotton_core::kit::AppKit>) -> Result<(), MethodError> {    // THE TABLES THE KIT GAINED COME WHOLE, THE REST SINCE THE CURSOR (21 Nov    // 2026): pulled again from the start, every row of the whole object came    // down again after the update. The copy's record owes the gained tables    // alone (`owe_whole`), and its next pass asks them `again=`.    let pulled_for = copy_kit(path);    let (_, had, had_whole) = cotton_core::kit::AppKit::read_copy_mark(&pulled_for);    let mut gained: Vec<String> = kit.map(|kit| kit.pulled()).unwrap_or_default().into_iter().filter(|table| !had.contains(table)).collect();    // ALL MAIL ON THE PHONE (24 Nov 2026): a table the kit now keeps whole past its window owes the rows the window    // left on the object, so it comes whole as a gained table does. One the kit keeps to its window again needs    // nothing: the older rows the copy holds stay, and the window keeps out only what it never pulled.    let widened: Vec<String> = kit.map(|kit| kit.whole_past_window()).unwrap_or_default().into_iter().filter(|table| !had_whole.contains(table) && !gained.contains(table)).collect();    gained.extend(widened);    // NOTHING GAINED KEEPS THE CURSOR (the coordinator's review of COMMS WITHOUT MAIL, 27 Nov 2026): the kit's tables    // are the copy's or fewer (Comms letting its eight mail tables go; a table kept to its window again), so nothing the    // cursor went past is owed. Asking the tables EQUAL deleted the cursor of a kit that only lets tables go, and the    // first launch pulled every table from the start again on a copy of several gigabytes. The rows of a table let go    // stay in the copy; the pass no longer asks for them.    if kit.is_some() && gained.is_empty() {        mark_copy_kit(path, kit).map_err(|reason| MethodError::new("io", reason))?;        eprintln!("[object] this phone's kit gained no table: the rows it holds stay, it pulls on from its cursor");        return Ok(());    }    if !gained.is_empty() && cotton_client::transport::object::owe_whole(path, &gained).map_err(|reason| MethodError::new("io", reason))? {        mark_copy_kit(path, kit).map_err(|reason| MethodError::new("io", reason))?;        eprintln!("[object] this phone's kit gained {}: those tables come whole on the next pass, the rest since its cursor", gained.join(", "));        return Ok(());    }    let db = cotton_store::driver::Driver::open(path).map_err(|error| MethodError::new("io", format!("this phone's copy could not be opened to pull again ({error})")))?;    db.run("DELETE FROM _cursors WHERE author_device_id = ?", &[rusqlite::types::Value::Text(cotton_client::transport::object::PASSED_KEY.to_string())])        .map_err(|error| MethodError::new("io", format!("this phone's copy could not be set to pull again ({error})")))?;    drop(db);    mark_copy_kit(path, kit).map_err(|reason| MethodError::new("io", reason))?;    eprintln!("[object] this phone's copy was pulled for an earlier shape of its kit: it is kept and pulled again from the start");    Ok(())}/// How many rows a person made in the local database at `path`: the rows/// its unsent writes name — queued (`_outbox`), parked, or held because no/// server ever checked this phone's clock (`held = 1`, every write of a/// phone that started alone) — counted once each, and only in a table a/// tool of this database draws (Todos' todo, the Notebook's note, a kit/// tool's own records). What the app writes for itself as it runs (usage/// counts, the vault's keys, its admissions and statements, news settings)/// is in no tool's tables and waits for nobody; nor do the shell and the/// genesis tools, written served as the file is founded.pub fn made_rows(path: &std::path::Path) -> Result<u64, MethodError> {    Ok(persons_rows(path)?.made.len() as u64)}/// The rows of a local database that are the person's, by `(store table,/// row id)` as receipts name them: what an adopt sends to the object.#[derive(Debug, Default, Clone)]pub struct PersonsRows {    /// The rows a person made ([`made_rows`]): in a table a tool draws.    pub made: std::collections::BTreeSet<(String, String)>,    /// The person's choices that are rows too and go with them: the face    /// each table wears (`face_settings`), and the definitions they changed    /// (a tool added or removed, a board, a table's look, a theme), sent    /// through the object's definition act after the rows.    pub choices: std::collections::BTreeSet<(String, String)>,    /// Changes set aside because they did not read (QUEUE BAD OP 3): a database holding one is never empty, so a    /// sign-in never lets it give way and removes its folder.    pub set_aside: usize,    /// The local vault key's wrap this phone's founding made (KEPT FOUR 2): it founds a first-ever account (decision    /// a), so a database holding it never gives way; into an account with a vault it never goes.    pub founding: std::collections::BTreeSet<(String, String)>,    /// The person's rows sealed under the local vault key (`vault_keep::SEALED`), among `made`: posted as they are    /// only when the local key founds the account; otherwise they wait for the re-seal (`vault_carry`).    pub sealed: std::collections::BTreeSet<(String, String)>,    /// The person's rows that name one of `sealed` (KEPT FOUR 3 LOW: a passkey's or a placement's link to a password    /// held back): into an account with a vault they wait with it, quietly, never refused `bad_link` and kept.    pub linked: std::collections::BTreeSet<(String, String)>,}impl PersonsRows {    pub fn is_empty(&self) -> bool {        self.made.is_empty() && self.choices.is_empty() && self.set_aside == 0 && self.founding.is_empty()    }    /// Whether an adopt into an account whose vault stands as `vault` posts this row (KEPT FOUR 2).    pub(crate) fn goes(&self, vault: crate::phone::adopt::AccountVault, table: &str, row: &str) -> bool {        let key = (table.to_string(), row.to_string());        match vault {            crate::phone::adopt::AccountVault::Unfounded => self.holds(table, row) || self.founding.contains(&key),            crate::phone::adopt::AccountVault::Founded => self.holds(table, row) && !self.sealed.contains(&key) && !self.linked.contains(&key),        }    }    pub fn holds(&self, table: &str, row: &str) -> bool {        let key = (table.to_string(), row.to_string());        self.made.contains(&key) || self.choices.contains(&key)    }}/// Where a list and its members are kept here.const GROUPS_STORE: &str = "cotton_groups";const MEMBERS_STORE: &str = "cotton_group_members";/// The person's rows among the unsent writes of the local database at `path`.pub fn persons_rows(path: &std::path::Path) -> Result<PersonsRows, MethodError> {    let mut rows = PersonsRows::default();    if !path.exists() {        return Ok(rows);    }    let unreadable = |reason: String| MethodError::new("io", format!("this phone's database could not be read ({reason})"));    let unsent = cotton_client::unsent::unsent_changes(path).map_err(unreadable)?;    let db = cotton_store::driver::Driver::open_reader(path).map_err(|error| unreadable(error.to_string()))?;    rows.set_aside = cotton_store::rejected::set_aside(&db).map_err(|error| unreadable(error.to_string()))?.len();    let drawn = drawn_tables(&db).map_err(unreadable)?;    let stores: std::collections::BTreeSet<&str> =        drawn.iter().filter_map(|table| cotton_core::definitions::builtin_store_table(table)).collect();    // A list of a drawn table, and each of its members, is the person's too:    // a list is kept in `cotton_groups` and its members in    // `cotton_group_members`, which no tool names (books-4-walk, 6 Nov 2026:    // a Books list made before sign-in never reached the object).    let listed = |sql: &str, id: &str| -> Result<bool, String> {        let row = db.get(sql, &[rusqlite::types::Value::Text(id.to_string())]).map_err(|error| error.to_string())?;        Ok(row.and_then(|row| row.text("table_id").map(|table| drawn.contains(table))).unwrap_or(false))    };    for change in unsent {        let key = (change.table.clone(), change.row_id.clone());        // The local database's own founding (its person, vault, admission: KEPT FOUR) is never a person's row, though        // a tool draws a vault's key table. Its vault key's wrap is kept apart (KEPT FOUR 2): it founds a first-ever        // account, and never goes into one that has a vault.        if cotton_client::founding::is_founding(&change.table) {            if change.table == "cotton_vault_keys" {                rows.founding.insert(key);            }            continue;        }        if cotton_client::vault_keep::SEALED.iter().any(|(table, _, _)| *table == change.table) {            rows.sealed.insert(key.clone());        }        if stores.contains(change.table.as_str()) {            rows.made.insert(key);        } else if change.table == GROUPS_STORE && listed("SELECT table_id FROM cotton_groups WHERE id = ?", &change.row_id).map_err(unreadable)?            || change.table == MEMBERS_STORE                && listed("SELECT g.table_id FROM cotton_group_members m JOIN cotton_groups g ON g.id = m.group_id WHERE m.id = ?", &change.row_id).map_err(unreadable)?        {            rows.made.insert(key);        } else if cotton_client::transport::object::DEFINITION_TABLES.contains(&change.table.as_str())            || cotton_core::kit::face_choice_tables().iter().any(|table| change.table.strip_prefix("cotton_") == Some(table.as_str()))        {            // A data table's rows are kept in `cotton_<id>`.            rows.choices.insert(key);        } else if change.table.strip_prefix("cotton_").is_some_and(|table| drawn.contains(table)) {            // A kit table a tool draws keeps its rows in `cotton_<id>` too            // (Books' book and highlight): a person's rows, as a primitive's            // are (a book added before sign-in was left behind, 5 Nov 2026).            rows.made.insert(key);        }    }    // The rows that name a row sealed under the local key wait with it (KEPT FOUR 3 LOW).    let ids: std::collections::BTreeSet<String> = rows.sealed.iter().map(|(_, id)| id.clone()).collect();    let candidates: Vec<(String, String)> = rows.made.iter().chain(rows.choices.iter()).filter(|key| !rows.sealed.contains(*key)).cloned().collect();    rows.linked = cotton_client::vault_keep::rows_naming(path, &ids, &candidates).map_err(unreadable)?;    Ok(rows)}/// The tables the tools of the database open in `db` draw, by id.fn drawn_tables(db: &cotton_store::driver::Driver) -> Result<std::collections::BTreeSet<String>, String> {    let mut drawn = std::collections::BTreeSet::new();    // A kit table no tool draws (Sites' `site`, Post's `email_account`) is the person's too where the copy holds it:    // its rows made before sign-in go up with the rest (genesis makes kit tables, 25 Nov 2026).    for table in cotton_core::kit::kit_own_tables() {        if db.get("SELECT 1 AS n FROM cotton_table_definitions WHERE id = ?", &[rusqlite::types::Value::Text(table.to_string())]).map_err(|error| error.to_string())?.is_some() {            drawn.insert(table.to_string());        }    }    for row in db.all("SELECT definition FROM cotton_tool_definitions", &[]).map_err(|error| error.to_string())? {        let Some(definition) = row.text("definition") else { continue };        let definition: Value = serde_json::from_str(definition).map_err(|error| error.to_string())?;        for table in definition["tables"].as_array().into_iter().flatten().filter_map(Value::as_str) {            drawn.insert(table.to_string());        }    }    Ok(drawn)}/// `personal.standLocal`: this phone holds no credential the object takes/// — it stopped backing up, or the object signed it out, or nobody has/// signed in — so whatever copy it holds stays, as its local database (it is/// the person's data), and no pass dials the object again: the loop's far/// end, the object's door and its picture fetch go, and `connection.json`/// says `local`. The app forgets the credential itself (the Keychain is/// Swift's). Signing in again with the same number connects the same copy/// (`personal.connect`). `{signedOut: true}` says the credential is forgotten/// too (Sign out, or the object's 401): a failed sign-in stops being said./// Answers `{"databaseId"}` of the database kept, or `{}` with none.pub fn stand_local(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    crate::phone::adopt::stop(handle);    let client = handle.client();    // From the detach until the database this phone stands on next is    // written and open, a read on another thread waits (`shell::swap`): Sign    // out drew "has not started or joined a database yet" for a moment.    let _swap = client.swapping();    let stood = stand_local_swapping(handle, request);    client.let_go_if_stale();    stood}/// [`stand_local`], inside its turn to swap.fn stand_local_swapping(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let client = handle.client();    // `{signedOut: true}`: the person signed out, or the object did it for    // them. Nothing of a sign-in is left to say: a connect that was refused    // and an adopt that failed are forgotten with the credential.    if request["signedOut"] == json!(true) {        client.keep_signed_in(None);        client.note_connect_refused(None);        client.note_trouble(None);        client.note_topped_up(None);        client.set_adopting(None);    }    let layout = client.layout().clone();    let connection = ConnectionFile::at(layout.connection_json());    let held = connection.read();    client.detach();    let_go_of_the_object(&client);    // SIGNED OUT, THE COPY IS SET ASIDE (one copy, one object, 14 Nov 2026):    // nothing of the person who signed out is drawn or read again on this    // phone until they sign in; their copy and its unsent writes wait aside    // for them (`phone::copy_aside`), and the phone stands on a fresh local    // database of its own. A database never signed in is the phone's and stays.    if request["signedOut"] == json!(true) {        return stand_signed_out(handle, request, held);    }    let Some(held) = held else { return Ok(json!({})) };    let database = held.workspace_id.clone();    if held.mode.has_server() {        connection            .write(StoredConnection { mode: ConnectionMode::Local, base_url: String::new(), ..held })            .map_err(|error| MethodError::new("io", error.to_string()))?;    }    Ok(database.map_or_else(|| json!({}), |database| json!({"databaseId": database})))}/// `standLocal {signedOut}`: every copy of an object where copies open goes/// aside — the held one, and any a sign-in that did not finish left there/// with no address (an object's copy taken back for it while an adopt of the/// phone's own database stopped part way, or the app closed under it). The/// phone stands on its own database, one it started and never signed in,/// else on a fresh one — never a second start refused `already_started`,/// which left nothing to read. Holding nothing at all, the boot starts one.fn stand_signed_out(handle: &CottonHandle, request: &Value, held: Option<StoredConnection>) -> Result<Value, MethodError> {    let client = handle.client();    let layout = client.layout().clone();    let connection = ConnectionFile::at(layout.connection_json());    let named = request.get("deviceName").and_then(Value::as_str).map(str::to_string).or_else(|| held.as_ref().and_then(|held| own_name(&client, held)));    let mut own = None;    // The phone's own database whose backup into the held copy waits for its data key (another device of the    // person's holds it): the rows made before sign-in have not gone up. Signing out gives it back to the phone,    // as it was before the sign-in, never aside with the account's copy (walk 3, 24 Nov 2026: Days Dev's event made    // signed out was gone for good after "One more step", then Sign out). A later sign-in backs it up again.    let held_database = held.as_ref().and_then(|held| held.workspace_id.clone()).filter(|id| !id.is_empty());    let waiting = held_database.as_deref().and_then(|database| {        cotton_client::join::held_workspaces(&layout, database).into_iter().find(|stray| {            cotton_client::transport::object::AdoptLog::beside(&stray.replica).waits_in().as_deref() == Some(database)                && !crate::phone::adopt::former_copy(&stray.replica).unwrap_or(true)        })    });    if let Some(stray) = &waiting {        crate::phone::copy_aside::unmark(&stray.replica)?;        // not a copy: the adopt's log beside it.        let _ = std::fs::remove_file(stray.replica.with_file_name("adopt.log"));        client.set_carried_key(None);    }    if let Some(held) = &held {        if crate::phone::copy_aside::belongs(&layout, held)?.is_some() {            crate::phone::copy_aside::set_aside(&layout, held)?;        } else {            own = held.workspace_id.clone().filter(|id| !id.is_empty());        }    }    if own.is_none() {        own = waiting.map(|stray| stray.workspace_id);    }    let mut set_aside_any = false;    for stray in cotton_client::join::held_workspaces(&layout, own.as_deref().unwrap_or_default()) {        let as_held = StoredConnection {            device_scope: None,            takes_placements: false,            mode: ConnectionMode::Local,            base_url: String::new(),            workspace_id: Some(stray.workspace_id.clone()),            owner_id: crate::phone::adopt::local_owner(&stray.replica),            connected_at: None,        };        if crate::phone::copy_aside::belongs(&layout, &as_held)?.is_some() {            crate::phone::copy_aside::set_aside(&layout, &as_held)?;            set_aside_any = true;        } else if own.is_none() {            own = Some(stray.workspace_id);        }    }    if let Some(own) = own {        if held.as_ref().and_then(|held| held.workspace_id.as_deref()) != Some(own.as_str()) {            connection                .write(StoredConnection {                    device_scope: None,                    takes_placements: false,                    mode: ConnectionMode::Local,                    base_url: String::new(),                    workspace_id: Some(own.clone()),                    owner_id: crate::phone::adopt::local_owner(&layout.replica(&own)),                    connected_at: None,                })                .map_err(|error| MethodError::new("io", error.to_string()))?;        }        return Ok(json!({"databaseId": own}));    }    if held.is_none() && !set_aside_any {        return Ok(json!({}));    }    let started = crate::phone::commands::start_local(handle, &json!({"deviceName": named}))?;    Ok(json!({"databaseId": started["workspaceId"]}))}/// What this phone is called in the copy `held` names: its own device row's/// name, so the fresh local database files it the same.fn own_name(client: &crate::shell::client::ClientController, held: &StoredConnection) -> Option<String> {    let key = client.self_device_id()?;    let path = client.layout().replica(held.workspace_id.as_deref()?);    let db = cotton_store::driver::Driver::open_reader(&path).ok()?;    cotton_tools::devices::FileDevices::new(&db).row_for(&key).ok().flatten().map(|row| row.name)}/// `personal.remove`: the copy this phone holds is deleted — its folder,/// with every unsent write in it — and `connection.json` with it, so the/// next start makes a fresh local database. The person's own destructive/// act, asked first on the screen. Answers `{"removed": <id or null>}`.pub fn remove(handle: &CottonHandle) -> Result<Value, MethodError> {    crate::phone::adopt::stop(handle);    let client = handle.client();    // A read meanwhile waits for the copy to be gone (`shell::swap`), never    // reopening a file whose folder is being deleted.    let _swap = client.swapping();    let layout = client.layout().clone();    let held = ConnectionFile::at(layout.connection_json()).read().and_then(|held| held.workspace_id);    client.detach();    let_go_of_the_object(&client);    client.note_signed_out(None);    client.note_connect_refused(None);    client.note_trouble(None);    client.note_topped_up(None);    client.set_adopting(None);    if let Some(database) = &held {        // The person's own Remove, asked first on the screen: it really removes (QUEUE BAD OP 4, one of three). This        // handler is one of the three that make the person's act (QUEUE BAD OP 5, item 5).        let act = cotton_client::copy_keep::PersonsAct::of_the_person();        remove_database_folder(&layout, database, cotton_client::copy_keep::Ending::OwnRemove(&act));    }    // not a copy: the connection file.    match std::fs::remove_file(layout.connection_json()) {        Ok(()) => {}        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}        Err(error) => return Err(MethodError::new("io", format!("this phone's connection could not be removed ({error})"))),    }    client.let_go_if_stale();    Ok(json!({"removed": held}))}/// Nothing this launch holds reaches the object any more (`account.forget` too).pub(crate) fn let_go(client: &crate::shell::client::ClientController) {    let_go_of_the_object(client);}/// Nothing this launch holds reaches the object any more.fn let_go_of_the_object(client: &crate::shell::client::ClientController) {    // Signed out: Hidden shuts for this account first, while its key still names it (re-review 3, finding 6).    crate::phone::cinemas_home::lock_account(client);    client.set_transport(None);    client.set_object_door(None);    client.set_media_fetch(None);    client.set_media_upload(None);    client.set_pictures_sweep(None);    client.set_sync_progress(None);    client.set_sync_heal(None);    client.set_restore_heal(None);}/// A database's whole folder on this phone, its copy and journal with it, through the one function a copy leaves its/// place by (QUEUE BAD OP 4, `cotton_client::copy_keep`): with `Ending::Keep` a copy holding anything unsent is kept/// whole aside, never removed.pub(crate) fn remove_database_folder(layout: &cotton_client::layout::Layout, database: &str, ending: cotton_client::copy_keep::Ending<'_>) {    // QUEUE BAD OP 6 (H1): its media folder goes with it through the one function: kept with a kept copy, removed only    // when the copy went; a folder that stays keeps its media where they are.    let folder = layout.client_dir().join(database);    if let Err(error) = cotton_client::copy_keep::retire_database(layout, database, &folder, &layout.client_media_dir().join(database), ending) {        eprintln!("[object] the folder of database {database} stays where it is, with its media: {error}");    }}/// An empty local database gives way to the copy now open, `live` (QUEUE BAD OP 6, H2): kept, it is filed under/// `live`, where recovery, Storage and account delete read; never under the local id nobody reads.pub(crate) fn give_way(layout: &cotton_client::layout::Layout, local: &str, live: &str, why: &str) {    remove_database_folder(layout, local, cotton_client::copy_keep::Ending::keep_into(why, live, &[]));}/// What this phone is called, as `personal.connect` was told: its own row/// in the copy and the object's row of its credential say the same.fn device_named(phone: &Phone, request: &Value) -> DeviceNamed {    let named = |field: &str| request.get(field).and_then(Value::as_str).map(str::trim).filter(|value| !value.is_empty());    DeviceNamed {        name: named("deviceName").unwrap_or("This phone").to_string(),        platform: Some(crate::phone::commands::asked_platform(named("platform")).as_str().to_string()),        app_version: named("appVersion").map(str::to_string).or(Some(phone.app_version.clone())),    }}/// This phone in its copy's own device list, as a phone that starts a/// database of its own writes itself (`workspace.startLocal`): the object/// admitted it by its credential, and every write here is the owner's at this/// row. Written once and found on every later launch; a phone whose Keychain/// held no key writes none, and its writes say so (`authoring::NO_DEVICE_ROW`).fn own_device_row(device_key: Option<String>, named: &DeviceNamed, path: &std::path::Path, database: &str, owner: &str) -> Result<(), MethodError> {    use cotton_tools::devices::{DeviceWrite, FileDevices, NewDeviceRow, SELF_APPROVER};    let Some(key) = device_key else { return Ok(()) };    let failed = |error: cotton_store::StoreError| MethodError::new("io", format!("this phone could not be written into its copy ({error})"));    let db = cotton_store::driver::Driver::open(path).map_err(failed)?;    if FileDevices::new(&db).row_for(&key).map_err(failed)?.is_some_and(|row| row.revoked_at.is_none()) {        return Ok(());    }    let named = named.clone();    let now = chrono::Utc::now();    DeviceWrite { db: &db, workspace_id: database, owner_id: owner, now, random: Arc::new(cotton_tools::random::SystemRandom) }        .insert(&NewDeviceRow {            device_id: key,            workspace_id: database.to_string(),            name: named.name,            platform: Some(crate::phone::commands::asked_platform(named.platform.as_deref())),            app_version: named.app_version,            approved_at: now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true),            approved_by: SELF_APPROVER.to_string(),            relay_identity_key: None,        })        .map(|_| ())        .map_err(failed)}/// `MediaFetch` at the personal object: `GET /v1/media/<key>` with the/// credential. A rendition the phone names (`.t256.jpg`, `.d1600.jpg`) is the/// object's original at that width — a photo's original found by its hash in/// The person's own object, asked directly: one request with this phone's/// credential, answered as the object's JSON or its refusal. Held by the/// client from `personal.connect` on; the credential never leaves it.pub struct ObjectDoor {    pub address: ObjectAddress,    pub exchange: Arc<dyn Exchange>,    pub credential: String,}impl std::fmt::Debug for ObjectDoor {    // The credential is never said, however the door is printed.    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("ObjectDoor").field("address", &self.address).finish_non_exhaustive()    }}impl ObjectDoor {    pub fn send(&self, method: &str, path: &str, body: Option<&Value>) -> Result<Value, MethodError> {        Ok(self.address.send(self.exchange.as_ref(), method, path, bearer(&self.credential), body)?)    }}/// this phone's copy, a film's by its poster, a conversation's picture by the/// key its thumbnail carries — so nothing here makes a thumbnail.#[derive(Debug)]struct ObjectMedia {    transport: ObjectMediaTransport,    replica: std::path::PathBuf,    /// The data keys and database a sealed story's picture opens under: its    /// file key is derived from the DK, not kept in the row.    stories: Option<StoryKeys>,}/// What opens a sealed story's picture: the held data keys and the database/// whose DK derives the file key (`cotton_core::seal::file::derived_key`).pub(crate) struct StoryKeys {    pub keys: Arc<cotton_client::seal::HeldDataKeys>,    pub database: String,}impl std::fmt::Debug for StoryKeys {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("StoryKeys").field("database", &self.database).finish_non_exhaustive()    }}impl ObjectMedia {    /// The key the object keeps for `key`, and the width to ask it at.    fn source(&self, key: &str) -> Result<(String, Option<u32>), crate::phone::media::NotFetched> {        // A conversation's picture: its thumbnail carries the picture's key.        if let Some(picture) = cotton_core::media::keys::message_picture_of_thumb(key) {            return Ok((picture.to_string(), Some(THUMB_WIDTH)));        }        let Some((folder, sha, width)) = rendition(key) else { return Ok((key.to_string(), None)) };        let database = key.split('/').next().unwrap_or_default();        if folder == "videos" {            return Ok((format!("{database}/videos/{sha}.poster.jpg"), Some(width)));        }        let file = cotton_store::driver::Driver::open_reader(&self.replica)            .map_err(|error| not_fetched(format!("this phone's copy could not be read ({error})"), None))?;        let original = file.get("SELECT key FROM cotton_photos WHERE sha256 = ?1 AND key IS NOT NULL LIMIT 1", &[rusqlite::types::Value::Text(sha.to_string())])            .map_err(|error| not_fetched(error.to_string(), None))?            .and_then(|row| row.text("key").map(str::to_string));        let original = match original {            Some(original) => Some(original),            None => super::media_sweep::declared_pictures(&file, database)                .map_err(|error| not_fetched(error, None))?                .into_iter().map(|(_, original)| original)                .find(|original| cotton_core::media::keys::thumb_key_for(original).as_deref() == Some(key)                    || cotton_core::media::keys::display_key_for(original).as_deref() == Some(key)),        };        original.map(|original| (original, Some(width))).ok_or_else(|| not_fetched(format!("no picture of this copy is {sha}"), Some(404)))    }}fn not_fetched(reason: String, status: Option<u16>) -> crate::phone::media::NotFetched {    crate::phone::media::NotFetched { waiting: None, reason, status }}/// The per-file key of a sealed message's file (sealing plan L8): the media/// entry naming `media` in this copy's messages (opened when they came down)/// carries it as `fileKey`. None when no message here names the key.fn sealed_file_key(replica: &std::path::Path, media: &str, stories: Option<&StoryKeys>) -> Result<cotton_core::seal::file::FileKey, crate::phone::media::NotFetched> {    let file = cotton_store::driver::Driver::open_reader(replica).map_err(|error| not_fetched(format!("this phone's copy could not be read ({error})"), None))?;    // A sealed story's picture: its row keeps the key alone, and the file key is the DK's to derive.    let a_story = file        .get("SELECT 1 AS held FROM cotton_stories WHERE media_key = ?1 LIMIT 1", &[rusqlite::types::Value::Text(media.to_string())])        .map_err(|error| not_fetched(error.to_string(), None))?        .is_some();    if a_story {        use cotton_client::seal::DataKeyStore as _;        let held = stories.ok_or_else(|| not_fetched(format!("{}: no data key reaches this fetch", cotton_client::seal::SEAL_KEY_MISSING), None))?;        let dk = held            .keys            .data_key(&held.database)            .map_err(|why| not_fetched(why, None))?            .ok_or_else(|| not_fetched(format!("{}: this phone holds no data key yet, so the story's picture waits", cotton_client::seal::SEAL_KEY_MISSING), None))?;        let bk = cotton_core::seal::blind_key(&dk, &held.database, "story").map_err(|error| not_fetched(error.to_string(), None))?;        return Ok(cotton_core::seal::file::derived_key(&bk, media));    }    let found = file        .get(            "SELECT json_extract(j.value, '$.fileKey') AS file_key FROM cotton_msg_messages m, json_each(m.media) j              WHERE json_valid(m.media) AND json_extract(j.value, '$.key') = ?1 AND json_extract(j.value, '$.fileKey') IS NOT NULL LIMIT 1",            &[rusqlite::types::Value::Text(media.to_string())],        )        .map_err(|error| not_fetched(error.to_string(), None))?        .and_then(|row| row.text("file_key").map(str::to_string));    // A mail's file the Mac brought when it was opened (mac-import, Mac 9; chat CONTRACT "A mail's page and files"):    // an attachment keeps its key beside its name in `attachments`, the designed page in `media`. A copy whose    // email table has no `media` column yet answers nothing from it.    let found = match found {        Some(found) => Some(found),        None => ["attachments", "media"].iter().find_map(|column| {            file.get(                &format!(                    "SELECT json_extract(j.value, '$.fileKey') AS file_key FROM cotton_emails e, json_each(e.{column}) j                      WHERE json_valid(e.{column}) AND json_extract(j.value, '$.key') = ?1 AND json_extract(j.value, '$.fileKey') IS NOT NULL LIMIT 1"                ),                &[rusqlite::types::Value::Text(media.to_string())],            )            .ok()            .flatten()            .and_then(|row| row.text("file_key").map(str::to_string))        }),    }    .ok_or_else(|| not_fetched(format!("no message or mail of this copy holds the key that opens {media}"), Some(404)))?;    cotton_core::seal::file::FileKey::read(&found).map_err(|error| not_fetched(error.to_string(), None))}/// A sealed file fetched whole into `raw`, opened into `dest` with its file/// key; `raw` goes either way. A file that does not open writes nothing to/// `dest` but what opened before the part that did not, and says so by name.pub(crate) fn open_sealed_download(replica: &std::path::Path, key: &str, raw: &std::path::Path, dest: &std::path::Path) -> Result<(), crate::phone::media::NotFetched> {    open_sealed_download_with(replica, None, key, raw, dest)}/// [`open_sealed_download`] that also opens a sealed story's picture, with/// the file key `stories`' data key derives.pub(crate) fn open_sealed_download_with(replica: &std::path::Path, stories: Option<&StoryKeys>, key: &str, raw: &std::path::Path, dest: &std::path::Path) -> Result<(), crate::phone::media::NotFetched> {    let opened = (|| {        let fk = sealed_file_key(replica, key, stories)?;        let mut sealed = std::fs::File::open(raw).map_err(|error| not_fetched(error.to_string(), None))?;        // not a copy: a sealed media file opened into the media folder.        let mut out = std::fs::File::create(dest).map_err(|error| not_fetched(error.to_string(), None))?;        cotton_core::seal::file::open_file(&fk, key, &mut sealed, &mut out).map_err(|error| not_fetched(format!("{}: {error}", error.code()), None))?;        Ok(())    })();    // not a copy: a sealed download, opened into its file.    let _ = std::fs::remove_file(raw);    opened}impl crate::phone::media::MediaFetch for ObjectMedia {    fn fetch_to(&self, _database: &str, key: &str, dest: &std::path::Path) -> Result<(), crate::phone::media::NotFetched> {        // A sealed message's file: fetched as the object keeps it (no size is        // drawn from sealed bytes), opened here with the row's file key.        if cotton_core::seal::file::is_sealed_key(key) {            let raw = dest.with_extension("sealed");            self.transport.fetch_to(key, None, &raw).map_err(|refusal| not_fetched(refusal.message, Some(refusal.status)))?;            return open_sealed_download_with(&self.replica, self.stories.as_ref(), key, &raw, dest);        }        let refused = |refusal: cotton_client::transport::ServerRefusal| not_fetched(refusal.message, Some(refusal.status));        let (source, width) = self.source(key)?;        let Some(width) = width else {            return self.transport.fetch_opened_to(&source, dest).map_err(refused);        };        if cotton_core::media::keys::message_picture_of_thumb(key).is_some() {            return self.transport.fetch_to(&source, Some(width), dest).map_err(refused);        }        // A RENDITION THE DEVICE MADE (R6): its own sealed file under its own        // key, opened here. One no device made yet is drawn by the object from        // a clear original stored before R6; a sealed original is never drawn        // there, so the original itself comes down, opened, in its place.        match self.transport.fetch_opened_to(key, dest) {            Ok(()) => return Ok(()),            Err(refusal) if refusal.status != 404 => return Err(refused(refusal)),            Err(_) => {}        }        match self.transport.fetch_to(&source, Some(width), dest) {            Err(refusal) if refusal.code.as_deref() == Some("sealed_file") => self.transport.fetch_opened_to(&source, dest).map_err(refused),            other => other.map_err(refused),        }    }}/// The person's own files of `database` on this phone, opened with the data key the shell holds.pub(crate) fn person_files_of(client: &crate::shell::client::ClientController, database: &str) -> Arc<cotton_client::media::sealed::PersonFiles> {    Arc::new(cotton_client::media::sealed::PersonFiles::new(database, Arc::clone(client.data_keys()) as Arc<dyn cotton_client::seal::DataKeyStore>))}fn windows(request: &Value) -> Result<Vec<(String, u32)>, MethodError> {    let Some(windows) = request.get("windows") else { return Ok(Vec::new()) };    let Some(windows) = windows.as_object() else {        return Err(MethodError::new("bad_request", "`windows` is {table: days}"));    };    windows        .iter()        .map(|(table, days)| {            days.as_u64()                .filter(|days| (1..=36_500).contains(days))                .map(|days| (table.clone(), days as u32))                .ok_or_else(|| MethodError::new("bad_request", format!("the window of {table} is a number of days")))        })        .collect()}/// `database`'s sealing on this device: the data key the shell handed over/// (`phone::seal`) and each sealed table's version as the object says it.////// One per database and key store while anything holds it: the sync loop's/// passes and an unlock window's advance (`phone::unlock`) share it, so a/// table moved to its next version seals under it from the next write on.pub(crate) fn sealer_of(client: &crate::shell::client::ClientController, database: &str) -> Arc<cotton_client::seal::Sealer> {    static SEALERS: std::sync::Mutex<Vec<(usize, String, std::sync::Weak<cotton_client::seal::Sealer>)>> = std::sync::Mutex::new(Vec::new());    let keys = Arc::as_ptr(client.data_keys()) as usize;    let mut held = SEALERS.lock().unwrap_or_else(std::sync::PoisonError::into_inner);    held.retain(|(_, _, sealer)| sealer.strong_count() > 0);    if let Some(sealer) = held.iter().find(|(k, d, _)| *k == keys && d == database).and_then(|(_, _, sealer)| sealer.upgrade()) {        return sealer;    }    let sealer = cotton_client::seal::Sealer::new(database, Arc::clone(client.data_keys()) as Arc<dyn cotton_client::seal::DataKeyStore>);    held.push((keys, database.to_string(), Arc::downgrade(&sealer)));    sealer}/// The copy that is not this sign-in's own, gone so the object's can be made/// in its place: every write it holds that the object does not is posted/// first (`ObjectTransport::send_before_remake`), and only then is the file/// removed, its journal with it, and the note an earlier build's stopped/// move left beside it./// Said once in the log. An object that does not answer keeps the copy where/// it is, and the connect says why; the next one tries again.////// SIGN-IN NEVER WAITS ON THE KEY IT BRINGS (17 Nov/// 2026): a write of a sealed table goes up only sealed, and the data key/// reaches a phone only once its copy is connected (`seal.useKey` and/// `seal.openKey` answer on the attached copy, whose `seal_key` and vault/// rows a pass pulls). When what stops the send is that key alone, the copy/// is not refused — that was the deadlock of an updated app holding unsent/// rows and no key — it waits WHOLE at [`waiting_copy`], every row and/// receipt in it, and this build's copy is made in its place. The first pass/// once the key is held sends it sealed ([`send_waiting`]) before it pulls,/// and only then is it let go. One copy waits at a time: a second is refused/// `copy_kept` as before.#[allow(clippy::too_many_arguments)]fn remake(    layout: &cotton_client::layout::Layout,    path: &std::path::Path,    database: &str,    address: &ObjectAddress,    exchange: &Arc<dyn Exchange>,    credential: &str,    tables: &Arc<ObjectTables>,    windows: &[(String, u32)],    sealer: Arc<cotton_client::seal::Sealer>,    why: &str,    now: &str,) -> Result<(), MethodError> {    let waits = !sealer.has_key();    match send_whole(layout, path, database, address, exchange, credential, tables, windows, sealer, now) {        Ok(sent) => {            end_remade(layout, database, path, why, &sent)?;            eprintln!("[object] this phone's copy {why}: it is made again from the object ({} unsent writes sent, {} not taken and written down; {} rows the object lacked sent, {} refused)", sent.delivered, sent.refused, sent.topped, sent.topped_refused);            Ok(())        }        Err(kept) if waits && kept.message.contains(cotton_client::seal::SEAL_KEY_MISSING) && !waiting_copy(layout, database).exists() => {            shift_copy(path, &waiting_copy(layout, database))?;            eprintln!("[object] this phone's copy {why}: it waits whole for the data key, and is made again from the object ({})", kept.message);            Ok(())        }        // A send that did not finish keeps the copy where it is, untouched, and the sign-in says why (owner, 11 Nov        // 2026: a copy is never trusted as only a cache; a table this build cannot name is named). Nothing is removed.        Err(kept) => Err(kept),    }}/// What [`send_whole`] sent.#[derive(Default)]pub(crate) struct SentWhole {    /// The writes the object took or answered for good (QUEUE BAD OP 4).    pub(crate) acknowledged: Vec<String>,    /// The writes the object never took that no copy of this app can send (QUEUE BAD OP 5): kept, listed, never sent.    pub(crate) held_back: Vec<String>,    pub(crate) delivered: usize,    pub(crate) refused: usize,    pub(crate) topped: usize,    pub(crate) topped_refused: usize,}/// Every write the copy at `path` holds that the object does not, posted,/// and every live row it lacks, topped up; answered once the object holds/// every row of it but the ones it refused for good. Any other end keeps/// the copy, refused `copy_kept` with the reason.#[allow(clippy::too_many_arguments)]fn send_whole(    layout: &cotton_client::layout::Layout,    path: &std::path::Path,    database: &str,    address: &ObjectAddress,    exchange: &Arc<dyn Exchange>,    credential: &str,    tables: &Arc<ObjectTables>,    windows: &[(String, u32)],    sealer: Arc<cotton_client::seal::Sealer>,    now: &str,) -> Result<SentWhole, MethodError> {    // A sealed table's rows go up sealed; with no key the send stops and    // the copy stays (no sealed row the object lacks is ever let go).    let kit = cotton_core::kit::AppKit::at(layout.root()).map_err(|reason| MethodError::new("io", reason))?.map(Arc::new);    let transport = ObjectTransport::new(address.clone(), Arc::clone(exchange), credential.to_string(), Arc::clone(tables), path.to_path_buf(), windows.to_vec()).sealing_with(sealer).keeping_to(kit.clone());    let sent = transport        .send_before_remake(layout, database, now)        .map_err(|reason| MethodError::new("copy_kept", format!("this phone's copy holds writes the object has not taken, and they could not be sent ({reason}); it is kept until they are")))?;    // A COPY IS NEVER TRUSTED AS ONLY A CACHE (owner, 11 Nov 2026): before    // it goes, the object is asked what it holds and takes every live row    // of this copy it lacks. A copy that cannot say its rows, or an object    // that does not answer, keeps the copy.    let kept = |reason: String| MethodError::new("copy_kept", format!("this phone's copy holds rows the object may lack, and they could not be sent ({reason}); it is kept until they are"));    // The object's own words, with its status and code: a dropped line says status 0.    let said = |refusal: cotton_client::transport::object::ObjectRefusal| format!("{}, status {} {}", refusal.message, refusal.status, refusal.code);    let served_tables = cotton_client::transport::object::object_definitions(path).map_err(kept)?;    // Every table the copy may hold, not this app's kit alone: a copy pulled    // for another kit holds the others' rows too.    // But never a table the app's kit does not carry and the copy holds no    // definition of (the zone claim's news_settings on Books, Music,    // Cinemas and Story): whether the object seals it is unknown here, so its    // rows can be neither sealed nor sent in the clear, and no copy of the    // app takes them; they go with the copy, said in the log.    let (every_table, unsaid): (Vec<String>, Vec<String>) = cotton_core::kit::AppKit::tables_of("personal")        .into_iter()        .partition(|table| kit.as_ref().is_none_or(|kit| kit.keeps_table(table)) || served_tables.iter().any(|definition| definition["id"] == serde_json::json!(table)));    let rekey = cotton_client::transport::object::Rekey::default();    let left = cotton_client::transport::object::RestoreInto { layout, object_id: database, served_tables: &served_tables, tables: &unsaid, rekey: &rekey, at: now };    let left = cotton_client::transport::object::whole_rows(path, &left).unwrap_or_else(|reason| {        eprintln!("[object] the rows of tables this app's kit does not carry could not be counted: {reason}");        Vec::new()    });    if !left.is_empty() {        let named: Vec<String> = left.iter().map(|row| row.address()).collect();        eprintln!("[object] this phone's copy is made again without {} row(s) of tables this app's kit does not carry and no copy of it takes: {}", left.len(), named.join(", "));    }    let into = cotton_client::transport::object::RestoreInto { layout, object_id: database, served_tables: &served_tables, tables: &every_table, rekey: &rekey, at: now };    // A TABLE NOTHING HERE HAS A NAME FOR IS NEVER SKIPPED (owner, 11 Nov    // 2026): its rows cannot be said to the object, so while it holds a live    // row the copy stays, and the log and the Account card name the table.    let unnamed = cotton_client::transport::object::unnamed_tables(path, &into).map_err(kept)?;    if !unnamed.is_empty() {        let named: Vec<String> = unnamed.iter().map(|(table, rows)| format!("{table} ({rows} rows)")).collect();        eprintln!("[object] this phone's copy is kept: this build has no name for {}", named.join(", "));        return Err(MethodError::new("copy_kept", format!("this phone's copy holds rows in a table this build has no name for: {}; it is kept until a build that reads them sends them", named.join(", "))));    }    // A row the object refuses for good is written down with its id and the    // object's reason (Feedback) and said in the log; any other failure    // stops here with the copy whole.    let mut refused: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();    let topped = transport        .top_up(&into, &mut |row, landing| {            if let cotton_client::transport::object::Landing::Refused(reason) = landing {                eprintln!("[object] before this phone's copy is made again, the object refused {} {} for good: {reason}", row.table, row.id);                refused.insert(row.address());            }            true        }, cotton_client::transport::object::Written::Down)        .map_err(|refusal| kept(said(refusal)))?;    // THE COPY GOES ONLY ONCE THE OBJECT HOLDS IT: asked again, the object    // lacks no live row of this copy but the ones it refused for good.    let still: Vec<String> = transport.lacking(&into).map_err(|refusal| kept(said(refusal)))?.into_iter().map(|row| row.address()).filter(|row| !refused.contains(row)).collect();    if !still.is_empty() {        return Err(kept(format!("the object still lacks {} of its rows after they were sent", still.len())));    }    Ok(SentWhole { acknowledged: sent.acknowledged, held_back: sent.held_back, delivered: sent.delivered, refused: sent.refused, topped: topped.sent, topped_refused: topped.refused })}/// The copy that waited for the data key ([`remake`]), sent once the key is/// held — sealed, as [`send_whole`] sends a copy before it goes — and let go/// once the object holds every row of it. Run at the start of every pass of/// a connected copy, before the pass pulls; with no copy waiting, or no key/// yet, it does nothing and asks nothing. A send that stops keeps the copy/// whole for the next pass, and says why on the Account card. Answers/// whether a waiting copy was let go.#[allow(clippy::too_many_arguments)]pub(crate) fn send_waiting(    client: &crate::shell::client::ClientController,    database: &str,    address: &ObjectAddress,    exchange: &Arc<dyn Exchange>,    credential: &str,    tables: &Arc<ObjectTables>,    windows: &[(String, u32)],    sealer: &Arc<cotton_client::seal::Sealer>,) -> bool {    let layout = client.layout();    let waiting = waiting_copy(layout, database);    if !sealer.has_key() || !waiting.exists() {        return false;    }    let now = client.clock().now_iso();    match send_whole(layout, &waiting, database, address, exchange, credential, tables, windows, Arc::clone(sealer), &now) {        Ok(sent) => {            // QUEUE BAD OP 4 (B1b): the waiting copy leaves through the one function; anything in it beyond what the            // object answered keeps it whole aside.            if let Err(error) = end_waiting(layout, database, &waiting, &sent) {                eprintln!("[object] the copy that waited for the data key stays where it is: {error}");                return false;            }            eprintln!("[object] the copy that waited for the data key went up sealed and is let go ({} unsent writes sent, {} not taken and written down; {} rows the object lacked sent, {} refused)", sent.delivered, sent.refused, sent.topped, sent.topped_refused);            true        }        Err(kept) => {            eprintln!("[object] the copy that waited for the data key is kept: {}", kept.message);            client.note_trouble_coded(&kept.code, Some(kept.message));            false        }    }}/// Move the copy at `from` — file, journal and the marks beside it — to `to`,/// whose folder is made; nothing is moved over a file already there.fn shift_copy(from: &std::path::Path, to: &std::path::Path) -> Result<(), MethodError> {    // Through the one place a copy moves (QUEUE BAD OP 4): journal folded in, its own files with it, the file last.    cotton_client::copy_keep::relocate(from, to).map_err(|error| MethodError::new("copy_kept", format!("this phone's copy could not be set to wait for the data key ({error}); it is kept where it is")))}/// What makes this phone's copy again when its passes are stuck on one page/// (`SyncProgress::stuck`): everything `personal.connect` made it with.struct Heal {    client: std::sync::Weak<crate::shell::client::ClientController>,    layout: cotton_client::layout::Layout,    path: std::path::PathBuf,    database: String,    owner: String,    address: ObjectAddress,    exchange: Arc<dyn Exchange>,    credential: String,    tables: Arc<ObjectTables>,    windows: Vec<(String, u32)>,    kit: Option<Arc<cotton_core::kit::AppKit>>,    progress: Arc<SyncProgress>,    definitions: Arc<HeldDefinitions>,    device_key: Option<String>,    named: DeviceNamed,}impl Heal {    /// Make the copy again from the object, on the heal's own thread: the    /// loop stops and the copy is let go, the object's definitions are asked    /// (an object that does not answer keeps the copy), the copy's unsent    /// writes are posted and it goes ([`remake`], which says so once in the    /// log), the object's copy is made in its place with its definitions    /// laid, and the loop starts again over it — its first page asks from    /// nothing, and writes `copy_remade_at` on the row (`SyncProgress::remade`).    /// A copy that cannot be made again is opened again as it was, and keeps    /// saying why.    fn run(&self, why: &str) {        let Some(client) = self.client.upgrade() else { return };        client.set_placing(true);        client.detach();        if let Err(refused) = self.make_again(&client, why) {            eprintln!("[object] this phone's copy stalled three passes running on one page ({why}) and was not made again: {}", refused.message);            client.note_trouble_coded(&refused.code, Some(refused.message));        }        if let Err(reason) = client.attach_now() {            eprintln!("[object] this phone's copy did not open after it stalled: {reason}");        }    }    /// THE SERVER WAS PUT BACK TO AN EARLIER TIME (RESTORE 2): the copy holds changes the server no longer has, and    /// may hold the damage the restore undid. The loop stops and the copy is let go, the copy is set aside through    /// the one function, marked as from before the restore ([`end_restored`]: what it holds unsent is listed for the    /// person and never sent by itself), and the server's copy is made in its place as any copy made again is; the    /// loop starts again over it, its first sync from nothing taking the new generation. Nothing is posted first:    /// every post would be refused. The Sync page says it meanwhile (`SyncProgress::restoring`). A copy that cannot    /// be made again is opened again as it was; the next pass meets the restore again and tries again.    fn run_restored(&self, restored: cotton_client::transport::object::ServerRestored) {        let Some(client) = self.client.upgrade() else { return };        // When it was put back to, as the answer that met it said, or as the server says of the account.        let restored_to = restored.restored_to.clone().or_else(|| self.asked_restored_to());        self.progress.restoring(Some(restored_to.clone().unwrap_or_default()));        client.set_placing(true);        client.detach();        if let Err(refused) = self.make_again_restored(&client, restored_to.as_deref().unwrap_or_default()) {            eprintln!("[object] the server was put back to an earlier time and this phone's copy was not made again: {}", refused.message);            client.note_trouble_coded(&refused.code, Some(refused.message));            self.progress.restoring(None);        }        if let Err(reason) = client.attach_now() {            eprintln!("[object] this phone's copy did not open after the server was put back: {reason}");        }    }    /// The time the server says the account was put back to (`/v1/me` `restored_to`), when it answers.    fn asked_restored_to(&self) -> Option<String> {        let me = self.address.send(self.exchange.as_ref(), "GET", routes::ME, bearer(&self.credential), None).ok()?;        me["restored_to"].as_str().filter(|at| !at.is_empty()).map(str::to_string)    }    fn make_again_restored(&self, client: &crate::shell::client::ClientController, restored_to: &str) -> Result<(), MethodError> {        self.make_again_by(client, |_now| {            end_restored(&self.layout, &self.database, &self.path, restored_to)?;            eprintln!("[object] the server was put back to an earlier time: this phone's copy is set aside and made again from it");            Ok(())        })    }    fn make_again(&self, client: &crate::shell::client::ClientController, why: &str) -> Result<(), MethodError> {        let said = format!("stalled three passes running on one page ({why})");        self.make_again_by(client, |now| remake(&self.layout, &self.path, &self.database, &self.address, &self.exchange, &self.credential, &self.tables, &self.windows, sealer_of(client, &self.database), &said, now))    }    /// The copy made again: the object's definitions asked (an object that does not answer keeps the copy), its    /// ledger read, the copy ended by `end` (handed now), the object's copy made in its place with its definitions,    /// ledger and device row.    fn make_again_by(&self, client: &crate::shell::client::ClientController, end: impl FnOnce(&str) -> Result<(), MethodError>) -> Result<(), MethodError> {        let served = self.address.send(self.exchange.as_ref(), "GET", routes::DEFINITIONS, bearer(&self.credential), None)?;        let now = client.clock().now_iso();        let ledger = kept_ledger(&self.path)?;        end(&now)?;        let author = cotton_client::replica::resolve_device_id(&self.layout, client.clock().as_ref(), client.random().as_ref())            .map_err(|error| MethodError::new("io", error.to_string()))?;        let tools = cotton_core::genesis::GenesisTools::at(self.layout.root()).map_err(|reason| MethodError::new("io", reason))?;        let make = || {            make_copy(&self.path, &self.database, &self.owner, &author, &now, &tools, client.receipt_signer_slot())                .and_then(|()| mark_copy_kit(&self.path, self.kit.as_deref()))                .map_err(|reason| MethodError::new("io", reason))        };        make()?;        let now_ms = cotton_store::protocol::js::parse_date_ms(&now).unwrap_or_else(|| chrono::Utc::now().timestamp_millis());        // A copy that cannot take the definitions is made bare: its first        // page asks for them whole.        if let Err(reason) = lay_served_definitions(&self.path, &self.database, &kept_to(&served, self.kit.as_deref()), now_ms) {            eprintln!("[object] the object's definitions did not lay into the copy made again ({reason}): its first page asks for them");            remove_copy(&self.layout, &self.database, &self.path);            make()?;        }        carry_ledger(&self.path, &ledger, &now)?;        own_device_row(self.device_key.clone(), &self.named, &self.path, &self.database, &self.owner)?;        self.definitions.forget();        self.progress.remade(now);        Ok(())    }}/// The media ledger of the copy at `path`, read before the copy is made again.////// A COPY MADE AGAIN LOST ITS LEDGER (21 Nov 2026): a copy/// another build wrote (every schema rise) or one pulled for another kit is/// remade from the object, and `_media` is this phone's alone — never on the/// object — so the new copy knew none of the files in this database's media/// folder. A file still to go up (a picture taken, a chat imported) was never/// sent, and every other device asked the object for it in vain; every file/// already here stayed on the disk with nothing naming it, never counted,/// evicted or removed, and its thumbnail was fetched again over it. The rows/// go into the new copy as they stood ([`carry_ledger`]). A copy that cannot/// be read is not made again: it is kept, as a copy with unsent writes is.fn kept_ledger(path: &std::path::Path) -> Result<Vec<cotton_store::media_ledger::MediaRow>, MethodError> {    let kept = |error: String| MethodError::new("copy_kept", format!("this phone's copy names files whose ledger could not be read ({error}); it is kept until it can be"));    let db = cotton_store::driver::Driver::open_snapshot_reader(path).map_err(|error| kept(error.to_string()))?;    let held = db        .get("SELECT 1 AS held FROM sqlite_master WHERE type = 'table' AND name = '_media'", &[])        .map_err(|error| kept(error.to_string()))?        .is_some();    if !held {        return Ok(Vec::new());    }    cotton_store::media_ledger::every_media_row(&db).map_err(|error| kept(error.to_string()))}/// The ledger [`kept_ledger`] read, written into the new copy at `path`/// before it is attached: each file as it stood — still to go up, up, or on/// its way out — and a pin the person set kept.fn carry_ledger(path: &std::path::Path, rows: &[cotton_store::media_ledger::MediaRow], now: &str) -> Result<(), MethodError> {    if rows.is_empty() {        return Ok(());    }    let failed = |error: cotton_store::StoreError| MethodError::new("io", format!("this phone's media could not be written into its copy made again ({error})"));    let db = cotton_store::driver::Driver::open(path).map_err(failed)?;    db.transaction(|db| {        for row in rows {            cotton_store::media_ledger::enqueue_media(                db,                &cotton_store::media_ledger::MediaEnqueueInput {                    key: row.key.clone(),                    workspace_id: row.workspace_id.clone(),                    sha256: row.sha256.clone(),                    content_type: row.content_type.clone(),                    size_bytes: row.size_bytes,                    local_path: row.local_path.clone(),                    state: Some(row.state.clone()),                    after: row.after.clone(),                    after_row_id: row.after_row_id.clone(),                    tier: row.tier,                    captured_here: row.captured_here,                    now: now.to_string(),                },            )?;            if row.pinned {                cotton_store::media_ledger::set_media_pinned(db, &row.key, true, now)?;            }        }        Ok(())    })    .map_err(failed)}/// The copy a remake replaces leaves through the one function: what the object took or answered does not count,/// what no copy can send is kept and listed, anything else keeps it aside.pub(crate) fn end_remade(layout: &cotton_client::layout::Layout, database: &str, path: &std::path::Path, why: &str, sent: &SentWhole) -> Result<(), MethodError> {    let why_kept = format!("this phone's copy {why}, and was made again");    cotton_client::copy_keep::retire(layout, database, path, cotton_client::copy_keep::Ending::keep_beyond_holding(&why_kept, &sent.acknowledged, &sent.held_back)).map(|_| ()).map_err(|error| {        // SHARED COPY, OLDER CORE: an app on an older core than the copy's says so plainly, by its own code.        MethodError::new(if error.starts_with(cotton_client::copy_keep::OLDER_CORE) { "older_core" } else { "copy_kept" }, error)    })}/// THE COPY A RESTORE LEFT BEHIND (RESTORE 2) leaves through the one function, marked as from before the server was/// put back to `restored_to`: anything unsent keeps it aside, and recovery lists what it holds and never sends it (the/// damage the restore undid may be among it). The rows the server refused, kept beside it, go with it/// ([`cotton_client::copy_keep::fence_kept_rows`]: no pass posts them again), and so does the copy that waited for the/// data key, which stood before the restore too. Any step that fails keeps what is left where it is.pub(crate) fn end_restored(layout: &cotton_client::layout::Layout, database: &str, path: &std::path::Path, restored_to: &str) -> Result<(), MethodError> {    const WHY: &str = "the server was put back to an earlier time, and this phone's copy was made again from it";    let kept = |error: String| MethodError::new("copy_kept", error);    cotton_client::copy_keep::fence_kept_rows(path).map_err(kept)?;    cotton_client::copy_keep::retire(layout, database, path, cotton_client::copy_keep::Ending::keep_restored(WHY, restored_to)).map_err(kept)?;    cotton_client::copy_keep::retire(layout, database, &waiting_copy(layout, database), cotton_client::copy_keep::Ending::keep_restored(WHY, restored_to)).map_err(kept)?;    Ok(())}/// The copy that waited for the data key leaves through the one function once it went up, as [`end_remade`].pub(crate) fn end_waiting(layout: &cotton_client::layout::Layout, database: &str, waiting: &std::path::Path, sent: &SentWhole) -> Result<(), String> {    cotton_client::copy_keep::retire(layout, database, waiting, cotton_client::copy_keep::Ending::keep_beyond_holding("the copy that waited for the data key went up", &sent.acknowledged, &sent.held_back)).map(|_| ())}/// A copy that did not finish being made, let go through the one function (QUEUE BAD OP 4): anything unsent in it/// (an adopt's carried rows) keeps it whole aside.pub(crate) fn remove_copy(layout: &cotton_client::layout::Layout, database: &str, path: &std::path::Path) {    if let Err(error) = cotton_client::copy_keep::retire(layout, database, path, cotton_client::copy_keep::Ending::keep("a copy that did not finish being made")) {        eprintln!("[object] a copy that did not finish being made stays where it is: {error}");    }}#[cfg(test)]#[path = "personal_object_tests.rs"]mod tests;#[cfg(test)]#[path = "offline_start_tests.rs"]mod offline_start_tests;#[cfg(test)]#[path = "swap_tests.rs"]mod swap_tests;#[cfg(test)]#[path = "personal_object_e2e.rs"]mod e2e;/// Where the copy an earlier build wrote waits for the data key, whole, when/// a sign-in made this build's copy before the key reached the phone.pub fn waiting_copy(layout: &cotton_client::layout::Layout, database: &str) -> std::path::PathBuf {    layout.client_dir().join(WAITING_FOR_KEY).join(database).join("replica.db")}const WAITING_FOR_KEY: &str = "waiting-for-key";#[cfg(test)]#[path = "upgrade_writer.rs"]mod upgrade_writer;#[cfg(test)]#[path = "upgrade_proof.rs"]mod upgrade_proof;