Cotton code
1110 lines · 59.8 KB · RustRaw
//! BACKUP IS ADOPT (owner, 1 Nov 2026): a used local database becomes the//! object's.//!//! Before anyone signs in, the phone's own database is the authority; once an//! object exists it is. When `personal.connect` finds the phone's local//! database holding rows a person made, it never connects over them: it//! starts an adopt here and answers at once, `{"adopt": {"status"://! "started", "rows": n}}`, the work running on its own thread the way the//! media drain runs beside the sync loop. `personal.adoptStatus` says where//! it stands — `sending`, `making_copy`, `done` or `failed`, with the rows//! sent of the rows counted, the rows the object refused, and the object's//! word when it failed — and the app is told once it ends (`client`//! `{phase: personal, stage: adopted | adopt_failed}`).//!//! In order, on the local database://!//! 1. **Every unsent write goes to the object**//!    (`ObjectTransport::adopt_writes`): held, queued and parked, posted//!    through the object's map as a pass posts them, the local database's id//!    and owner rewritten to the object's, each marked delivered in the LOCAL//!    database as it lands — so an adopt stopped part way (a dropped line,//!    the app killed) begins again from the receipts still unsent and sends//!    nothing twice. A write the object refuses for good, or a row whose//!    object version stands, is written down (filed in Feedback once the copy//!    opens) and counted refused; a dropped line, a failing object or a 401//!    stops the adopt `failed` with the local database whole, and Back up//!    again resumes it.//! 2. **The media stay on the phone and move to the copy**: each file the//!    local `_media` ledger names is linked into the object's media folder//!    under the object's key, and the ledger rows are written into the new//!    copy before it is attached, so the drain `personal.connect` starts//!    puts them up and the device row counts them.//! 3. **The object's copy is made exactly as a sign-in makes it**//!    (`personal_object::connect_copy`), the writes made on the local//!    database meanwhile are sent, and only then is the local database's//!    folder removed, with its media folder. `done`.//!//! An existing object (the number already had a Cotton) takes the same path://! its rows and the adopted rows both show, and where a local row carries an//! id the object holds, the object's version stands.use std::collections::{BTreeMap, BTreeSet};use std::path::{Path, PathBuf};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, Mutex};use cotton_client::connection::ConnectionFile;use cotton_client::transport::object::{bearer, caught_up, object_definitions, routes, whole_rows, AdoptInto, AdoptLog, Landing, ObjectAddress, ObjectRefusal, ObjectTables, ObjectTransport, Rekey, RestoreInto, WholeRow, ADOPT_DISCARDED_WHY, ADOPT_STOPPED, DEFINITION_TABLES};use cotton_client::transport::Exchange;use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::phone::personal_object::{connect_copy, persons_rows, remove_database_folder, Phone};pub const SENDING: &str = "sending";pub const MAKING_COPY: &str = "making_copy";pub const DONE: &str = "done";pub const FAILED: &str = "failed";/// The copy is connected and the rows wait for this phone to hold the/// object's data key: founded on a new database, or let in on one another/// device holds.pub const WAITING_KEY: &str = "waiting_key";/// What `personal.adopt` answers as it starts one, or finds one running.pub const STARTED: &str = "started";/// The origin of the data event that says this phone's account stands/// otherwise ([`account_moved`]).pub const ACCOUNT_ORIGIN: &str = "account";/// THE ACCOUNT CARD IS ASKED AGAIN WHEREVER IT STANDS OTHERWISE (fault 3 of/// 21 Nov 2026: right after sign-in the card still offered Back up now and/// Sign out after the backup had ended, and both answered "That didn't/// work": the core no longer took them). A backup that ends, fails or waits/// for the key changes the acts the core takes, and the `client` event said/// so moves no read and asks no screen again: a data event naming no table/// does both, on either phone, so the card is drawn from the core's answer/// as it stands now.pub(crate) fn account_moved(events: &crate::events::EventBus) {    events.emit(crate::events::EventKind::Data, json!({"tables": [], "origin": ACCOUNT_ORIGIN}));}/// What `personal.adoptStatus` answers when no adopt ran this launch.pub const NONE: &str = "none";/// The stages of the event that says an adopt ended.pub const ADOPTED: &str = "adopted";pub const ADOPT_FAILED: &str = "adopt_failed";/// Where an adopt stands.#[derive(Debug, Clone, PartialEq, Eq)]pub struct AdoptStatus {    pub status: &'static str,    /// Rows the object has, of `rows`.    pub sent: u64,    pub rows: u64,    /// Rows the object did not take, written down.    pub refused: u64,    /// The object's word and line when it failed.    pub code: Option<String>,    pub line: Option<String>,}impl AdoptStatus {    pub fn json(&self) -> Value {        let mut said = json!({"status": self.status, "sent": self.sent, "rows": self.rows, "refused": self.refused});        if let Some(line) = &self.line {            said["line"] = json!(line);        }        if let Some(code) = &self.code {            said["code"] = json!(code);        }        json!({ "adopt": said })    }}/// One adopt of this launch, held by the client: its status, whether its/// thread still runs, and the person's word to stop.#[derive(Debug)]pub struct Adopting {    status: Mutex<AdoptStatus>,    running: AtomicBool,    stop: AtomicBool,    thread: Mutex<Option<std::thread::JoinHandle<()>>>,}impl Adopting {    fn new(status: AdoptStatus) -> Arc<Adopting> {        Arc::new(Adopting { status: Mutex::new(status), running: AtomicBool::new(true), stop: AtomicBool::new(false), thread: Mutex::new(None) })    }    pub fn status(&self) -> AdoptStatus {        self.status.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }    fn set(&self, change: impl FnOnce(&mut AdoptStatus)) {        change(&mut self.status.lock().unwrap_or_else(|poisoned| poisoned.into_inner()));    }    pub fn running(&self) -> bool {        self.running.load(Ordering::SeqCst)    }    /// The person stopped backing up, or removed the database: the adopt    /// stops after the op in flight, and this returns once it has.    pub fn stop(&self) {        self.stop.store(true, Ordering::SeqCst);        let thread = self.thread.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take();        if let Some(thread) = thread {            if thread.thread().id() != std::thread::current().id() {                let _ = thread.join();            }        }    }    /// Wait for the adopt's thread to end (tests, and a stop).    pub fn join(&self) {        let thread = self.thread.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).take();        if let Some(thread) = thread {            let _ = thread.join();        }    }}/// `personal.adoptStatus {}`.pub fn status(handle: &CottonHandle) -> Value {    handle        .client()        .adopting()        .map(|adopting| adopting.status())        .unwrap_or(AdoptStatus { status: NONE, sent: 0, rows: 0, refused: 0, code: None, line: None })        .json()}/// Whether an adopt of the local database `local` began and has not ended:/// its log is beside the database (it goes with the database's folder).pub fn underway(layout: &cotton_client::layout::Layout, local: &str) -> bool {    layout.replica(local).with_file_name("adopt.log").exists()}/// Stop a running adopt, if one runs: before the phone stands local or its/// database is removed.pub fn stop(handle: &CottonHandle) {    if let Some(adopting) = handle.client().adopting() {        adopting.stop();    }}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")))}/// `personal.adopt { server, databaseId, credential, windows?, deviceName?,/// appVersion? }` (and `personal.connect` over a local database holding/// rows a person made): start bringing the local database into the object,/// or answer the one running. A phone with nothing to adopt connects.pub fn adopt(handle: &CottonHandle, request: &Value, exchange: Arc<dyn Exchange>) -> Result<Value, MethodError> {    ObjectAddress::open(text(request, "server")?).map_err(|reason| MethodError::new("bad_request", reason))?;    let asked = text(request, "databaseId")?.to_string();    text(request, "credential")?;    let client = handle.client();    if let Some(running) = client.adopting().filter(|adopting| adopting.running()) {        return Ok(json!({"adopt": {"status": STARTED, "rows": running.status().rows}}));    }    let layout = client.layout().clone();    let local = ConnectionFile::at(layout.connection_json())        .read()        .filter(|mine| !mine.mode.has_server())        .and_then(|mine| mine.workspace_id)        .filter(|id| !id.is_empty() && *id != asked);    let Some(local) = local else {        return crate::phone::personal_object::call_with(handle, "personal.connect", request, exchange);    };    // A copy another object's person left is never adopted by another person    // (one copy, one object, 14 Nov 2026): `personal.connect` sets it aside.    if let Some(held) = ConnectionFile::at(layout.connection_json()).read() {        if let Some(whose) = crate::phone::copy_aside::belongs(&layout, &held)?.filter(|whose| whose.database != asked) {            let same_person = match &whose.person {                Some(person) => crate::phone::personal_object::asked_person(handle, request, exchange.as_ref())?.as_deref() == Some(person.as_str()),                None => false,            };            if !same_person {                return crate::phone::personal_object::call_with(handle, "personal.connect", request, exchange);            }        }    }    start(handle, request, exchange, local, &asked)}/// THE ADOPT THAT WAITS FOR THE KEY, GONE ON AT A LATER CONNECT: a launch/// connected to `databaseId` sends the rows of the local database whose adopt/// connected this copy to take its data key ([`run`]), once the key is held./// Nothing when an adopt runs, or none waits for this object.pub(crate) fn resume_waiting(handle: &CottonHandle, request: &Value, exchange: Arc<dyn Exchange>) {    let Ok(asked) = text(request, "databaseId") else { return };    let client = handle.client();    if client.adopting().is_some_and(|adopting| adopting.running()) {        return;    }    let layout = client.layout().clone();    let Some(local) = waiting_for(&layout, asked) else { return };    if let Err(refused) = start(handle, request, exchange, local.clone(), asked) {        eprintln!("[adopt] the backup of {local} waiting for this phone's key did not go on: {}", refused.message);    }}/// The local database whose adopt connected `asked`'s copy and waits for its/// data key, if one does ([`AdoptLog::waits_key`]).fn waiting_for(layout: &cotton_client::layout::Layout, asked: &str) -> Option<String> {    std::fs::read_dir(layout.client_dir()).ok()?.flatten().find_map(|folder| {        let local = folder.file_name().to_str()?.to_string();        let path = layout.replica(&local);        (local != asked && path.exists() && AdoptLog::beside(&path).waits_in().as_deref() == Some(asked)).then_some(local)    })}/// Start the adopt of the local database `local` into `asked`, counting its/// rows as the screen says them, on its own thread.fn start(handle: &CottonHandle, request: &Value, exchange: Arc<dyn Exchange>, local: String, asked: &str) -> Result<Value, MethodError> {    let client = handle.client();    let layout = client.layout().clone();    let asked = asked.to_string();    let path = layout.replica(&local);    let log = AdoptLog::beside(&path);    let memory = log.read();    let (sent, rows, refused) = if former_copy(&path)? {        // A FORMER OBJECT'S COPY goes whole: its rows are counted from its        // tables, and what earlier adopts sent from the log.        let whole = whole_here(&layout, &path)?;        if whole.is_empty() && !underway(&layout, &local) {            return crate::phone::personal_object::call_with(handle, "personal.connect", request, exchange);        }        let restored = log.restored();        let refused = whole.iter().filter(|row| restored.lost.contains(&row.address())).count() as u64;        let sent = whole.iter().filter(|row| !restored.owes(row) && !restored.lost.contains(&row.address())).count() as u64;        (sent, (whole.len() as u64).max(memory.rows.unwrap_or(0)), refused)    } else {        let persons = persons_rows(&path)?;        let remaining = persons.made.len() as u64;        if persons.is_empty() && !underway(&layout, &local) {            return crate::phone::personal_object::call_with(handle, "personal.connect", request, exchange);        }        // THE ROWS COUNTED, kept across launches: the screen's "n of m" is of        // the rows connect counted when the adopt began, and a relaunch part way        // goes on from where it was.        let refused = refused_rows(&layout, &asked);        let sent = memory.rows.map_or(0, |rows| rows.saturating_sub(remaining + refused));        (sent, memory.rows.unwrap_or(0).max(sent + remaining + refused), refused)    };    if memory.rows != Some(rows) {        log.rows(rows).map_err(|reason| MethodError::new("io", reason))?;    }    let adopting = Adopting::new(AdoptStatus { status: SENDING, sent, rows, refused, code: None, line: None });    client.set_adopting(Some(Arc::clone(&adopting)));    let phone = Phone::of(handle);    let request = request.clone();    let running = Arc::clone(&adopting);    let thread = std::thread::Builder::new()        .name("cotton-adopt".into())        .spawn(move || {            // A panic part way is a failed adopt, never one that runs for ever:            // the local database is whole, and Try again resumes it.            let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&running, &phone, &request, exchange, &local)))                .unwrap_or_else(|_| Err(refusal("internal_error", "the backup stopped on a fault in this phone's core")));            let event = match ended {                Ok(()) => {                    running.set(|status| status.status = DONE);                    json!({"phase": "personal", "stage": ADOPTED})                }                Err(refusal) => {                    eprintln!("[adopt] stopped: {} ({})", refusal.code, refusal.message);                    phone.client.note_trouble_coded(&refusal.code, Some(refusal.message.clone()));                    running.set(|status| {                        status.status = FAILED;                        status.code = Some(refusal.code.clone());                        // A sealing refusal's own words, and an object's that                        // did not answer, stay in the log: the screen says                        // the kit's line for its code.                        status.line = Some(refusal.message.clone()).filter(|words| !cotton_client::seal::names_a_seal_refusal(words) && !cotton_client::transport::object::names_an_unanswered_object(&refusal.code, words));                    });                    json!({"phase": "personal", "stage": ADOPT_FAILED, "code": refusal.code, "message": refusal.message})                }            };            running.running.store(false, Ordering::SeqCst);            phone.events.emit(crate::events::EventKind::Client, event);            account_moved(&phone.events);        })        .map_err(|error| MethodError::new("io", format!("the backup could not start ({error})")))?;    *adopting.thread.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(thread);    Ok(json!({"adopt": {"status": STARTED, "rows": rows}}))}/// The rows an earlier adopt into `object` wrote down as refused, from the/// record kept until Feedback files it.fn refused_rows(layout: &cotton_client::layout::Layout, object: &str) -> u64 {    cotton_client::unsent::discarded(layout, object)        .iter()        .filter(|entry| entry.why == ADOPT_DISCARDED_WHY)        .flat_map(|entry| entry.changes.iter())        .filter(|change| !change.is_bookkeeping() && !cotton_core::kit::face_choice_tables().iter().any(|choice| change.table.strip_prefix("cotton_") == Some(choice.as_str())))        .map(|change| (change.table.clone(), change.row_id.clone()))        .collect::<BTreeSet<_>>()        .len() as u64}fn refusal(code: &str, message: impl Into<String>) -> ObjectRefusal {    ObjectRefusal { status: 0, code: code.into(), message: message.into() }}fn of_method(error: MethodError) -> ObjectRefusal {    refusal(&error.code, error.message)}/// A question the backup opens with, asked up to three times when the object/// gives no answer: one call that ran out of time is not the backup's end./// Whether the account the adopt goes into already has a vault (KEPT FOUR 2): asked of the object before anything is/// sent, from its own rows (`GET /v1/sync?tables=vault_key,vault_state`, the owner's): a vault key row holding a wrap,/// or a vault state row, is a vault. Its answer decides what the local vault key becomes:/// - none (a first-ever sign-in): the local key founds the account, as it always did: its wrap goes up first, then///   the rows sealed under it, as they are;/// - one: the rows sealed under the local key are never posted as they are; the local copy keeps them and the only///   wrap of the local key, and the next unlock seals them again under the account's key (`vault_carry`).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(crate) enum AccountVault {    Unfounded,    Founded,}/// A test's meeting point: each adopt waits here once it has heard whether the account has a vault.#[cfg(test)]pub(crate) static HEARD_THE_VAULT: std::sync::Mutex<Option<Arc<std::sync::Barrier>>> = std::sync::Mutex::new(None);fn account_vault(address: &ObjectAddress, exchange: &dyn Exchange, credential: &str) -> Result<AccountVault, ObjectRefusal> {    let mut path = format!("{}?since=0&tables=vault_key,vault_state&limit=1000", routes::SYNC);    for _ in 0..50 {        let page = asked_again(routes::SYNC, || address.send(exchange, "GET", &path, bearer(credential), None))?;        for row in page["rows"].as_array().into_iter().flatten() {            if row["deleted"] == json!(true) {                continue;            }            let wrapped = row["data"]["wrapped_vmk"].as_str().is_some_and(|wrap| !wrap.is_empty());            if row["table"] == json!("vault_state") || (row["table"] == json!("vault_key") && wrapped) {                return Ok(AccountVault::Founded);            }        }        match page["next"].as_str() {            Some(next) => path = format!("{}?cursor={next}", routes::SYNC),            None => return Ok(AccountVault::Unfounded),        }    }    // Never decided on a part: a vault not seen is never taken for none.    Ok(AccountVault::Founded)}fn asked_again(what: &str, ask: impl Fn() -> Result<Value, ObjectRefusal>) -> Result<Value, ObjectRefusal> {    let mut tries = 0;    loop {        let began = std::time::Instant::now();        match ask() {            Err(unanswered) if unanswered.status == 0 && unanswered.code == "offline" => {                // Named, with how long it waited (`backup` `call.question`).                let message = backup_line("call.question", &[("what", what), ("seconds", &began.elapsed().as_secs().to_string()), ("why", &unanswered.message)]).unwrap_or_else(|| unanswered.message.clone());                if tries == 2 {                    return Err(ObjectRefusal { message, ..unanswered });                }                tries += 1;                eprintln!("[adopt] {message}; asked again");                std::thread::sleep(std::time::Duration::from_secs(2));            }            answered => return answered,        }    }}fn backup_line(line: &str, fills: &[(&str, &str)]) -> Option<String> {    cotton_core::rules::shell_lines::LineSet::shipped("backup").and_then(|lines| lines.say(line, fills))}/// The tables a former object's copy goes up by: the app's kit first, then/// every other table this build names, so a row the copy holds outside the/// app's kit goes too (a table holding nothing sends nothing). The seal keys/// stay out: the object refuses a former database's, and a copy holding one/// is kept ([`left_behind`]).fn copy_tables(layout: &cotton_client::layout::Layout) -> Result<Vec<String>, MethodError> {    let mut tables = kit_tables(layout)?;    for table in cotton_core::kit::AppKit::tables_of("personal") {        if !tables.contains(&table) {            tables.push(table);        }    }    tables.retain(|table| table != cotton_core::seal::SEAL_KEY_TABLE);    Ok(tables)}/// What a former copy holds live that did not go up, each table with its/// rows: a table nothing here names (`unnamed_tables`), and the former/// database's seal keys, which no other database takes. A COPY HOLDING ANY/// IS NEVER DELETED (owner, 12 Nov 2026).fn left_behind(layout: &cotton_client::layout::Layout, path: &Path) -> Result<Vec<(String, usize)>, String> {    let held = object_definitions(path)?;    let rekey = Rekey::default();    let keys = vec![cotton_core::seal::SEAL_KEY_TABLE.to_string()];    let into = RestoreInto { layout, object_id: "", served_tables: &held, tables: &keys, rekey: &rekey, at: "" };    let mut left = cotton_client::transport::object::unnamed_tables(path, &into)?;    let sealed = whole_rows(path, &into)?.len();    if sealed > 0 {        left.push((cotton_core::seal::SEAL_KEY_TABLE.to_string(), sealed));    }    Ok(left)}/// The adopt itself, on its own thread (see the module's note).fn run(adopting: &Adopting, phone: &Phone, request: &Value, exchange: Arc<dyn Exchange>, local: &str) -> Result<(), ObjectRefusal> {    let server = text(request, "server").map_err(of_method)?;    let address = ObjectAddress::open(server).map_err(|reason| refusal("bad_request", reason))?;    let asked = text(request, "databaseId").map_err(of_method)?.to_string();    let credential = text(request, "credential").map_err(of_method)?.to_string();    let layout = phone.client.layout().clone();    let path = layout.replica(local);    // WHICH OBJECT, AND WHOSE: as a sign-in asks it.    let served = asked_again(routes::DEFINITIONS, || address.send(exchange.as_ref(), "GET", routes::DEFINITIONS, bearer(&credential), None))?;    if served["business"]["kind"] != json!("personal") {        return Err(refusal("not_personal", "this object is a business's, not your personal database"));    }    if served["business"]["database_id"].as_str() != Some(asked.as_str()) {        return Err(refusal("wrong_database", format!("the sign-in named database {asked}, and the object is another")));    }    let me = asked_again(routes::ME, || address.send(exchange.as_ref(), "GET", routes::ME, bearer(&credential), None))?;    if me["person"]["role"] != json!("owner") {        return Err(refusal("owner_only", "only the owner backs up into the personal database"));    }    let owner = me["person"]["id"].as_str().unwrap_or_default().to_string();    // From here this database is the object's person's: should they sign out    // part way, another person's sign-in sets it aside, never sends the rest.    crate::phone::copy_aside::mark(&path, &asked, crate::phone::copy_aside::person_in(&me, &phone.client.self_device_id().unwrap_or_default()).as_deref()).map_err(of_method)?;    let rekey = Rekey::new([(local.to_string(), asked.clone()), (local_owner(&path).unwrap_or_default(), owner)]);    let served_tables = served["tables"].as_array().cloned().unwrap_or_default();    // A sealed table's rows go up sealed under the object's own data key.    let sealer = crate::phone::personal_object::sealer_of(&phone.client, &asked);    let transport = ObjectTransport::new(address.clone(), Arc::clone(&exchange), credential.clone(), ObjectTables::personal(), path.clone(), Vec::new())        .sealing_with(Arc::clone(&sealer));    if former_copy(&path).map_err(of_method)? {        return run_whole(adopting, phone, request, exchange, local, &asked, &rekey, &served_tables, &transport, &sealer);    }    // This phone's own database, made before it signed in, may hold a key made with no question    // (`seal.makeKey`): a new object takes that key as its own when it founds one, so what was made    // with it keeps its ids; an object that has a key keeps its own and this one is retired.    phone.client.set_carried_key(Some((asked.clone(), local.to_string())));    // KEPT FOUR 3 B: the local vault key's wrap into its own file before anything is sent, so no removal of this copy    // (here, in copy_keep, anywhere) can take the only wrap of it.    cotton_client::vault_keep::secure(&layout, local, &[path.clone()], Some(&asked)).map_err(|reason| refusal("io", format!("this phone's vault key could not be kept in its own file ({reason})")))?;    // KEPT FOUR 2: what the local vault key becomes, decided before anything is sent.    // A question that is not answered is never taken for "none": nothing sealed under the local key is posted, and    // the re-seal carries it whichever key the account ends up with.    let vault = std::cell::Cell::new(account_vault(&address, exchange.as_ref(), &credential).unwrap_or_else(|refusal| {        eprintln!("[adopt] whether the account has a vault was not answered ({}): taken as one", refusal.message);        AccountVault::Founded    }));    #[cfg(test)]    {        // A test's two phones both hear the account's vault before either posts (the race, KEPT FOUR 3 B). The barrier is        // taken out first and the lock let go: waited inside `if let` on the lock itself, the guard lived through the        // wait, and the second phone stood forever at the lock the first held.        let barrier = HEARD_THE_VAULT.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clone();        if let Some(barrier) = barrier {            barrier.wait();        }    }    // 1. EVERY UNSENT WRITE, until none is left: a person using the phone    // meanwhile writes to the local database, and those go too.    let mut seen: BTreeSet<(String, String)> = BTreeSet::new();    // Every write the object took or answered for good (QUEUE BAD OP 5, item 1): only what the adopt did not carry    // keeps the local database aside.    let carried_ops: std::cell::RefCell<Vec<String>> = std::cell::RefCell::new(Vec::new());    let send = |seen: &mut BTreeSet<(String, String)>| -> Result<bool, ObjectRefusal> {        let persons = persons_rows(&path).map_err(of_method)?;        let unsent = cotton_client::unsent::unsent_changes(&path).map_err(|reason| refusal("io", format!("this phone's own database could not be read ({reason})")))?;        // Every site goes up with the rest: none is kept only on this phone (Sites' switch removed, 27 Nov 2026).        let unsent: Vec<_> = unsent.into_iter().filter(|change| persons.goes(vault.get(), &change.table, &change.row_id)).collect();        if unsent.is_empty() {            return Ok(false);        }        // Each row a person made waits for its every op; it is sent once all        // have landed.        let mut waiting: BTreeMap<(String, String), (usize, bool)> = BTreeMap::new();        for change in &unsent {            let key = (change.table.clone(), change.row_id.clone());            if persons.made.contains(&key) {                waiting.entry(key).or_default().0 += 1;            }        }        let new = waiting.keys().filter(|row| !seen.contains(*row)).count() as u64;        seen.extend(waiting.keys().cloned());        let rows_now = {            let status = adopting.status();            let known = status.sent + status.refused + waiting.len() as u64;            status.rows.max(known)        };        if new > 0 {            adopting.set(|status| status.rows = rows_now);            let _ = AdoptLog::beside(&path).rows(rows_now);        }        let sends = |table: &str, row: &str| persons.goes(vault.get(), table, row);        let into = AdoptInto { layout: &layout, object_id: &asked, served_tables: &served_tables, rekey: &rekey, sends: &sends, at: &phone.client.clock().now_iso() };        transport.adopt_writes(&into, &mut |change, landing| {            carried_ops.borrow_mut().push(change.op_id.clone());            if let Some(row) = waiting.get_mut(&(change.table.clone(), change.row_id.clone())) {                row.0 = row.0.saturating_sub(1);                if matches!(landing, Landing::Refused(_)) {                    row.1 = true;                }                if row.0 == 0 {                    let refused = row.1;                    adopting.set(|status| if refused { status.refused += 1 } else { status.sent += 1 });                }            } else if cotton_client::transport::object::DEFINITION_TABLES.contains(&change.table.as_str()) && matches!(landing, Landing::Refused(_)) {                adopting.set(|status| status.refused = refused_rows(&layout, &asked));            }            !adopting.stop.load(Ordering::SeqCst)        })?;        Ok(true)    };    // THE KEY COMES ONLY TO A CONNECTED COPY (seal_key_missing after    // sign-in, 21 Nov 2026): a sealed row goes up only under the object's    // data key, and a phone takes that key only on the object's copy - a new    // person's founded there with no question (`seal.status` `founds`), an    // existing one's opened, approved from another device or with a recovery    // code. So a send stopped by the key alone never fails the backup: the    // copy is connected with the local database kept whole, and its rows go    // once the key is held.    // A FIRST-EVER SIGN-IN (KEPT FOUR 2, decision a): the local key's wrap goes up first and alone, so it founds the    // account before any row sealed under it is posted. Refused (another device founded the vault since the object was    // asked), the adopt goes on as into an account with a vault: nothing sealed under the local key is posted.    if vault.get() == AccountVault::Unfounded {        let persons = persons_rows(&path).map_err(of_method)?;        eprintln!("[adopt] the account has no vault yet; this phone's founding rows to send: {}", persons.founding.len());        if !persons.founding.is_empty() {            let sends = |table: &str, row: &str| persons.founding.contains(&(table.to_string(), row.to_string()));            let into = AdoptInto { layout: &layout, object_id: &asked, served_tables: &served_tables, rekey: &rekey, sends: &sends, at: &phone.client.clock().now_iso() };            let mut founded = true;            transport.adopt_writes(&into, &mut |change, landing| {                if matches!(landing, Landing::Refused(_)) {                    founded = false;                } else {                    carried_ops.borrow_mut().push(change.op_id.clone());                }                true            })?;            if founded {                // The server took this key's founding: the account's key is this key, recorded, and its file goes on                // that evidence (`vault_keep::settle`), so the local copy may go with nothing depending on it.                cotton_client::vault_keep::note_founded(&layout, local, &asked).map_err(|reason| refusal("io", reason))?;                cotton_client::vault_keep::settle(&layout, local, None).map_err(|reason| refusal("io", reason))?;            } else {                // KEPT FOUR 3 B: another device founded first (`vault_founded`): this founding is dropped (never kept,                // never posted again), the local key stays in its own file, and the adopt goes on exactly as into an                // account with a vault. Nothing shows on the Sync screen.                eprintln!("[adopt] the local vault key did not found the account (another device holds its key): its sealed rows wait for this phone's unlock");                vault.set(AccountVault::Founded);            }        }    }    if vault.get() == AccountVault::Founded {        // The rows sealed under the local key wait for the re-seal: not counted as rows this adopt sends.        let persons = persons_rows(&path).map_err(of_method)?;        let held = persons.sealed.iter().chain(persons.linked.iter()).filter(|row| persons.holds(&row.0, &row.1)).count() as u64;        adopting.set(|status| status.rows = status.rows.saturating_sub(held));    }    let mut waits = false;    let mut passes = 0;    loop {        match send(&mut seen) {            Ok(true) => {                passes += 1;                if passes > 8 {                    return Err(refusal("still_writing", "this phone kept writing while it was backed up; back up again"));                }            }            Ok(false) => break,            Err(stopped) if stopped.code == cotton_client::seal::SEAL_KEY_MISSING && !sealer.has_key() => {                waits = true;                break;            }            Err(stopped) => return Err(stopped),        }    }    // An earlier launch's adopt connected this copy to wait for the key: its    // media and keeps moved then.    let waited_before = AdoptLog::beside(&path).waits_in().as_deref() == Some(asked.as_str()) && phone.client.attached_database().as_deref() == Some(asked.as_str());    if !waited_before {        // 2. THE MEDIA: linked into the object's folder under the object's key.        adopting.set(|status| status.status = MAKING_COPY);        let media = local_media(&path).map_err(|reason| refusal("io", reason))?;        let moved = move_media(&layout, local, &asked, &rekey, media).map_err(|reason| refusal("io", reason))?;        // 3. THE OBJECT'S COPY, as a sign-in makes it, the ledger laid in first.        let now = phone.client.clock().now_iso();        let carry = |copy: &Path, database: &str| carry_media(copy, database, &moved, &now);        if waits {            AdoptLog::beside(&path).waits_key(&asked).map_err(|reason| refusal("io", reason))?;        }        connect_copy(phone, request, Arc::clone(&exchange), Some(&carry)).map_err(of_method)?;        // The books this phone kept stay kept, under the object's keys.        crate::phone::books::rekey_here(&phone.client, &|key| rekey.text(key)).map_err(of_method)?;        // And so do the songs, which the player plays from here, never streamed.        crate::phone::songs::rekey_here(&phone.client, &|key| rekey.text(key)).map_err(of_method)?;        // And the films and episodes, which On this phone lists by their files.        crate::phone::films::rekey_here(&phone.client, &|key| rekey.text(key)).map_err(of_method)?;    }    if waits {        adopting.set(|status| status.status = WAITING_KEY);        phone.events.emit(crate::events::EventKind::Client, json!({"phase": "personal", "stage": WAITING_KEY}));        account_moved(&phone.events);        wait_for_key(adopting, &sealer)?;        adopting.set(|status| status.status = SENDING);    }    // What was written to the local database while the copy was made, and    // every row that waited for the key.    while send(&mut seen)? {}    // DONE IS WHEN THE COPY HOLDS IT (Story walk, 25 Nov 2026): the local    // database goes next, so the copy pulls down every row the object took    // before the backup says it ended, as a restore's copy does.    let me = asked_again(routes::ME, || address.send(exchange.as_ref(), "GET", routes::ME, bearer(&credential), None))?;    catch_up(phone, &asked, me["version"].as_i64().unwrap_or(0), Some(&adopting.stop))?;    // What Sites kept of each site on this phone goes with its rows to the new copy.    if let Err(reason) = crate::phone::sites::carry(&layout, local, &asked) {        // The earlier copy stays, said on the Account card: Sites' carried file is the only route of sites kept only        // on this phone (review of SITES ROWS 5, item 2).        let said = backup_line("kept.sites", &[]).unwrap_or_else(|| reason.clone());        eprintln!("[adopt] {reason}");        phone.client.note_trouble(Some(said));        return Ok(());    }    end_adopt(&layout, local, &asked, carried_ops.borrow().clone());    phone.client.wake_media_drain();    Ok(())}/// The local database an adopt carried leaves through the one function (QUEUE BAD OP 4, 5 and 6), its media with it:/// `carried` (the op ids the adopt posted) and what its rule answers do not count; anything else keeps it whole/// aside, FILED UNDER THE SIGNED-IN DATABASE `asked` it now belongs to.pub(crate) fn end_adopt(layout: &cotton_client::layout::Layout, local: &str, asked: &str, carried_ops: Vec<String>) {    // QUEUE BAD OP 4 and 5: the local database leaves through the one function. What the adopt carried does not    // count; anything else in its folder keeps it whole aside, FILED UNDER THE SIGNED-IN DATABASE it now belongs to    // (listed in You > Sync there, removed with that account), never under the local id nobody reads.    let mut carried = carried_ops;    // QUEUE BAD OP 6 (the reviewer's answer to round 5's decision): what the adopt did not carry counts as answered    // ONLY when its table never goes to any server (this device's own history) or is named below as bookkeeping. Any    // other change it did not carry, a person-written table `persons_rows` does not place included, keeps the copy.    // Read on a read-only connection: the copy's bytes stay as they are until it leaves.    if let Ok(unsent) = cotton_client::copy_keep::changes_in(&layout.replica(local)) {        carried.extend(unsent.into_iter().filter(|change| answered_by_rule(&change.table)).map(|change| change.op_id));    }    // The media the adopt moved into the signed-in database's folder, whose rows the new copy now holds under the    // object's key: the new copy uploads them, so the local copy's rows for them do not count.    if let (Ok(rows), Ok(live)) = (local_media(&layout.replica(local)), cotton_store::Driver::open_snapshot_reader(&layout.replica(asked))) {        for row in rows {            let key = row.key.replacen(local, asked, 1);            if live.get("SELECT 1 FROM _media WHERE key = ?", &[rusqlite::types::Value::Text(key)]).ok().flatten().is_some() {                carried.push(format!("media:{}", row.key));            }        }    }    remove_database_folder(layout, local, cotton_client::copy_keep::Ending::keep_into("a local database was adopted into the signed-in copy", asked, &carried));}/// Tables whose changes an adopt leaves behind by its rule and that are no one's data: each named, with why. A table/// that never goes to any server (`is_handed_over` false) is answered too; nothing else is.pub(crate) const ADOPT_BOOKKEEPING: &[(&str, &str)] = &[    ("cotton_changes", "the history line of each act on the local database, never a record of the person's: the acts themselves are what the adopt carries"),    ("cotton_media_holdings", "which device holds which file's bytes, never a record of the person's: the signed-in copy states its own for the files it now holds"),    ("cotton_imports", "a run's line in the Imports tool's history (an address book or a file read), never a record of the person's: the contacts, notes and groups the run made are what the adopt carries (a signed-out vCard import kept the local copy, Android 28 Nov 2026)"),];/// Whether an adopt that did not carry a change of `table` may count it answered (QUEUE BAD OP 6).pub(crate) fn answered_by_rule(table: &str) -> bool {    !cotton_store::schema::table_specs::is_handed_over(table) || ADOPT_BOOKKEEPING.iter().any(|(name, _)| *name == table)}/// How often an adopt waiting for the key looks whether it is held.const KEY_LOOK: std::time::Duration = std::time::Duration::from_millis(250);/// Until this phone holds the object's data key (the shell founds it, opens/// it, or is let in for it on the connected copy), or the backup is stopped.fn wait_for_key(adopting: &Adopting, sealer: &cotton_client::seal::Sealer) -> Result<(), ObjectRefusal> {    while !sealer.has_key() {        if adopting.stop.load(Ordering::SeqCst) {            return Err(refusal(ADOPT_STOPPED, "the backup was stopped"));        }        std::thread::sleep(KEY_LOOK);    }    Ok(())}/// Whether the local database at `path` was an object's copy: it holds/// definitions an object wrote. A database this phone started itself holds/// none, and adopts by its unsent writes.pub fn former_copy(path: &Path) -> Result<bool, MethodError> {    object_definitions(path).map(|held| !held.is_empty()).map_err(|reason| MethodError::new("io", reason))}/// The tables this app keeps: its kit's, or the personal kit's whole.pub(crate) fn kit_tables(layout: &cotton_client::layout::Layout) -> Result<Vec<String>, MethodError> {    let kit = cotton_core::kit::AppKit::at(layout.root()).map_err(|reason| MethodError::new("io", reason))?;    Ok(kit.map_or_else(|| cotton_core::kit::AppKit::tables_of("personal"), |kit| kit.tables))}/// Every live row of a former object's copy, placed by the definitions the/// copy holds: what connect counts before the object is asked anything.fn whole_here(layout: &cotton_client::layout::Layout, path: &Path) -> Result<Vec<WholeRow>, MethodError> {    let held = object_definitions(path).map_err(|reason| MethodError::new("io", reason))?;    let tables = copy_tables(layout)?;    let rekey = Rekey::default();    let into = RestoreInto { layout, object_id: "", served_tables: &held, tables: &tables, rekey: &rekey, at: "" };    whole_rows(path, &into).map_err(|reason| MethodError::new("io", reason))}/// Whether the local database at `path` is a former object's copy holding/// any live row of the app's tables: adopted whole, never given way.pub fn holds_rows(layout: &cotton_client::layout::Layout, path: &Path) -> Result<bool, MethodError> {    Ok(former_copy(path)? && !whole_here(layout, path)?.is_empty())}/// How many passes the new copy is given to pull the restored rows down/// before the adopt stops and keeps the old copy; the next sign-in finishes.const CATCH_UP_PASSES: usize = 60;/// A FORMER OBJECT'S COPY, BROUGHT WHOLE (restore-from-phone, 10 Nov 2026):/// every live row of the kit's tables goes to the object/// (`ObjectTransport::restore_rows`), then the definitions the person/// changed as an adopt sends them, then the media and the new copy as an/// adopt makes them, then what changed meanwhile; and only once the new/// copy has pulled every row down is the old copy removed.#[allow(clippy::too_many_arguments)]fn run_whole(adopting: &Adopting, phone: &Phone, request: &Value, exchange: Arc<dyn Exchange>, local: &str, asked: &str, rekey: &Rekey, served_tables: &[Value], transport: &ObjectTransport, sealer: &cotton_client::seal::Sealer) -> Result<(), ObjectRefusal> {    let layout = phone.client.layout().clone();    let path = layout.replica(local);    let tables = copy_tables(&layout).map_err(of_method)?;    // Each row counted once this launch, though a row changed meanwhile goes twice.    let restored = AdoptLog::beside(&path).restored();    let mut counted: BTreeSet<String> = restored.restored.keys().chain(restored.lost.iter()).cloned().collect();    let mut version = 0;    // Every row goes up, every site among them (Sites' switch removed, 27 Nov 2026).    let kept_here = |_: &str, _: &str| false;    let mut send = |counted: &mut BTreeSet<String>| -> Result<(), ObjectRefusal> {        let at = phone.client.clock().now_iso();        let into = RestoreInto { layout: &layout, object_id: asked, served_tables, tables: &tables, rekey, at: &at };        let sent = transport.restore_rows_except(&into, &mut |row, landing| {            if counted.insert(row.address()) {                adopting.set(|status| {                    if matches!(landing, Landing::Refused(_)) { status.refused += 1 } else { status.sent += 1 }                    status.rows = status.rows.max(status.sent + status.refused);                });            }            !adopting.stop.load(Ordering::SeqCst)        }, &kept_here)?;        version = version.max(sent.version);        // The definitions the person changed go as an adopt sends them.        let sends = |table: &str, _: &str| DEFINITION_TABLES.contains(&table);        let adopt = AdoptInto { layout: &layout, object_id: asked, served_tables, rekey, sends: &sends, at: &at };        transport.adopt_writes(&adopt, &mut |change, landing| {            if DEFINITION_TABLES.contains(&change.table.as_str()) && matches!(landing, Landing::Refused(_)) {                adopting.set(|status| status.refused += 1);            }            !adopting.stop.load(Ordering::SeqCst)        })?;        Ok(())    };    // THE KEY COMES ONLY TO A CONNECTED COPY, as for a database this phone    // started ([`run`]): a former copy's sealed rows go up only under the new    // object's data key, which this phone takes on the new object's copy    // (opened, approved from another device or with a recovery code; founded    // there for a new database). A send stopped by the key alone connects    // the copy with the former copy kept whole, and its rows go once the key    // is held; never in the clear, and no second key is made for them.    let waits = match send(&mut counted) {        Ok(()) => false,        Err(stopped) if stopped.code == cotton_client::seal::SEAL_KEY_MISSING && !sealer.has_key() => true,        Err(stopped) => return Err(stopped),    };    // An earlier launch's restore connected this copy to wait for the key:    // its media and keeps moved then.    let waited_before = AdoptLog::beside(&path).waits_in().as_deref() == Some(asked) && phone.client.attached_database().as_deref() == Some(asked);    if !waited_before {        // THE MEDIA, as an adopt carries them: a file the ledger says is stored        // stays stored (the object's media are moved beside it), one still        // waiting goes up from the new copy.        adopting.set(|status| status.status = MAKING_COPY);        let media = local_media(&path).map_err(|reason| refusal("io", reason))?;        let moved = move_media(&layout, local, asked, rekey, media).map_err(|reason| refusal("io", reason))?;        let now = phone.client.clock().now_iso();        let carry = |copy: &Path, database: &str| carry_media(copy, database, &moved, &now);        if waits {            AdoptLog::beside(&path).waits_key(asked).map_err(|reason| refusal("io", reason))?;        }        connect_copy(phone, request, Arc::clone(&exchange), Some(&carry)).map_err(of_method)?;        crate::phone::books::rekey_here(&phone.client, &|key| rekey.text(key)).map_err(of_method)?;        crate::phone::songs::rekey_here(&phone.client, &|key| rekey.text(key)).map_err(of_method)?;        crate::phone::films::rekey_here(&phone.client, &|key| rekey.text(key)).map_err(of_method)?;    }    if waits {        adopting.set(|status| status.status = WAITING_KEY);        phone.events.emit(crate::events::EventKind::Client, json!({"phase": "personal", "stage": WAITING_KEY}));        account_moved(&phone.events);        wait_for_key(adopting, sealer)?;        adopting.set(|status| status.status = SENDING);    }    // What changed in the old copy while the new one was made, and every row    // that waited for the key.    send(&mut counted)?;    AdoptLog::beside(&path).restored_whole(asked, version).map_err(|reason| refusal("io", reason))?;    finish_whole(phone, local, asked, version, Some(&adopting.stop))}/// Passes of the new copy until it has pulled the object to `version`.fn catch_up(phone: &Phone, asked: &str, version: i64, stop: Option<&AtomicBool>) -> Result<(), ObjectRefusal> {    let copy = phone.client.layout().replica(asked);    let mut passes = 0;    while !caught_up(&copy, version).map_err(|reason| refusal("io", reason))? {        if stop.is_some_and(|stop| stop.load(Ordering::SeqCst)) {            return Err(refusal(ADOPT_STOPPED, "the backup was stopped"));        }        if passes == CATCH_UP_PASSES {            return Err(refusal("not_caught_up", "the object holds every row, and this phone's new copy has not pulled them all down yet: the old copy is kept until it has"));        }        passes += 1;        if let Err(reason) = phone.client.sync_now() {            eprintln!("[adopt] a pass of the new copy failed while it caught up: {reason}");            std::thread::sleep(std::time::Duration::from_millis(500));        }    }    Ok(())}/// The old copy goes once the new copy has pulled the object through/// `version` (every restored row is in it): passes are run until it has, and/// an adopt stopped or a copy that has not caught up keeps the old copy for/// the next sign-in to finish ([`finish_left`]).fn finish_whole(phone: &Phone, local: &str, asked: &str, version: i64, stop: Option<&AtomicBool>) -> Result<(), ObjectRefusal> {    let layout = phone.client.layout().clone();    catch_up(phone, asked, version, stop)?;    // THE OLD COPY GOES ONLY IF ALL OF IT WENT UP: while it holds a live row    // in a table that did not, it stays, and the Account card names the    // table and how many (the phone is signed in; nothing else waits on it).    let left = left_behind(&layout, &layout.replica(local)).map_err(|reason| refusal("io", reason))?;    if !left.is_empty() {        let tables: Vec<String> = left.iter().map(|(table, rows)| backup_line("kept.table", &[("table", table), ("rows", &rows.to_string())]).unwrap_or_else(|| table.clone())).collect();        let said = backup_line("kept.left_behind", &[("tables", &tables.join(", "))]).unwrap_or_else(|| tables.join(", "));        eprintln!("[adopt] {said}");        phone.client.note_trouble(Some(said));        return Ok(());    }    // What Sites kept of each site on this phone goes with its rows to the new copy.    if let Err(reason) = crate::phone::sites::carry(&layout, local, asked) {        // The earlier copy stays, said on the Account card: Sites' carried file is the only route of sites kept only        // on this phone (review of SITES ROWS 5, item 2).        let said = backup_line("kept.sites", &[]).unwrap_or_else(|| reason.clone());        eprintln!("[adopt] {reason}");        phone.client.note_trouble(Some(said));        return Ok(());    }    // QUEUE BAD OP 4 and 5: the former copy leaves through the one function; anything in its folder keeps it whole    // aside, filed under the signed-in database it now belongs to.    // The same ending, its media with it (QUEUE BAD OP 6, H1); a whole adopt names no op ids of its own.    end_adopt(&layout, local, asked, Vec::new());    phone.client.wake_media_drain();    Ok(())}/// A former copy restored whole into `asked` whose removal an earlier launch/// did not see through (the app killed, or the new copy not caught up): once/// the new copy has pulled through, it goes, on its own thread.pub(crate) fn finish_left(phone: &Phone, asked: &str) {    let layout = phone.client.layout().clone();    // A Sites carry the plain adopt could not finish (the earlier copy kept): tried again at each launch.    crate::phone::sites::retry_carry(&layout, Some(asked));    let Ok(folders) = std::fs::read_dir(layout.client_dir()) else { return };    for folder in folders.flatten() {        let Some(local) = folder.file_name().to_str().map(str::to_string) else { continue };        if local == asked {            continue;        }        let Some((into, version)) = AdoptLog::beside(&layout.replica(&local)).restored_into() else { continue };        if into != asked {            continue;        }        let phone = phone.clone();        let asked = asked.to_string();        let _ = std::thread::Builder::new().name("cotton-adopt-finish".into()).spawn(move || {            if let Err(refused) = finish_whole(&phone, &local, &asked, version, None) {                eprintln!("[adopt] the old copy {local} is kept: {}", refused.message);            }        });    }}/// The owner the local database was made under.pub(crate) fn local_owner(path: &Path) -> Option<String> {    let db = cotton_store::Driver::open_snapshot_reader(path).ok()?;    db.get("SELECT owner_id FROM _meta", &[]).ok()??.text("owner_id").map(str::to_string)}/// One file of the local ledger, under the object's key and folder.#[derive(Debug, Clone)]struct Moved {    row: cotton_store::media_ledger::MediaRow,    key: String,    after_row_id: Option<String>,    local_path: Option<String>,}fn local_media(path: &Path) -> Result<Vec<cotton_store::media_ledger::MediaRow>, String> {    let db = cotton_store::Driver::open_snapshot_reader(path).map_err(|error| format!("this phone's own database could not be read ({error})"))?;    let keys = db.all("SELECT key FROM _media", &[]).map_err(|error| error.to_string())?;    let mut rows = Vec::new();    for key in keys.iter().filter_map(|row| row.text("key")) {        if let Some(row) = cotton_store::media_ledger::media_by_key(&db, key).map_err(|error| error.to_string())? {            rows.push(row);        }    }    Ok(rows)}/// Each file the local ledger names, linked (or copied) into the object's/// folder: its bytes stay on the phone, where the new copy's drain finds them.fn move_media(layout: &cotton_client::layout::Layout, local: &str, object: &str, rekey: &Rekey, rows: Vec<cotton_store::media_ledger::MediaRow>) -> Result<Vec<Moved>, String> {    let from_root = layout.client_media_dir().join(local);    let to_root = layout.client_media_dir().join(object);    let mut moved = Vec::with_capacity(rows.len());    for row in rows {        let local_path = match row.local_path.as_deref().map(PathBuf::from) {            Some(file) => match file.strip_prefix(&from_root) {                Ok(rest) => {                    let to = to_root.join(rest);                    if !to.exists() && file.is_file() {                        if let Some(parent) = to.parent() {                            std::fs::create_dir_all(parent).map_err(|error| format!("the object's media folder could not be made ({error})"))?;                        }                        // not a copy: a media file linked, or copied, into the object's media folder; the original stays where it is.                        if std::fs::hard_link(&file, &to).is_err() {                            // not a copy: a media file linked, or copied, into the object's media folder; the original stays where it is.                            std::fs::copy(&file, &to).map_err(|error| format!("a file could not be moved to the object's media folder ({error})"))?;                        }                    }                    Some(to.to_string_lossy().to_string())                }                // A file kept outside the database's folder stays where it is.                Err(_) => Some(file.to_string_lossy().to_string()),            },            None => None,        };        moved.push(Moved { key: rekey.text(&row.key), after_row_id: row.after_row_id.as_deref().map(|id| rekey.text(id)), local_path, row });    }    Ok(moved)}/// The local ledger's rows, in the new copy before it is attached: the drain/// connect starts puts them up.fn carry_media(copy: &Path, database: &str, moved: &[Moved], now: &str) -> Result<(), MethodError> {    if moved.is_empty() || !copy.exists() {        return Ok(());    }    let failed = |error: cotton_store::StoreError| MethodError::new("io", format!("this phone's media could not be written into its copy ({error})"));    let db = cotton_store::driver::Driver::open(copy).map_err(failed)?;    for file in moved {        cotton_store::media_ledger::enqueue_media(            &db,            &cotton_store::media_ledger::MediaEnqueueInput {                key: file.key.clone(),                workspace_id: database.to_string(),                sha256: file.row.sha256.clone(),                content_type: file.row.content_type.clone(),                size_bytes: file.row.size_bytes,                local_path: file.local_path.clone(),                state: Some(file.row.state.clone()),                after: file.row.after.clone(),                after_row_id: file.after_row_id.clone(),                tier: file.row.tier,                captured_here: file.row.captured_here,                now: now.to_string(),            },        )        .map_err(failed)?;    }    Ok(())}#[cfg(test)]#[path = "adopt_tests.rs"]mod tests;/// What a top-up sent.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct ToppedUp {    pub sent: u64,    pub refused: u64,}/// A COPY IS NEVER TRUSTED AS ONLY A CACHE (owner, 11 Nov 2026). At sign-in/// and at every Back up now, once this phone's copy is the object's/// (`connect_copy`), the object is asked what it holds and every live row of/// the app's tables it lacks goes up (`ObjectTransport::top_up`), whatever/// the database's id and whatever the copy's cursor or receipts say was/// sent: an object emptied or founded again under the same id gets every/// row back, one holding some gets the rest, a row it binned stays binned,/// and a second run sends nothing. The unsent writes go first, by a pass;/// while any still waits the top-up does not run, so no row goes twice. The/// Account card says what went (`ClientController::topped_up`).pub(crate) fn top_up(phone: &Phone, request: &Value, exchange: Arc<dyn Exchange>) -> Result<ToppedUp, ObjectRefusal> {    let server = text(request, "server").map_err(of_method)?;    let address = ObjectAddress::open(server).map_err(|reason| refusal("bad_request", reason))?;    let asked = text(request, "databaseId").map_err(of_method)?.to_string();    let credential = text(request, "credential").map_err(of_method)?.to_string();    let layout = phone.client.layout().clone();    let path = layout.replica(&asked);    phone.client.sync_now().map_err(|why| refusal("not_synced", why))?;    if phone.client.sync_status()["pending"].as_u64().unwrap_or(0) > 0 {        return Err(refusal("unsent", "this phone still has changes waiting to send: they go first"));    }    let served = address.send(exchange.as_ref(), "GET", routes::DEFINITIONS, bearer(&credential), None)?;    if served["business"]["kind"] != json!("personal") {        return Err(refusal("not_personal", "this object is a business's, not your personal database"));    }    if served["business"]["database_id"].as_str() != Some(asked.as_str()) {        return Err(refusal("wrong_database", format!("the sign-in named database {asked}, and the object is another")));    }    let served_tables = served["tables"].as_array().cloned().unwrap_or_default();    let tables = kit_tables(&layout).map_err(of_method)?;    let transport = ObjectTransport::new(address, Arc::clone(&exchange), credential, ObjectTables::personal(), path, Vec::new())        .sealing_with(crate::phone::personal_object::sealer_of(&phone.client, &asked));    let rekey = Rekey::default();    let at = phone.client.clock().now_iso();    let into = RestoreInto { layout: &layout, object_id: &asked, served_tables: &served_tables, tables: &tables, rekey: &rekey, at: &at };    let mut went = ToppedUp::default();    transport.top_up(&into, &mut |_, landing| {        if matches!(landing, Landing::Refused(_)) { went.refused += 1 } else { went.sent += 1 }        true    }, cotton_client::transport::object::Written::Nothing)?;    // What went up comes back as the object's own rows on the next pass.    if went.sent > 0 {        let _ = phone.client.sync_now();    }    Ok(went)}/// [`top_up`] on a thread of its own, one at a time: what it sent, or why/// it stopped, is the client's to say (the Account card's lines).pub(crate) fn top_up_beside(phone: Phone, request: Value, exchange: Arc<dyn Exchange>) {    if !phone.client.set_topping_up(true) {        return;    }    std::thread::spawn(move || {        match top_up(&phone, &request, exchange) {            Ok(went) => phone.client.note_topped_up(Some((went.sent, went.refused))),            Err(refused) => {                eprintln!("[object] top-up: {} ({})", refused.message, refused.code);                phone.client.note_trouble_coded(&refused.code, Some(refused.message));            }        }        phone.client.set_topping_up(false);    });}